@daybook/feedback 1.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/dist/files.js ADDED
@@ -0,0 +1,61 @@
1
+ /**
2
+ * Files the reporter attached themselves, by paste or drop.
3
+ *
4
+ * Added because automatic screen capture needs a browser permission prompt, and a reporter who
5
+ * declines it loses the most useful part of the report. The predecessor's widget only ever worked
6
+ * this way — a reviewer takes a screenshot with the tool they already use and pastes it — and for the
7
+ * decline case that is strictly better than nothing.
8
+ */
9
+ const ALLOWED = /^(image\/(png|jpeg|gif|webp)|video\/(mp4|quicktime|webm))$/;
10
+ /** Matches the server's per-report cap, so a fifth file is refused here rather than silently dropped. */
11
+ export const MAX_FILES = 5;
12
+ /** 25 MB. Under the server's 50, because a phone video hits that in seconds. */
13
+ const MAX_BYTES = 25 * 1024 * 1024;
14
+ export function stage(files, existing) {
15
+ const staged = [];
16
+ for (const file of files) {
17
+ if (existing + staged.length >= MAX_FILES)
18
+ break;
19
+ const error = !ALLOWED.test(file.type) ? 'Only images and short videos.'
20
+ : file.size > MAX_BYTES ? `Too large (${(file.size / 1048576).toFixed(1)} MB, max 25).`
21
+ : null;
22
+ staged.push({
23
+ blob: file,
24
+ // A pasted screenshot arrives as "image.png" or nothing at all, so give it something a triager
25
+ // can distinguish in a list of five.
26
+ filename: file.name || `pasted-${staged.length + 1}.${extensionFor(file.type)}`,
27
+ contentType: file.type,
28
+ preview: error ? null : URL.createObjectURL(file),
29
+ error,
30
+ });
31
+ }
32
+ return staged;
33
+ }
34
+ /** From a paste event. Ignores the text/plain that accompanies most clipboard images. */
35
+ export function fromPaste(event) {
36
+ const items = event.clipboardData?.items;
37
+ if (!items)
38
+ return [];
39
+ const files = [];
40
+ for (const item of items) {
41
+ if (item.kind !== 'file')
42
+ continue;
43
+ const file = item.getAsFile();
44
+ if (file)
45
+ files.push(file);
46
+ }
47
+ return files;
48
+ }
49
+ /**
50
+ * Releases the object URLs. Not calling this leaks the whole file into memory for the lifetime of the
51
+ * page, which on a long-lived single-page app is a real leak rather than a theoretical one.
52
+ */
53
+ export function revoke(files) {
54
+ for (const file of files) {
55
+ if (file.preview)
56
+ URL.revokeObjectURL(file.preview);
57
+ }
58
+ }
59
+ function extensionFor(contentType) {
60
+ return contentType.split('/')[1]?.replace('quicktime', 'mov') ?? 'bin';
61
+ }
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Whether a keystroke is someone typing rather than reaching for a shortcut.
3
+ *
4
+ * Its own module so it can be tested without a DOM, which is the level this rule lives at.
5
+ *
6
+ * The important part is composedPath() rather than event.target. The hotkey listener is on window,
7
+ * and an event raised inside a shadow root is RETARGETED before it arrives there — target becomes the
8
+ * shadow host, a plain div. A tagName check on target therefore passes happily while the reporter is
9
+ * typing in the widget's own textarea, and a bare "f" closed the composer and discarded what they had
10
+ * written. It only misbehaved inside the widget, which is the one place typing is guaranteed, so the
11
+ * guard looked correct everywhere it was easy to try.
12
+ *
13
+ * composedPath()[0] is the real innermost node, shadow boundaries included.
14
+ */
15
+ export declare function isTyping(event: KeyboardEvent): boolean;
package/dist/hotkey.js ADDED
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Whether a keystroke is someone typing rather than reaching for a shortcut.
3
+ *
4
+ * Its own module so it can be tested without a DOM, which is the level this rule lives at.
5
+ *
6
+ * The important part is composedPath() rather than event.target. The hotkey listener is on window,
7
+ * and an event raised inside a shadow root is RETARGETED before it arrives there — target becomes the
8
+ * shadow host, a plain div. A tagName check on target therefore passes happily while the reporter is
9
+ * typing in the widget's own textarea, and a bare "f" closed the composer and discarded what they had
10
+ * written. It only misbehaved inside the widget, which is the one place typing is guaranteed, so the
11
+ * guard looked correct everywhere it was easy to try.
12
+ *
13
+ * composedPath()[0] is the real innermost node, shadow boundaries included.
14
+ */
15
+ export function isTyping(event) {
16
+ const path = typeof event.composedPath === 'function' ? event.composedPath() : [];
17
+ const node = path[0] ?? event.target;
18
+ // ELEMENT_NODE. A keystroke can be reported against a text node or the document itself.
19
+ if (!node || node.nodeType !== 1)
20
+ return false;
21
+ if (/^(INPUT|TEXTAREA|SELECT)$/.test(node.tagName))
22
+ return true;
23
+ // A rich-text host app: the editable element is often an ancestor of the node holding focus, so
24
+ // checking only the node itself would miss it.
25
+ return typeof node.closest === 'function'
26
+ && node.closest('[contenteditable=""], [contenteditable="true"]') !== null;
27
+ }
@@ -0,0 +1,108 @@
1
+ import type { IngestRequest, IngestResponse, FeedbackOptions } from './types.js';
2
+ export type { Anchor, Breadcrumb, FeedbackKind, FeedbackTheme, HandshakeRequest, HandshakeResponse, IngestRequest, IngestResponse, FeedbackOptions, ReporterStatus, } from './types.js';
3
+ export { captureAnchor, resolveAnchor } from './anchor.js';
4
+ /**
5
+ * In-app feedback for the web.
6
+ *
7
+ * import { init } from '@daybook/feedback'
8
+ *
9
+ * init({
10
+ * apiUrl: 'https://pm-api.hreben.us',
11
+ * ingestKey: 'pmi_…',
12
+ * app: { version: '1.4.0', environment: 'production' },
13
+ * })
14
+ *
15
+ * The reporter clicks the thing that is wrong and says what happened. Everything else — which page,
16
+ * which element, which browser, what errored just before — is captured without asking them, because
17
+ * the alternative is a reply thread asking questions the reporter has already forgotten the answer to.
18
+ */
19
+ export declare class DaybookFeedback {
20
+ private options;
21
+ private readonly client;
22
+ private readonly trail;
23
+ private widget;
24
+ constructor(options: FeedbackOptions);
25
+ /**
26
+ * Idempotent, because a host app has every reason to call it again.
27
+ *
28
+ * init() starts the widget, and an app that shows it only to signed-in people then calls start()
29
+ * on sign-in — which used to construct and mount a SECOND widget over the first, leaving two
30
+ * launchers and a stale one holding the events. Calling start() twice should mean the widget is
31
+ * running, not that there are two of them.
32
+ */
33
+ start(): this;
34
+ private started;
35
+ /**
36
+ * Puts the widget on the page if it is not already there.
37
+ *
38
+ * Idempotent, and called from the handshake as well as from start(). A handshake that fails takes
39
+ * the widget away — which is right for a blocked reporter and for a domain that is not allowed —
40
+ * but under the Daybook sign-in mode the FIRST handshake is *supposed* to fail, and signing in
41
+ * afterwards has to bring it back. Without this, signIn() succeeded and left the page with no
42
+ * widget on it, which is the one flow that mode exists for.
43
+ */
44
+ private mount;
45
+ /**
46
+ * Asks who may report from here and what the widget should look like.
47
+ *
48
+ * Never allowed to break the host page. A failed handshake — an unverified domain, a revoked key,
49
+ * a network that is down — takes the widget away and logs one line; the alternative is an
50
+ * exception in somebody else's application, thrown by a feedback button.
51
+ */
52
+ /**
53
+ * At most one handshake in flight per identity.
54
+ *
55
+ * Our own app fires three at once on first paint — init() calls start(), and two watchers with
56
+ * `immediate: true` call identify() and start() again — and a customer's app is free to do the
57
+ * same. All three then find no reporter row, all three insert one, and two lose on the unique
58
+ * index. Nobody saw an error, because the server recovers by re-reading; what it cost was an
59
+ * error-level stack trace in the production log per losing request, forever, which is how a real
60
+ * error becomes invisible.
61
+ *
62
+ * Keyed on the identity rather than a bare flag: a handshake already running for the previous
63
+ * reporter must not be handed back to identify() as though it answered for the new one.
64
+ */
65
+ private inFlight;
66
+ /** Bumped when a sign-in changes who we are, which the options object does not show. */
67
+ private epoch;
68
+ private handshake;
69
+ private runHandshake;
70
+ /** The last handshake, for a host app that wants to explain a state in its own words. */
71
+ private ready;
72
+ /**
73
+ * Says who is reporting, once the host app knows.
74
+ *
75
+ * A single-page app mounts the widget at boot and learns who is signed in a moment later, so a
76
+ * reporter passed to init() is either absent or stale. Without this, every report from a signed-in
77
+ * user arrived as Anonymous and triage had no address to reply to — which is the most useful field
78
+ * on a bug report after the words themselves.
79
+ *
80
+ * Merges rather than replaces, so supplying only a name does not wipe an email the reporter typed
81
+ * into the composer. Passing null clears it, which is what signing out should do.
82
+ */
83
+ identify(reporter: FeedbackOptions['reporter'] | null): void;
84
+ /**
85
+ * Signs the reporter in with a Daybook account and re-handshakes.
86
+ *
87
+ * Only meaningful when the integration is set to that mode. Call it from a button in your own UI —
88
+ * it opens a popup, so it has to be triggered by a click or the browser will block it.
89
+ */
90
+ signIn(): Promise<void>;
91
+ /**
92
+ * The signature for the current reporter, from the host's backend.
93
+ *
94
+ * Separate from identify() because the two arrive at different times: an app knows who signed in
95
+ * immediately and has to ask its own server for the signature.
96
+ */
97
+ authenticate(signature: string | null): void;
98
+ stop(): void;
99
+ /** Opens the picker programmatically, for a host app's own "Report a problem" menu item. */
100
+ open(): void;
101
+ /**
102
+ * Files a report without any UI, for a host app that has its own form or wants to report a caught
103
+ * error. Screenshots are not taken here: there is no user present to consent to a screen share.
104
+ */
105
+ report(message: string, extra?: Partial<IngestRequest>): Promise<IngestResponse>;
106
+ private submit;
107
+ }
108
+ export declare function init(options: FeedbackOptions): DaybookFeedback;
package/dist/index.js ADDED
@@ -0,0 +1,274 @@
1
+ import { BreadcrumbTrail } from './breadcrumbs.js';
2
+ import { IngestClient } from './client.js';
3
+ import { captureContext } from './context.js';
4
+ import { captureScreenshot } from './screenshot.js';
5
+ import { FeedbackWidget } from './widget.js';
6
+ export { captureAnchor, resolveAnchor } from './anchor.js';
7
+ /**
8
+ * In-app feedback for the web.
9
+ *
10
+ * import { init } from '@daybook/feedback'
11
+ *
12
+ * init({
13
+ * apiUrl: 'https://pm-api.hreben.us',
14
+ * ingestKey: 'pmi_…',
15
+ * app: { version: '1.4.0', environment: 'production' },
16
+ * })
17
+ *
18
+ * The reporter clicks the thing that is wrong and says what happened. Everything else — which page,
19
+ * which element, which browser, what errored just before — is captured without asking them, because
20
+ * the alternative is a reply thread asking questions the reporter has already forgotten the answer to.
21
+ */
22
+ export class DaybookFeedback {
23
+ constructor(options) {
24
+ this.options = options;
25
+ this.widget = null;
26
+ this.started = false;
27
+ /**
28
+ * Asks who may report from here and what the widget should look like.
29
+ *
30
+ * Never allowed to break the host page. A failed handshake — an unverified domain, a revoked key,
31
+ * a network that is down — takes the widget away and logs one line; the alternative is an
32
+ * exception in somebody else's application, thrown by a feedback button.
33
+ */
34
+ /**
35
+ * At most one handshake in flight per identity.
36
+ *
37
+ * Our own app fires three at once on first paint — init() calls start(), and two watchers with
38
+ * `immediate: true` call identify() and start() again — and a customer's app is free to do the
39
+ * same. All three then find no reporter row, all three insert one, and two lose on the unique
40
+ * index. Nobody saw an error, because the server recovers by re-reading; what it cost was an
41
+ * error-level stack trace in the production log per losing request, forever, which is how a real
42
+ * error becomes invisible.
43
+ *
44
+ * Keyed on the identity rather than a bare flag: a handshake already running for the previous
45
+ * reporter must not be handed back to identify() as though it answered for the new one.
46
+ */
47
+ this.inFlight = null;
48
+ /** Bumped when a sign-in changes who we are, which the options object does not show. */
49
+ this.epoch = 0;
50
+ /** The last handshake, for a host app that wants to explain a state in its own words. */
51
+ this.ready = null;
52
+ if (!options.apiUrl)
53
+ throw new Error('apiUrl is required');
54
+ if (!options.ingestKey)
55
+ throw new Error('ingestKey is required');
56
+ this.client = new IngestClient(options.apiUrl, options.ingestKey);
57
+ this.trail = options.breadcrumbs === false
58
+ ? null
59
+ : new BreadcrumbTrail(40, options.redact !== false);
60
+ }
61
+ /**
62
+ * Idempotent, because a host app has every reason to call it again.
63
+ *
64
+ * init() starts the widget, and an app that shows it only to signed-in people then calls start()
65
+ * on sign-in — which used to construct and mount a SECOND widget over the first, leaving two
66
+ * launchers and a stale one holding the events. Calling start() twice should mean the widget is
67
+ * running, not that there are two of them.
68
+ */
69
+ start() {
70
+ this.trail?.start();
71
+ this.mount();
72
+ // Once per session, not once per call. start() is called again by hosts that gate the widget on
73
+ // a session, and flushing twice sends the queue twice.
74
+ if (!this.started) {
75
+ this.started = true;
76
+ // Anything left from a previous visit goes now. A report written offline yesterday should
77
+ // arrive without the reporter having to do it again.
78
+ void this.client.flush();
79
+ }
80
+ void this.handshake();
81
+ return this;
82
+ }
83
+ /**
84
+ * Puts the widget on the page if it is not already there.
85
+ *
86
+ * Idempotent, and called from the handshake as well as from start(). A handshake that fails takes
87
+ * the widget away — which is right for a blocked reporter and for a domain that is not allowed —
88
+ * but under the Daybook sign-in mode the FIRST handshake is *supposed* to fail, and signing in
89
+ * afterwards has to bring it back. Without this, signIn() succeeded and left the page with no
90
+ * widget on it, which is the one flow that mode exists for.
91
+ */
92
+ mount() {
93
+ if (this.widget)
94
+ return;
95
+ this.widget = new FeedbackWidget(this.options, input => this.submit(input));
96
+ this.widget.setReporter(this.options.reporter);
97
+ this.widget.mount();
98
+ }
99
+ handshake() {
100
+ const key = JSON.stringify([this.options.reporter ?? null, this.options.signature ?? null, this.epoch]);
101
+ if (this.inFlight?.key === key)
102
+ return this.inFlight.promise;
103
+ const promise = this.runHandshake().finally(() => {
104
+ if (this.inFlight?.promise === promise)
105
+ this.inFlight = null;
106
+ });
107
+ this.inFlight = { key, promise };
108
+ return promise;
109
+ }
110
+ async runHandshake() {
111
+ try {
112
+ const result = await this.client.handshake({
113
+ identity: this.options.reporter,
114
+ signature: this.options.signature,
115
+ locale: typeof navigator !== 'undefined' ? navigator.language : undefined,
116
+ });
117
+ this.ready = result;
118
+ this.options.onReady?.(result);
119
+ // Blocked means gone, and indistinguishable from an integration that has no widget at all.
120
+ // Pending means visibly waiting, because somebody who was told their company uses this should
121
+ // not be left thinking it is broken.
122
+ if (result.reporterStatus === 'Blocked') {
123
+ this.widget?.unmount();
124
+ this.widget = null;
125
+ return;
126
+ }
127
+ this.mount();
128
+ this.widget.setTheme(parseTheme(result.theme));
129
+ this.widget.setState(result.reporterStatus === 'Pending' ? 'pending' : 'ready');
130
+ }
131
+ catch (error) {
132
+ // Told to the host as well as the console. In the Daybook sign-in mode the widget is *meant*
133
+ // to be absent until somebody signs in, and the host needs to know that to render its own
134
+ // button — without this it sees an empty page and no reason for it.
135
+ this.options.onError?.(error);
136
+ console.warn('[feedback] handshake failed; the widget will not appear', error);
137
+ this.widget?.unmount();
138
+ this.widget = null;
139
+ }
140
+ }
141
+ /**
142
+ * Says who is reporting, once the host app knows.
143
+ *
144
+ * A single-page app mounts the widget at boot and learns who is signed in a moment later, so a
145
+ * reporter passed to init() is either absent or stale. Without this, every report from a signed-in
146
+ * user arrived as Anonymous and triage had no address to reply to — which is the most useful field
147
+ * on a bug report after the words themselves.
148
+ *
149
+ * Merges rather than replaces, so supplying only a name does not wipe an email the reporter typed
150
+ * into the composer. Passing null clears it, which is what signing out should do.
151
+ */
152
+ identify(reporter) {
153
+ this.options = {
154
+ ...this.options,
155
+ reporter: reporter ? { ...this.options.reporter, ...reporter } : undefined,
156
+ };
157
+ // Pushed down, not merely stored. The widget was constructed with the options object as it was
158
+ // at mount, so without this it keeps whoever was signed in then — which in a single-page app is
159
+ // nobody, and is why the composer went on asking for an address the host already knew.
160
+ this.widget?.setReporter(this.options.reporter);
161
+ // And re-handshake, because who is reporting is the question the handshake answers. Without
162
+ // this, signing in gets the widget the anonymous verdict it was given at boot — so an approval
163
+ // granted to that person is never seen, and a block never takes effect until a reload.
164
+ if (this.widget)
165
+ void this.handshake();
166
+ }
167
+ /**
168
+ * Signs the reporter in with a Daybook account and re-handshakes.
169
+ *
170
+ * Only meaningful when the integration is set to that mode. Call it from a button in your own UI —
171
+ * it opens a popup, so it has to be triggered by a click or the browser will block it.
172
+ */
173
+ async signIn() {
174
+ await this.client.signIn();
175
+ // The identity changed in a way the options object cannot show, so the dedupe key has to move
176
+ // or a handshake still in flight for the signed-out state would answer for this one.
177
+ this.epoch++;
178
+ await this.handshake();
179
+ }
180
+ /**
181
+ * The signature for the current reporter, from the host's backend.
182
+ *
183
+ * Separate from identify() because the two arrive at different times: an app knows who signed in
184
+ * immediately and has to ask its own server for the signature.
185
+ */
186
+ authenticate(signature) {
187
+ this.options = { ...this.options, signature: signature ?? undefined };
188
+ if (this.widget)
189
+ void this.handshake();
190
+ }
191
+ stop() {
192
+ this.started = false;
193
+ this.trail?.stop();
194
+ this.widget?.unmount();
195
+ this.widget = null;
196
+ }
197
+ /** Opens the picker programmatically, for a host app's own "Report a problem" menu item. */
198
+ open() {
199
+ this.widget?.open();
200
+ }
201
+ /**
202
+ * Files a report without any UI, for a host app that has its own form or wants to report a caught
203
+ * error. Screenshots are not taken here: there is no user present to consent to a screen share.
204
+ */
205
+ async report(message, extra = {}) {
206
+ return this.client.send({
207
+ message,
208
+ surface: this.options.surface,
209
+ ...extra,
210
+ context: {
211
+ ...captureContext({ breadcrumbs: this.trail?.list(), app: this.options.app }),
212
+ ...(extra.context ?? {}),
213
+ },
214
+ reporter: extra.reporter ?? this.options.reporter,
215
+ });
216
+ }
217
+ async submit(input) {
218
+ const screenshot = input.withScreenshot && this.options.screenshots !== false
219
+ ? await captureScreenshot(this.options.redact !== false)
220
+ : null;
221
+ // Attached files first, so a reporter's own screenshot leads the list — they chose it, and it is
222
+ // usually more pointed than a whole-viewport capture.
223
+ const uploads = [...input.files, ...(screenshot ? [screenshot] : [])];
224
+ const request = {
225
+ message: input.message,
226
+ kind: input.kind,
227
+ app: this.options.app,
228
+ surface: this.options.surface,
229
+ reporter: input.email
230
+ ? { ...this.options.reporter, email: input.email }
231
+ : this.options.reporter,
232
+ context: captureContext({
233
+ anchor: input.anchor,
234
+ breadcrumbs: this.trail?.list(),
235
+ app: this.options.app,
236
+ }),
237
+ };
238
+ try {
239
+ const response = await this.client.send(request, uploads);
240
+ this.options.onSent?.(response);
241
+ // Handed back so the widget can quote it in the confirmation. The reference is the whole
242
+ // point of being able to say "F-0007" to support later.
243
+ return response.reference;
244
+ }
245
+ catch (error) {
246
+ // Queued before rethrowing, so the words survive a failed send and the widget can say so
247
+ // rather than pretending it worked.
248
+ this.client.queue(request);
249
+ this.options.onError?.(error);
250
+ throw error;
251
+ }
252
+ }
253
+ }
254
+ export function init(options) {
255
+ return new DaybookFeedback(options).start();
256
+ }
257
+ /**
258
+ * The theme, as an object, or null.
259
+ *
260
+ * Served as a JSON string because that is what it is in the database — a jsonb column, so a token
261
+ * added later needs no server change. Anything unparseable is no theme rather than an exception:
262
+ * a malformed setting should cost the customer their accent colour, not their feedback widget.
263
+ */
264
+ function parseTheme(theme) {
265
+ if (!theme)
266
+ return null;
267
+ try {
268
+ const parsed = JSON.parse(theme);
269
+ return parsed && typeof parsed === 'object' ? parsed : null;
270
+ }
271
+ catch {
272
+ return null;
273
+ }
274
+ }
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Redaction, applied before anything leaves the device.
3
+ *
4
+ * This exists because of what automatic capture implies. The predecessor's widget captured nothing on
5
+ * its own — a reviewer typed a comment and optionally attached a file they had chosen — so it never
6
+ * had this problem. The moment breadcrumbs, console lines and screenshots are collected without
7
+ * anyone reading them first, the report can carry someone else's message, an account number, or a
8
+ * half-written email. The server cannot undo a leak that has already crossed the wire, so this runs
9
+ * on the client and is on by default.
10
+ */
11
+ /** Query strings routinely carry tokens and search terms. Neither belongs in a breadcrumb. */
12
+ export declare function redactUrl(url: string): string;
13
+ /**
14
+ * Describes a value without reproducing it. Length is kept because "empty" versus "they typed
15
+ * something" is often the whole bug.
16
+ */
17
+ export declare function redactValue(value: string, key?: string): string;
18
+ /**
19
+ * A label for an element that never includes what the user typed. An input's value is exactly the
20
+ * kind of thing a click breadcrumb must not carry.
21
+ */
22
+ export declare function describeElement(element: Element): string;
23
+ /**
24
+ * Console and error text can contain interpolated user data. Long numeric runs, anything that looks
25
+ * like an email, and bearer tokens are the three that show up in practice.
26
+ */
27
+ export declare function redactText(text: string): string;
28
+ /** Selector for elements the host app has marked as never-capture. */
29
+ export declare const PRIVATE_ATTRIBUTE = "data-daybook-private";
package/dist/redact.js ADDED
@@ -0,0 +1,76 @@
1
+ /**
2
+ * Redaction, applied before anything leaves the device.
3
+ *
4
+ * This exists because of what automatic capture implies. The predecessor's widget captured nothing on
5
+ * its own — a reviewer typed a comment and optionally attached a file they had chosen — so it never
6
+ * had this problem. The moment breadcrumbs, console lines and screenshots are collected without
7
+ * anyone reading them first, the report can carry someone else's message, an account number, or a
8
+ * half-written email. The server cannot undo a leak that has already crossed the wire, so this runs
9
+ * on the client and is on by default.
10
+ */
11
+ /** Query strings routinely carry tokens and search terms. Neither belongs in a breadcrumb. */
12
+ export function redactUrl(url) {
13
+ try {
14
+ const parsed = new URL(url, location.href);
15
+ return parsed.origin === location.origin
16
+ ? parsed.pathname
17
+ : `${parsed.origin}${parsed.pathname}`;
18
+ }
19
+ catch {
20
+ // Not a URL. Cut at the first ? so a malformed one cannot smuggle a query through.
21
+ return url.split('?')[0] ?? url;
22
+ }
23
+ }
24
+ const SENSITIVE_KEY = /pass|secret|token|auth|cvv|card|ssn|pin|otp|key/i;
25
+ /**
26
+ * Describes a value without reproducing it. Length is kept because "empty" versus "they typed
27
+ * something" is often the whole bug.
28
+ */
29
+ export function redactValue(value, key) {
30
+ if (value.length === 0)
31
+ return '';
32
+ if (key && SENSITIVE_KEY.test(key))
33
+ return '[redacted]';
34
+ return `[${value.length} chars]`;
35
+ }
36
+ /**
37
+ * A label for an element that never includes what the user typed. An input's value is exactly the
38
+ * kind of thing a click breadcrumb must not carry.
39
+ */
40
+ export function describeElement(element) {
41
+ const tag = element.tagName.toLowerCase();
42
+ // A bare "div" tells a triager nothing. Walk up to the nearest thing with an identity, which is
43
+ // usually the button or link the person meant to press.
44
+ if (!element.getAttribute('aria-label')
45
+ && !element.getAttribute('data-testid')
46
+ && !(element.textContent ?? '').trim()) {
47
+ const meaningful = element.closest('button, a, [role=button], [data-testid], label');
48
+ if (meaningful && meaningful !== element)
49
+ return describeElement(meaningful);
50
+ }
51
+ if (element instanceof HTMLInputElement
52
+ || element instanceof HTMLTextAreaElement
53
+ || element instanceof HTMLSelectElement) {
54
+ const name = element.getAttribute('name') ?? element.id ?? '';
55
+ const type = element instanceof HTMLInputElement ? element.type : tag;
56
+ return `${tag}[${type}]${name ? ` name=${name}` : ''}`;
57
+ }
58
+ const label = element.getAttribute('aria-label')
59
+ ?? element.getAttribute('data-testid')
60
+ ?? (element.textContent ?? '').replace(/\s+/g, ' ').trim().slice(0, 40);
61
+ return label ? `${tag} "${label}"` : tag;
62
+ }
63
+ /**
64
+ * Console and error text can contain interpolated user data. Long numeric runs, anything that looks
65
+ * like an email, and bearer tokens are the three that show up in practice.
66
+ */
67
+ export function redactText(text) {
68
+ return text
69
+ .replace(/[\w.+-]+@[\w-]+\.[\w.]+/g, '[email]')
70
+ .replace(/\b[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\b/g, '[jwt]')
71
+ .replace(/\bBearer\s+[\w.-]+/gi, 'Bearer [redacted]')
72
+ .replace(/\b\d{12,19}\b/g, '[number]')
73
+ .slice(0, 500);
74
+ }
75
+ /** Selector for elements the host app has marked as never-capture. */
76
+ export const PRIVATE_ATTRIBUTE = 'data-daybook-private';
@@ -0,0 +1,17 @@
1
+ /**
2
+ * A picture of the viewport at the moment of capture.
3
+ *
4
+ * Deliberately not a DOM-to-canvas rasteriser. Those need to reimplement layout, get fonts, shadows
5
+ * and cross-origin images wrong, and ship a large dependency onto someone else's page. This uses the
6
+ * browser's own capture through getDisplayMedia when the host app asks for it, and otherwise records
7
+ * a structural snapshot — which is less pretty and always correct.
8
+ *
9
+ * Either way, elements marked data-daybook-private are hidden BEFORE the frame is taken. A screenshot is
10
+ * the single most likely thing in a report to carry information the reporter never meant to send.
11
+ */
12
+ export interface Screenshot {
13
+ blob: Blob;
14
+ filename: string;
15
+ contentType: string;
16
+ }
17
+ export declare function captureScreenshot(redact: boolean): Promise<Screenshot | null>;