@littlefriend/feedback 0.0.0-stage → 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 ZVN DEV
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,102 @@
1
- # Temporary Holding Version
1
+ # @littlefriend/feedback
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A small feedback button for Little Friend. A person who finds a page confusing can say so right there, and the note reaches your team with the page, the time and, in journey mode, a link to that visit's session replay.
4
+
5
+ `lf-feedback.js` is 5,117 bytes gzip (4,472 brotli), styles included. Pages without feedback load none of it.
6
+
7
+ ## Before you start
8
+
9
+ - Switch feedback on for the project in the dashboard (Settings, Feedback), or from the CLI. It is off by default, and the button shows nothing until it is on.
10
+ - In Settings you choose the button's words, where it sits, an optional question above the text box, the email addresses notes are sent to, and a webhook.
11
+
12
+ ## Install
13
+
14
+ ### Script tag
15
+
16
+ Add `data-feedback` to the `lf.js` tag. lf.js loads `lf-feedback.js` from next to itself:
17
+
18
+ ```html
19
+ <script defer src="https://cdn.littlefriend.io/lf.js" data-site="lf_your_site_key" data-feedback></script>
20
+ ```
21
+
22
+ Or load it on its own, with or without lf.js:
23
+
24
+ ```html
25
+ <script defer src="https://cdn.littlefriend.io/lf-feedback.js" data-site="lf_your_site_key"></script>
26
+ ```
27
+
28
+ It reads `data-site`, `data-api` (the collector origin, default `https://in.littlefriend.io`) and `data-routes` from its own tag, or from the lf.js tag that loaded it.
29
+
30
+ ### npm
31
+
32
+ ```sh
33
+ pnpm add @littlefriend/feedback
34
+ ```
35
+
36
+ ```ts
37
+ import { init } from '@littlefriend/tracker';
38
+ import { startFeedback } from '@littlefriend/feedback';
39
+
40
+ init({ site: 'lf_your_site_key', mode: 'journey' });
41
+ startFeedback({ site: 'lf_your_site_key' });
42
+ ```
43
+
44
+ `startFeedback` takes `site`, `api` and `routes` (the same route templates as the tracker's `routes` option). On the server every function is a no-op.
45
+
46
+ ## Your own button or form
47
+
48
+ Choose the placement "No button" in Settings, then open the dialog from your own control:
49
+
50
+ ```js
51
+ lf('feedback'); // script tag
52
+ openFeedback(); // npm
53
+ ```
54
+
55
+ To send from your own form, without the dialog:
56
+
57
+ ```js
58
+ lf('feedback', { text: 'The export button does nothing', category: 'bug' }, (result) => {
59
+ if (!result.ok) console.warn(result.error);
60
+ });
61
+ ```
62
+
63
+ ```ts
64
+ import { consentLine, sendFeedback } from '@littlefriend/feedback';
65
+
66
+ const result = await sendFeedback({ text, category: 'confusing' });
67
+ ```
68
+
69
+ `category` is optional: `confusing`, `bug`, `idea` or `other`. Text is cut at 2,000 characters. The result is `{ ok: true }` once the collector stored the note, or `{ ok: false, error }` with a short code: `feedback_off`, `empty`, `bad_category`, `rate_limited`, `quota_exceeded`, `network`, `not_started` or another refusal from the collector. Show your visitors the same consent line the dialog shows before they send; `consentLine({ site, days, visit })` returns it.
70
+
71
+ Calls work in any load order: before lf.js or this script loads (they wait in the stub queue), and alongside `lf-replay.js`.
72
+
73
+ ## What is sent
74
+
75
+ Only when the person presses Send (or Ctrl or Cmd with Enter in the text box), one `POST /v1/f` with:
76
+
77
+ - the note as typed (the collector removes card numbers),
78
+ - the category, if they picked one,
79
+ - the page's route, with the same rules as page views: no query, no fragment, ids and personal-looking segments replaced, route templates applied, and only the file name for a page opened from a file,
80
+ - the journey session id, only in journey mode, after consent, without Global Privacy Control, before opt-out and while the session is live (the same gates as `getSession()`),
81
+ - the widget's version.
82
+
83
+ No IP address, cookie, other page text, form value or storage leaves the page. Closing the dialog, pressing Escape, clicking outside or leaving the page sends nothing. Before anything is sent, the dialog says what goes with the note, that it goes to the team behind the site, and how long it is kept. Notes are kept for the project's feedback retention, 90 days by default.
84
+
85
+ A person who opted out, or whose browser sends Global Privacy Control, can still send a note on purpose. It carries no session id.
86
+
87
+ ## Accessibility
88
+
89
+ - The button is a real button, reachable with Tab. The dialog is a labelled modal dialog: focus moves into it, Tab stays inside it, and Escape closes it and returns focus to the control that opened it.
90
+ - The text box, the category group and the close button are labelled. The characters left are read with the text box. A live region announces when a note was sent or failed.
91
+ - Light and dark follow the visitor's system setting, motion follows reduced-motion preferences, and the dialog becomes a bottom sheet on narrow screens.
92
+ - Everything lives in a shadow root, so the site's styles never change the widget and the widget never changes the site. The widget is left out of session replay recordings.
93
+
94
+ ## Development
95
+
96
+ ```sh
97
+ pnpm --filter @littlefriend/feedback build # dist/lf-feedback.js and dist/index.js
98
+ pnpm --filter @littlefriend/feedback size # gzip budget: 5.5 KiB
99
+ pnpm --filter @littlefriend/feedback test
100
+ ```
101
+
102
+ MIT licensed.
@@ -0,0 +1,36 @@
1
+ /**
2
+ * The feedback add-on for one page: it asks the collector whether the project has feedback on,
3
+ * draws the button (unless placement is `manual`), opens the dialog, and sends a note when the
4
+ * person presses Send or the site calls `lf('feedback', { text })`.
5
+ *
6
+ * What it reads: the page's path, protocol and host name, the journey session id from the running
7
+ * tracker (`lf('session')`, with getSession()'s gates), and its own settings. Never page text, a
8
+ * form, a cookie or storage.
9
+ */
10
+ import { type FeedbackClientConfig } from '@littlefriend/contract';
11
+ import type { FeedbackOptions, FeedbackResult } from './types.js';
12
+ import { type Widget } from './widget.js';
13
+ type Lf = ((...a: unknown[]) => void) & {
14
+ v?: string;
15
+ q?: unknown;
16
+ };
17
+ export type Win = Window & typeof globalThis & {
18
+ lf?: Lf;
19
+ };
20
+ export interface Feedback {
21
+ /** The project's settings, or null when feedback is off or the collector could not be read. */
22
+ ready: Promise<FeedbackClientConfig | null>;
23
+ open(opener?: Element | null): Promise<void>;
24
+ send(note: unknown): Promise<FeedbackResult>;
25
+ stop(): void;
26
+ /** The widget once drawn, for tests. */
27
+ widget(): Widget | undefined;
28
+ }
29
+ /** Tries after the first send fails with a 5xx, a 429 or no answer. Each uses the same note id. */
30
+ export declare const RETRIES = 3;
31
+ /** The collector's answer, or null for off and anything malformed. */
32
+ export declare function readConfig(raw: unknown): FeedbackClientConfig | null;
33
+ export declare function createFeedback(w: Win, opts: FeedbackOptions): Feedback;
34
+ /** One add-on per page: a second start returns the first. */
35
+ export declare function start(w: Win, opts: FeedbackOptions): Feedback;
36
+ export {};
@@ -0,0 +1,25 @@
1
+ import type { FeedbackCategory, FeedbackNoteInput, FeedbackOptions, FeedbackResult } from './types.js';
2
+ export { VERSION } from './version.js';
3
+ export type { FeedbackCategory, FeedbackNoteInput, FeedbackOptions, FeedbackResult };
4
+ /**
5
+ * The consent line the widget shows before a send, for a site's own form: what is sent, who sees
6
+ * it and how long it is kept. `days` is the project's feedback retention; `visit` is true when
7
+ * the page has a live journey session, which goes along with the note.
8
+ */
9
+ export declare function consentLine(input: {
10
+ site: string;
11
+ days: number;
12
+ visit: boolean;
13
+ }): string;
14
+ /** Ask the collector for the project's feedback settings, and draw the button when it is on. Later calls are ignored until `stopFeedback()`. */
15
+ export declare function startFeedback(options: FeedbackOptions): void;
16
+ /** Open the dialog, for a site that draws its own feedback control (placement `manual`). */
17
+ export declare function openFeedback(): void;
18
+ /**
19
+ * Send a note from the site's own form, without the widget. Show the site's visitors the same
20
+ * consent line the widget shows before they send. Resolves `{ ok: true }` once the collector
21
+ * stored it, or `{ ok: false, error }`.
22
+ */
23
+ export declare function sendFeedback(note: FeedbackNoteInput): Promise<FeedbackResult>;
24
+ /** Remove the button and the dialog. */
25
+ export declare function stopFeedback(): void;
package/dist/index.js ADDED
@@ -0,0 +1,645 @@
1
+ // ../contract/dist/limits.js
2
+ var LIMITS = {
3
+ /** Max request body accepted by the collector, in bytes (before decompression). */
4
+ maxBodyBytes: 16 * 1024,
5
+ /** Max events in one batch. */
6
+ maxEventsPerBatch: 50,
7
+ /** Max custom properties on one event. */
8
+ maxProps: 8,
9
+ maxPropKeyLength: 32,
10
+ maxPropStringLength: 64,
11
+ maxEventNameLength: 64,
12
+ maxRouteLength: 256,
13
+ maxHostLength: 253,
14
+ maxCampaignValueLength: 64,
15
+ /** Events observed further in the past than this are rejected as stale. */
16
+ maxPastSkewMs: 24 * 60 * 60 * 1e3,
17
+ /** Events observed further in the future than this are rejected as clock skew. */
18
+ maxFutureSkewMs: 10 * 60 * 1e3,
19
+ /** Browser SDK flush triggers. */
20
+ browserFlushEvents: 10,
21
+ browserFlushMs: 5e3,
22
+ /** Browser SDK bounded pending queue, in bytes of serialized events. */
23
+ browserMaxPendingBytes: 64 * 1024,
24
+ /** Journey sessions: inactivity timeout and hard lifetime. */
25
+ sessionIdleMs: 30 * 60 * 1e3,
26
+ sessionMaxMs: 24 * 60 * 60 * 1e3
27
+ };
28
+ var RETENTION_DAYS = {
29
+ events: { min: 1, max: 365, default: 7 },
30
+ aggregates: { min: 30, max: 395, default: 395 },
31
+ feedback: { min: 1, max: 365, default: 90 }
32
+ };
33
+ var SESSION_ID_RE = /^[A-Za-z0-9_-]{16,32}$/;
34
+
35
+ // ../contract/dist/sanitize.js
36
+ var EMAIL_RE = new RegExp("[^\\s@/]{1,64}@[^\\s@/]{1,253}\\.\\p{L}{2,24}", "iu");
37
+ var LONG_DIGITS_RE = /\d[\d\s().-]{7,}\d/;
38
+ var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
39
+ var HEXISH_RE = /^[0-9a-f]{16,}$/i;
40
+ var HEX_LETTER_RE = /[a-f]/i;
41
+ var NUMERIC_RE = /^\d+$/;
42
+ var TOKENISH_RE = /^(?=.*\d)(?=.*[a-zA-Z])[A-Za-z0-9_-]{20,}$/;
43
+ var DOTTED_TOKEN_RE = /^(?:eyJ[A-Za-z0-9_-]{4,}(?:\.[A-Za-z0-9_-]*){1,4}|(?=.*\d)(?=.*[A-Z])[A-Za-z0-9_-]{16,}(?:\.[A-Za-z0-9_-]{16,}){2})$/;
44
+ var ROUTE_PARAM_RE = /^:[a-z_][a-z0-9_]{0,31}$/;
45
+ var CONTROL_RE = /[\u0000-\u001f\u007f]/g;
46
+ var LONE_SURROGATE_RE = new RegExp("[\\ud800-\\udbff](?![\\udc00-\\udfff])|(?<![\\ud800-\\udbff])[\\udc00-\\udfff]", "g");
47
+ var MAX_RAW_PATH = 2048;
48
+ var PII_SCAN_LIMIT = 2048;
49
+ function cleanText(value) {
50
+ return value.replace(CONTROL_RE, "").replace(LONE_SURROGATE_RE, "");
51
+ }
52
+ function looksLikePII(input) {
53
+ const value = input.length > PII_SCAN_LIMIT ? input.slice(0, PII_SCAN_LIMIT) : input;
54
+ if (value.includes("@") && EMAIL_RE.test(value))
55
+ return true;
56
+ if ((HEXISH_RE.test(value) || UUID_RE.test(value)) && HEX_LETTER_RE.test(value))
57
+ return false;
58
+ return LONG_DIGITS_RE.test(value);
59
+ }
60
+ var CONTACT_EMAIL_RE = new RegExp("(?<![\\p{L}\\p{N}._%+-])[\\p{L}\\p{N}._%+-]{1,64}@(?:[\\p{L}\\p{N}](?:[\\p{L}\\p{N}-]{0,61}[\\p{L}\\p{N}])?\\.){1,8}\\p{L}{2,24}(?![\\p{L}\\p{N}_%+-]|\\.[\\p{L}\\p{N}])", "gu");
61
+ var PHONES_RE = new RegExp("(?<![\\w+.-])(?:\\+\\d{1,3}(?:[ .-]?\\(?\\d{1,5}\\)?){1,6}|(?:1[ .-]?)?(?:\\(\\d{3}\\)[ .-]?|\\d{3}[ .-])\\d{3}[ .-]\\d{4}|0\\d{1,4}[ -]\\d{3,4}[ -]?\\d{3,4})(?![\\d]|[.-]\\d)", "g");
62
+ function sanitizeRoute(input) {
63
+ return cleanPath(input, false);
64
+ }
65
+ var PARAM_NAME_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
66
+ var isParamValue = (body) => NUMERIC_RE.test(body) || UUID_RE.test(body) || HEXISH_RE.test(body) || DOTTED_TOKEN_RE.test(body);
67
+ function cleanPath(input, strictParams, keep) {
68
+ if (typeof input !== "string" || input.length > MAX_RAW_PATH)
69
+ return null;
70
+ let path = input;
71
+ const cut = path.search(/[?#]/);
72
+ if (cut >= 0)
73
+ path = path.slice(0, cut);
74
+ if (!path.startsWith("/"))
75
+ path = `/${path}`;
76
+ let decoded = path;
77
+ try {
78
+ decoded = decodeURIComponent(path);
79
+ } catch {
80
+ }
81
+ decoded = cleanText(decoded);
82
+ const decodedCut = decoded.search(/[?#]/);
83
+ if (decodedCut >= 0)
84
+ decoded = decoded.slice(0, decodedCut);
85
+ const raw = decoded.split("/");
86
+ const segments = raw.map((seg) => {
87
+ if (seg.includes("="))
88
+ return ":redacted";
89
+ if (seg === "")
90
+ return seg;
91
+ if (seg.startsWith(":") && !strictParams) {
92
+ const body2 = seg.slice(1);
93
+ if (PARAM_NAME_RE.test(body2))
94
+ return seg;
95
+ if (isParamValue(body2))
96
+ return ":id";
97
+ return looksLikePII(body2) ? ":redacted" : seg;
98
+ }
99
+ if (ROUTE_PARAM_RE.test(seg))
100
+ return seg;
101
+ const body = seg.startsWith(":") ? seg.slice(1) : seg;
102
+ if (NUMERIC_RE.test(body) || UUID_RE.test(body) || HEXISH_RE.test(body) || TOKENISH_RE.test(body) || DOTTED_TOKEN_RE.test(body))
103
+ return ":id";
104
+ if (looksLikePII(body))
105
+ return ":redacted";
106
+ return seg;
107
+ });
108
+ keep?.(raw, segments);
109
+ let out = segments.join("/");
110
+ if (out.length > 1 && out.endsWith("/"))
111
+ out = out.slice(0, -1);
112
+ if (out.length > LIMITS.maxRouteLength)
113
+ return null;
114
+ return out;
115
+ }
116
+
117
+ // ../contract/dist/feedback.js
118
+ var FEEDBACK_CATEGORIES = ["confusing", "bug", "idea", "other"];
119
+ function isFeedbackCategory(value) {
120
+ return typeof value === "string" && FEEDBACK_CATEGORIES.includes(value);
121
+ }
122
+ var FEEDBACK_CATEGORY_LABELS = {
123
+ confusing: "Confusing",
124
+ bug: "Something broke",
125
+ idea: "Idea",
126
+ other: "Other"
127
+ };
128
+ var FEEDBACK_PLACEMENTS = ["bottom_right", "bottom_left", "right_edge", "manual"];
129
+ function isFeedbackPlacement(value) {
130
+ return typeof value === "string" && FEEDBACK_PLACEMENTS.includes(value);
131
+ }
132
+ var FEEDBACK_LIMITS = {
133
+ /** Characters of note text, after trimming. The widget stops typing here; the collector refuses more. */
134
+ maxTextChars: 2e3,
135
+ /** One POST body. 2,000 characters of four-byte text plus the envelope fit. */
136
+ maxBodyBytes: 12 * 1024,
137
+ /** The button label. */
138
+ maxLabelChars: 24,
139
+ /** The optional question above the text box. */
140
+ maxPromptChars: 140,
141
+ /** Addresses each new note is emailed to: verified members of the project's workspace only. */
142
+ maxEmails: 5,
143
+ /**
144
+ * Feedback emails one address receives per hour, across every project. Notes past it wait and
145
+ * go out together, in one digest email, once the hour allows another.
146
+ */
147
+ emailsPerRecipientHour: 10,
148
+ /** Notes in one digest email. More wait for the next one. */
149
+ digestMaxNotes: 50,
150
+ maxEmailLength: 254,
151
+ maxWebhookUrlLength: 2048,
152
+ /** Notes one project may store per UTC day. Past it the collector answers 429. */
153
+ projectDailyNotes: 1e3,
154
+ /** Per client address: a note every 10 seconds on average, 5 at once. */
155
+ clientPerSecond: 0.1,
156
+ clientBurst: 5,
157
+ /** Per project: 2 notes a second, 30 at once. */
158
+ projectPerSecond: 2,
159
+ projectBurst: 30,
160
+ /** Forwarding: tries per email or webhook delivery, then it is marked failed. */
161
+ deliveryAttempts: 6,
162
+ /** Wait before the second try; each later try waits four times longer, up to deliveryMaxBackoffMs. */
163
+ deliveryBackoffMs: 3e4,
164
+ deliveryMaxBackoffMs: 2 * 60 * 60 * 1e3,
165
+ /** One webhook request, from connect to the response status. */
166
+ webhookTimeoutMs: 1e4,
167
+ /** Resolving a webhook's host: each try, and how many tries. */
168
+ webhookDnsTimeoutMs: 2e3,
169
+ webhookDnsTries: 2,
170
+ /** Webhook requests one API process makes at once. */
171
+ webhookConcurrency: 4
172
+ };
173
+ var DEFAULT_FEEDBACK_LABEL = "Feedback";
174
+ var CARD_CANDIDATE_RE = new RegExp("(?<![\\d-])\\d(?:[ -]?\\d){12,18}(?![\\d])", "g");
175
+ function feedbackConsentLine(input) {
176
+ const what = input.visit ? "Your note, this page's address, the time, your device type and a link to this visit" : "Your note, this page's address, the time and your device type";
177
+ const site = input.site.replace(/^www\./, "") || "this site";
178
+ const days = input.days === 1 ? "1 day" : `${input.days} days`;
179
+ return `${what} go to the team behind ${site} when you press Send, and are kept for ${days}. Please leave out passwords and card numbers.`;
180
+ }
181
+
182
+ // src/queue.ts
183
+ function attachQueue(f, name, handle) {
184
+ let q = f.q;
185
+ if (!q || typeof q.push !== "function") {
186
+ q = [];
187
+ f.q = q;
188
+ }
189
+ const run = (a) => {
190
+ try {
191
+ handle(a);
192
+ } catch (e) {
193
+ setTimeout(() => {
194
+ throw e;
195
+ });
196
+ }
197
+ };
198
+ if (Array.isArray(q))
199
+ for (let i = 0; i < q.length; ) {
200
+ const a = q[i];
201
+ if (a?.[0] === name) run(q.splice(i, 1)[0]);
202
+ else i++;
203
+ }
204
+ const queue = q;
205
+ const prev = queue.push;
206
+ queue.push = (a) => a?.[0] === name ? run(a) : prev.call(queue, a);
207
+ return queue;
208
+ }
209
+
210
+ // src/route.ts
211
+ function compileRoutes(templates) {
212
+ if (!Array.isArray(templates)) return [];
213
+ return templates.filter((t) => typeof t === "string" && t.startsWith("/")).map((t) => [
214
+ t,
215
+ RegExp(
216
+ `^${t.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/:\w+/g, "[^/]+").replace(/\*/g, ".*")}/?$`
217
+ )
218
+ ]);
219
+ }
220
+ function routeOf(loc, templates) {
221
+ const p = loc.pathname;
222
+ const path = loc.protocol === "file:" ? p.slice(p.lastIndexOf("/")) : p;
223
+ for (const [t, re] of templates) if (re.test(path)) return sanitizeRoute(t) ?? "/";
224
+ return sanitizeRoute(path) ?? "/";
225
+ }
226
+
227
+ // src/version.ts
228
+ var VERSION = "0.1.0";
229
+
230
+ // src/styles.ts
231
+ var CSS = `:host{all:initial}
232
+ *{box-sizing:border-box;font:14px/1.45 system-ui,sans-serif;color:inherit}
233
+ .w{--b:#fff;--f:#1d1d22;--m:#55555f;--l:#cfcfd8;--a:#3346c4;--o:#fff;--e:#b42318;color:var(--f)}
234
+ @media (prefers-color-scheme:dark){.w{--b:#1d1d23;--f:#f2f2f5;--m:#b0b0bc;--l:#45454f;--a:#9aa5ff;--o:#11131f;--e:#ff9b91}}
235
+ button{border:1px solid var(--l);border-radius:8px;background:none;cursor:pointer;padding:8px 16px}
236
+ .f{position:fixed;z-index:2147483000;right:16px;bottom:16px;border-radius:99px;background:var(--b);box-shadow:0 2px 10px #0003}
237
+ .f.l{right:auto;left:16px}
238
+ .f.e{right:0;bottom:auto;top:50%;transform:translateY(-50%) rotate(180deg);writing-mode:vertical-rl;padding:14px 8px}
239
+ :focus-visible{outline:3px solid var(--a);outline-offset:2px}
240
+ .b{position:fixed;inset:0;z-index:2147483001;display:flex;align-items:flex-end;justify-content:flex-end;padding:16px;background:#0004}
241
+ .b.l{justify-content:flex-start}
242
+ [hidden]{display:none!important}
243
+ .d{position:relative;width:min(380px,100%);max-height:calc(100vh - 32px);overflow:auto;padding:20px;border:1px solid var(--l);border-radius:12px;background:var(--b);box-shadow:0 12px 40px #0005}
244
+ @media (max-width:480px){.b{padding:0;justify-content:center}.d{width:100%;border-radius:12px 12px 0 0}}
245
+ h2{margin:0 36px 12px 0;font-size:17px;font-weight:600}
246
+ label,legend{display:block;margin:0 0 6px;font-weight:500}
247
+ textarea{display:block;width:100%;min-height:112px;resize:vertical;padding:8px 10px;border:1px solid var(--l);border-radius:8px;background:none}
248
+ .n,.c{margin:4px 0 12px;color:var(--m);font-size:12.5px}
249
+ fieldset{margin:0;padding:0;border:0}
250
+ .r label{display:inline-flex;gap:4px;align-items:center;margin:0 12px 6px 0;font-weight:400}
251
+ input{margin:0;accent-color:var(--a)}
252
+ .a{display:flex;justify-content:flex-end;gap:8px}
253
+ .s{border-color:var(--a);background:var(--a);color:var(--o);font-weight:600}
254
+ .s:disabled{opacity:.6}
255
+ .x{position:absolute;top:10px;right:10px;width:34px;height:34px;padding:0;border:0;font-size:22px;line-height:1}
256
+ .t{min-height:1.45em;margin:10px 0 0}
257
+ .t.e{color:var(--e)}
258
+ @media (prefers-reduced-motion:no-preference){.d{animation:i .16s ease-out}@keyframes i{from{opacity:0;transform:translateY(8px)}}}`;
259
+
260
+ // src/widget.ts
261
+ var DEFAULT_PROMPT = "What could be better on this page?";
262
+ var SENT_MESSAGE = "Thanks. Your note was sent.";
263
+ var CHANGED_MESSAGE = "The line above changed. Read it, then press Send again.";
264
+ function errorMessage(code) {
265
+ if (code === "empty") return "Write a note first.";
266
+ if (code === "rate_limited" || code === "quota_exceeded")
267
+ return "Too many notes right now. Please try again in a minute.";
268
+ if (code === "network") return "Your note was not sent. Check your connection and try again.";
269
+ if (code === "feedback_off") return "Feedback is turned off for this site.";
270
+ return "Your note was not sent. Please try again.";
271
+ }
272
+ var MARKUP = `<div class="w"><button type="button" class="f" aria-haspopup="dialog"></button><div class="b" hidden><div class="d" role="dialog" aria-modal="true" aria-labelledby="h" aria-describedby="c"><button type="button" class="x" aria-label="Close">\xD7</button><h2 id="h">Send feedback</h2><form novalidate><label for="m"></label><textarea id="m" aria-describedby="n"></textarea><p class="n" id="n"></p><fieldset><legend>Kind of note (optional)</legend><div class="r"></div></fieldset><p class="c" id="c"></p><div class="a"><button type="button" class="k">Cancel</button><button type="submit" class="s">Send</button></div></form><p class="t" role="status" aria-live="polite"></p></div></div></div>`;
273
+ function createWidget(deps) {
274
+ const { w, config } = deps;
275
+ const d = w.document;
276
+ const host = d.createElement("div");
277
+ host.setAttribute("data-lf-block", "");
278
+ host.setAttribute("data-lf-feedback", "");
279
+ const root = host.attachShadow({ mode: "open" });
280
+ root.innerHTML = `<style>${CSS}</style>${MARKUP}`;
281
+ const $ = (sel) => root.querySelector(sel);
282
+ const fab = $(".f");
283
+ const back = $(".b");
284
+ const dialog = $(".d");
285
+ const form = $("form");
286
+ const text = $("textarea");
287
+ const count = $(".n");
288
+ const consent = $(".c");
289
+ const status = $(".t");
290
+ const send = $(".s");
291
+ const closeButton = $(".x");
292
+ fab.textContent = config.label;
293
+ if (config.placement === "manual") fab.remove();
294
+ else if (config.placement === "bottom_left") {
295
+ fab.classList.add("l");
296
+ back.classList.add("l");
297
+ } else if (config.placement === "right_edge") fab.classList.add("e");
298
+ $("label").textContent = config.prompt || DEFAULT_PROMPT;
299
+ text.maxLength = FEEDBACK_LIMITS.maxTextChars;
300
+ const radios = $(".r");
301
+ for (const c of FEEDBACK_CATEGORIES) {
302
+ const label = d.createElement("label");
303
+ const input = d.createElement("input");
304
+ input.type = "radio";
305
+ input.name = "k";
306
+ input.value = c;
307
+ label.append(input, FEEDBACK_CATEGORY_LABELS[c]);
308
+ radios.append(label);
309
+ }
310
+ let opener = null;
311
+ let busy = false;
312
+ const counter = () => {
313
+ const left = FEEDBACK_LIMITS.maxTextChars - text.value.length;
314
+ count.textContent = `${left.toLocaleString("en-US")} ${left === 1 ? "character" : "characters"} left`;
315
+ };
316
+ text.addEventListener("input", counter);
317
+ const say = (message, error = false) => {
318
+ status.textContent = message;
319
+ status.classList.toggle("e", error);
320
+ };
321
+ const focusables = () => [...dialog.querySelectorAll("button,textarea,input")].filter(
322
+ (el) => !el.disabled && !el.closest("[hidden]") && (el.tagName !== "INPUT" || el.checked || !radios.querySelector(":checked"))
323
+ );
324
+ const close = () => {
325
+ if (back.hidden) return;
326
+ back.hidden = true;
327
+ const to = opener && opener.isConnected ? opener : fab.isConnected ? fab : null;
328
+ opener = null;
329
+ to?.focus?.();
330
+ };
331
+ const open = (from) => {
332
+ if (!host.isConnected) (d.body || d.documentElement).append(host);
333
+ opener = from ?? null;
334
+ if (form.hidden) {
335
+ form.hidden = false;
336
+ form.reset();
337
+ say("");
338
+ }
339
+ consent.textContent = deps.consent();
340
+ counter();
341
+ back.hidden = false;
342
+ text.focus();
343
+ };
344
+ const submit = async () => {
345
+ if (busy) return;
346
+ if (!text.value.trim()) {
347
+ say(errorMessage("empty"), true);
348
+ text.focus();
349
+ return;
350
+ }
351
+ const now = deps.consent();
352
+ if (now !== consent.textContent) {
353
+ consent.textContent = now;
354
+ say(CHANGED_MESSAGE, true);
355
+ return;
356
+ }
357
+ busy = true;
358
+ send.disabled = true;
359
+ say("Sending");
360
+ const picked = radios.querySelector(":checked")?.value;
361
+ const result = await deps.submit({ text: text.value, ...picked ? { category: picked } : {} });
362
+ busy = false;
363
+ send.disabled = false;
364
+ if (result.ok) {
365
+ form.hidden = true;
366
+ say(SENT_MESSAGE);
367
+ closeButton.focus();
368
+ } else say(errorMessage(result.error), true);
369
+ };
370
+ fab.addEventListener("click", () => open(fab));
371
+ closeButton.addEventListener("click", close);
372
+ $(".k").addEventListener("click", close);
373
+ back.addEventListener("click", (e) => {
374
+ if (e.target === back) close();
375
+ });
376
+ form.addEventListener("submit", (e) => {
377
+ e.preventDefault();
378
+ void submit();
379
+ });
380
+ text.addEventListener("keydown", (e) => {
381
+ if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) {
382
+ e.preventDefault();
383
+ void submit();
384
+ }
385
+ });
386
+ dialog.addEventListener("keydown", (e) => {
387
+ if (e.key === "Escape") {
388
+ e.preventDefault();
389
+ close();
390
+ } else if (e.key === "Tab") {
391
+ const all = focusables();
392
+ const first = all[0];
393
+ const last = all[all.length - 1];
394
+ const active = root.activeElement;
395
+ if (!first || !last) return;
396
+ if (e.shiftKey ? active === first || !active : active === last || !active) {
397
+ e.preventDefault();
398
+ (e.shiftKey ? last : first).focus();
399
+ }
400
+ }
401
+ });
402
+ if (config.placement !== "manual") (d.body || d.documentElement).append(host);
403
+ return {
404
+ open,
405
+ close,
406
+ destroy: () => {
407
+ back.hidden = true;
408
+ host.remove();
409
+ },
410
+ root
411
+ };
412
+ }
413
+
414
+ // src/feedback.ts
415
+ var RETRIES = 3;
416
+ var MAX_WAIT_MS = 1e4;
417
+ var ATTACH_MS = 1e3;
418
+ var ATTACH_MAX_MS = 3e4;
419
+ function readConfig(raw) {
420
+ const c = raw;
421
+ if (c?.on !== true) return null;
422
+ const label = typeof c.label === "string" ? c.label.trim().slice(0, FEEDBACK_LIMITS.maxLabelChars) : "";
423
+ const prompt = typeof c.prompt === "string" ? c.prompt.trim().slice(0, FEEDBACK_LIMITS.maxPromptChars) : "";
424
+ const days = c.days;
425
+ return {
426
+ v: 1,
427
+ on: true,
428
+ label: label || DEFAULT_FEEDBACK_LABEL,
429
+ placement: isFeedbackPlacement(c.placement) ? c.placement : "bottom_right",
430
+ prompt: prompt || null,
431
+ days: typeof days === "number" && Number.isInteger(days) && days >= 1 ? days : RETENTION_DAYS.feedback.default
432
+ };
433
+ }
434
+ var rid = () => [...crypto.getRandomValues(new Uint8Array(20))].map((b) => (b & 31).toString(32)).join("");
435
+ function createFeedback(w, opts) {
436
+ const d = w.document;
437
+ const api = (opts.api || "https://in.littlefriend.io").replace(/\/+$/, "");
438
+ const templates = compileRoutes(opts.routes);
439
+ let stopped = false;
440
+ let widget;
441
+ let timer;
442
+ const ready = new Promise(
443
+ (shown) => d.prerendering ? d.addEventListener("prerenderingchange", () => shown(), { once: true }) : shown()
444
+ ).then(() => w.fetch(`${api}/v1/f/config?k=${encodeURIComponent(opts.site)}`, { credentials: "omit" })).then((r) => r.ok ? r.json() : null).then(readConfig, () => null);
445
+ const session = () => {
446
+ let id = null;
447
+ const f = w.lf;
448
+ if (f?.v)
449
+ try {
450
+ f("session", (s) => {
451
+ id = typeof s === "string" && SESSION_ID_RE.test(s) ? s : null;
452
+ });
453
+ } catch {
454
+ }
455
+ return id;
456
+ };
457
+ const post = async (wire) => {
458
+ for (let attempt = 0; ; attempt++) {
459
+ if (wire.s && session() !== wire.s) {
460
+ delete wire.s;
461
+ wire.m = "a";
462
+ }
463
+ const body = JSON.stringify(wire);
464
+ let status = 0;
465
+ let error = "network";
466
+ let wait2 = 1e3 * 2 ** attempt;
467
+ try {
468
+ const r = await w.fetch(`${api}/v1/f`, {
469
+ method: "POST",
470
+ body,
471
+ credentials: "omit",
472
+ keepalive: true
473
+ });
474
+ status = r.status;
475
+ if (status >= 200 && status < 300) return { ok: true };
476
+ const after = Number(r.headers.get("retry-after"));
477
+ if (after > 0) wait2 = after * 1e3;
478
+ try {
479
+ const j = await r.json();
480
+ error = typeof j?.error === "string" && /^[a-z_]{1,40}$/.test(j.error) ? j.error : "refused";
481
+ } catch {
482
+ error = "refused";
483
+ }
484
+ if (status !== 429 && status < 500) return { ok: false, error };
485
+ } catch {
486
+ }
487
+ if (attempt >= RETRIES || wait2 > MAX_WAIT_MS || stopped) return { ok: false, error };
488
+ await new Promise((r) => setTimeout(r, wait2));
489
+ }
490
+ };
491
+ const send = async (note) => {
492
+ const config = await ready;
493
+ if (stopped || !config) return { ok: false, error: "feedback_off" };
494
+ const n = note ?? {};
495
+ const text = typeof n.text === "string" ? n.text.trim() : "";
496
+ if (!text) return { ok: false, error: "empty" };
497
+ if (n.category != null && !isFeedbackCategory(n.category)) return { ok: false, error: "bad_category" };
498
+ const s = session();
499
+ const wire = {
500
+ v: 1,
501
+ k: opts.site,
502
+ i: rid(),
503
+ // Cut by code points, so a long note never ends in half a character.
504
+ t: [...text].slice(0, FEEDBACK_LIMITS.maxTextChars).join(""),
505
+ ...isFeedbackCategory(n.category) ? { c: n.category } : {},
506
+ u: routeOf(w.location, templates),
507
+ m: s ? "j" : "a",
508
+ ...s ? { s } : {},
509
+ sv: `feedback-${VERSION}`
510
+ };
511
+ return post(wire);
512
+ };
513
+ const draw = (config) => widget ||= createWidget({
514
+ w,
515
+ config,
516
+ consent: () => feedbackConsentLine({ site: w.location.hostname, days: config.days, visit: session() !== null }),
517
+ submit: send
518
+ });
519
+ const open = async (opener) => {
520
+ const config = await ready;
521
+ if (!stopped && config) draw(config).open(opener ?? null);
522
+ };
523
+ void ready.then((config) => {
524
+ if (!stopped && config && config.placement !== "manual") draw(config);
525
+ });
526
+ const handle = (a) => {
527
+ const arg = a[1];
528
+ const done = a[2];
529
+ if (arg && typeof arg === "object")
530
+ void send(arg).then((r) => {
531
+ if (typeof done === "function") done(r);
532
+ });
533
+ else void open(d.activeElement);
534
+ };
535
+ let attachedTo;
536
+ let wait = ATTACH_MS;
537
+ const attach = () => {
538
+ clearTimeout(timer);
539
+ if (stopped) return;
540
+ let f = w.lf;
541
+ if (!f) {
542
+ const stub = ((...a) => stub.q.push(a));
543
+ stub.q = [];
544
+ w.lf = f = stub;
545
+ }
546
+ if (!f.q || f.q !== attachedTo) attachedTo = attachQueue(f, "feedback", handle);
547
+ if (!f.v) {
548
+ timer = setTimeout(attach, wait);
549
+ wait = Math.min(wait * 2, ATTACH_MAX_MS);
550
+ }
551
+ };
552
+ const before = Object.getOwnPropertyDescriptor(w, "lf");
553
+ const accessor = !!before && !("value" in before);
554
+ let current2 = w.lf;
555
+ let watch;
556
+ if (!before || before.configurable) {
557
+ watch = {
558
+ configurable: true,
559
+ enumerable: before ? before.enumerable : true,
560
+ get: accessor ? () => before.get?.call(w) : () => current2,
561
+ set: (v) => {
562
+ if (accessor) before.set?.call(w, v);
563
+ else current2 = v;
564
+ if (v?.v) attach();
565
+ }
566
+ };
567
+ try {
568
+ Object.defineProperty(w, "lf", watch);
569
+ } catch {
570
+ watch = void 0;
571
+ }
572
+ }
573
+ attach();
574
+ return {
575
+ ready,
576
+ open,
577
+ send,
578
+ stop: () => {
579
+ stopped = true;
580
+ clearTimeout(timer);
581
+ if (watch && Object.getOwnPropertyDescriptor(w, "lf")?.get === watch.get)
582
+ try {
583
+ Object.defineProperty(
584
+ w,
585
+ "lf",
586
+ accessor && before ? before : { configurable: true, enumerable: watch.enumerable, writable: true, value: current2 }
587
+ );
588
+ } catch {
589
+ }
590
+ widget?.destroy();
591
+ widget = void 0;
592
+ },
593
+ widget: () => widget
594
+ };
595
+ }
596
+ var RUNNING = Symbol.for("littlefriend.feedback");
597
+ function start(w, opts) {
598
+ const g = w;
599
+ const running = g[RUNNING];
600
+ if (running) return running;
601
+ const f = createFeedback(w, opts);
602
+ g[RUNNING] = f;
603
+ const stop = f.stop;
604
+ f.stop = () => {
605
+ stop();
606
+ if (g[RUNNING] === f) delete g[RUNNING];
607
+ };
608
+ return f;
609
+ }
610
+
611
+ // src/index.ts
612
+ function consentLine(input) {
613
+ return feedbackConsentLine(input);
614
+ }
615
+ var current;
616
+ function startFeedback(options) {
617
+ if (current || typeof window === "undefined" || typeof document === "undefined") return;
618
+ if (!options?.site) {
619
+ console.warn(
620
+ 'Little Friend: startFeedback() needs a site key, for example startFeedback({ site: "lf_..." })'
621
+ );
622
+ return;
623
+ }
624
+ current = start(window, options);
625
+ }
626
+ function openFeedback() {
627
+ if (typeof document === "undefined") return;
628
+ void current?.open(document.activeElement);
629
+ }
630
+ function sendFeedback(note) {
631
+ if (!current) return Promise.resolve({ ok: false, error: "not_started" });
632
+ return current.send(note);
633
+ }
634
+ function stopFeedback() {
635
+ current?.stop();
636
+ current = void 0;
637
+ }
638
+ export {
639
+ VERSION,
640
+ consentLine,
641
+ openFeedback,
642
+ sendFeedback,
643
+ startFeedback,
644
+ stopFeedback
645
+ };
@@ -0,0 +1 @@
1
+ (()=>{var e=/^[A-Za-z0-9_-]{16,32}$/,t=new RegExp("[^\\s@/]{1,64}@[^\\s@/]{1,253}\\.\\p{L}{2,24}","iu"),n=/\d[\d\s().-]{7,}\d/,r=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,a=/^[0-9a-f]{16,}$/i,i=/[a-f]/i,o=/^\d+$/,l=/^(?=.*\d)(?=.*[a-zA-Z])[A-Za-z0-9_-]{20,}$/,d=/^(?:eyJ[A-Za-z0-9_-]{4,}(?:\.[A-Za-z0-9_-]*){1,4}|(?=.*\d)(?=.*[A-Z])[A-Za-z0-9_-]{16,}(?:\.[A-Za-z0-9_-]{16,}){2})$/,s=/^:[a-z_][a-z0-9_]{0,31}$/,c=/[\u0000-\u001f\u007f]/g,p=new RegExp("[\\ud800-\\udbff](?![\\udc00-\\udfff])|(?<![\\ud800-\\udbff])[\\udc00-\\udfff]","g");function u(e){let o=e.length>2048?e.slice(0,2048):e;return!(!o.includes("@")||!t.test(o))||(!a.test(o)&&!r.test(o)||!i.test(o))&&n.test(o)}function f(e){return(e=>{if("string"!=typeof e||e.length>2048)return null;let t=e,n=t.search(/[?#]/);n>=0&&(t=t.slice(0,n)),t.startsWith("/")||(t=`/${t}`);let i=t;try{i=decodeURIComponent(t)}catch{}i=(e=>e.replace(c,"").replace(p,""))(i);let f=i.search(/[?#]/);f>=0&&(i=i.slice(0,f));let m=i.split("/").map(e=>{if(e.includes("="))return":redacted";if(""===e)return e;if(e.startsWith(":")){let t=e.slice(1);return g.test(t)?e:b(t)?":id":u(t)?":redacted":e}if(s.test(e))return e;let t=e.startsWith(":")?e.slice(1):e;return o.test(t)||r.test(t)||a.test(t)||l.test(t)||d.test(t)?":id":u(t)?":redacted":e}).join("/");return m.length>1&&m.endsWith("/")&&(m=m.slice(0,-1)),m.length>256?null:m})(e)}new RegExp("(?<![\\p{L}\\p{N}._%+-])[\\p{L}\\p{N}._%+-]{1,64}@(?:[\\p{L}\\p{N}](?:[\\p{L}\\p{N}-]{0,61}[\\p{L}\\p{N}])?\\.){1,8}\\p{L}{2,24}(?![\\p{L}\\p{N}_%+-]|\\.[\\p{L}\\p{N}])","gu"),new RegExp("(?<![\\w+.-])(?:\\+\\d{1,3}(?:[ .-]?\\(?\\d{1,5}\\)?){1,6}|(?:1[ .-]?)?(?:\\(\\d{3}\\)[ .-]?|\\d{3}[ .-])\\d{3}[ .-]\\d{4}|0\\d{1,4}[ -]\\d{3,4}[ -]?\\d{3,4})(?![\\d]|[.-]\\d)","g");var g=/^[A-Za-z_][A-Za-z0-9_]*$/,b=e=>o.test(e)||r.test(e)||a.test(e)||d.test(e),m=["confusing","bug","idea","other"];function h(e){return"string"==typeof e&&m.includes(e)}var y={confusing:"Confusing",bug:"Something broke",idea:"Idea",other:"Other"},x=["bottom_right","bottom_left","right_edge","manual"];function v(e){return"string"==typeof e&&x.includes(e)}var w=2e3;function k(e,t){let n=e.pathname,r="file:"===e.protocol?n.slice(n.lastIndexOf("/")):n;for(let[e,n]of t)if(n.test(r))return f(e)??"/";return f(r)??"/"}function L(e){return"empty"===e?"Write a note first.":"rate_limited"===e||"quota_exceeded"===e?"Too many notes right now. Please try again in a minute.":"network"===e?"Your note was not sent. Check your connection and try again.":"feedback_off"===e?"Feedback is turned off for this site.":"Your note was not sent. Please try again."}function $(e){let t=e;if(!0!==t?.on)return null;let n="string"==typeof t.label?t.label.trim().slice(0,24):"",r="string"==typeof t.prompt?t.prompt.trim().slice(0,140):"",a=t.days;return{v:1,on:!0,label:n||"Feedback",placement:v(t.placement)?t.placement:"bottom_right",prompt:r||null,days:"number"==typeof a&&Number.isInteger(a)&&a>=1?a:90}}new RegExp("(?<![\\d-])\\d(?:[ -]?\\d){12,18}(?![\\d])","g");var _,E=Symbol.for("littlefriend.feedback"),A=document,S=A.currentScript,z=S?.hasAttribute("data-site")?S:A.querySelector("script[data-site][data-feedback]"),C=e=>z?.getAttribute(`data-${e}`)||void 0,j=C("site");try{_=JSON.parse(C("routes")||A.querySelector("script[data-site][data-routes]")?.getAttribute("data-routes")||"[]")}catch{}j&&((t,n)=>{let r=t,a=r[E];if(a)return a;let i=function(t,n){let r,a,i=t.document,o=(n.api||"https://in.littlefriend.io").replace(/\/+$/,""),l=(e=>Array.isArray(e)?e.filter(e=>"string"==typeof e&&e.startsWith("/")).map(e=>[e,RegExp(`^${e.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/:\w+/g,"[^/]+").replace(/\*/g,".*")}/?$`)]):[])(n.routes),d=!1,s=new Promise(e=>i.prerendering?i.addEventListener("prerenderingchange",()=>e(),{once:!0}):e()).then(()=>t.fetch(`${o}/v1/f/config?k=${encodeURIComponent(n.site)}`,{credentials:"omit"})).then(e=>e.ok?e.json():null).then($,()=>null),c=()=>{let n=null,r=t.lf;if(r?.v)try{r("session",t=>{n="string"==typeof t&&e.test(t)?t:null})}catch{}return n},p=async e=>{let r=await s;if(d||!r)return{ok:!1,error:"feedback_off"};let a=e??{},i="string"==typeof a.text?a.text.trim():"";if(!i)return{ok:!1,error:"empty"};if(null!=a.category&&!h(a.category))return{ok:!1,error:"bad_category"};let p=c();return(async e=>{for(let n=0;;n++){e.s&&c()!==e.s&&(delete e.s,e.m="a");let r=JSON.stringify(e),a=0,i="network",l=1e3*2**n;try{let e=await t.fetch(`${o}/v1/f`,{method:"POST",body:r,credentials:"omit",keepalive:!0});if(a=e.status,a>=200&&a<300)return{ok:!0};let n=Number(e.headers.get("retry-after"));n>0&&(l=1e3*n);try{let t=await e.json();i="string"==typeof t?.error&&/^[a-z_]{1,40}$/.test(t.error)?t.error:"refused"}catch{i="refused"}if(429!==a&&a<500)return{ok:!1,error:i}}catch{}if(n>=3||l>1e4||d)return{ok:!1,error:i};await new Promise(e=>setTimeout(e,l))}})({v:1,k:n.site,i:[...crypto.getRandomValues(new Uint8Array(20))].map(e=>(31&e).toString(32)).join(""),t:[...i].slice(0,w).join(""),...h(a.category)?{c:a.category}:{},u:k(t.location,l),m:p?"j":"a",...p?{s:p}:{},sv:"feedback-0.1.0"})},u=e=>r||=(e=>{let{w:t,config:n}=e,r=t.document,a=r.createElement("div");a.setAttribute("data-lf-block",""),a.setAttribute("data-lf-feedback","");let i=a.attachShadow({mode:"open"});i.innerHTML='<style>:host{all:initial}\n*{box-sizing:border-box;font:14px/1.45 system-ui,sans-serif;color:inherit}\n.w{--b:#fff;--f:#1d1d22;--m:#55555f;--l:#cfcfd8;--a:#3346c4;--o:#fff;--e:#b42318;color:var(--f)}\n@media (prefers-color-scheme:dark){.w{--b:#1d1d23;--f:#f2f2f5;--m:#b0b0bc;--l:#45454f;--a:#9aa5ff;--o:#11131f;--e:#ff9b91}}\nbutton{border:1px solid var(--l);border-radius:8px;background:none;cursor:pointer;padding:8px 16px}\n.f{position:fixed;z-index:2147483000;right:16px;bottom:16px;border-radius:99px;background:var(--b);box-shadow:0 2px 10px #0003}\n.f.l{right:auto;left:16px}\n.f.e{right:0;bottom:auto;top:50%;transform:translateY(-50%) rotate(180deg);writing-mode:vertical-rl;padding:14px 8px}\n:focus-visible{outline:3px solid var(--a);outline-offset:2px}\n.b{position:fixed;inset:0;z-index:2147483001;display:flex;align-items:flex-end;justify-content:flex-end;padding:16px;background:#0004}\n.b.l{justify-content:flex-start}\n[hidden]{display:none!important}\n.d{position:relative;width:min(380px,100%);max-height:calc(100vh - 32px);overflow:auto;padding:20px;border:1px solid var(--l);border-radius:12px;background:var(--b);box-shadow:0 12px 40px #0005}\n@media (max-width:480px){.b{padding:0;justify-content:center}.d{width:100%;border-radius:12px 12px 0 0}}\nh2{margin:0 36px 12px 0;font-size:17px;font-weight:600}\nlabel,legend{display:block;margin:0 0 6px;font-weight:500}\ntextarea{display:block;width:100%;min-height:112px;resize:vertical;padding:8px 10px;border:1px solid var(--l);border-radius:8px;background:none}\n.n,.c{margin:4px 0 12px;color:var(--m);font-size:12.5px}\nfieldset{margin:0;padding:0;border:0}\n.r label{display:inline-flex;gap:4px;align-items:center;margin:0 12px 6px 0;font-weight:400}\ninput{margin:0;accent-color:var(--a)}\n.a{display:flex;justify-content:flex-end;gap:8px}\n.s{border-color:var(--a);background:var(--a);color:var(--o);font-weight:600}\n.s:disabled{opacity:.6}\n.x{position:absolute;top:10px;right:10px;width:34px;height:34px;padding:0;border:0;font-size:22px;line-height:1}\n.t{min-height:1.45em;margin:10px 0 0}\n.t.e{color:var(--e)}\n@media (prefers-reduced-motion:no-preference){.d{animation:i .16s ease-out}@keyframes i{from{opacity:0;transform:translateY(8px)}}}</style><div class="w"><button type="button" class="f" aria-haspopup="dialog"></button><div class="b" hidden><div class="d" role="dialog" aria-modal="true" aria-labelledby="h" aria-describedby="c"><button type="button" class="x" aria-label="Close">×</button><h2 id="h">Send feedback</h2><form novalidate><label for="m"></label><textarea id="m" aria-describedby="n"></textarea><p class="n" id="n"></p><fieldset><legend>Kind of note (optional)</legend><div class="r"></div></fieldset><p class="c" id="c"></p><div class="a"><button type="button" class="k">Cancel</button><button type="submit" class="s">Send</button></div></form><p class="t" role="status" aria-live="polite"></p></div></div></div>';let o=e=>i.querySelector(e),l=o(".f"),d=o(".b"),s=o(".d"),c=o("form"),p=o("textarea"),u=o(".n"),f=o(".c"),g=o(".t"),b=o(".s"),h=o(".x");l.textContent=n.label,"manual"===n.placement?l.remove():"bottom_left"===n.placement?(l.classList.add("l"),d.classList.add("l")):"right_edge"===n.placement&&l.classList.add("e"),o("label").textContent=n.prompt||"What could be better on this page?",p.maxLength=w;let x=o(".r");for(let e of m){let t=r.createElement("label"),n=r.createElement("input");n.type="radio",n.name="k",n.value=e,t.append(n,y[e]),x.append(t)}let v=null,k=!1,$=()=>{let e=w-p.value.length;u.textContent=`${e.toLocaleString("en-US")} ${1===e?"character":"characters"} left`};p.addEventListener("input",$);let _=(e,t=!1)=>{g.textContent=e,g.classList.toggle("e",t)},E=()=>{if(d.hidden)return;d.hidden=!0;let e=v&&v.isConnected?v:l.isConnected?l:null;v=null,e?.focus?.()},A=t=>{a.isConnected||(r.body||r.documentElement).append(a),v=t??null,c.hidden&&(c.hidden=!1,c.reset(),_("")),f.textContent=e.consent(),$(),d.hidden=!1,p.focus()},S=async()=>{if(k)return;if(!p.value.trim())return _(L("empty"),!0),void p.focus();let t=e.consent();if(t!==f.textContent)return f.textContent=t,void _("The line above changed. Read it, then press Send again.",!0);k=!0,b.disabled=!0,_("Sending");let n=x.querySelector(":checked")?.value,r=await e.submit({text:p.value,...n?{category:n}:{}});k=!1,b.disabled=!1,r.ok?(c.hidden=!0,_("Thanks. Your note was sent."),h.focus()):_(L(r.error),!0)};return l.addEventListener("click",()=>A(l)),h.addEventListener("click",E),o(".k").addEventListener("click",E),d.addEventListener("click",e=>{e.target===d&&E()}),c.addEventListener("submit",e=>{e.preventDefault(),S()}),p.addEventListener("keydown",e=>{"Enter"===e.key&&(e.metaKey||e.ctrlKey)&&(e.preventDefault(),S())}),s.addEventListener("keydown",e=>{if("Escape"===e.key)e.preventDefault(),E();else if("Tab"===e.key){let t=[...s.querySelectorAll("button,textarea,input")].filter(e=>!e.disabled&&!e.closest("[hidden]")&&("INPUT"!==e.tagName||e.checked||!x.querySelector(":checked"))),n=t[0],r=t[t.length-1],a=i.activeElement;if(!n||!r)return;(e.shiftKey?a===n||!a:a===r||!a)&&(e.preventDefault(),(e.shiftKey?r:n).focus())}}),"manual"!==n.placement&&(r.body||r.documentElement).append(a),{open:A,close:E,destroy:()=>{d.hidden=!0,a.remove()},root:i}})({w:t,config:e,consent:()=>(e=>`${e.visit?"Your note, this page's address, the time, your device type and a link to this visit":"Your note, this page's address, the time and your device type"} go to the team behind ${e.site.replace(/^www\./,"")||"this site"} when you press Send, and are kept for ${1===e.days?"1 day":`${e.days} days`}. Please leave out passwords and card numbers.`)({site:t.location.hostname,days:e.days,visit:null!==c()}),submit:p}),f=async e=>{let t=await s;!d&&t&&u(t).open(e??null)};s.then(e=>{!d&&e&&"manual"!==e.placement&&u(e)});let g,b,x=e=>{let t=e[1],n=e[2];t&&"object"==typeof t?p(t).then(e=>{"function"==typeof n&&n(e)}):f(i.activeElement)},v=1e3,_=()=>{if(clearTimeout(a),d)return;let e=t.lf;if(!e){let n=(...e)=>n.q.push(e);n.q=[],t.lf=e=n}(!e.q||e.q!==g)&&(g=((e,t,n)=>{let r=e.q;(!r||"function"!=typeof r.push)&&(r=[],e.q=r);let a=e=>{try{n(e)}catch(e){setTimeout(()=>{throw e})}};if(Array.isArray(r))for(let e=0;e<r.length;)r[e]?.[0]===t?a(r.splice(e,1)[0]):e++;let i=r,o=i.push;return i.push=e=>e?.[0]===t?a(e):o.call(i,e),i})(e,"feedback",x)),e.v||(a=setTimeout(_,v),v=Math.min(2*v,3e4))},E=Object.getOwnPropertyDescriptor(t,"lf"),A=!!E&&!("value"in E),S=t.lf;if(!E||E.configurable){b={configurable:!0,enumerable:!E||E.enumerable,get:A?()=>E.get?.call(t):()=>S,set:e=>{A?E.set?.call(t,e):S=e,e?.v&&_()}};try{Object.defineProperty(t,"lf",b)}catch{b=void 0}}return _(),{ready:s,open:f,send:p,stop:()=>{if(d=!0,clearTimeout(a),b&&Object.getOwnPropertyDescriptor(t,"lf")?.get===b.get)try{Object.defineProperty(t,"lf",A&&E?E:{configurable:!0,enumerable:b.enumerable,writable:!0,value:S})}catch{}r?.destroy(),r=void 0},widget:()=>r}}(t,n);r[E]=i;let o=i.stop;i.stop=()=>{o(),r[E]===i&&delete r[E]}})(window,{site:j,api:C("api"),routes:Array.isArray(_)?_:[]})})();
@@ -0,0 +1,13 @@
1
+ /**
2
+ * The add-on queue protocol, the same in lf-replay.js and lf-feedback.js. lf.js keeps every
3
+ * command it does not handle in `lf.q`, an array, and calls `lf.q.push` for each later one. An
4
+ * add-on takes its own commands out of that array, then wraps `push`: its own command is handled,
5
+ * and anything else goes to the push it wrapped, which ends at the array's own push. So each
6
+ * add-on gets its commands in any load order, and a command for an add-on that has not loaded yet
7
+ * waits in the array.
8
+ */
9
+ export type QueuedCall = ArrayLike<unknown>;
10
+ /** Attach `handle` for `name` to `f.q`, making the queue first when there is none. Returns the queue. */
11
+ export declare function attachQueue(f: {
12
+ q?: unknown;
13
+ }, name: string, handle: (a: QueuedCall) => void): object;
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Route templates, compiled exactly as lf.js compiles its `routes` setting: `:name` matches one
3
+ * segment, `*` anything, an optional trailing slash. First match wins.
4
+ */
5
+ export declare function compileRoutes(templates: unknown): [string, RegExp][];
6
+ /** The page's route with the page view rules: a template, else the sanitized path. A file page keeps only its file name. */
7
+ export declare function routeOf(loc: Location, templates: [string, RegExp][]): string;
@@ -0,0 +1,6 @@
1
+ /**
2
+ * The widget's only styles, inside its shadow root: nothing here reaches the page, and the
3
+ * host element resets every inherited property. Light and dark follow the visitor's system
4
+ * setting; motion only when the visitor has not asked for less.
5
+ */
6
+ export declare const CSS = ":host{all:initial}\n*{box-sizing:border-box;font:14px/1.45 system-ui,sans-serif;color:inherit}\n.w{--b:#fff;--f:#1d1d22;--m:#55555f;--l:#cfcfd8;--a:#3346c4;--o:#fff;--e:#b42318;color:var(--f)}\n@media (prefers-color-scheme:dark){.w{--b:#1d1d23;--f:#f2f2f5;--m:#b0b0bc;--l:#45454f;--a:#9aa5ff;--o:#11131f;--e:#ff9b91}}\nbutton{border:1px solid var(--l);border-radius:8px;background:none;cursor:pointer;padding:8px 16px}\n.f{position:fixed;z-index:2147483000;right:16px;bottom:16px;border-radius:99px;background:var(--b);box-shadow:0 2px 10px #0003}\n.f.l{right:auto;left:16px}\n.f.e{right:0;bottom:auto;top:50%;transform:translateY(-50%) rotate(180deg);writing-mode:vertical-rl;padding:14px 8px}\n:focus-visible{outline:3px solid var(--a);outline-offset:2px}\n.b{position:fixed;inset:0;z-index:2147483001;display:flex;align-items:flex-end;justify-content:flex-end;padding:16px;background:#0004}\n.b.l{justify-content:flex-start}\n[hidden]{display:none!important}\n.d{position:relative;width:min(380px,100%);max-height:calc(100vh - 32px);overflow:auto;padding:20px;border:1px solid var(--l);border-radius:12px;background:var(--b);box-shadow:0 12px 40px #0005}\n@media (max-width:480px){.b{padding:0;justify-content:center}.d{width:100%;border-radius:12px 12px 0 0}}\nh2{margin:0 36px 12px 0;font-size:17px;font-weight:600}\nlabel,legend{display:block;margin:0 0 6px;font-weight:500}\ntextarea{display:block;width:100%;min-height:112px;resize:vertical;padding:8px 10px;border:1px solid var(--l);border-radius:8px;background:none}\n.n,.c{margin:4px 0 12px;color:var(--m);font-size:12.5px}\nfieldset{margin:0;padding:0;border:0}\n.r label{display:inline-flex;gap:4px;align-items:center;margin:0 12px 6px 0;font-weight:400}\ninput{margin:0;accent-color:var(--a)}\n.a{display:flex;justify-content:flex-end;gap:8px}\n.s{border-color:var(--a);background:var(--a);color:var(--o);font-weight:600}\n.s:disabled{opacity:.6}\n.x{position:absolute;top:10px;right:10px;width:34px;height:34px;padding:0;border:0;font-size:22px;line-height:1}\n.t{min-height:1.45em;margin:10px 0 0}\n.t.e{color:var(--e)}\n@media (prefers-reduced-motion:no-preference){.d{animation:i .16s ease-out}@keyframes i{from{opacity:0;transform:translateY(8px)}}}";
@@ -0,0 +1,26 @@
1
+ /** The fixed categories, the contract's FEEDBACK_CATEGORIES (kept in step by a test). */
2
+ export type FeedbackCategory = 'confusing' | 'bug' | 'idea' | 'other';
3
+ export interface FeedbackOptions {
4
+ /** Public site key, `lf_` followed by base62 characters: the same key lf.js uses. */
5
+ site: string;
6
+ /** Collector origin. Default `https://in.littlefriend.io`. */
7
+ api?: string;
8
+ /** Route templates such as `/docs/:slug`, matched as lf.js's `routes` setting is. */
9
+ routes?: string[];
10
+ }
11
+ /** A note sent without the widget, from a site's own form. */
12
+ export interface FeedbackNoteInput {
13
+ text: string;
14
+ category?: FeedbackCategory;
15
+ }
16
+ /**
17
+ * The outcome of a send. `error` is a short code: `feedback_off`, `empty`, `too_long`,
18
+ * `bad_category`, `rate_limited`, `quota_exceeded`, `network`, `not_started`, or another refusal
19
+ * code from the collector.
20
+ */
21
+ export type FeedbackResult = {
22
+ ok: true;
23
+ } | {
24
+ ok: false;
25
+ error: string;
26
+ };
@@ -0,0 +1,2 @@
1
+ /** Kept in step with package.json by test/size.test.ts. */
2
+ export declare const VERSION = "0.1.0";
@@ -0,0 +1,35 @@
1
+ /**
2
+ * The button and the dialog, drawn inside a shadow root so the page's styles never reach them
3
+ * and theirs never reach the page. The host carries `data-lf-block`, so session replay draws it
4
+ * as an empty box and a note being typed is never recorded.
5
+ *
6
+ * Nothing is sent until the person presses Send (or Ctrl or Cmd with Enter in the text box).
7
+ * Closing, Escape, a click outside, leaving the page: none of them send. The only page state read
8
+ * is what the caller passes in.
9
+ */
10
+ import { type FeedbackClientConfig } from '@littlefriend/contract';
11
+ import type { FeedbackNoteInput, FeedbackResult } from './types.js';
12
+ type Win = Window & typeof globalThis;
13
+ export interface Widget {
14
+ /** Opens the dialog. Focus returns to `opener` when it closes. */
15
+ open(opener?: Element | null): void;
16
+ close(): void;
17
+ destroy(): void;
18
+ /** The shadow root, for tests. */
19
+ root: ShadowRoot;
20
+ }
21
+ export interface WidgetDeps {
22
+ w: Win;
23
+ config: FeedbackClientConfig;
24
+ /** The consent line for this moment: it names the visit only when a live session goes along. */
25
+ consent: () => string;
26
+ submit: (note: FeedbackNoteInput) => Promise<FeedbackResult>;
27
+ }
28
+ export declare const DEFAULT_PROMPT = "What could be better on this page?";
29
+ export declare const SENT_MESSAGE = "Thanks. Your note was sent.";
30
+ /** Shown when the line under the text box changed since it was read: nothing was sent. */
31
+ export declare const CHANGED_MESSAGE = "The line above changed. Read it, then press Send again.";
32
+ /** Plain words for a refused or failed send. */
33
+ export declare function errorMessage(code: string): string;
34
+ export declare function createWidget(deps: WidgetDeps): Widget;
35
+ export {};
package/package.json CHANGED
@@ -1,6 +1,46 @@
1
1
  {
2
2
  "name": "@littlefriend/feedback",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
4
+ "type": "module",
5
+ "description": "Little Friend feedback button: a small, accessible widget where a person can tell you a page is confusing, at the moment it happens. Sent only when they press Send.",
6
+ "keywords": [
7
+ "analytics",
8
+ "privacy",
9
+ "feedback",
10
+ "feedback-widget",
11
+ "littlefriend"
12
+ ],
13
+ "homepage": "https://littlefriend.io/docs/feedback",
14
+ "author": "ZVN DEV <dev@zvndev.com>",
15
+ "license": "MIT",
16
+ "sideEffects": false,
17
+ "exports": {
18
+ ".": {
19
+ "types": "./dist/index.d.ts",
20
+ "import": "./dist/index.js"
21
+ },
22
+ "./lf-feedback.js": "./dist/lf-feedback.js"
23
+ },
24
+ "main": "./dist/index.js",
25
+ "types": "./dist/index.d.ts",
26
+ "files": [
27
+ "dist",
28
+ "LICENSE"
29
+ ],
30
+ "publishConfig": {
31
+ "access": "public"
32
+ },
33
+ "devDependencies": {
34
+ "esbuild": "^0.25.0",
35
+ "happy-dom": "^20.0.0",
36
+ "terser": "^5.51.2",
37
+ "@littlefriend/contract": "0.1.0",
38
+ "@littlefriend/tracker": "0.1.3"
39
+ },
40
+ "scripts": {
41
+ "build": "node scripts/build.mjs",
42
+ "size": "node scripts/build.mjs && node scripts/size.mjs",
43
+ "typecheck": "tsc -p tsconfig.json --noEmit",
44
+ "test": "node scripts/build.mjs && node scripts/size.mjs && vitest run"
45
+ }
6
46
  }