@seanhogg/builderforce-insights 0.0.0-stage → 2026.11.30

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/README.md +277 -2
  2. package/dist/assets/embed/v1.js +1 -0
  3. package/dist/assets/replay/manifest.json +16 -0
  4. package/dist/assets/replay/r/pagekit.ca1bd1d2c19b.js +1 -0
  5. package/dist/assets/replay/r/player.35d774f1c2e0.js +147 -0
  6. package/dist/assets/replay/r/player.64d720c3a896.css +79 -0
  7. package/dist/assets/replay/r/recorder.efbf70969285.js +148 -0
  8. package/dist/assets/replay/v1/loader.js +1 -0
  9. package/dist/chunk-B2H4MPZI.mjs +18 -0
  10. package/dist/chunk-B2H4MPZI.mjs.map +1 -0
  11. package/dist/chunk-S24NNQ7M.mjs +69 -0
  12. package/dist/chunk-S24NNQ7M.mjs.map +1 -0
  13. package/dist/chunk-YW7PF6RP.mjs +101 -0
  14. package/dist/chunk-YW7PF6RP.mjs.map +1 -0
  15. package/dist/embed.js +1 -0
  16. package/dist/errors.cjs +1154 -0
  17. package/dist/errors.cjs.map +1 -0
  18. package/dist/errors.global.js +1146 -0
  19. package/dist/errors.global.js.map +1 -0
  20. package/dist/errors.mjs +999 -0
  21. package/dist/errors.mjs.map +1 -0
  22. package/dist/feedback.cjs +424 -0
  23. package/dist/feedback.cjs.map +1 -0
  24. package/dist/feedback.global.js +409 -0
  25. package/dist/feedback.global.js.map +1 -0
  26. package/dist/feedback.mjs +369 -0
  27. package/dist/feedback.mjs.map +1 -0
  28. package/dist/index.cjs +19 -0
  29. package/dist/index.cjs.map +1 -0
  30. package/dist/index.mjs +1 -0
  31. package/dist/index.mjs.map +1 -0
  32. package/dist/loader.js +1 -0
  33. package/dist/pagekit.js +1 -0
  34. package/dist/player.js +147 -0
  35. package/dist/recorder.js +148 -0
  36. package/dist/replay.cjs +58 -0
  37. package/dist/replay.cjs.map +1 -0
  38. package/dist/replay.global.js +56 -0
  39. package/dist/replay.global.js.map +1 -0
  40. package/dist/replay.mjs +23 -0
  41. package/dist/replay.mjs.map +1 -0
  42. package/dist/server.cjs +145 -0
  43. package/dist/server.cjs.map +1 -0
  44. package/dist/server.mjs +20 -0
  45. package/dist/server.mjs.map +1 -0
  46. package/package.json +91 -4
package/README.md CHANGED
@@ -1,3 +1,278 @@
1
- # Temporary Holding Version
1
+ # `@seanhogg/builderforce-insights`
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
+ One package for everything Builderforce.ai embeds in your product to **measure** it:
4
+
5
+ | Subpath | What it is | Replaces |
6
+ | --- | --- | --- |
7
+ | [`/errors`](#errors--seanhoggbuilderforce-insightserrors) | Browser error capture for the Product Quality pillar | `@seanhogg/builderforce-quality` |
8
+ | [`/server`](#server--seanhoggbuilderforce-insightsserver) | The same capture for Node, workers and CLIs | `@seanhogg/builderforce-quality/server` |
9
+ | [`/replay`](#replay--seanhoggbuilderforce-insightsreplay) | Session replay for Insights (PRD 33) | `@seanhogg/builderforce-replay` |
10
+ | [`/feedback`](#feedback--seanhoggbuilderforce-insightsfeedback) | Product-feedback widget | `@seanhogg/builderforce-feedback` |
11
+
12
+ The root (`.`) exports shared **types only** and imports nothing that pulls in rrweb, so an
13
+ errors-only (or feedback-only) install never bundles the recorder.
14
+
15
+ ## Where this fits
16
+ Part of BuilderForce's **Idea → Make → Run → Measure → Reach** method ([definitions](../docs/specs/README.md)). This package serves **Measure**: errors, sessions and on-page feedback flow back into Builderforce so you can tell whether the product is working.
17
+
18
+ ## What the modules share
19
+
20
+ - **One listener pair.** `error` and `unhandledrejection` are registered once per page
21
+ (`src/shared/pageErrors.ts`), however many modules listen; the last one out removes them.
22
+ - **One stack reader** (`src/shared/stack.ts`): frames for the error client, first frame and
23
+ fingerprint for replay.
24
+ - **One delivery path** (`src/shared/transport.ts` over `@builderforce/write-outbox`): ordered
25
+ queueing, JSON POST with `keepalive`, retry with backoff on 5xx / network failure, `429`
26
+ `Retry-After` honoured.
27
+ - **One endpoint rule** (`src/shared/endpoint.ts`): the default API base and trailing-slash
28
+ handling.
29
+
30
+ ## errors — `@seanhogg/builderforce-insights/errors`
31
+
32
+ Capture browser errors and ship them to your keyed ingest endpoint in the canonical format —
33
+ they appear, grouped by fingerprint, in your Quality dashboard, ready for a one-click agent
34
+ fix. Create a source under **Quality → Sources** in Builderforce to mint an ingest key
35
+ (`bfq_…`) and get your endpoint.
36
+
37
+ Script tag:
38
+
39
+ ```html
40
+ <script src="https://unpkg.com/@seanhogg/builderforce-insights/dist/errors.global.js"></script>
41
+ <script>
42
+ BuilderforceQuality.init({
43
+ key: 'bfq_xxx',
44
+ endpoint: 'https://api.builderforce.ai/api/quality-ingest',
45
+ release: '1.4.0',
46
+ environment: 'production',
47
+ });
48
+ </script>
49
+ ```
50
+
51
+ `window.onerror` and `unhandledrejection` are captured automatically. Capture manually with
52
+ `BuilderforceQuality.captureException(err)` / `captureMessage('…')`.
53
+
54
+ Bundler:
55
+
56
+ ```ts
57
+ import { init, captureException } from '@seanhogg/builderforce-insights/errors';
58
+
59
+ init({ key: 'bfq_xxx', endpoint: 'https://api.builderforce.ai/api/quality-ingest' });
60
+
61
+ try { risky(); } catch (e) { captureException(e, { tags: { area: 'checkout' } }); }
62
+ ```
63
+
64
+ Events are batched (`maxBatch`, default 20; `flushIntervalMs`, default 5 s) and sent through the
65
+ write outbox. A batch the ingest could not take is retried with backoff, not dropped; on page
66
+ hide the queue is flushed with a `keepalive` request (`sendBeacon` as the fallback).
67
+
68
+ ### Canvas preview reporting
69
+
70
+ A page inside an iframe is opaque to whatever framed it: the embedder cannot read your
71
+ `console`, cannot receive your error events and cannot see your failed requests. So a
72
+ [Builderforce Creation Canvas](https://builderforce.ai) preview of your site can look
73
+ perfectly fine while the page is throwing on every load.
74
+
75
+ `init()` fixes that for your own pages, on by default and **only when the page is
76
+ framed** — an ordinary page pays nothing, not even a listener:
77
+
78
+ ```ts
79
+ init({ key: 'bfq_xxx', endpoint: 'https://api.builderforce.ai/api/quality-ingest' });
80
+ // framePreview: false to opt out; installCanvasPreviewReporter() to use it on its own.
81
+ ```
82
+
83
+ Framed, the page posts each console line, thrown error, subresource that failed to load
84
+ and request that failed or returned 4xx/5xx to the framing document, and the canvas shows
85
+ them under the preview. Only a level, a truncated line of text and a millisecond offset
86
+ are posted — never page content, request bodies or headers, because the document that
87
+ framed you may be anyone's.
88
+
89
+ ### Other sources
90
+
91
+ Any source works: point an **OpenTelemetry** OTLP/HTTP exporter at
92
+ `<endpoint>/otlp` (it appends `/v1/logs` and `/v1/traces`), or configure a
93
+ **Sentry / PostHog / LogRocket** webhook against the source's webhook URL — the
94
+ server translates each into the same canonical format.
95
+
96
+ ## server — `@seanhogg/builderforce-insights/server`
97
+
98
+ Node / server / compiled-code entry: the same canonical contract without the DOM hooks, one
99
+ awaited POST per report.
100
+
101
+ ```ts
102
+ import { createServerCapture } from '@seanhogg/builderforce-insights/server';
103
+
104
+ const quality = createServerCapture({
105
+ key: 'bfq_xxx',
106
+ endpoint: 'https://api.builderforce.ai/api/quality-ingest',
107
+ environment: 'production',
108
+ });
109
+
110
+ try { await work(); } catch (e) { await quality.captureException(e); }
111
+ ```
112
+
113
+ ## replay — `@seanhogg/builderforce-insights/replay`
114
+
115
+ Session replay for Builderforce.ai Insights (PRD 33). One loader, one recorder, one public API.
116
+
117
+ Paste into `<head>`:
118
+
119
+ ```html
120
+ <script async src="https://cdn.builderforce.ai/replay/v1/loader.js" data-site="bfr_YOUR_SITE_KEY"></script>
121
+ ```
122
+
123
+ or from npm (it injects the same loader, so the recorder updates without a reinstall):
124
+
125
+ ```ts
126
+ import { startReplay } from '@seanhogg/builderforce-insights/replay';
127
+ startReplay({ site: 'bfr_YOUR_SITE_KEY' });
128
+ ```
129
+
130
+ Optional tag attributes: `data-release` (your release name; otherwise the
131
+ recorder fingerprints the page's hashed assets), `data-variant` (A/B label),
132
+ `data-api` (API origin override).
133
+
134
+ ### What the loader does
135
+
136
+ 1. Installs a queued `window.BFReplay` stub, so page code never breaks.
137
+ 2. Stops — before any network call — under Do Not Track or Global Privacy Control.
138
+ 3. Fetches `https://api.builderforce.ai/api/replay-ingest/v1/config?site=…`
139
+ (no credentials). Stops when the site is disabled.
140
+ 4. When the site requires consent, waits for `BFReplay.consent(true)`.
141
+ 5. Injects the recorder the config names (`/replay/r/recorder.<hash>.js`).
142
+
143
+ ### `window.BFReplay`
144
+
145
+ | Call | Effect |
146
+ | --- | --- |
147
+ | `consent(granted)` | `false` stops recording and ends the visit |
148
+ | `event(name)` | custom event (≤80 chars of `[\w .:-]`) |
149
+ | `tag(key, value)` | sticky tag (key ≤64, value ≤200, ≤20 keys); keeps the recording. Values that look like an email or a card number are refused |
150
+ | `identify(id, traits?)` | only when the site enables identify; traits are a flat string map (≤20 keys) |
151
+ | `keep()` | keep this session's recording |
152
+ | `stop()` | stop recording and end the visit |
153
+ | `version` | recorder version |
154
+
155
+ ### Privacy
156
+
157
+ - Every input is masked (`maskAllInputs` is hard-coded on). Password and
158
+ payment-card (`autocomplete="cc-*"`) fields are never captured.
159
+ - `data-bf-mask` masks text (all text when the site sets "mask all text");
160
+ `data-bf-block` replaces a region with a placeholder.
161
+ - Canvas frames only when the site enables canvas recording (2 fps, JPEG 0.4).
162
+
163
+ ### Recording
164
+
165
+ Every session sends marks (pages, clicks with grid cells, rage, dead clicks,
166
+ quick backs, excessive scrolling, errors, custom events, scroll depth, Core
167
+ Web Vitals) so counts are exact. Full recordings are kept for a head sample
168
+ (`keepRate`) or when something happens: frustration, an error, a sign-up /
169
+ purchase / checkout, a tag or `keep()`. Until then the recorder holds the last
170
+ 60 s in memory, so a kept recording includes the moments before the trigger.
171
+
172
+ Chunks go to `/api/replay-ingest/v1/chunks` every 5 s while visible and on
173
+ pagehide (`keepalive`), gzip-compressed when the browser supports
174
+ `CompressionStream`.
175
+
176
+ Ids: `bf_visitor_id` / `bf_visit_id` on builderforce.ai (shared with the
177
+ product's visitor journey), `bfr_visitor_id` / `bfr_visit_id` elsewhere. A
178
+ visit rotates after 30 minutes idle.
179
+
180
+ ## feedback — `@seanhogg/builderforce-insights/feedback`
181
+
182
+ Drops a small tab onto the edge of any page. Clicking it slides out a panel that files a
183
+ feature request, bug report or idea straight into a Builderforce project's backlog.
184
+
185
+ Script tag (no build step):
186
+
187
+ ```html
188
+ <script src="https://unpkg.com/@seanhogg/builderforce-insights/dist/feedback.global.js"></script>
189
+ <script>
190
+ BuilderforceFeedback.init({ key: 'bff_your_ingest_key' });
191
+ </script>
192
+ ```
193
+
194
+ Or as a module:
195
+
196
+ ```bash
197
+ npm install @seanhogg/builderforce-insights
198
+ ```
199
+
200
+ ```ts
201
+ import { init } from '@seanhogg/builderforce-insights/feedback';
202
+
203
+ init({ key: process.env.FEEDBACK_KEY!, appVersion: '2026.7.19' });
204
+ ```
205
+
206
+ Get the ingest key from **Quality → Feedback** in Builderforce, with the project selected.
207
+ It is shown once, at creation.
208
+
209
+ ### Options
210
+
211
+ | Option | Default | Description |
212
+ | --- | --- | --- |
213
+ | `key` | *(required)* | The project's ingest key (`bff_…`). |
214
+ | `endpoint` | `https://api.builderforce.ai/api/feedback-ingest` | Ingest base for self-hosted deployments. |
215
+ | `side` | `'right'` | Which edge the tab docks to. |
216
+ | `accent` | `'#f4726e'` | Accent colour for the tab and submit button. |
217
+ | `theme` | `'auto'` | `'light'`, `'dark'`, or follow the page's `prefers-color-scheme`. |
218
+ | `kinds` | all four | Subset of `feature` \| `bug` \| `idea` \| `other`. |
219
+ | `collectEmail` | `true` | Ask for an email so the team can follow up. |
220
+ | `appVersion` | — | Release recorded against each request. |
221
+ | `context` | — | Extra structured context attached to every submission. |
222
+ | `labels` | English | Override any visible string (see `FeedbackLabels`). |
223
+ | `showTab` | `true` | Set `false` to drive the panel yourself via `open()`. |
224
+ | `onSubmit` | — | Called with `{ submissionId, deduped }` once accepted. |
225
+
226
+ ### Driving it yourself
227
+
228
+ ```ts
229
+ init({ key: 'bff_…', showTab: false });
230
+
231
+ document.querySelector('#help-menu-feedback')
232
+ .addEventListener('click', () => BuilderforceFeedback.open());
233
+ ```
234
+
235
+ `open()`, `close()` and `destroy()` are exported alongside `init`.
236
+
237
+ ### What happens to a submission
238
+
239
+ Each request opens a ticket in the project's backlog marked as an **external request**.
240
+ Those tickets are hard-gated: no agent can pick one up — autonomously or via Run now —
241
+ until a human approves it in the feedback triage queue. Approving is the only thing that
242
+ makes the ticket executable, so nothing gets built because a stranger asked for it.
243
+
244
+ Duplicate submissions (same kind, title and body) collapse onto the existing request
245
+ rather than opening a second ticket, and each collector enforces a rolling 24-hour
246
+ submission ceiling.
247
+
248
+ Everything renders inside a shadow root with its own reset, so the widget can neither
249
+ inherit nor leak page styles. No dependencies, no framework, works on any page.
250
+
251
+ ## Migrating
252
+
253
+ | Before | After |
254
+ | --- | --- |
255
+ | `@seanhogg/builderforce-quality` | `@seanhogg/builderforce-insights/errors` |
256
+ | `@seanhogg/builderforce-quality/server` | `@seanhogg/builderforce-insights/server` |
257
+ | `@seanhogg/builderforce-replay` | `@seanhogg/builderforce-insights/replay` |
258
+ | `@seanhogg/builderforce-feedback` | `@seanhogg/builderforce-insights/feedback` |
259
+
260
+ Options, globals (`BuilderforceQuality`, `BuilderforceFeedback`, `window.BFReplay`) and wire
261
+ formats are unchanged. The CDN snippet URLs are unchanged.
262
+
263
+ ## Build
264
+
265
+ `npm run build` writes the npm files to `dist/` and the CDN layout to `dist/assets/`:
266
+
267
+ ```
268
+ replay/v1/loader.js loader (≤ 2 KB gzip)
269
+ replay/r/recorder.<hash>.js recorder incl. rrweb (≤ 80 KB gzip), immutable
270
+ replay/manifest.json { "latest": { "version", "url", "hash", "builtAt" } }
271
+ embed/v1.js unified embed rail (boots replay from data-site)
272
+ ```
273
+
274
+ `npm run size` checks the layout and the gzip budgets. The release workflow's
275
+ `publish-cdn` job uploads it with `.github/scripts/cdn-publish.sh` (manifest
276
+ last); see `infra/cdn/README.md`.
277
+
278
+ MIT © Sean Hogg
@@ -0,0 +1 @@
1
+ "use strict";var BuilderforceEmbed=(()=>{var l=Object.defineProperty;var P=Object.getOwnPropertyDescriptor;var S=Object.getOwnPropertyNames;var I=Object.prototype.hasOwnProperty;var A=(e,t)=>{for(var a in t)l(e,a,{get:t[a],enumerable:!0})},T=(e,t,a,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let p of S(t))!I.call(e,p)&&p!==a&&l(e,p,{get:()=>t[p],enumerable:!(i=P(t,p))||i.enumerable});return e};var v=e=>T(l({},"__esModule",{value:!0}),e);var O={};A(O,{bootEmbed:()=>_});var c="https://api.builderforce.ai";var h=new RegExp("^[0-9a-f]{12}$");var R={ingestConfig:"/api/replay-ingest/v1/config",ingestChunks:"/api/replay-ingest/v1/chunks",sites:"/api/replay/sites",site:"/api/replay/sites/:siteId",siteVerify:"/api/replay/sites/:siteId/verify",recordings:"/api/replay/recordings",recording:"/api/replay/recordings/:recordingId",recordingChunk:"/api/replay/recordings/:recordingId/chunks/:seq",recordingStatus:"/api/replay/recordings/:recordingId/status",releases:"/api/replay/releases",release:"/api/replay/releases/:releaseKey",kpis:"/api/replay/kpis",issues:"/api/replay/issues",issue:"/api/replay/issues/:issueId",live:"/api/replay/live",usage:"/api/replay/usage",heatGrid:"/api/replay/heatmap/grid",heatElements:"/api/replay/heatmap/elements",heatScroll:"/api/replay/heatmap/scroll",heatRoutes:"/api/replay/heatmap/routes",heatInsights:"/api/replay/heatmap/insights",heatSnapshot:"/api/replay/heatmap/snapshot",recordingExport:"/api/replay/recordings/:recordingId/export",exportStatus:"/api/replay/exports/:exportId",exportDownload:"/api/replay/exports/:exportId/download",projectSite:"/api/projects/:projectId/replay/site",capabilityState:"/api/capabilities/:slug/state",capabilityPacks:"/api/capabilities/session-replay/packs",capabilityPackCheckout:"/api/capabilities/session-replay/packs/:packId/checkout",opsSummary:"/api/admin/replay-ops/summary",opsTenantSettings:"/api/admin/replay-ops/tenants/:tenantId/settings",opsGrants:"/api/admin/replay-ops/grants",segments:"/api/replay/segments",segment:"/api/replay/segments/:segmentId",filterOptions:"/api/replay/filter-options",overview:"/api/replay/overview",smartEvents:"/api/replay/smart-events",smartEvent:"/api/replay/smart-events/:eventId",smartEventPreview:"/api/replay/smart-events/preview",funnels:"/api/replay/funnels",funnel:"/api/replay/funnels/:funnelId",funnelEvaluate:"/api/replay/funnels/:funnelId/evaluate",flow:"/api/replay/flow",recordingSummary:"/api/replay/recordings/:recordingId/summary",segmentSummary:"/api/replay/summary",visitor:"/api/replay/visitors/:visitorId",ticketEffect:"/api/replay/ticket-effect/:taskId",opsSeedMethodFunnel:"/api/admin/replay-ops/sites/:siteId/seed-method-funnel",prescriptions:"/api/replay/prescriptions",prescription:"/api/replay/prescriptions/:prescriptionId",prescriptionAction:"/api/replay/prescriptions/:prescriptionId/:action",prescriptionSweep:"/api/replay/prescriptions/sweep",releaseReport:"/api/replay/releases/:releaseKey/report",pages:"/api/replay/pages",pageReview:"/api/replay/pages/review",pageCapture:"/api/replay/pages/capture",capturesAsset:"/api/replay/pages/captures/:captureId/:asset",improvementPrompt:"/api/replay/prescriptions/:prescriptionId/prompt",pagePrompt:"/api/replay/pages/prompt",previewUrl:"/api/replay/releases/:releaseKey/preview",sequences:"/api/replay/sequences",codingAgents:"/api/replay/coding-agents"};var L=c;function E(e,t=L){return(e??t).trim().replace(/\/+$/,"").replace(/\/submit$/,"")||t}var g=["consent","event","tag","identify","keep","stop"];function M(){let e=navigator;return e.doNotTrack==="1"||e.globalPrivacyControl===!0}function C(e){let t=document.createElement("script");t.async=!0,t.src=e,t.crossOrigin="anonymous",(document.head||document.documentElement).appendChild(t)}function f(e={}){let t=e.script!==void 0?e.script:document.currentScript,a=t?t.dataset:{},i=a.site;if(!i||window.BFReplay)return Promise.resolve();let p=[],o=!1,s=null,y={version:"loader"};for(let r of g)y[r]=(...n)=>{p.push([r,n]),r==="consent"&&(o=n[0]===!0,o&&s&&s())};if(window.BFReplay=y,M())return Promise.resolve();let d=E(a.api);return(e.fetchFn??fetch)(`${d}${R.ingestConfig}?site=${encodeURIComponent(i)}`,{credentials:"omit"}).then(r=>r.ok?r.json():null).then(r=>{let n=r&&r.enabled?r.recorderUrl:void 0;if(!r||!n)return;let u=r,m=()=>{s=null,window.__bfReplay={config:u,site:i,release:a.release,variant:a.variant,api:d,queue:p},C(n)};u.consentRequired&&!o?s=m:m()}).catch(()=>{})}function _(e=document.currentScript){return!e||!e.dataset.site?Promise.resolve():f({script:e})}typeof document<"u"&&_();return v(O);})();
@@ -0,0 +1,16 @@
1
+ {
2
+ "latest": {
3
+ "version": "2026.11.30",
4
+ "url": "https://cdn.builderforce.ai/replay/r/recorder.efbf70969285.js",
5
+ "hash": "efbf70969285",
6
+ "builtAt": "2026-11-28T22:58:17.542Z"
7
+ },
8
+ "player": {
9
+ "url": "https://cdn.builderforce.ai/replay/r/player.35d774f1c2e0.js",
10
+ "cssUrl": "https://cdn.builderforce.ai/replay/r/player.64d720c3a896.css",
11
+ "rrweb": "2.1.7"
12
+ },
13
+ "pageKit": {
14
+ "url": "https://cdn.builderforce.ai/replay/r/pagekit.ca1bd1d2c19b.js"
15
+ }
16
+ }
@@ -0,0 +1 @@
1
+ "use strict";var BuilderforcePageKit=(()=>{var T=Object.defineProperty;var H=Object.getOwnPropertyDescriptor;var N=Object.getOwnPropertyNames;var w=Object.prototype.hasOwnProperty;var $=(t,r)=>{for(var e in r)T(t,e,{get:r[e],enumerable:!0})},F=(t,r,e,n)=>{if(r&&typeof r=="object"||typeof r=="function")for(let o of N(r))!w.call(t,o)&&o!==e&&T(t,o,{get:()=>r[o],enumerable:!(n=H(r,o))||n.enumerable});return t};var V=t=>F(T({},"__esModule",{value:!0}),t);var q={};$(q,{applyVisualPatch:()=>I,deriveSelector:()=>g,selectorIndex:()=>S});function D(t){let r=t.getAttribute("aria-label");if(r)return r.trim().slice(0,120);let e=(t.textContent??"").replace(/\s+/g," ").trim();return e?e.slice(0,120):(t.getAttribute("title")??t.getAttribute("placeholder")??"").trim().slice(0,120)}function U(t){let r=[],e=t,n=0;for(;e&&n<4&&e.nodeType===1;){let o=e.tagName.toLowerCase();if(e.id){o+=`#${e.id}`,r.unshift(o);break}let i=(e.getAttribute("class")??"").split(/\s+/).filter(Boolean)[0];i&&(o+=`.${i}`),r.unshift(o),e=e.parentElement,n++}return r.join(" > ").slice(0,400)}function g(t){let r=t.getAttribute("data-testid")??t.getAttribute("data-test-id");if(r)return{selector:`getByTestId(${JSON.stringify(r)})`,label:r};let e=t.getAttribute("role")??Y(t),n=D(t);return e&&n?{selector:`getByRole(${JSON.stringify(e)}, { name: ${JSON.stringify(n)} })`,label:n}:n?{selector:`getByText(${JSON.stringify(n)})`,label:n}:{selector:U(t),label:t.tagName.toLowerCase()}}function Y(t){let r=t.tagName.toLowerCase();if(r==="a")return"link";if(r==="button")return"button";if(r==="input"){let e=(t.getAttribute("type")??"text").toLowerCase();return e==="submit"||e==="button"?"button":e==="checkbox"?"checkbox":e==="radio"?"radio":"textbox"}return r==="select"?"combobox":r==="textarea"?"textbox":/^h[1-6]$/.test(r)?"heading":null}var m={maxOps:12,maxText:500,maxAttr:300,maxStyleValue:64,maxHtml:2e3},A=["color","background-color","border-color"],O=["display","flex-direction","flex-wrap","justify-content","align-items","gap","order","text-align","margin","margin-top","margin-right","margin-bottom","margin-left","padding","padding-top","padding-right","padding-bottom","padding-left","width","height","max-width","min-width","min-height","font-size","font-weight","line-height","letter-spacing",...A,"visibility","opacity"],v=["p","span","strong","em","b","i","br","small","ul","ol","li","h2","h3","h4","a","div","section","blockquote"],B=new Set(["br"]),K=new Set(["href","title","aria-label","style"]),h=/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/,G=/^[-a-z0-9.%\s]+$/i,z=/^(#[0-9a-f]{3,8}|rgba?\([\d\s.,%]+\)|hsla?\([\d\s.,%deg]+\))$/i;function R(t){let r=t.trim().toLowerCase().replace(/\s+/g,""),e=/^#([0-9a-f])([0-9a-f])([0-9a-f])$/.exec(r);return e?`#${e[1]}${e[1]}${e[2]}${e[2]}${e[3]}${e[3]}`:r}function E(t,r){let e=t.trim();if(!e||h.test(e)||/^\s*(javascript|data|vbscript):/i.test(e))return!1;if(e.startsWith("#"))return!0;if(e.startsWith("/"))return!e.startsWith("//")&&!e.startsWith("/\\");if(!r)return!1;try{return new URL(e).origin===new URL(r).origin}catch{return!1}}function x(t,r,e){let n=t.trim().toLowerCase();if(!O.includes(n))return`style property "${n}" is not allowed`;let o=r.trim();return!o||o.length>m.maxStyleValue?`style value for "${n}" is empty or too long`:A.includes(n)?e===null?z.test(o)?null:`colour "${o}" is not a colour`:e.has(R(o))?null:`colour "${o}" is not in the page's palette`:G.test(o)?null:`style value "${o}" is not allowed`}function j(t,r){let e=[];for(let n of t.split(";")){if(!n.trim())continue;let o=n.indexOf(":");if(o<=0)return{ok:!1,reason:"a style declaration is malformed"};let i=n.slice(0,o).trim().toLowerCase(),s=n.slice(o+1).trim(),a=x(i,s,r);if(a)return{ok:!1,reason:a};e.push(`${i}: ${s}`)}return{ok:!0,value:e.join("; ")}}var W=t=>t.replace(/&(?![a-z]+;|#\d+;|#x[0-9a-f]+;)/gi,"&amp;").replace(/>/g,"&gt;"),C=t=>t.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),d=/<\/([a-z][a-z0-9]*)\s*>|<([a-z][a-z0-9]*)((?:\s+[^\s"'<>/=]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s"'=<>`]+))?)*)\s*(\/?)>|([^<]+)/giy,k=/([^\s"'<>/=]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))?/g;function _(t,r){if(typeof t!="string"||!t.trim())return{ok:!1,reason:"the inserted HTML is empty"};if(t.length>m.maxHtml)return{ok:!1,reason:"the inserted HTML is too long"};if(h.test(t))return{ok:!1,reason:"the inserted HTML has control characters"};let e=[],n=[];d.lastIndex=0;let o=0;for(;o<t.length;){d.lastIndex=o;let i=d.exec(t);if(!i||i.index!==o)return{ok:!1,reason:"the inserted HTML has markup outside the allow-list"};o=d.lastIndex;let[,s,a,l,M,L]=i;if(L!==void 0){e.push(W(L));continue}if(s!==void 0){let p=s.toLowerCase();if(n.pop()!==p)return{ok:!1,reason:`the inserted HTML closes <${p}> out of order`};e.push(`</${p}>`);continue}let u=(a??"").toLowerCase();if(!v.includes(u))return{ok:!1,reason:`the tag <${u}> is not allowed`};let y=[];k.lastIndex=0;for(let p of(l??"").matchAll(k)){let c=p[1].toLowerCase(),f=p[2]??p[3]??p[4]??"";if(c.startsWith("on"))return{ok:!1,reason:"event handlers are not allowed"};if(!K.has(c)||c==="href"&&u!=="a")return{ok:!1,reason:`the attribute "${c}" is not allowed`};if(h.test(f)||f.length>m.maxAttr)return{ok:!1,reason:`the attribute "${c}" is too long`};if(c==="href"&&!E(f,r.origin))return{ok:!1,reason:"links must stay on this site"};if(c==="style"){let P=j(f,r.palette);if(!P.ok)return P;y.push(`style="${C(P.value)}"`);continue}y.push(`${c}="${C(f)}"`)}let b=`<${u}${y.length?` ${y.join(" ")}`:""}>`;if(B.has(u)){e.push(b);continue}if(M)return{ok:!1,reason:`<${u}/> cannot be self-closing`};e.push(b),n.push(u)}return n.length>0?{ok:!1,reason:`the inserted HTML leaves <${n[n.length-1]}> open`}:{ok:!0,html:e.join("")}}function S(t){let r=new Map,e=t.querySelectorAll("body *");for(let n=0;n<e.length;n++){let o=e[n],{selector:i}=g(o);r.has(i)||r.set(i,o)}return r}function I(t,r,e={}){let n=S(t),o=[],i=0;for(let s of r.ops){let a=n.get(s.selector);if(!a){o.push(s.selector);continue}switch(s.op){case"setText":a.textContent=s.text;break;case"setAttr":a.setAttribute(s.name,s.value);break;case"setStyle":a.style.setProperty(s.property.trim().toLowerCase(),s.value.trim());break;case"hide":a.style.setProperty("display","none");break;case"moveBefore":case"moveAfter":{let l=n.get(s.anchor);if(!l){o.push(s.anchor);continue}s.op==="moveBefore"?l.before(a):l.after(a);break}case"insertAfter":{let l=_(s.html,{palette:null,origin:e.origin??null});if(!l.ok){o.push(s.selector);continue}a.insertAdjacentHTML("afterend",l.html);break}}i+=1}return{applied:i,skipped:o}}return V(q);})();