@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.
@@ -0,0 +1,198 @@
1
+ // Point's trigger (VISION.md §4.4) — the only part of Point in the base SDK.
2
+ // It waits for the project's settings, decides whether this visitor may use
3
+ // Point at all, and on the configured gesture loads the rest (./index.js) and
4
+ // opens it. Everything else loads on first use.
5
+ //
6
+ // Modes (Settings → Point):
7
+ // double-ctrl tap Ctrl (⌘ on a Mac also works) twice quickly — the default
8
+ // hold-alt hold Alt / Option alone for 400 ms
9
+ // hold-ctrl hold Ctrl alone for 400 ms
10
+ // chord Alt+Shift+P
11
+ // custom the project's own combination ({ key, alt, ctrl, shift, meta })
12
+ // none no gesture: the launcher, links and Specto.point() only
13
+ // A modifier that is part of a shortcut (Ctrl+C), a click (Ctrl+click opens
14
+ // a tab) or a key repeat never arms. Who: 'everyone', 'identified' (people
15
+ // the host app identified, plus link holders) or 'link' (only people who
16
+ // opened a page with ?specto=point — remembered for the browser tab).
17
+
18
+ const HOLD_MS = 400
19
+ const TAP_MS = 250 // a tap is shorter than this
20
+ const DOUBLE_MS = 330 // and the second follows within this (release to release)
21
+ const QUIET_MS = 300 // no other key just before the first tap: it is not mid-typing
22
+ const GAP_MIN_MS = 40 // a real double tap has a gap; key chatter does not
23
+ const LINK_KEY = 'specto-point'
24
+ const RECEIPTS = 'specto-point-receipts' // entry.js keeps them: [{ r, at }]
25
+ const CHECK_MS = 6e5 // ask about them at most every 10 minutes
26
+
27
+ // The gesture state machine, DOM-free so it can be tested on its own.
28
+ // feed(event) takes { type: 'keydown'|'keyup'|'pointerdown'|'wheel'|'blur', key,
29
+ // code, repeat, altKey, ctrlKey, metaKey, shiftKey, time } and calls arm()
30
+ // when the gesture completes; release() when a held trigger is let go.
31
+ // the modifier an event is about: by `key`, else by `code` (some synthetic
32
+ // and remote-desktop events carry only one of them)
33
+ const CODE_KEY = { ControlLeft: 'Control', ControlRight: 'Control', AltLeft: 'Alt', AltRight: 'Alt', MetaLeft: 'Meta', MetaRight: 'Meta' }
34
+ const keyOf = (e) => e.key || CODE_KEY[e.code] || ''
35
+
36
+ // a combination matches on the physical key (Alt changes e.key on a Mac);
37
+ // the settings send the chord's too ({ key: 'P', alt: true, shift: true })
38
+ const combo = (e, s) => !!s && !!e.altKey === !!s.alt && !!e.shiftKey === !!s.shift && !!e.ctrlKey === !!s.ctrl && !!e.metaKey === !!s.meta
39
+ && String(e.code || e.key).replace(/^(Key|Digit)/, '').toUpperCase() === s.key
40
+
41
+ export function createTrigger(mode, { arm, release = () => {}, now = () => Date.now(), setTimer = setTimeout, clearTimer = clearTimeout, shortcut } = {}) {
42
+ const holdKey = mode === 'hold-alt' ? 'Alt' : mode === 'hold-ctrl' ? 'Control' : null
43
+ let timer = null
44
+ let holding = false // the hold completed and Point was armed by it
45
+ let down = null // { key, at } the lone modifier pressed, nothing else since
46
+ let lastTap = 0
47
+ let lastOther = -Infinity // the last key that was not the tap key
48
+ const cancel = () => { if (timer) clearTimer(timer); timer = null; down = null }
49
+ const isTapKey = (k) => k === 'Control' || k === 'Meta'
50
+ return {
51
+ feed(raw) {
52
+ const e = { ...raw, key: keyOf(raw) }
53
+ const t = e.time ?? now()
54
+ if (e.type === 'blur') { cancel(); lastTap = 0; if (holding) { holding = false; release() } return }
55
+ if (e.type === 'pointerdown' || e.type === 'wheel') { cancel(); lastTap = 0; return } // modifier+click / Ctrl+wheel zoom are the app's
56
+ if (e.type === 'keydown') {
57
+ if (e.repeat) return
58
+ if (shortcut || mode === 'none') {
59
+ if (combo(e, shortcut)) arm(mode)
60
+ return
61
+ }
62
+ if (holdKey) {
63
+ if (e.key === holdKey && !down) {
64
+ down = { key: e.key, at: t }
65
+ timer = setTimer(() => { timer = null; if (down) { down = null; holding = true; arm(mode) } }, HOLD_MS)
66
+ } else cancel() // another key: a shortcut
67
+ return
68
+ }
69
+ // double-ctrl
70
+ if (isTapKey(e.key) && !down) down = { key: e.key, at: t, quiet: t - lastOther >= QUIET_MS }
71
+ else { down = null; lastTap = 0; lastOther = t }
72
+ return
73
+ }
74
+ if (e.type === 'keyup') {
75
+ if (holdKey) {
76
+ if (e.key === holdKey) { cancel(); if (holding) { holding = false; release() } }
77
+ return
78
+ }
79
+ if (mode === 'double-ctrl' && down && e.key === down.key) {
80
+ const d = down
81
+ down = null
82
+ if (t - d.at >= TAP_MS) { lastTap = 0; return }
83
+ // the second tap: soon after the first, but not chatter
84
+ if (lastTap && t - lastTap < DOUBLE_MS && d.at - lastTap >= GAP_MIN_MS) { lastTap = 0; arm('double-ctrl'); return }
85
+ // a first tap counts only when nothing else was being typed
86
+ lastTap = d.quiet ? t : 0
87
+ }
88
+ }
89
+ },
90
+ cancel,
91
+ }
92
+ }
93
+
94
+ // a report this browser sent asked to hear when it's fixed (entry.js keeps
95
+ // the receipts): ask, now and then; a fixed one shows its note once
96
+ function fixedYet(rec, load, open) {
97
+ try {
98
+ const t = Date.now()
99
+ const list = JSON.parse(localStorage.getItem(RECEIPTS) || '[]').filter((x) => t - x.at < 7776e6)
100
+ if (!list.length || t - (+localStorage.getItem(RECEIPTS + '-at') || 0) < CHECK_MS) return
101
+ localStorage.setItem(RECEIPTS + '-at', t)
102
+ fetch(rec._point.endpoint + '-status', { method: 'POST', headers: { 'Content-Type': 'text/plain;charset=UTF-8' }, credentials: 'omit', body: JSON.stringify({ key: rec._point.key, receipts: list.map((x) => x.r) }) })
103
+ .then((r) => (r.ok ? r.json() : null))
104
+ .then((j) => {
105
+ if (!j) return
106
+ const done = [...(j.gone || []), ...(j.fixed || []).map((x) => x.receipt)]
107
+ localStorage.setItem(RECEIPTS, JSON.stringify(list.filter((x) => !done.includes(x.r))))
108
+ if (j.fixed?.length) load().then((m) => m.showFixed?.(j.fixed, { open }))
109
+ }).catch(() => {})
110
+ } catch { /* storage off */ }
111
+ }
112
+
113
+ // may this visitor use Point? (the project's `who`)
114
+ export function allowed(who, { identified, link }) {
115
+ if (who === 'everyone') return true
116
+ if (who === 'link') return link
117
+ return link || Boolean(identified) // 'identified' (default): identified people and link holders
118
+ }
119
+
120
+ // ?specto=point (or #…specto=point) anywhere in the address
121
+ function linkGranted() {
122
+ try {
123
+ if (/[?&#]specto=point\b/.test(location.href)) sessionStorage.setItem(LINK_KEY, '1')
124
+ return sessionStorage.getItem(LINK_KEY) === '1'
125
+ } catch { return false }
126
+ }
127
+
128
+ // Wire the trigger to a running recorder. load() → Promise<{ openPoint,
129
+ // mountEntry }>. Returns { open(via), stop() } — open() is the host app's own
130
+ // entry point (Specto.point()): it skips the gesture and the `who` check,
131
+ // since the app chose to offer it. A ?specto=point link opens Point on
132
+ // arrival; the launcher, the nudge and the reminder (VISION.md §4.10) live
133
+ // in point.js, loaded on idle once this visitor may use Point. `launcher`:
134
+ // the page's own say over the launcher (false: none here; { position,
135
+ // offset, label, color } over Settings → Point) — also launcher() later.
136
+ export function installPoint(rec, load, { launcher } = {}) {
137
+ let cfg = null
138
+ let session = null // the open Point, while it is open
139
+ let opening = null
140
+ let entry = null // the launcher, nudge and reminder, once mounted
141
+ let mount = null // mounts them once this visitor may use Point
142
+ const may = () => allowed(cfg.who, { identified: rec._point?.identified(), link: linkGranted() })
143
+ const open = async (via = 'api', target = null, about = null) => {
144
+ if (session || opening || !rec?._point) return session
145
+ opening = (async () => {
146
+ const remote = await rec._ready
147
+ cfg = remote?.point || cfg
148
+ if (!cfg?.enabled) return null
149
+ const mod = await load()
150
+ session = mod.openPoint(rec, { ...cfg, via, target, about, onClose: () => { session = null } })
151
+ return session
152
+ })().catch((e) => { try { console.warn('[specto] Point:', e?.message || e) } catch { /* no console */ } return null }).finally(() => { opening = null })
153
+ return opening
154
+ }
155
+ let trigger = null
156
+ const onKey = (e) => {
157
+ // keys typed into Point itself (its notes) are its own
158
+ if (session && e.composedPath?.().some((n) => n?.id === 'specto-point')) return
159
+ trigger?.feed({ type: e.type, key: e.key, code: e.code, repeat: e.repeat, altKey: e.altKey, ctrlKey: e.ctrlKey, metaKey: e.metaKey, shiftKey: e.shiftKey })
160
+ }
161
+ const feed = (type) => () => trigger?.feed({ type })
162
+ // [target, event, handler, options]
163
+ const L = [[window, 'keydown', onKey, true], [window, 'keyup', onKey, true], [window, 'pointerdown', feed('pointerdown'), true], [window, 'wheel', feed('wheel'), { capture: true, passive: true }], [window, 'blur', feed('blur')]]
164
+ let listening = false
165
+ rec._ready?.then((remote) => {
166
+ cfg = remote?.point || null
167
+ if (!cfg?.enabled) return
168
+ linkGranted() // remember ?specto=point for the tab, whatever page it was on
169
+ // who may use it is checked at each gesture: identify() can come later
170
+ trigger = createTrigger(cfg.trigger, {
171
+ shortcut: cfg.shortcut,
172
+ arm: () => {
173
+ if (!may()) return
174
+ if (session) session.toggle?.()
175
+ else open('shortcut')
176
+ },
177
+ release: () => session?.released?.(),
178
+ })
179
+ for (const [t, ev, fn, o] of L) t.addEventListener(ev, fn, o)
180
+ listening = true
181
+ // a link from the "fixed" email carries #specto-about=<receipt>
182
+ const about = (location.hash.match(/specto-about=([\w-]{20,40})/) || [])[1]
183
+ if (/[?&#]specto=point\b/.test(location.href)) open(about ? 'fixed' : 'link', null, about)
184
+ if (cfg.notify) fixedYet(rec, load, open)
185
+ mount = () => { if (listening && !entry) may() ? load().then((m) => { entry = entry || m.mountEntry?.(rec, cfg, { open, may, local: launcher }) }) : setTimeout(mount, 2000) }
186
+ if ((cfg.launcher && launcher !== false) || launcher || cfg.nudge || cfg.hint || (cfg.context && cfg.context !== 'off')) setTimeout(mount, 600)
187
+ })
188
+ return {
189
+ open: (via) => open(via || 'api'),
190
+ launcher(o) { launcher = o; entry ? entry.launcher(o) : o && mount?.() },
191
+ stop() {
192
+ if (listening) for (const [t, ev, fn, o] of L) t.removeEventListener(ev, fn, o)
193
+ listening = false
194
+ session?.close?.()
195
+ entry?.stop?.()
196
+ },
197
+ }
198
+ }
@@ -0,0 +1,131 @@
1
+ // Talking while pointing (VISION.md §4.6). Only when the instance can
2
+ // transcribe and the project left voice on (the settings say `voice: true`),
3
+ // and only after the person agrees — the first time the rail explains it and
4
+ // the browser asks for the microphone.
5
+ //
6
+ // Live, phrase by phrase: the microphone feeds one MediaRecorder per phrase.
7
+ // A phrase ends at a pause (quiet for PAUSE_MS after speech), when the
8
+ // person moves to another marker (cut()), or at MAX_PHRASE_MS; each finished
9
+ // phrase is a complete little file handed to onPhrase, which the rail sends
10
+ // to the instance's transcription service — the words come back in about a
11
+ // second and land on the marker that was current. Phrases with no speech in
12
+ // them are dropped unsent. The Web Speech API is never used: it sends audio
13
+ // to a party no one chose.
14
+ //
15
+ // `keep` also records the whole thing in one file, for a project that lets
16
+ // people attach their recording (30 days, then purged — speech.js).
17
+ // `level()` reads the loudness (0..1) for the pulsing ring.
18
+
19
+ const TYPES = ['audio/webm;codecs=opus', 'audio/ogg;codecs=opus', 'audio/mp4', 'audio/webm']
20
+ const SPEAKING = 0.08 // level that counts as speech (the room's hum stays near 0.02)
21
+ const PAUSE_MS = 700
22
+ const MAX_PHRASE_MS = 20_000
23
+ export const voiceSupported = () => typeof window !== 'undefined' && typeof window.MediaRecorder !== 'undefined' && Boolean(navigator.mediaDevices?.getUserMedia)
24
+
25
+ export async function startVoice({ onPhrase = () => {}, keep = false } = {}) {
26
+ const stream = await navigator.mediaDevices.getUserMedia({ audio: { channelCount: 1, echoCancellation: true, noiseSuppression: true } })
27
+ const mimeType = TYPES.find((t) => { try { return MediaRecorder.isTypeSupported(t) } catch { return false } }) || ''
28
+ const opts = { ...(mimeType ? { mimeType } : {}), audioBitsPerSecond: 16_000 } // speech: Whisper hears 16 kHz anyway — ~2 KB/s
29
+ const startedAt = Date.now()
30
+ // loudness: for the ring and for finding pauses
31
+ let analyser = null
32
+ let ctx = null
33
+ let data = null
34
+ try {
35
+ const AC = window.AudioContext || window.webkitAudioContext
36
+ ctx = new AC()
37
+ const src = ctx.createMediaStreamSource(stream)
38
+ analyser = ctx.createAnalyser()
39
+ analyser.fftSize = 1024 // ~20 ms a look: short syllables are not missed
40
+ data = new Uint8Array(analyser.fftSize)
41
+ src.connect(analyser)
42
+ } catch { /* no pauses found: phrases end at marker changes and MAX_PHRASE_MS */ }
43
+ const level = () => {
44
+ if (!analyser) return 0
45
+ analyser.getByteTimeDomainData(data)
46
+ let sum = 0
47
+ for (const v of data) sum += (v - 128) * (v - 128)
48
+ return Math.min(1, Math.sqrt(sum / data.length) / 40)
49
+ }
50
+
51
+ // ---- phrases ------------------------------------------------------------------
52
+ let phrase = null // { rec, chunks, at, spoke, loudAt }
53
+ let closing = false
54
+ const begin = () => {
55
+ if (closing) return
56
+ const rec = new MediaRecorder(stream, opts)
57
+ const p = { rec, chunks: [], at: Date.now(), spoke: !analyser, loudAt: 0 }
58
+ rec.ondataavailable = (e) => { if (e.data?.size) p.chunks.push(e.data) }
59
+ rec.start()
60
+ phrase = p
61
+ }
62
+ // end the current phrase → Promise (resolves once it was handed over)
63
+ const end = () => new Promise((resolve) => {
64
+ const p = phrase
65
+ phrase = null
66
+ if (!p) return resolve()
67
+ p.rec.onstop = () => {
68
+ if (p.spoke && p.chunks.length) {
69
+ const mime = p.rec.mimeType || mimeType || 'audio/webm'
70
+ try { onPhrase({ blob: new Blob(p.chunks, { type: mime }), mime, startedAt: p.at, endedAt: Date.now() }) } catch { /* the rail's problem */ }
71
+ }
72
+ resolve()
73
+ }
74
+ try { p.rec.stop() } catch { resolve() }
75
+ })
76
+ // a new phrase from now: what follows belongs to the marker that is current
77
+ // now, even if nothing was said yet (end() drops a phrase without speech)
78
+ const cut = () => { if (phrase) { end(); begin() } }
79
+ begin()
80
+ const timer = setInterval(() => {
81
+ if (!phrase) return
82
+ const now = Date.now()
83
+ if (analyser && level() >= SPEAKING) { phrase.spoke = true; phrase.loudAt = now }
84
+ if (phrase.spoke && ((phrase.loudAt && now - phrase.loudAt > PAUSE_MS) || now - phrase.at > MAX_PHRASE_MS)) cut()
85
+ }, 50)
86
+
87
+ // ---- the whole recording, when it may be kept ------------------------------------
88
+ let whole = null
89
+ if (keep) {
90
+ whole = { rec: new MediaRecorder(stream, opts), chunks: [] }
91
+ whole.rec.ondataavailable = (e) => { if (e.data?.size) whole.chunks.push(e.data) }
92
+ whole.rec.start(1000)
93
+ }
94
+
95
+ let stopped = null
96
+ // → { blob, mime, startedAt } of the whole recording when kept, else null;
97
+ // the last phrase is handed over first, and the tracks are released
98
+ const stop = () => {
99
+ if (stopped) return stopped
100
+ closing = true
101
+ clearInterval(timer)
102
+ stopped = (async () => {
103
+ await end()
104
+ let out = null
105
+ if (whole) {
106
+ out = await new Promise((resolve) => {
107
+ const mime = whole.rec.mimeType || mimeType || 'audio/webm'
108
+ const done = () => resolve({ blob: new Blob(whole.chunks, { type: mime }), mime, startedAt })
109
+ if (whole.rec.state === 'inactive') return done()
110
+ whole.rec.onstop = done
111
+ try { whole.rec.stop() } catch { done() }
112
+ })
113
+ }
114
+ for (const t of stream.getTracks()) t.stop()
115
+ try { ctx?.close() } catch { /* already closed */ }
116
+ return out
117
+ })()
118
+ return stopped
119
+ }
120
+ return { startedAt, level, cut, stop }
121
+ }
122
+
123
+ // a Blob → base64 (reports and phrases travel as JSON bodies)
124
+ export function base64Of(blob) {
125
+ return new Promise((resolve, reject) => {
126
+ const r = new FileReader()
127
+ r.onload = () => resolve(String(r.result).split(',')[1] || '')
128
+ r.onerror = () => reject(r.error)
129
+ r.readAsDataURL(blob)
130
+ })
131
+ }
package/src/react.js CHANGED
@@ -15,7 +15,7 @@
15
15
  // records the page, not a component). On the server it renders its children
16
16
  // and does nothing else. React is a peer dependency.
17
17
  import { Component, createContext, createElement, useContext, useEffect, useState } from 'react'
18
- import { startRecording, identify, track, captureError, sessionUrl, stopRecording, grantConsent, revokeConsent, optOut, optIn } from './index.js'
18
+ import { startRecording, identify, track, captureError, sessionUrl, stopRecording, grantConsent, revokeConsent, optOut, optIn, openPoint } from './index.js'
19
19
 
20
20
  const api = { identify, track, captureError, sessionUrl, stop: stopRecording, grantConsent, revokeConsent, optOut, optIn }
21
21
  const SpectoContext = createContext(api)
@@ -63,8 +63,14 @@ export class SpectoErrorBoundary extends Component {
63
63
  render() {
64
64
  const { error } = this.state
65
65
  if (!error) return this.props.children
66
- const { fallback } = this.props
67
- return typeof fallback === 'function' ? fallback({ error, reset: this.reset }) : (fallback ?? null)
66
+ const { fallback, reportButton } = this.props
67
+ // reportButton: a "Show us what happened" button under the fallback that
68
+ // opens Point (VISION.md §4.10) — true for ours, or a string for its label
69
+ const report = () => openPoint('error')
70
+ const shown = typeof fallback === 'function' ? fallback({ error, reset: this.reset, report }) : (fallback ?? null)
71
+ if (!reportButton) return shown
72
+ const button = createElement('button', { type: 'button', onClick: report, 'data-specto-report': '' }, typeof reportButton === 'string' ? reportButton : 'Show us what happened')
73
+ return createElement('div', null, shown, button)
68
74
  }
69
75
  }
70
76
 
package/src/recorder.js CHANGED
@@ -12,6 +12,10 @@
12
12
  // requests; the request's trace id links it to the server's spans
13
13
  // - heatmaps: each click's page position and a selector (tag, id,
14
14
  // classes — never text), and how far down each page view scrolled
15
+ // - dead clicks: a click on something that looks clickable and does
16
+ // nothing — no DOM change, request or navigation within a second
17
+ // - for Point (the cursor mode, ./point/): a short in-memory memory of
18
+ // recent requests, console lines and clicks — never sent by itself
15
19
  //
16
20
  // Starts capturing the moment startRecording runs: errors, console, network
17
21
  // and the DOM are held in memory while the project's settings load (one
@@ -27,13 +31,16 @@
27
31
  // only the path of recorded URLs;
28
32
  // `specto-mask` / `specto-block` classes for fine control; sensitive
29
33
  // attributes, URL credentials and PII-looking text are scrubbed in the
30
- // browser. Honors Do-Not-Track / Global Privacy Control, an opt-out flag, and
31
- // consent mode (nothing is recorded or stored until Specto.consent(true)).
34
+ // browser. Honors an opt-out flag, Do-Not-Track / Global Privacy Control when
35
+ // the project or the page asks (Brave sends GPC on every page, so honoring it
36
+ // by default would hide every Brave visitor), and consent mode (nothing is
37
+ // recorded or stored until Specto.consent(true)).
32
38
  import { record } from 'rrweb'
33
39
  import { createUploader } from './uploader.js'
34
40
  import { resolveDestination } from './destination.js'
41
+ import { scrubText } from './scrub.js'
35
42
 
36
- export const SDK_VERSION = '0.2.4'
43
+ export const SDK_VERSION = '0.3.0'
37
44
 
38
45
  // ---- privacy helpers --------------------------------------------------------
39
46
  // Attribute scrubbing — rrweb masks text/inputs but NOT element attributes,
@@ -65,20 +72,7 @@ function scrubEvent(e, strict) {
65
72
  return e
66
73
  }
67
74
 
68
- // Free text the app itself produces (console lines, error messages) can carry
69
- // PII. Redact the shapes that are never useful for debugging.
70
- const TEXT_SCRUBBERS = [
71
- [/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/gi, '[email]'],
72
- [/\beyJ[\w-]{6,}\.[\w-]{6,}\.[\w-]{6,}\b/g, '[jwt]'],
73
- [/\b(Bearer|Basic)\s+[\w.~+/=-]{8,}/gi, '$1 [token]'],
74
- [/\b(?:\d[ -]?){13,19}\b/g, '[number]'], // card / account numbers
75
- [/\b(sk|pk|rk)_(live|test)_[\w]{8,}\b/g, '[key]'],
76
- ]
77
- export function scrubText(s) {
78
- let out = String(s ?? '')
79
- for (const [re, rep] of TEXT_SCRUBBERS) out = out.replace(re, rep)
80
- return out
81
- }
75
+ export { scrubText }
82
76
 
83
77
  // ---- network capture helpers ------------------------------------------------
84
78
  // fetch() accepts a string, a URL (has .href, NOT .url), a Request (has .url),
@@ -259,6 +253,9 @@ async function remoteConfig(url, key) {
259
253
  * configUrl project config URL (default: endpoint's /api/sdk/config; false = none)
260
254
  * privacy 'balanced' | 'strict' (strict masks all text, drops console text and URL query strings)
261
255
  * sampleRate 0..1 — fraction of sessions recorded (decided once per session)
256
+ * privacySignals 'respect' never records visitors whose browser sends
257
+ * Do-Not-Track or Global Privacy Control; by default the
258
+ * project's setting decides (Settings → Privacy & masking)
262
259
  * consent 'granted' (default) | 'required' (wait for Specto.consent(true))
263
260
  * console capture console (default true)
264
261
  * networkDetails devtools-style request details (default true)
@@ -266,6 +263,8 @@ async function remoteConfig(url, key) {
266
263
  * backend spans join the replay (default false)
267
264
  * traceOrigins more origins to send it to, e.g. ['https://api.example.com']
268
265
  * (their CORS must allow the traceparent header)
266
+ * release your build's version (a git SHA or tag): bugs know the release that
267
+ * introduced them (also <meta name="specto-release"> or data-release)
269
268
  * createWorker () => Worker (the snippet/npm builds pass an inlined worker)
270
269
  */
271
270
  export function startRecording(opts = {}) {
@@ -280,14 +279,17 @@ export function startRecording(opts = {}) {
280
279
  const { key, endpoint, configUrl } = dest
281
280
 
282
281
  const handle = { disabled: true, reason: 'starting', sessionId: null, stop() {}, flushNow() {}, count: () => 0, identify() {}, track() {}, sessionUrl: () => null }
283
- if (navigator.doNotTrack === '1' || navigator.globalPrivacyControl) return Object.assign(handle, { reason: 'dnt' })
282
+ // Do-Not-Track / GPC: honored here when the page asks; otherwise once the
283
+ // project's setting arrives (_begin) — nothing is sent before it does
284
+ const signal = navigator.doNotTrack === '1' || navigator.globalPrivacyControl === true
285
+ if (signal && opts.privacySignals === 'respect') return Object.assign(handle, { reason: 'dnt' })
284
286
  if (isOptedOut()) return Object.assign(handle, { reason: 'opted-out' })
285
287
  if (opts.consent === 'required' && !hasConsent()) return Object.assign(handle, { reason: 'consent-required' })
286
288
 
287
289
  // capture starts now; it's sent once the project config resolves (one
288
290
  // edge-cached request). A host the SDK assumed must confirm the key first:
289
291
  // a couple of retries, then nothing is recorded on this page.
290
- const api = createRecorder(opts, dest)
292
+ const api = createRecorder(opts, dest, signal)
291
293
  window.__spectoRec = api
292
294
  const confirm = (attempt) => remoteConfig(configUrl, key).then((remote) => {
293
295
  if (remote?.failed && dest.guessed && attempt < 3) return setTimeout(() => confirm(attempt + 1), attempt * 2000)
@@ -303,7 +305,7 @@ const warn = (msg) => { try { console.warn(`[specto] ${msg}`) } catch { /* no co
303
305
  // DOM limit the replay restarts from a fresh snapshot instead
304
306
  const EARLY_MAX = { dom: 4000, console: 200, network: 300, event: 300, identify: 20 }
305
307
 
306
- function createRecorder(opts, dest) {
308
+ function createRecorder(opts, dest, signal = false) {
307
309
  const { key, endpoint } = dest
308
310
  let buffer = []
309
311
  let total = 0
@@ -320,6 +322,8 @@ function createRecorder(opts, dest) {
320
322
  const local = { strict: opts.privacy === 'strict', console: opts.console !== false, networkDetails: opts.networkDetails !== false }
321
323
  let cfg = null
322
324
  const now = () => cfg || local
325
+ // the page an error or rage click happened on (sessions span page loads)
326
+ const herePath = () => { try { return scrubUrl(location.pathname, now().strict).slice(0, 300) } catch { return undefined } }
323
327
  let viewChanged = () => {} // heatmaps: a new path is a new page view (set once recording begins)
324
328
  const seen = typeof WeakSet !== 'undefined' ? new WeakSet() : null // errors already reported (boundary + window)
325
329
  let worker = null
@@ -330,6 +334,26 @@ function createRecorder(opts, dest) {
330
334
  let unconfirmed = []
331
335
  let mainUploader = null
332
336
  let lastActive = Date.now()
337
+ // epoch ms of the recorder's clock origin: payload `t` + this = when
338
+ const epoch0 = Date.now() - (performance.now() - t0)
339
+ const release = releaseOf(opts)
340
+
341
+ // Point's memory (never sent by itself): the last few requests, console
342
+ // lines and interactions with their times, and the elements last clicked
343
+ // (kept as references only, to find the requests a click caused)
344
+ const recent = { network: [], console: [], event: [], clicks: [] }
345
+ const RECENT_MAX = { network: 100, console: 60, event: 80, clicks: 40 }
346
+ const remember = (kind, p) => {
347
+ const list = recent[kind]
348
+ if (!list || !p || typeof p !== 'object') return
349
+ list.push({ ...p, at: Math.round(epoch0 + (Number(p.t) || 0)) })
350
+ if (list.length > RECENT_MAX[kind]) list.shift()
351
+ }
352
+ let netSeen = 0 // requests and errors so far (a dead click watches it stay put)
353
+ let identified = null
354
+ let pointOn = false // Point is open: its clicks are not the app's
355
+ let readyResolve
356
+ const ready = new Promise((r) => { readyResolve = r })
333
357
 
334
358
  // everything captured before recording begins (the project's settings are
335
359
  // still loading): kept in memory, sent once it does — filtered by those
@@ -339,6 +363,7 @@ function createRecorder(opts, dest) {
339
363
  let domOverflow = false
340
364
  const push = (kind, payload) => {
341
365
  if (stopped) return
366
+ if (kind !== 'dom') { remember(kind, payload); if (kind === 'network' || payload?.type === 'error') netSeen++ }
342
367
  if (!started) {
343
368
  const n = (earlyCount[kind] = (earlyCount[kind] || 0) + 1)
344
369
  if (n > (EARLY_MAX[kind] ?? 100)) { if (kind === 'dom') domOverflow = true; return }
@@ -376,7 +401,7 @@ function createRecorder(opts, dest) {
376
401
 
377
402
  function send(events) {
378
403
  if (!events.length || !session?.sampled) return
379
- const item = { b: session.b++, json: JSON.stringify({ key, sessionId: session.id, ...(session.sk ? { sk: session.sk } : {}), b: session.b - 1, sdk: SDK_VERSION, meta: { page: scrubUrl(location.pathname), userAgent: navigator.userAgent, visitorId: visitorId() }, events }) }
404
+ const item = { b: session.b++, json: JSON.stringify({ key, sessionId: session.id, ...(session.sk ? { sk: session.sk } : {}), b: session.b - 1, sdk: SDK_VERSION, meta: { page: scrubUrl(location.pathname), userAgent: navigator.userAgent, visitorId: visitorId(), ...(release ? { release } : {}) }, events }) }
380
405
  session.active = Math.max(session.active, lastActive)
381
406
  persist()
382
407
  if (worker) {
@@ -441,7 +466,8 @@ function createRecorder(opts, dest) {
441
466
  // attach your own user id (+ a few flat traits) to the current session
442
467
  identify(id, traits) {
443
468
  if (id == null || id === '') return
444
- push('identify', { id: String(id).slice(0, 256), traits: traits && typeof traits === 'object' ? traits : undefined })
469
+ identified = String(id).slice(0, 256)
470
+ push('identify', { id: identified, traits: traits && typeof traits === 'object' ? traits : undefined })
445
471
  },
446
472
  // custom product events, searchable on the session timeline
447
473
  track(name, props) {
@@ -457,13 +483,26 @@ function createRecorder(opts, dest) {
457
483
  const component = info?.componentStack
458
484
  ? scrubText(String(info.componentStack)).split('\n').map((l) => l.trim()).filter(Boolean).slice(0, 8).join('\n').slice(0, 800)
459
485
  : undefined
460
- push('event', { t: rel(), type: 'error', message, ...(stack ? { stack } : {}), ...(component ? { component } : {}), ...(info?.source ? { source: String(info.source).slice(0, 40) } : {}) })
486
+ push('event', { t: rel(), type: 'error', message, path: herePath(), ...(stack ? { stack } : {}), ...(component ? { component } : {}), ...(info?.source ? { source: String(info.source).slice(0, 40) } : {}) })
461
487
  },
462
488
  sessionUrl() {
463
489
  try { return session ? `${dest.host || new URL(endpoint, location.href).origin}/#replay/${session.id}` : null } catch { return null }
464
490
  },
491
+ // ---- for Point (./point/) ----
492
+ // resolves with the project's settings once they arrive (null: never)
493
+ _ready: ready,
494
+ _point: {
495
+ key,
496
+ endpoint: endpoint.replace(/\/api\/ingest$/, '/api/point'),
497
+ release,
498
+ strict: () => now().strict,
499
+ identified: () => identified,
500
+ recent: () => ({ network: recent.network.slice(), console: recent.console.slice(), event: recent.event.slice(), clicks: recent.clicks.slice() }),
501
+ active: (on) => { pointOn = Boolean(on) },
502
+ },
465
503
  stop(reason) {
466
504
  if (stopped) return
505
+ readyResolve(null)
467
506
  stopped = true
468
507
  api.disabled = true
469
508
  api.reason = reason || 'stopped'
@@ -488,7 +527,10 @@ function createRecorder(opts, dest) {
488
527
  api.stop('unconfirmed')
489
528
  return warn(`couldn't reach ${where} to confirm the key ${key}, so this page isn't recorded.`)
490
529
  }
491
- if (r.enabled === false) return api.stop('recording-disabled')
530
+ if (r.enabled === false) { readyResolve(null); return api.stop('recording-disabled') }
531
+ // a privacy signal the project honors — or one we couldn't ask about
532
+ if (signal && (r.respectPrivacySignals === true || r.failed)) return api.stop('dnt')
533
+ readyResolve(r)
492
534
  cfg = {
493
535
  strict: opts.privacy === 'strict' || r.privacy === 'strict',
494
536
  console: opts.console !== false && r.captureConsole !== false,
@@ -718,7 +760,7 @@ function createRecorder(opts, dest) {
718
760
  const onError = (e) => {
719
761
  const err = e.error || e.reason
720
762
  const stack = framesOf(err?.stack)
721
- const payload = { t: rel(), type: 'error', message: scrubText(String(e.message || err?.message || e.reason || 'error')).slice(0, 500), ...(stack ? { stack } : {}) }
763
+ const payload = { t: rel(), type: 'error', message: scrubText(String(e.message || err?.message || e.reason || 'error')).slice(0, 500), path: herePath(), ...(stack ? { stack } : {}) }
722
764
  setTimeout(() => {
723
765
  if (err && typeof err === 'object' && seen) { if (seen.has(err)) return; seen.add(err) }
724
766
  push('event', payload)
@@ -769,12 +811,13 @@ function createRecorder(opts, dest) {
769
811
  // ---- rage clicks (>=3 clicks within 800ms near same spot) ----
770
812
  let clicks = []
771
813
  const onClick = (e) => {
814
+ if (pointOn) return
772
815
  const now = performance.now()
773
816
  clicks = clicks.filter((c) => now - c.t < 800 && Math.abs(c.x - e.clientX) < 40 && Math.abs(c.y - e.clientY) < 40)
774
817
  clicks.push({ t: now, x: e.clientX, y: e.clientY })
775
818
  if (clicks.length >= 3) {
776
819
  const sel = e.target?.tagName ? e.target.tagName.toLowerCase() + (e.target.id ? '#' + e.target.id : '') : 'element'
777
- push('event', { t: rel(), type: 'rage', target: sel.slice(0, 80), count: clicks.length })
820
+ push('event', { t: rel(), type: 'rage', target: sel.slice(0, 80), count: clicks.length, path: herePath() })
778
821
  clicks = []
779
822
  }
780
823
  }
@@ -807,10 +850,34 @@ function createRecorder(opts, dest) {
807
850
  requestAnimationFrame(() => { scrollPending = false; measure() })
808
851
  }
809
852
  const onHeatClick = (e) => {
853
+ if (pointOn) return
854
+ recent.clicks.push({ at: Date.now(), el: e.target })
855
+ if (recent.clicks.length > RECENT_MAX.clicks) recent.clicks.shift()
856
+ watchDead(e)
810
857
  if (!view || view.clicks >= 300) return
811
858
  view.clicks++
812
859
  push('event', { t: rel(), type: 'click', path: view.path, pv: view.id, x: Math.round(e.pageX), y: Math.round(e.pageY), vw: window.innerWidth, dh: docHeight(), sel: selectorOf(e.target) })
813
860
  }
861
+ // ---- dead clicks: something that looks clickable, clicked, and for a
862
+ // second nothing — no DOM change, no request, no navigation (and no
863
+ // error: then the error is the bug)
864
+ let deadWatch = null
865
+ const watchDead = (e) => {
866
+ const t = e.target
867
+ const el = t?.closest?.('a,button,[role=button],[role=link],[role=tab],[onclick],[type=submit],summary') || (t?.nodeType === 1 && cursorIsPointer(t) ? t : null)
868
+ if (!el || deadWatch || typeof MutationObserver === 'undefined') return
869
+ const net0 = netSeen
870
+ const href = location.href
871
+ let changed = false
872
+ const mo = new MutationObserver(() => { changed = true })
873
+ try { mo.observe(document.documentElement, { subtree: true, childList: true, attributes: true, characterData: true }) } catch { return }
874
+ deadWatch = setTimeout(() => {
875
+ mo.disconnect()
876
+ deadWatch = null
877
+ if (!changed && netSeen === net0 && location.href === href && !pointOn) push('event', { t: rel(), type: 'dead', target: selectorOf(el), path: herePath() })
878
+ }, 1000)
879
+ }
880
+ restore.push(() => { if (deadWatch) clearTimeout(deadWatch) })
814
881
  window.addEventListener('scroll', onScroll, { passive: true, capture: true })
815
882
  window.addEventListener('click', onHeatClick, true)
816
883
  restore.push(() => { window.removeEventListener('scroll', onScroll, { capture: true }); window.removeEventListener('click', onHeatClick, true) })
@@ -847,12 +914,14 @@ const randomHex = (bytes) => {
847
914
  }
848
915
  const TRACEPARENT = /^00-([0-9a-f]{32})-[0-9a-f]{16}-[0-9a-f]{2}$/i
849
916
 
850
- // a click's target as tag#id or tag.class.class, up to 3 levels below
851
- // <body> — never text
917
+ // a click's target as tag[data-testid], tag#id or tag.class.class, up to 3
918
+ // levels below <body> — never text
852
919
  function selectorOf(el) {
853
920
  const parts = []
854
921
  for (let n = el, i = 0; n && n.nodeType === 1 && i < 3 && n !== document.body && n !== document.documentElement; n = n.parentElement, i++) {
855
922
  const tag = String(n.tagName || '').toLowerCase()
923
+ const tid = n.getAttribute('data-testid')
924
+ if (tid) { parts.unshift(`[data-testid="${tid}"]`); break }
856
925
  if (n.id) { parts.unshift(`${tag}#${n.id}`); break }
857
926
  const cls = typeof n.className === 'string' ? n.className.trim().split(/\s+/).filter((c) => c && !c.startsWith('specto-')).slice(0, 2) : []
858
927
  parts.unshift(cls.length ? `${tag}.${cls.join('.')}` : tag)
@@ -860,6 +929,17 @@ function selectorOf(el) {
860
929
  return scrubText(parts.join(' > ') || 'body').slice(0, 160)
861
930
  }
862
931
 
932
+ // the customer's release: the option, or <meta name="specto-release"
933
+ // content="…"> (the snippet passes data-release as the option)
934
+ function releaseOf(opts) {
935
+ let r = opts.release
936
+ try { if (!r) r = document.querySelector('meta[name="specto-release"]')?.getAttribute('content') } catch { /* no document */ }
937
+ return r ? String(r).trim().slice(0, 80) || null : null
938
+ }
939
+ function cursorIsPointer(el) {
940
+ try { return getComputedStyle(el).cursor === 'pointer' } catch { return false }
941
+ }
942
+
863
943
  function fmt(a) {
864
944
  if (typeof a === 'string') return a
865
945
  if (a instanceof Error) return `${a.name}: ${a.message}`