@spectosh/browser 0.2.4 → 0.3.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/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@spectosh/browser",
3
- "version": "0.2.4",
4
- "description": "Specto session-replay recorder for bundler users — rrweb DOM capture, console/network/error/rage signals, privacy-masked in the browser.",
3
+ "version": "0.3.0",
4
+ "description": "Specto for bundler users — session replay (rrweb DOM capture, console/network/error/rage/dead-click signals, privacy-masked in the browser) and Point, the cursor mode people use to mark what is broken.",
5
5
  "type": "module",
6
6
  "publishConfig": {
7
7
  "access": "public"
@@ -26,6 +26,8 @@
26
26
  "import": "./dist/react.js",
27
27
  "require": "./dist/react.cjs"
28
28
  },
29
+ "./point": "./src/point/index.js",
30
+ "./point-trigger": "./src/point/trigger.js",
29
31
  "./recorder": "./src/recorder.js",
30
32
  "./recorder-worker": "./src/recorder.worker.js",
31
33
  "./destination": {
@@ -45,7 +47,7 @@
45
47
  "test": "node --test \"test/*.test.mjs\" && tsc -p test/types"
46
48
  },
47
49
  "dependencies": {
48
- "rrweb": "^2.1.6"
50
+ "rrweb": "^2.1.7"
49
51
  },
50
52
  "peerDependencies": {
51
53
  "react": ">=17"
@@ -59,8 +61,8 @@
59
61
  "@types/react": "^19.2.0",
60
62
  "react": "^19.2.0",
61
63
  "react-dom": "^19.2.0",
62
- "typescript": "^5.9.3",
63
- "vite": "^8.3.1"
64
+ "typescript": "^7.0.2",
65
+ "vite": "^8.3.4"
64
66
  },
65
67
  "keywords": [
66
68
  "session-replay",
package/src/index.js CHANGED
@@ -15,11 +15,19 @@
15
15
  // Start it before your app renders (your entry file) — capture begins at
16
16
  // once, so the first requests and errors of a page load are in the replay.
17
17
  // React: @spectosh/browser/react.
18
+ //
19
+ // Point, the cursor mode people use to mark what is broken (Settings →
20
+ // Point), comes with it: its gesture opens it, openPoint() opens it from
21
+ // your own UI. Its code is a separate chunk, loaded on first use.
22
+ // startRecording({ …, point: false }) leaves it out.
18
23
  import { startRecording as start, isOptedOut, hasConsent, scrubText, SDK_VERSION } from './recorder.js'
19
24
  import { DEFAULT_HOST, parseKey } from './destination.js'
20
25
  import RecorderWorker from './recorder.worker.js?worker&inline'
26
+ import { installPoint } from './point/trigger.js'
21
27
 
22
28
  let lastOpts = null
29
+ let point = null
30
+ const loadPoint = () => import('./point/index.js')
23
31
 
24
32
  export function startRecording(opts = {}) {
25
33
  if (!opts.key) throw new Error('@spectosh/browser: opts.key is required — your pk_… key from the project\'s Install page')
@@ -27,7 +35,11 @@ export function startRecording(opts = {}) {
27
35
  // a key that names no host belongs to the hosted service — which must
28
36
  // confirm it before anything is sent (an EU or self-hosted key without its
29
37
  // host records nothing rather than reaching the wrong place)
30
- return start({ createWorker: () => new RecorderWorker(), _fallback: DEFAULT_HOST, _guessed: true, ...opts })
38
+ const rec = start({ createWorker: () => new RecorderWorker(), _fallback: DEFAULT_HOST, _guessed: true, ...opts })
39
+ if (opts.point !== false && rec && !rec.disabled && !point) {
40
+ try { point = installPoint(rec, loadPoint, { launcher: opts.launcher }) } catch { /* Point is an extra: the recording goes on */ }
41
+ }
42
+ return rec
31
43
  }
32
44
 
33
45
  const current = () => (typeof window !== 'undefined' ? window.__spectoRec : null)
@@ -35,7 +47,11 @@ export const identify = (id, traits) => current()?.identify(id, traits)
35
47
  export const track = (name, props) => current()?.track(name, props)
36
48
  export const captureError = (error, info) => current()?.captureError?.(error, info)
37
49
  export const sessionUrl = () => current()?.sessionUrl?.() || null
38
- export const stopRecording = () => current()?.stop()
50
+ export const stopRecording = () => { point?.stop(); point = null; current()?.stop() }
51
+ // open Point from your own UI ("Report a problem")
52
+ export const openPoint = (via) => point?.open(via) ?? null
53
+ // the "Report a problem" button on this page: { position, offset: [x, y], label, color }, or false
54
+ export const setLauncher = (o) => point?.launcher(o)
39
55
 
40
56
  // Consent mode: record (and store anything) only after the visitor agreed.
41
57
  export function grantConsent() {
@@ -55,4 +71,4 @@ export function optIn() {
55
71
  }
56
72
 
57
73
  export { isOptedOut, hasConsent, scrubText, parseKey, DEFAULT_HOST, SDK_VERSION }
58
- export default { startRecording, identify, track, captureError, sessionUrl, stopRecording, grantConsent, revokeConsent, optOut, optIn }
74
+ export default { startRecording, identify, track, captureError, sessionUrl, stopRecording, openPoint, setLauncher, grantConsent, revokeConsent, optOut, optIn }
@@ -0,0 +1,61 @@
1
+ // The context a marker carries (VISION.md §4.5), picked from the recorder's
2
+ // short memory (recorder.js → _point.recent()): the requests around the last
3
+ // time the person clicked this element (or the last few seconds when they
4
+ // never did), the console errors and warnings since the page loaded, and the
5
+ // interactions just before. Pure: times in epoch ms, `contains` tells whether
6
+ // a clicked element is the marked one or inside it.
7
+
8
+ const AROUND_BEFORE = 1000
9
+ const AROUND_AFTER = 6000
10
+ const RECENT_MS = 10_000
11
+
12
+ // the last click on (or inside) the marked element, within the last minute
13
+ export function lastClickOn(clicks, contains, now = Date.now()) {
14
+ for (let i = clicks.length - 1; i >= 0; i--) {
15
+ const c = clicks[i]
16
+ if (now - c.at > 60_000) break
17
+ try { if (c.el && contains(c.el)) return c.at } catch { /* detached */ }
18
+ }
19
+ return null
20
+ }
21
+
22
+ export function contextFor({ recent, contains, now = Date.now() }) {
23
+ const clickedAt = lastClickOn(recent.clicks || [], contains, now)
24
+ const [from, to] = clickedAt ? [clickedAt - AROUND_BEFORE, clickedAt + AROUND_AFTER] : [now - RECENT_MS, now]
25
+ const network = (recent.network || [])
26
+ .filter((n) => n.at >= from && n.at <= to)
27
+ .slice(-20)
28
+ .map((n) => ({ at: n.at, method: n.method, url: n.url, status: n.status, dur: n.dur, ...(n.error ? { error: true } : {}) }))
29
+ const console = (recent.console || [])
30
+ .filter((c) => c.level === 'error' || c.level === 'warn')
31
+ .slice(-15)
32
+ .map((c) => ({ at: c.at, level: c.level, text: c.text }))
33
+ // JS errors are events, not console lines: they belong here too
34
+ const errors = (recent.event || [])
35
+ .filter((e) => e.type === 'error')
36
+ .slice(-5)
37
+ .map((e) => ({ at: e.at, level: 'error', text: e.message, stack: e.stack }))
38
+ const events = (recent.event || [])
39
+ .filter((e) => ['click', 'nav', 'rage', 'dead', 'custom'].includes(e.type) && e.at <= now && now - e.at < 120_000)
40
+ .slice(-15)
41
+ .map((e) => ({ at: e.at, type: e.type, target: e.sel || e.target || null, path: e.path || null, name: e.name || null }))
42
+ return { network, console: [...console, ...errors].sort((a, b) => a.at - b.at).slice(-20), events, clickedAt }
43
+ }
44
+
45
+ // where the person is: browser, OS, device class, locale, preferences
46
+ export function environment() {
47
+ const ua = navigator.userAgent || ''
48
+ const w = window.innerWidth
49
+ const touch = (navigator.maxTouchPoints || 0) > 0
50
+ const mq = (q) => { try { return window.matchMedia(q).matches } catch { return false } }
51
+ return {
52
+ browser: ua.slice(0, 200),
53
+ os: /Windows/.test(ua) ? 'Windows' : /Mac OS X|Macintosh/.test(ua) ? (touch ? 'iPadOS' : 'macOS') : /Android/.test(ua) ? 'Android' : /iPhone|iPad|iOS/.test(ua) ? 'iOS' : /Linux/.test(ua) ? 'Linux' : null,
54
+ device: w < 640 ? 'phone' : w < 1024 && touch ? 'tablet' : 'desktop',
55
+ locale: navigator.language || null,
56
+ tz: (() => { try { return Intl.DateTimeFormat().resolvedOptions().timeZone } catch { return null } })(),
57
+ reducedMotion: mq('(prefers-reduced-motion: reduce)'),
58
+ colorScheme: mq('(prefers-color-scheme: dark)') ? 'dark' : 'light',
59
+ viewport: { w, h: window.innerHeight },
60
+ }
61
+ }
@@ -0,0 +1,241 @@
1
+ // What Point knows about an element (VISION.md §4.5): ways to find it again
2
+ // (selectors), the component and file it comes from when the framework says,
3
+ // a readable name, where it sits (breadcrumb), its state, the styles that
4
+ // usually explain a bug, and a masked snapshot of its markup. Masking follows
5
+ // the recording's rules: inputs never give their value, `specto-mask` and
6
+ // strict privacy hide text, sensitive attributes are dropped.
7
+ import { scrubText } from '../scrub.js'
8
+
9
+ const TEST_ATTRS = ['data-testid', 'data-test', 'data-test-id', 'data-cy', 'data-qa']
10
+ const STYLE_KEYS = ['display', 'visibility', 'opacity', 'pointerEvents', 'zIndex', 'overflow', 'cursor', 'color', 'background']
11
+ const KEEP_ATTRS = new Set(['id', 'class', 'role', 'type', 'name', 'href', 'disabled', 'aria-disabled', 'aria-expanded', 'aria-busy', 'aria-hidden', 'aria-pressed', 'aria-selected', 'aria-checked', 'for', 'data-specto-src', ...TEST_ATTRS])
12
+ const VOID = new Set(['area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'link', 'meta', 'source', 'track', 'wbr'])
13
+
14
+ const esc = (s) => String(s).replace(/\\/g, '\\\\').replace(/"/g, '\\"')
15
+ const tagOf = (el) => String(el?.tagName || '').toLowerCase()
16
+ const attr = (el, k) => { try { return el.getAttribute(k) } catch { return null } }
17
+
18
+ // an id a build or library generated is no way to find the element again
19
+ export const stableId = (id) => Boolean(id) && id.length <= 64 && !/\d{4,}|^:|:r\w*:|^(ember|react|radix|headlessui|mui|rc|el)[-_:]?\d/i.test(id) && /^[A-Za-z][\w-]*$/.test(id)
20
+ const stableClass = (c) => c && !c.startsWith('specto-') && c.length <= 40 && !/\d{3,}|^(css|sc|jsx|emotion|tw)-|__[A-Za-z0-9]{5,}$|^[a-z0-9]{6,}$/i.test(c)
21
+
22
+ export function isMasked(el, strict) {
23
+ if (strict) return true
24
+ for (let n = el; n && n.nodeType === 1; n = n.parentElement) {
25
+ if (n.classList?.contains('specto-mask') || n.classList?.contains('specto-block')) return true
26
+ }
27
+ const t = tagOf(el)
28
+ return t === 'input' || t === 'textarea' || t === 'select' || attr(el, 'contenteditable') === 'true'
29
+ }
30
+
31
+ function testIdOf(el) {
32
+ for (const a of TEST_ATTRS) { const v = attr(el, a); if (v) return [a, v] }
33
+ return null
34
+ }
35
+
36
+ // one level of a CSS path: tag#id, tag[data-testid], tag.class, or with
37
+ // :nth-of-type when siblings share it
38
+ function step(el) {
39
+ const tag = tagOf(el)
40
+ const id = el.id
41
+ if (stableId(id)) return { sel: `${tag}#${id}`, anchor: true }
42
+ const tid = testIdOf(el)
43
+ if (tid) return { sel: `${tag}[${tid[0]}="${esc(tid[1])}"]`, anchor: true }
44
+ const cls = typeof el.className === 'string' ? el.className.trim().split(/\s+/).filter(stableClass).slice(0, 2) : []
45
+ let sel = cls.length ? `${tag}.${cls.join('.')}` : tag
46
+ const parent = el.parentElement
47
+ if (parent) {
48
+ const same = Array.from(parent.children || []).filter((c) => tagOf(c) === tag)
49
+ if (same.length > 1) sel += `:nth-of-type(${same.indexOf(el) + 1})`
50
+ }
51
+ return { sel, anchor: false }
52
+ }
53
+
54
+ export function cssPath(el, max = 5) {
55
+ const parts = []
56
+ for (let n = el, i = 0; n && n.nodeType === 1 && i < max && tagOf(n) !== 'html' && tagOf(n) !== 'body'; n = n.parentElement, i++) {
57
+ const s = step(n)
58
+ parts.unshift(s.sel)
59
+ if (s.anchor) break
60
+ }
61
+ return parts.join(' > ') || tagOf(el) || 'body'
62
+ }
63
+
64
+ // the accessible-ish name: what a person would call it
65
+ export function accessibleName(el, masked) {
66
+ const label = attr(el, 'aria-label') || attr(el, 'title') || attr(el, 'alt')
67
+ if (label && !masked) return scrubText(label).trim().slice(0, 80)
68
+ const labelledBy = attr(el, 'aria-labelledby')
69
+ if (labelledBy && !masked) {
70
+ try { const t = document.getElementById(labelledBy)?.textContent; if (t) return scrubText(t).trim().slice(0, 80) } catch { /* no document */ }
71
+ }
72
+ if (masked) return ''
73
+ const text = (el.innerText ?? el.textContent ?? '').replace(/\s+/g, ' ').trim()
74
+ return scrubText(text).slice(0, 80)
75
+ }
76
+
77
+ export function roleOf(el) {
78
+ const r = attr(el, 'role')
79
+ if (r) return r
80
+ const t = tagOf(el)
81
+ if (t === 'a' && attr(el, 'href') != null) return 'link'
82
+ if (t === 'button' || (t === 'input' && ['submit', 'button', 'reset'].includes(attr(el, 'type')))) return 'button'
83
+ if (t === 'input') return attr(el, 'type') === 'checkbox' ? 'checkbox' : attr(el, 'type') === 'radio' ? 'radio' : 'textbox'
84
+ if (t === 'select') return 'combobox'
85
+ if (t === 'textarea') return 'textbox'
86
+ if (/^h[1-6]$/.test(t)) return 'heading'
87
+ if (t === 'img') return 'img'
88
+ return null
89
+ }
90
+
91
+ // several ways to find it, best first
92
+ export function selectorsOf(el, { masked } = {}) {
93
+ const out = []
94
+ const tid = testIdOf(el)
95
+ if (tid) out.push(`[${tid[0]}="${esc(tid[1])}"]`)
96
+ if (stableId(el.id)) out.push(`#${el.id}`)
97
+ const role = roleOf(el)
98
+ const name = accessibleName(el, masked)
99
+ if (role && name && name.length <= 40) out.push(`role=${role}[name="${esc(name)}"]`)
100
+ out.push(cssPath(el))
101
+ return [...new Set(out)].slice(0, 6)
102
+ }
103
+
104
+ // The component the element belongs to, and the file when the build says:
105
+ // React (fiber), Vue 3, Svelte, or the Specto build plugin's data-specto-src.
106
+ export function componentOf(el) {
107
+ let source = null
108
+ for (let n = el; n && n.nodeType === 1 && !source; n = n.parentElement) source = attr(n, 'data-specto-src')
109
+ // React: the fiber hangs off the DOM node under a randomised key
110
+ const fiberKey = el && Object.keys(el).find((k) => k.startsWith('__reactFiber$') || k.startsWith('__reactInternalInstance$'))
111
+ if (fiberKey) {
112
+ for (let f = el[fiberKey], i = 0; f && i < 60; f = f.return, i++) {
113
+ const type = f.type
114
+ if (!type || typeof type === 'string') continue
115
+ const name = type.displayName || type.name || type.render?.displayName || type.render?.name || type.type?.displayName || type.type?.name
116
+ if (name && /^[A-Z]/.test(name) && !/^(Fragment|Suspense|StrictMode|Profiler|Provider|Consumer|Context)/.test(name)) {
117
+ const ds = f._debugSource
118
+ if (!source && ds?.fileName) source = `${String(ds.fileName).replace(/^.*?\/(src|app|pages|components)\//, '$1/')}:${ds.lineNumber}`
119
+ return { component: name.slice(0, 120), source }
120
+ }
121
+ }
122
+ }
123
+ // Vue 3
124
+ for (let n = el, i = 0; n && i < 20; n = n.parentElement, i++) {
125
+ const c = n.__vueParentComponent
126
+ if (c) {
127
+ const name = c.type?.name || c.type?.__name || (c.type?.__file && String(c.type.__file).split('/').pop().replace(/\.vue$/, ''))
128
+ if (name) return { component: name, source: source || (c.type?.__file ? String(c.type.__file).replace(/^.*?\/src\//, 'src/') : null) }
129
+ }
130
+ const svelte = n.__svelte_meta
131
+ if (svelte?.loc?.file) return { component: String(svelte.loc.file).split('/').pop().replace(/\.svelte$/, ''), source: source || `${svelte.loc.file}:${svelte.loc.line}` }
132
+ }
133
+ return { component: null, source }
134
+ }
135
+
136
+ // where it sits: the closest landmarks and headings, outermost first
137
+ export function breadcrumbOf(el) {
138
+ const out = []
139
+ for (let n = el.parentElement, i = 0; n && n.nodeType === 1 && i < 25 && out.length < 6; n = n.parentElement, i++) {
140
+ const t = tagOf(n)
141
+ if (t === 'body' || t === 'html') break
142
+ const role = attr(n, 'role')
143
+ const label = attr(n, 'aria-label')
144
+ if (['main', 'nav', 'header', 'footer', 'aside', 'form', 'dialog', 'section', 'table'].includes(t) || ['dialog', 'navigation', 'form', 'region', 'tabpanel', 'menu'].includes(role) || stableId(n.id) || testIdOf(n)) {
145
+ out.unshift(`${t}${stableId(n.id) ? `#${n.id}` : ''}${label ? `[${scrubText(label).slice(0, 30)}]` : ''}`)
146
+ }
147
+ }
148
+ return out
149
+ }
150
+
151
+ export function stateOf(el) {
152
+ const s = {}
153
+ const t = tagOf(el)
154
+ if (el.disabled === true || attr(el, 'aria-disabled') === 'true') s.disabled = true
155
+ else if (['button', 'input', 'select', 'textarea'].includes(t)) s.disabled = false
156
+ if (t === 'input' && ['checkbox', 'radio'].includes(attr(el, 'type'))) s.checked = Boolean(el.checked)
157
+ const exp = attr(el, 'aria-expanded')
158
+ if (exp != null) s.expanded = exp === 'true'
159
+ if (attr(el, 'aria-busy') === 'true') s.busy = true
160
+ return Object.keys(s).length ? s : undefined
161
+ }
162
+
163
+ export function stylesOf(el) {
164
+ try {
165
+ const cs = getComputedStyle(el)
166
+ const out = {}
167
+ for (const k of STYLE_KEYS) {
168
+ const v = k === 'background' ? cs.backgroundColor : cs[k]
169
+ if (v != null && v !== '') out[k] = String(v).slice(0, 80)
170
+ }
171
+ return out
172
+ } catch { return {} }
173
+ }
174
+
175
+ // a compact, masked snapshot of the element's markup (agents read it)
176
+ export function snapshotOf(el, { strict = false, maxNodes = 60, maxDepth = 4, maxChars = 4000 } = {}) {
177
+ let nodes = 0
178
+ const walk = (n, depth, masked) => {
179
+ if (nodes++ > maxNodes) return '…'
180
+ if (n.nodeType === 3) {
181
+ const t = String(n.textContent || '').replace(/\s+/g, ' ')
182
+ if (!t.trim()) return t ? ' ' : ''
183
+ return masked ? t.replace(/\S/g, '•').slice(0, 60) : scrubText(t).slice(0, 120).replace(/</g, '&lt;')
184
+ }
185
+ if (n.nodeType !== 1) return ''
186
+ const tag = tagOf(n)
187
+ if (['script', 'style', 'noscript', 'template', 'svg'].includes(tag)) return tag === 'svg' ? '<svg/>' : ''
188
+ const m = masked || isMasked(n, strict)
189
+ const attrs = []
190
+ for (const a of Array.from(n.attributes || [])) {
191
+ if (!KEEP_ATTRS.has(a.name)) continue
192
+ let v = a.value
193
+ if (a.name === 'href') { try { v = new URL(v, location.href).pathname } catch { v = '' } }
194
+ if (a.name === 'class') v = v.split(/\s+/).filter((c) => c && !c.startsWith('specto-')).slice(0, 4).join(' ')
195
+ attrs.push(v === '' ? a.name : `${a.name}="${scrubText(v).slice(0, 80).replace(/"/g, '&quot;')}"`)
196
+ }
197
+ if (tag === 'input') attrs.push('value="[masked]"')
198
+ const open = `<${tag}${attrs.length ? ' ' + attrs.join(' ') : ''}>`
199
+ if (VOID.has(tag)) return open
200
+ if (depth >= maxDepth) return `${open}…</${tag}>`
201
+ let inner = ''
202
+ for (const c of Array.from(n.childNodes || [])) {
203
+ inner += walk(c, depth + 1, m)
204
+ if (inner.length > maxChars) break
205
+ }
206
+ return `${open}${inner}</${tag}>`
207
+ }
208
+ return walk(el, 0, isMasked(el, strict)).slice(0, maxChars)
209
+ }
210
+
211
+ // the chip next to the cursor: component › test id › selector
212
+ export function chipOf(el, d) {
213
+ const tid = testIdOf(el)
214
+ return [d.component, tid ? tid[1] : null, d.name || tagOf(el)].filter(Boolean).slice(0, 2).join(' › ') || tagOf(el)
215
+ }
216
+
217
+ // everything at once, for a marker
218
+ export function describe(el, { strict = false } = {}) {
219
+ const masked = isMasked(el, strict)
220
+ const { component, source } = componentOf(el)
221
+ const name = accessibleName(el, masked)
222
+ const role = roleOf(el)
223
+ let rect = null
224
+ try { const r = el.getBoundingClientRect(); rect = { x: Math.round(r.left), y: Math.round(r.top), w: Math.round(r.width), h: Math.round(r.height) } } catch { /* detached */ }
225
+ const d = {
226
+ tag: tagOf(el),
227
+ role,
228
+ label: masked ? null : (attr(el, 'aria-label') ? scrubText(attr(el, 'aria-label')).slice(0, 120) : null),
229
+ name: name ? `${name}${role ? ` ${role}` : ''}` : (role || tagOf(el)),
230
+ component,
231
+ source,
232
+ selectors: selectorsOf(el, { masked }),
233
+ path: breadcrumbOf(el),
234
+ rect,
235
+ text: masked ? null : (name || null),
236
+ state: stateOf(el),
237
+ styles: stylesOf(el),
238
+ snapshot: snapshotOf(el, { strict }),
239
+ }
240
+ return d
241
+ }