@stefan.inc/feedback-engine 1.8.0 → 2.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.
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 }` for a proxy of your own.
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.
202
202
 
203
203
  ## Component data and untagged content
204
204
 
@@ -227,25 +227,45 @@ The editor works as on iOS, with these differences:
227
227
 
228
228
  ## Post to ProcrastiMate
229
229
 
230
- Optional, and off until the dev server has a token. [ProcrastiMate](https://github.com/smirea/procrastimate) is the task app that Feedback's author files feedback into. A page cannot call ProcrastiMate from another origin, and a token in the page would be public, so the dev server forwards the calls and adds the token:
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
+
232
+ ### With the signed-in ProcrastiMate account (recommended)
233
+
234
+ Pass the whitelisted `projects` to `setupFeedbackEngine()` with no `url` and no token:
235
+
236
+ ```ts
237
+ setupFeedbackEngine({
238
+ app: 'My App',
239
+ procrastimate: { projects: ['Website'] },
240
+ });
241
+ ```
242
+
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:
231
248
 
232
249
  ```ts
233
250
  // vite.config.ts
234
251
  import { feedbackProcrastimate } from '@stefan.inc/feedback-engine/vite';
235
252
 
236
253
  export default defineConfig({
237
- plugins: [feedbackProcrastimate({ token: process.env.PROCRASTIMATE_TOKEN }) /* and the plugins above */],
254
+ plugins: [
255
+ feedbackProcrastimate({ token: process.env.PROCRASTIMATE_TOKEN, projects: ['Website'] }),
256
+ /* and the plugins above */
257
+ ],
238
258
  });
239
259
  ```
240
260
 
241
- The token is the switch. With `PROCRASTIMATE_TOKEN` set, **ProcrastiMate** shows in the Share menu, with the same picker and task as on iOS. Without it, the entry is not there, and nothing else changes. `setupFeedbackEngine()` needs no option for either case.
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.
242
262
 
243
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.
244
- - `feedbackProcrastimate({ projects: ['Feedback Engine', 'Website'] })` lists the only projects the picker offers, by name (ignoring case) or id, in that order, so feedback cannot land anywhere else. The Inbox is not offered then, and 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.
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.
245
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.
246
- - `feedbackProcrastimate({ project })` names the project the picker opens on, by name (ignoring case) or id, so an app's feedback lands in its own project. Without it, the picker opens on the last project posted to. A name ProcrastiMate does not have shows as an error above the list.
247
- - The proxy runs in `vite dev` and `vite preview`. A build reads the token too. Build a site you deploy without it, because a static host has no proxy.
248
- - For a proxy of your own, pass its address to the page instead: `setupFeedbackEngine({ procrastimate: { url: '/my-proxy' } })`.
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.
249
269
 
250
270
  ## How capture works
251
271
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@stefan.inc/feedback-engine",
3
- "version": "1.8.0",
3
+ "version": "2.0.0",
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,29 +1,39 @@
1
1
  import { Problem } from '../core/problem.ts';
2
+ import { postId } from './webhook.ts';
2
3
 
3
4
  export type ProcrastimateConfig = {
4
- /** Where ProcrastiMate's API answers: the Vite plugin's proxy path, or a server that allows this origin. */
5
- url: string;
6
- /** Sent as a bearer token. Leave it out behind the proxy, which adds its own. */
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. */
7
12
  token?: string;
8
- /** The ProcrastiMate web app, for the link to a posted task. */
13
+ /** The ProcrastiMate web app, for the popup and for links to posted tasks and projects. */
9
14
  app?: string;
10
15
  /** The project the picker opens on, by name (ignoring case) or id, in place of the last one posted to. */
11
16
  project?: string;
12
17
  /**
13
- * The only projects the picker offers, by name (ignoring case) or id, in this order. The Inbox is not offered with
14
- * it. Without it, the picker lists the Inbox and every project.
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.
15
20
  */
16
- projects?: string[];
21
+ projects: string[];
22
+ /**
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.
25
+ */
26
+ space?: string;
17
27
  };
18
28
 
19
29
  export type Section = { id: string; name: string };
20
30
  export type Project = { id: string; name: string; sections: Section[] };
21
- /** Where a task goes: the Inbox without a project, and the project's top, above its sections, without a section. */
31
+ /** Where a task goes: the project's top, above its sections, without a section. No project yet while none is listed. */
22
32
  export type Place = { projectId?: string; sectionId?: string };
23
33
 
24
34
  /** ProcrastiMate's `FILE_PART_BYTES` (`shared/images.ts` there): the most it takes as a file in one request. */
25
- const fileMaxBytes = 16 * 1024 * 1024;
26
- const defaultApp = 'https://procrastimate.stf.lol';
35
+ export const fileMaxBytes = 16 * 1024 * 1024;
36
+ export const defaultProcrastimateApp = 'https://procrastimate.stf.lol';
27
37
 
28
38
  const projectsKey = 'feedback.procrastimate.projects';
29
39
  const lastProjectKey = 'feedback.procrastimate.project';
@@ -56,12 +66,8 @@ export const namedProject = (projects: Project[], name: string) =>
56
66
  projects.find(project => project.id === name) ??
57
67
  projects.find(project => project.name.toLowerCase() === name.toLowerCase());
58
68
 
59
- /**
60
- * The projects the picker lists: every one, or only those `names` lists, in its order. `missing` has the names
61
- * ProcrastiMate does not have.
62
- */
63
- export function listedProjects(all: Project[], names: string[] | undefined) {
64
- if (!names) return { projects: all, missing: [] as string[] };
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[]) {
65
71
  const projects: Project[] = [];
66
72
  const missing: string[] = [];
67
73
  for (const name of names) {
@@ -74,22 +80,23 @@ export function listedProjects(all: Project[], names: string[] | undefined) {
74
80
 
75
81
  /**
76
82
  * The project the picker opens on, among the listed ones: the one the app names, else the last one posted to, else
77
- * the first when the app lists its projects, as the Inbox is not offered then. `undefined` is the Inbox.
83
+ * the first. `undefined` only while none is listed.
78
84
  */
79
85
  export function startingProject(listed: Project[], config: ProcrastimateConfig, last: string | undefined) {
80
86
  if (config.project) return namedProject(listed, config.project)?.id;
81
87
  if (listed.some(project => project.id === last)) return last;
82
- return config.projects ? listed[0]?.id : undefined;
88
+ return listed[0]?.id;
83
89
  }
84
90
 
85
- const appURL = (config: ProcrastimateConfig) => (config.app ?? defaultApp).replace(/\/$/, '');
91
+ export const procrastimateAppURL = (config: ProcrastimateConfig) =>
92
+ (config.app ?? defaultProcrastimateApp).replace(/\/$/, '');
86
93
 
87
94
  /** The project's page in the ProcrastiMate web app, which opens for someone signed in to its space. */
88
95
  export const projectLink = (config: ProcrastimateConfig, id: string) =>
89
- `${appURL(config)}/projects/${encodeURIComponent(id)}`;
96
+ `${procrastimateAppURL(config)}/projects/${encodeURIComponent(id)}`;
90
97
 
91
98
  export const taskLink = (config: ProcrastimateConfig, id: string) =>
92
- `${appURL(config)}/inbox?task=${encodeURIComponent(id)}`;
99
+ `${procrastimateAppURL(config)}/inbox?task=${encodeURIComponent(id)}`;
93
100
 
94
101
  async function send(
95
102
  config: ProcrastimateConfig,
@@ -99,7 +106,11 @@ async function send(
99
106
  body?: BodyInit,
100
107
  type?: string,
101
108
  ) {
102
- const search = new URLSearchParams(Object.entries(query).toSorted(([a], [b]) => a.localeCompare(b)));
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)));
103
114
  const url = `${config.url.replace(/\/$/, '')}/${path}${search.size ? `?${search}` : ''}`;
104
115
  let response: Response;
105
116
  try {
@@ -161,13 +172,13 @@ export async function loadProjects(config: ProcrastimateConfig): Promise<Project
161
172
  return projects;
162
173
  }
163
174
 
164
- type Encoded = { blob: Blob; width: number; height: number };
175
+ export type EncodedImage = { blob: Blob; width: number; height: number };
165
176
 
166
177
  /**
167
178
  * A JPEG of the image no wider than `width` and no larger than `maxBytes`. ProcrastiMate's own clients fit the long
168
179
  * side. A full-length capture is many times taller than wide, so this fits the width, which keeps its text readable.
169
180
  */
170
- async function jpeg(image: HTMLCanvasElement, width: number, maxBytes: number): Promise<Encoded> {
181
+ async function jpeg(image: HTMLCanvasElement, width: number, maxBytes: number): Promise<EncodedImage> {
171
182
  for (let target = Math.min(width, image.width); target >= 64; target = Math.floor((target * 3) / 4)) {
172
183
  const scaled = document.createElement('canvas');
173
184
  scaled.width = target;
@@ -183,6 +194,13 @@ async function jpeg(image: HTMLCanvasElement, width: number, maxBytes: number):
183
194
  throw new Error('The image could not be made small enough to upload.');
184
195
  }
185
196
 
197
+ /** Encodes the full-size image and thumbnail JPEGs within ProcrastiMate's upload caps. */
198
+ export async function encodeTaskImages(image: HTMLCanvasElement): Promise<{ full: EncodedImage; thumb: EncodedImage }> {
199
+ const full = await jpeg(image, 2048, 1_500_000);
200
+ const thumb = await jpeg(image, 320, 200_000);
201
+ return { full, thumb };
202
+ }
203
+
186
204
  /**
187
205
  * Creates one task with the image export and `feedback.json` attached, and returns its id. The attachments upload
188
206
  * before the task that lists them, as ProcrastiMate's own clients do, so the task never names bytes the server
@@ -200,10 +218,10 @@ export async function postTask(
200
218
  if (bytes.length > fileMaxBytes)
201
219
  throw new Error('The JSON report is over the 16 MB ProcrastiMate takes in one upload.');
202
220
  step('Encoding the image');
203
- const full = await jpeg(image, 2048, 1_500_000);
204
- const thumb = await jpeg(image, 320, 200_000);
205
- const imageId = crypto.randomUUID();
206
- const reportId = crypto.randomUUID();
221
+ const { full, thumb } = await encodeTaskImages(image);
222
+ const imageId = postId();
223
+ const reportId = postId();
224
+ const taskId = postId();
207
225
  step('Uploading the image');
208
226
  await send(config, 'PUT', 'api/images', { id: imageId, size: 'full' }, full.blob, 'image/jpeg');
209
227
  step('Uploading the thumbnail');
@@ -223,30 +241,19 @@ export async function postTask(
223
241
  'POST',
224
242
  'api/tasks',
225
243
  {},
226
- JSON.stringify({ title, projectId: place.projectId ?? null, sectionId: place.sectionId ?? null }),
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
+ }),
227
254
  'application/json',
228
255
  );
229
256
  const { id } = (await created.json()) as { id: string };
230
- // The agent API cannot create a task with attachments, so a failed attach would leave a task without them, and a retry would add a second one.
231
- step('Attaching the files');
232
- try {
233
- await send(
234
- config,
235
- 'PATCH',
236
- 'api/tasks',
237
- { id },
238
- JSON.stringify({
239
- attachments: [
240
- { id: imageId, width: full.width, height: full.height },
241
- { id: reportId, name: 'feedback.json', type: 'application/json', bytes: bytes.length },
242
- ],
243
- }),
244
- 'application/json',
245
- );
246
- } catch (error) {
247
- await send(config, 'DELETE', 'api/tasks', { id }).catch(() => {});
248
- throw error;
249
- }
250
257
  store(lastProjectKey, place.projectId);
251
258
  return id;
252
259
  }
@@ -0,0 +1,194 @@
1
+ import type { Annotations } from '../core/annotations.ts';
2
+ import { Problem, type Fact } from '../core/problem.ts';
3
+ import type { Screen } from './capture.ts';
4
+ import { annotatedImage } from './image.ts';
5
+ import { encodeTaskImages, fileMaxBytes, procrastimateAppURL, type ProcrastimateConfig } from './procrastimate.ts';
6
+ import { postId } from './webhook.ts';
7
+
8
+ export const FEEDBACK_READY = 'feedback:ready';
9
+ export const FEEDBACK_DRAFT = 'feedback:draft';
10
+ export const FEEDBACK_POSTED = 'feedback:posted';
11
+ export const FEEDBACK_CANCELLED = 'feedback:cancelled';
12
+
13
+ export type PopupReply =
14
+ | { kind: 'ready' }
15
+ | { kind: 'posted'; id: string; destination: string; url: string }
16
+ | { kind: 'cancelled' };
17
+
18
+ function isHttpURL(value: unknown): value is string {
19
+ if (typeof value !== 'string') return false;
20
+ try {
21
+ const parsed = new URL(value);
22
+ return parsed.protocol === 'http:' || parsed.protocol === 'https:';
23
+ } catch {
24
+ return false;
25
+ }
26
+ }
27
+
28
+ /**
29
+ * Validates a message posted back from ProcrastiMate's `/feedback` popup. Every message must come from the configured
30
+ * ProcrastiMate origin, from the popup window we opened, and carry this handoff's nonce.
31
+ */
32
+ export function parsePopupReply(
33
+ event: { origin: string; source: unknown; data: unknown },
34
+ expected: { origin: string; source: unknown; nonce: string },
35
+ ): PopupReply | null {
36
+ if (event.origin !== expected.origin || event.source !== expected.source) return null;
37
+ const data = event.data;
38
+ if (!data || typeof data !== 'object') return null;
39
+ const record = data as Record<string, unknown>;
40
+ if (record.nonce !== expected.nonce) return null;
41
+ if (record.type === FEEDBACK_READY) return { kind: 'ready' };
42
+ if (record.type === FEEDBACK_CANCELLED) return { kind: 'cancelled' };
43
+ if (
44
+ record.type === FEEDBACK_POSTED &&
45
+ typeof record.id === 'string' &&
46
+ typeof record.destination === 'string' &&
47
+ isHttpURL(record.url)
48
+ ) {
49
+ return { kind: 'posted', id: record.id, destination: record.destination, url: record.url };
50
+ }
51
+ return null;
52
+ }
53
+
54
+ function popupFeatures() {
55
+ const width = 460;
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));
59
+ return `popup,width=${width},height=${height},left=${left},top=${top}`;
60
+ }
61
+
62
+ /**
63
+ * Opens ProcrastiMate's `/feedback` popup synchronously (so the browser's click gesture allows `window.open`) while
64
+ * encoding the screenshot in parallel, then hands over the draft over `postMessage` once the popup signals ready.
65
+ * No credential ever leaves ProcrastiMate's own origin.
66
+ */
67
+ export function openProcrastimatePopup({
68
+ config,
69
+ title,
70
+ app,
71
+ screen,
72
+ annotations,
73
+ report,
74
+ onposted,
75
+ onerror,
76
+ onclose,
77
+ }: {
78
+ config: ProcrastimateConfig;
79
+ title: string;
80
+ app?: string;
81
+ screen: Screen;
82
+ annotations: Annotations;
83
+ report: string;
84
+ onposted: (result: { id: string; destination: string; url: string }) => void;
85
+ onerror: (problem: Problem) => void;
86
+ onclose?: () => void;
87
+ }): { cancel: () => void } {
88
+ const base = procrastimateAppURL(config);
89
+ const expectedOrigin = new URL(base, location.href).origin;
90
+ const nonce = postId();
91
+ const url = `${base}/feedback?nonce=${encodeURIComponent(nonce)}`;
92
+ const environment: Fact[] = screen.capture.environment.map(entry => ({ label: entry.name, value: entry.value }));
93
+ const reportBytes = new TextEncoder().encode(report).byteLength;
94
+ if (reportBytes > fileMaxBytes) {
95
+ onerror(
96
+ Problem.from(new Error('The JSON report is over the 16 MB ProcrastiMate takes in one upload.')).with(
97
+ [{ label: 'Report', value: `${reportBytes} bytes` }],
98
+ environment,
99
+ ),
100
+ );
101
+ return { cancel() {} };
102
+ }
103
+
104
+ const popup = window.open(url, 'feedback-procrastimate', popupFeatures());
105
+ if (!popup) {
106
+ onerror(
107
+ new Problem('The browser blocked ProcrastiMate’s window. Allow pop-ups for this site and try again.', [
108
+ { label: 'URL', value: url },
109
+ ...environment,
110
+ ]),
111
+ );
112
+ return { cancel() {} };
113
+ }
114
+
115
+ // Render synchronously before any await; encode JPEGs while the popup loads.
116
+ let prepared: Promise<{ full: Blob; thumb: Blob; width: number; height: number }>;
117
+ try {
118
+ const canvas = annotatedImage(screen, annotations);
119
+ prepared = encodeTaskImages(canvas).then(({ full, thumb }) => ({
120
+ full: full.blob,
121
+ thumb: thumb.blob,
122
+ width: full.width,
123
+ height: full.height,
124
+ }));
125
+ } catch (error) {
126
+ prepared = Promise.reject(error);
127
+ }
128
+ // Prevent an unhandled rejection if the user closes the popup before encoding settles.
129
+ prepared.catch(() => {});
130
+
131
+ let done = false;
132
+ const cleanup = () => {
133
+ if (done) return;
134
+ done = true;
135
+ window.removeEventListener('message', onMessage);
136
+ clearInterval(closedCheck);
137
+ };
138
+
139
+ const onMessage = (event: MessageEvent) => {
140
+ const reply = parsePopupReply(event, { origin: expectedOrigin, source: popup, nonce });
141
+ if (!reply) return;
142
+ if (reply.kind === 'ready') {
143
+ void prepared
144
+ .then(image => {
145
+ if (done || popup.closed) return;
146
+ popup.postMessage(
147
+ {
148
+ type: FEEDBACK_DRAFT,
149
+ nonce,
150
+ title,
151
+ app,
152
+ project: config.project,
153
+ projects: config.projects,
154
+ space: config.space,
155
+ image,
156
+ report,
157
+ },
158
+ expectedOrigin,
159
+ );
160
+ })
161
+ .catch((error: unknown) => {
162
+ cleanup();
163
+ try {
164
+ popup.close();
165
+ } catch {
166
+ // Ignore if already closed.
167
+ }
168
+ onerror(
169
+ Problem.from(error).with(
170
+ [
171
+ { label: 'Step', value: 'Encoding the image' },
172
+ { label: 'URL', value: url },
173
+ ],
174
+ environment,
175
+ ),
176
+ );
177
+ });
178
+ return;
179
+ }
180
+ cleanup();
181
+ if (reply.kind === 'posted') onposted(reply);
182
+ else onclose?.();
183
+ };
184
+
185
+ window.addEventListener('message', onMessage);
186
+ const closedCheck = setInterval(() => {
187
+ if (popup.closed) {
188
+ cleanup();
189
+ onclose?.();
190
+ }
191
+ }, 400);
192
+
193
+ return { cancel: cleanup };
194
+ }
@@ -9,11 +9,13 @@
9
9
  Problem,
10
10
  Session,
11
11
  tag,
12
+ taskTitle,
12
13
  title,
13
14
  type Frame,
14
15
  type SavedWebhook,
15
16
  } from '../core/index.ts';
16
17
  import type { Screen } from '../dom/capture.ts';
18
+ import { openProcrastimatePopup } from '../dom/procrastimatePopup.ts';
17
19
  import {
18
20
  buildExport,
19
21
  canShare,
@@ -98,7 +100,10 @@
98
100
  let showsItems = $state(matchMedia('(min-width: 900px)').matches);
99
101
  let showsShare = $state(false);
100
102
  let showsProcrastimate = $state(false);
103
+ let popup = { cancel() {} };
101
104
  let posting = $state<Delivery>();
105
+
106
+ $effect(() => () => popup.cancel());
102
107
  let saved = $state(loadSavedWebhooks());
103
108
  /** The dialog for a saved webhook, `webhook` unset for a new one. */
104
109
  let editing = $state<{ webhook?: SavedWebhook }>();
@@ -275,8 +280,36 @@
275
280
 
276
281
  function send(destination: Destination) {
277
282
  showsShare = false;
278
- if (destination.kind === 'procrastimate') showsProcrastimate = true;
279
- else if (destination.kind === 'saved') edit(destination.saved);
283
+ if (destination.kind === 'procrastimate') {
284
+ const config = engine.options.procrastimate;
285
+ if (!config) return;
286
+ if (config.url !== undefined) {
287
+ showsProcrastimate = true;
288
+ } else {
289
+ popup.cancel();
290
+ const items = [...session.items];
291
+ const names = taskTitle(session.capture, items);
292
+ popup = openProcrastimatePopup({
293
+ config,
294
+ title: names.placeholder,
295
+ app: engine.options.app ?? (document.title.trim() || undefined),
296
+ screen,
297
+ annotations: session.annotations,
298
+ report: session.compactJSON,
299
+ onposted: ({ destination: where, url }) => {
300
+ act(() => {
301
+ session.markShared(items);
302
+ session.toast = { text: `Added to ${where} in ProcrastiMate`, link: url };
303
+ });
304
+ },
305
+ onerror: problem => {
306
+ act(() => {
307
+ session.toast = { text: 'Couldn’t open ProcrastiMate', problem };
308
+ });
309
+ },
310
+ });
311
+ }
312
+ } else if (destination.kind === 'saved') edit(destination.saved);
280
313
  else posting = destination.delivery;
281
314
  }
282
315
 
@@ -39,8 +39,6 @@
39
39
  let all = $state(cachedProjects());
40
40
  const projects = $derived(listedProjects(all, config.projects).projects);
41
41
  // svelte-ignore state_referenced_locally
42
- const inbox = !config.projects;
43
- // svelte-ignore state_referenced_locally
44
42
  let place = $state<Place>({ projectId: startingProject(projects, config, lastProject()) });
45
43
  let loading = $state(true);
46
44
  /** Whether the user chose a place, which a project list that finishes loading must not undo. */
@@ -50,8 +48,8 @@
50
48
  /** What the post is doing, while it runs. */
51
49
  let step = $state<string>();
52
50
  const posting = $derived(step !== undefined);
53
- /** Without a project, a post would land in the Inbox, which a project the app named or listed rules out. */
54
- const unresolved = $derived(!place.projectId && (!inbox || (loading && !!config.project)));
51
+ /** Without a project, a post would land in the Inbox, which Feedback never posts to. */
52
+ const unresolved = $derived(!place.projectId);
55
53
  let status = $state<HTMLElement>();
56
54
  // svelte-ignore state_referenced_locally
57
55
  const environment: Fact[] = session.capture.environment.map(entry => ({ label: entry.name, value: entry.value }));
@@ -63,18 +61,13 @@
63
61
  const listed = listedProjects(loaded, config.projects);
64
62
  if (!chosen) place = { projectId: startingProject(listed.projects, config, lastProject()) };
65
63
  const project = listed.projects.find(candidate => candidate.id === place.projectId);
66
- if (!project)
67
- place = { projectId: startingProject(listed.projects, { ...config, project: undefined }, undefined) };
64
+ if (!project) place = { projectId: listed.projects[0]?.id };
68
65
  else if (!project.sections.some(section => section.id === place.sectionId)) place = { projectId: project.id };
69
66
  const missing = [...listed.missing];
70
67
  if (config.project && !startingProject(listed.projects, config, undefined)) missing.push(config.project);
71
68
  if (missing.length) {
72
69
  const names = [...new Set(missing)].map(name => `"${name}"`).join(', ');
73
- throw new Error(
74
- config.projects
75
- ? `ProcrastiMate has no project named ${names} among the projects Feedback was set up with`
76
- : `ProcrastiMate has no project named ${names}`,
77
- );
70
+ throw new Error(`ProcrastiMate has no project named ${names} among the projects Feedback may post to`);
78
71
  }
79
72
  })
80
73
  .catch(
@@ -95,18 +88,18 @@
95
88
  const facts: Fact[] = [
96
89
  {
97
90
  label: 'Place',
98
- value: [project ? `${project.name} (${project.id})` : 'Inbox', section && `${section.name} (${section.id})`]
91
+ value: [project && `${project.name} (${project.id})`, section && `${section.name} (${section.id})`]
99
92
  .filter(Boolean)
100
93
  .join(' / '),
101
94
  },
102
95
  { label: 'Report', value: `${new TextEncoder().encode(report).length} bytes` },
103
- { label: 'Server', value: config.url },
96
+ { label: 'Server', value: config.url ?? '' },
104
97
  ];
105
98
  try {
106
99
  const image = annotatedImage(screen, session.annotations);
107
100
  facts.push({ label: 'Image', value: `${image.width} × ${image.height} px` });
108
101
  const id = await postTask(config, name.trim(), place, image, report, text => (step = text));
109
- const destination = [project?.name ?? 'Inbox', section?.name].filter(Boolean).join(' / ');
102
+ const destination = [project?.name, section?.name].filter(Boolean).join(' / ');
110
103
  onposted(items, { text: `Added to ${destination} in ProcrastiMate`, link: taskLink(config, id) });
111
104
  } catch (error) {
112
105
  const elapsed = { label: 'Elapsed', value: `${((performance.now() - started) / 1000).toFixed(1)} s` };
@@ -172,7 +165,6 @@
172
165
  </label>
173
166
  <span class="caption">Project{loading ? ' · loading…' : ''}</span>
174
167
  <div class="list" role="listbox" aria-label="Project">
175
- {#if inbox}{@render row('Inbox', !place.projectId, false, () => (place = {}))}{/if}
176
168
  {#each projects as project (project.id)}
177
169
  {@const open = project.id === place.projectId && project.sections.length > 0}
178
170
  {@render row(
@@ -26,8 +26,10 @@ export type FeedbackOptions = {
26
26
  */
27
27
  threeFingerHold?: boolean;
28
28
  /**
29
- * Adds ProcrastiMate to the Share menu. Leave it out behind `feedbackProcrastimate()` from the Vite entry point,
30
- * which adds the entry by itself when it has a token. Set it for a proxy of your own.
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.
31
33
  */
32
34
  procrastimate?: ProcrastimateConfig;
33
35
  /**
@@ -61,13 +61,14 @@ export function setupFeedbackEngine(options: FeedbackOptions = {}): FeedbackEngi
61
61
  const proxy = (import.meta as Meta).env && (import.meta as Meta).env!.FEEDBACK_PROCRASTIMATE;
62
62
  const project = (import.meta as Meta).env && (import.meta as Meta).env!.FEEDBACK_PROCRASTIMATE_PROJECT;
63
63
  const projects = (import.meta as Meta).env && (import.meta as Meta).env!.FEEDBACK_PROCRASTIMATE_PROJECTS;
64
- const listed = projects ? (JSON.parse(projects) as string[]) : [];
65
- const engine = new Engine({
66
- ...options,
67
- procrastimate:
68
- options.procrastimate ??
69
- (proxy ? { url: proxy, project: project || undefined, projects: listed.length ? listed : undefined } : undefined),
70
- });
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)
70
+ throw new Error('setupFeedbackEngine({ procrastimate }) needs the projects Feedback may post to, by name or id.');
71
+ const engine = new Engine({ ...options, procrastimate });
71
72
  const host = document.createElement('div');
72
73
  host.setAttribute(hostAttribute, '');
73
74
  // The shadow root keeps the app's styles out of the editor and the editor's styles out of the app.
@@ -24,23 +24,34 @@ export type FeedbackOptions = {
24
24
  */
25
25
  threeFingerHold?: boolean;
26
26
  /**
27
- * Adds ProcrastiMate to the Share menu. Leave it out behind `feedbackProcrastimate()` from the Vite entry point,
28
- * which adds the entry by itself when it has a token. Set it for a proxy of your own.
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.
29
31
  */
30
32
  procrastimate?: {
31
- /** Where ProcrastiMate's API answers: the Vite plugin's proxy path, or a server that allows this origin. */
32
- url: string;
33
- /** Sent as a bearer token. Leave it out behind the proxy, which adds its own. */
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. */
34
40
  token?: string;
35
- /** The ProcrastiMate web app, for the link to a posted task. */
41
+ /** The ProcrastiMate web app, for the popup and for links to posted tasks and projects. */
36
42
  app?: string;
37
43
  /** The project the picker opens on, by name (ignoring case) or id, in place of the last one posted to. */
38
44
  project?: string;
39
45
  /**
40
- * The only projects the picker offers, by name (ignoring case) or id, in this order. The Inbox is not offered
41
- * with it. Without it, the picker lists the Inbox and every project.
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.
48
+ */
49
+ projects: string[];
50
+ /**
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.
42
53
  */
43
- projects?: string[];
54
+ space?: string;
44
55
  };
45
56
  /**
46
57
  * Adds one entry to the Share menu per webhook. Choosing it posts the image export and the JSON export to the
@@ -14,9 +14,10 @@ export function feedbackEngine(options?: {
14
14
 
15
15
  /**
16
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.
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.
18
19
  */
19
- export function feedbackProcrastimate(options?: {
20
+ export function feedbackProcrastimate(options: {
20
21
  /** ProcrastiMate's origin. Defaults to `https://procrastimate.stf.lol`. */
21
22
  url?: string;
22
23
  /** A ProcrastiMate API token. Pass `process.env.PROCRASTIMATE_TOKEN`, so the entry shows only where it is set. */
@@ -26,10 +27,10 @@ export function feedbackProcrastimate(options?: {
26
27
  /** The project the picker opens on, by name (ignoring case) or id, in place of the last one posted to. */
27
28
  project?: string;
28
29
  /**
29
- * The only projects the picker offers, by name (ignoring case) or id, in this order, each with a link to its page
30
- * in ProcrastiMate. The Inbox is not offered with it. Without it, the picker lists the Inbox and every project.
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.
31
32
  */
32
- projects?: string[];
33
+ projects: string[];
33
34
  }): Plugin;
34
35
 
35
36
  /**
package/src/vite/index.js CHANGED
@@ -1,15 +1,11 @@
1
1
  import { basename, relative, sep } from 'node:path';
2
2
  import { parse } from 'svelte/compiler';
3
3
 
4
+ export { feedbackProcrastimate } from './procrastimate.js';
4
5
  export { addReact, feedbackEngineReact, sourceAttribute } from './react.js';
5
6
 
6
7
  const entry = '@stefan.inc/feedback-engine/svelte';
7
8
 
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
- const procrastimateProjectDefine = 'import.meta.env.FEEDBACK_PROCRASTIMATE_PROJECT';
11
- const procrastimateProjectsDefine = 'import.meta.env.FEEDBACK_PROCRASTIMATE_PROJECTS';
12
-
13
9
  /**
14
10
  * The name a tag gets without one: the file's, as `.feedback(self)` uses the type's on iOS. A SvelteKit route file is
15
11
  * named after its folder, so `routes/lists/[id]/+page.svelte` is `ListsIdPage`.
@@ -147,71 +143,3 @@ export function feedbackEngine(options = {}) {
147
143
  },
148
144
  };
149
145
  }
150
-
151
- /**
152
- * A Vite plugin that lets the page post to ProcrastiMate. A browser on another origin cannot call ProcrastiMate, and a
153
- * token in the page would be public, so the dev and preview servers forward `path` to ProcrastiMate and add the
154
- * token there.
155
- *
156
- * The token is the switch. With one, the plugin tells the page where the proxy is, and the Share menu lists
157
- * ProcrastiMate. Without one the page is told nothing, so the entry is not there. A page that names the path itself
158
- * then gets a 501 that says why.
159
- *
160
- * @param {{ url?: string, token?: string, path?: string, project?: string, projects?: string[] }} [options]
161
- */
162
- export function feedbackProcrastimate(options = {}) {
163
- if (options.projects && !options.projects.length)
164
- throw new Error('feedbackProcrastimate({ projects }) lists no projects. Leave it out to offer every project.');
165
- const path = options.path ?? '/__feedback/procrastimate';
166
- const target = (options.url ?? 'https://procrastimate.stf.lol').replace(/\/$/, '');
167
- /** @type {import('vite').Connect.NextHandleFunction} */
168
- const handler = async (request, response, next) => {
169
- if (!request.url?.startsWith(`${path}/`)) return next();
170
- const reply = (/** @type {number} */ status, /** @type {string} */ message) => {
171
- response.statusCode = status;
172
- response.setHeader('Content-Type', 'application/json');
173
- response.end(JSON.stringify({ message }));
174
- };
175
- if (!options.token)
176
- return reply(501, 'the dev server has no ProcrastiMate token. Pass one to feedbackProcrastimate().');
177
- try {
178
- const chunks = [];
179
- for await (const chunk of request) chunks.push(chunk);
180
- const body = Buffer.concat(chunks);
181
- const upstream = await fetch(target + request.url.slice(path.length), {
182
- method: request.method,
183
- headers: {
184
- Authorization: `Bearer ${options.token}`,
185
- 'User-Agent': 'Feedback',
186
- ...(request.headers['content-type'] ? { 'Content-Type': request.headers['content-type'] } : {}),
187
- },
188
- body: body.length ? body : undefined,
189
- });
190
- response.statusCode = upstream.status;
191
- response.setHeader('Content-Type', upstream.headers.get('content-type') ?? 'application/json');
192
- response.end(Buffer.from(await upstream.arrayBuffer()));
193
- } catch (error) {
194
- reply(502, `the dev server could not reach ${target}: ${/** @type {Error} */ (error).message}`);
195
- }
196
- };
197
- return {
198
- name: 'feedback-engine-procrastimate',
199
- config() {
200
- return {
201
- define: {
202
- [procrastimateDefine]: JSON.stringify(options.token ? path : ''),
203
- [procrastimateProjectDefine]: JSON.stringify(options.project ?? ''),
204
- [procrastimateProjectsDefine]: JSON.stringify(JSON.stringify(options.projects ?? [])),
205
- },
206
- };
207
- },
208
- /** @param {import('vite').ViteDevServer} server */
209
- configureServer(server) {
210
- server.middlewares.use(handler);
211
- },
212
- /** @param {import('vite').PreviewServer} server */
213
- configurePreviewServer(server) {
214
- server.middlewares.use(handler);
215
- },
216
- };
217
- }
@@ -0,0 +1,11 @@
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;
@@ -0,0 +1,187 @@
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
+ }