@spectosh/browser 0.2.2 → 0.2.4

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/src/recorder.js CHANGED
@@ -13,6 +13,12 @@
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
15
  //
16
+ // Starts capturing the moment startRecording runs: errors, console, network
17
+ // and the DOM are held in memory while the project's settings load (one
18
+ // edge-cached request that also confirms the key), then filtered by those
19
+ // settings and sent — or dropped, if the project is sampled out, disabled or
20
+ // unknown at that host. Nothing leaves the page before that answer.
21
+ //
16
22
  // Sessions: one visitor's continuous activity, kept across page loads in
17
23
  // sessionStorage; a new session starts after 30 minutes without interaction
18
24
  // or after 4 hours. Batches are numbered so the server de-duplicates retries.
@@ -25,8 +31,9 @@
25
31
  // consent mode (nothing is recorded or stored until Specto.consent(true)).
26
32
  import { record } from 'rrweb'
27
33
  import { createUploader } from './uploader.js'
34
+ import { resolveDestination } from './destination.js'
28
35
 
29
- export const SDK_VERSION = '0.2.2'
36
+ export const SDK_VERSION = '0.2.4'
30
37
 
31
38
  // ---- privacy helpers --------------------------------------------------------
32
39
  // Attribute scrubbing — rrweb masks text/inputs but NOT element attributes,
@@ -151,10 +158,11 @@ function bodySize(b) {
151
158
  }
152
159
 
153
160
  // Best-effort devtools-grade phases from PerformanceResourceTiming.
154
- function attachTiming(payload, absUrl, startedAt) {
161
+ function attachTiming(payload, absUrl, startedAt, wanted = () => true) {
155
162
  if (typeof performance === 'undefined' || !performance.getEntriesByName) return
156
163
  setTimeout(() => {
157
164
  try {
165
+ if (!wanted()) return // the project's settings turned request details off
158
166
  let best = null
159
167
  for (const e of performance.getEntriesByName(absUrl, 'resource')) {
160
168
  const gap = Math.abs(e.startTime - startedAt)
@@ -224,8 +232,9 @@ const SESSION_MAX_MS = 4 * 3600_000
224
232
  const WORKER_READY_MS = 4000
225
233
 
226
234
  // Remote project config (Settings → Privacy & masking), edge-cacheable. The
227
- // STRICTER of local and remote settings always wins; failures fall back to
228
- // the local options (the server enforces privacy settings again at ingest).
235
+ // STRICTER of local and remote settings always wins. It also confirms the
236
+ // key: { unknownKey } when that host has no such project, { failed } when it
237
+ // couldn't be asked (the server enforces privacy settings again at ingest).
229
238
  async function remoteConfig(url, key) {
230
239
  if (!url) return null
231
240
  try {
@@ -233,14 +242,20 @@ async function remoteConfig(url, key) {
233
242
  const t = ctrl && setTimeout(() => ctrl.abort(), 3000)
234
243
  const res = await fetch(`${url}?key=${encodeURIComponent(key)}`, { credentials: 'omit', signal: ctrl?.signal })
235
244
  if (t) clearTimeout(t)
236
- return res.ok ? await res.json() : null
237
- } catch { return null }
245
+ if (res.ok) return await res.json()
246
+ let body = null
247
+ try { body = await res.json() } catch { /* not ours */ }
248
+ return res.status === 404 && body?.error === 'unknown key' ? { unknownKey: true } : { failed: true }
249
+ } catch { return { failed: true } }
238
250
  }
239
251
 
240
252
  /**
241
253
  * startRecording(opts) → api
242
- * key (required) publishable project key
243
- * endpoint ingest URL (default /api/ingest)
254
+ * key (required) publishable project key — `pk_…`, or `pk_…@host` for
255
+ * an EU-region or self-hosted project (destination.js)
256
+ * host where the project lives, overriding the key's (e.g. your
257
+ * own domain proxying to Specto)
258
+ * endpoint full ingest URL (legacy; overrides host)
244
259
  * configUrl project config URL (default: endpoint's /api/sdk/config; false = none)
245
260
  * privacy 'balanced' | 'strict' (strict masks all text, drops console text and URL query strings)
246
261
  * sampleRate 0..1 — fraction of sessions recorded (decided once per session)
@@ -257,24 +272,39 @@ export function startRecording(opts = {}) {
257
272
  if (typeof window === 'undefined') return { disabled: true, reason: 'no window', stop() {} }
258
273
  // idempotency: never run two recorders (and two upload workers) at once
259
274
  if (window.__spectoRec && !window.__spectoRec.disabled) return window.__spectoRec
260
- if (!opts.key) throw new Error('Specto: a publishable key is required')
261
- const key = String(opts.key)
262
- const endpoint = opts.endpoint || '/api/ingest'
263
- const configUrl = opts.configUrl === false ? null : (opts.configUrl || String(endpoint).replace(/\/api\/ingest$/, '/api/sdk/config'))
275
+ // _fallback/_guessed: the host the entry point assumes when neither the
276
+ // options nor the key name one (npm: the hosted service; script tag: the
277
+ // origin that served it)
278
+ const dest = resolveDestination(opts, { fallback: opts._fallback || null, guessed: Boolean(opts._guessed) })
279
+ if (!dest.key) throw new Error('Specto: a publishable key is required — copy it from your project\'s Install page')
280
+ const { key, endpoint, configUrl } = dest
264
281
 
265
282
  const handle = { disabled: true, reason: 'starting', sessionId: null, stop() {}, flushNow() {}, count: () => 0, identify() {}, track() {}, sessionUrl: () => null }
266
283
  if (navigator.doNotTrack === '1' || navigator.globalPrivacyControl) return Object.assign(handle, { reason: 'dnt' })
267
284
  if (isOptedOut()) return Object.assign(handle, { reason: 'opted-out' })
268
285
  if (opts.consent === 'required' && !hasConsent()) return Object.assign(handle, { reason: 'consent-required' })
269
286
 
270
- // start after the project config resolves (one edge-cached request)
271
- const api = createRecorder(opts, key, endpoint)
287
+ // capture starts now; it's sent once the project config resolves (one
288
+ // edge-cached request). A host the SDK assumed must confirm the key first:
289
+ // a couple of retries, then nothing is recorded on this page.
290
+ const api = createRecorder(opts, dest)
272
291
  window.__spectoRec = api
273
- remoteConfig(configUrl, key).then((remote) => api._begin(remote)).catch(() => api._begin(null))
292
+ const confirm = (attempt) => remoteConfig(configUrl, key).then((remote) => {
293
+ if (remote?.failed && dest.guessed && attempt < 3) return setTimeout(() => confirm(attempt + 1), attempt * 2000)
294
+ api._begin(remote)
295
+ })
296
+ confirm(1)
274
297
  return api
275
298
  }
276
299
 
277
- function createRecorder(opts, key, endpoint) {
300
+ const warn = (msg) => { try { console.warn(`[specto] ${msg}`) } catch { /* no console */ } }
301
+
302
+ // what may be held before the project's settings arrive, per kind; past the
303
+ // DOM limit the replay restarts from a fresh snapshot instead
304
+ const EARLY_MAX = { dom: 4000, console: 200, network: 300, event: 300, identify: 20 }
305
+
306
+ function createRecorder(opts, dest) {
307
+ const { key, endpoint } = dest
278
308
  let buffer = []
279
309
  let total = 0
280
310
  let started = false
@@ -285,7 +315,13 @@ function createRecorder(opts, key, endpoint) {
285
315
  const rel = () => Math.round(performance.now() - t0)
286
316
  const sessKey = `specto-session:${key}`
287
317
  let session = null // { id, sk, b, started, active, sampled }
318
+ // the page's own settings apply until the project's arrive (then the
319
+ // stricter of both); `now()` is whichever is in force
320
+ const local = { strict: opts.privacy === 'strict', console: opts.console !== false, networkDetails: opts.networkDetails !== false }
288
321
  let cfg = null
322
+ const now = () => cfg || local
323
+ let viewChanged = () => {} // heatmaps: a new path is a new page view (set once recording begins)
324
+ const seen = typeof WeakSet !== 'undefined' ? new WeakSet() : null // errors already reported (boundary + window)
289
325
  let worker = null
290
326
  let workerReady = false
291
327
  // batches handed to the worker before it said it runs: a Content Security
@@ -295,13 +331,20 @@ function createRecorder(opts, key, endpoint) {
295
331
  let mainUploader = null
296
332
  let lastActive = Date.now()
297
333
 
298
- // identify/track called before recording begins (the project's settings
299
- // are still loading — e.g. identify() right after startRecording()) are
300
- // kept and sent once it does; dropped if it never starts
334
+ // everything captured before recording begins (the project's settings are
335
+ // still loading): kept in memory, sent once it does — filtered by those
336
+ // settings — and dropped if it never starts
301
337
  const early = []
338
+ const earlyCount = {}
339
+ let domOverflow = false
302
340
  const push = (kind, payload) => {
303
341
  if (stopped) return
304
- if (!started) { if (early.length < 50) early.push([kind, payload]); return }
342
+ if (!started) {
343
+ const n = (earlyCount[kind] = (earlyCount[kind] || 0) + 1)
344
+ if (n > (EARLY_MAX[kind] ?? 100)) { if (kind === 'dom') domOverflow = true; return }
345
+ early.push([kind, payload])
346
+ return
347
+ }
305
348
  buffer.push({ kind, payload })
306
349
  total++
307
350
  opts.onUpdate?.({ total, kind })
@@ -405,8 +448,19 @@ function createRecorder(opts, key, endpoint) {
405
448
  if (!name) return
406
449
  push('event', { t: rel(), type: 'custom', name: String(name).slice(0, 120), props: props && typeof props === 'object' ? JSON.parse(JSON.stringify(props, (k, v) => (typeof v === 'string' ? scrubText(v).slice(0, 500) : v))) : undefined })
407
450
  },
451
+ // an error the app caught itself — React error boundaries and root error
452
+ // handlers (react.js) — as an error signal; reported once per error
453
+ captureError(error, info) {
454
+ if (error && typeof error === 'object' && seen) { if (seen.has(error)) return; seen.add(error) }
455
+ const message = scrubText(String((error && error.message) || error || 'error')).slice(0, 500)
456
+ const stack = framesOf(error?.stack)
457
+ const component = info?.componentStack
458
+ ? scrubText(String(info.componentStack)).split('\n').map((l) => l.trim()).filter(Boolean).slice(0, 8).join('\n').slice(0, 800)
459
+ : undefined
460
+ push('event', { t: rel(), type: 'error', message, ...(stack ? { stack } : {}), ...(component ? { component } : {}), ...(info?.source ? { source: String(info.source).slice(0, 40) } : {}) })
461
+ },
408
462
  sessionUrl() {
409
- try { return session ? `${new URL(endpoint, location.href).origin}/#replay/${session.id}` : null } catch { return null }
463
+ try { return session ? `${dest.host || new URL(endpoint, location.href).origin}/#replay/${session.id}` : null } catch { return null }
410
464
  },
411
465
  stop(reason) {
412
466
  if (stopped) return
@@ -425,6 +479,15 @@ function createRecorder(opts, key, endpoint) {
425
479
  _begin(remote) {
426
480
  if (stopped || started) return
427
481
  const r = remote && typeof remote === 'object' ? remote : {}
482
+ const where = dest.host || endpoint
483
+ if (r.unknownKey) {
484
+ api.stop('unknown-key')
485
+ return warn(`${where} has no project with the key ${key}, so nothing is recorded. Copy the key from the project's Install page${dest.guessed ? ' — a self-hosted or EU-region project includes its host: pk_…@your-host' : ''}.`)
486
+ }
487
+ if (r.failed && dest.guessed) {
488
+ api.stop('unconfirmed')
489
+ return warn(`couldn't reach ${where} to confirm the key ${key}, so this page isn't recorded.`)
490
+ }
428
491
  if (r.enabled === false) return api.stop('recording-disabled')
429
492
  cfg = {
430
493
  strict: opts.privacy === 'strict' || r.privacy === 'strict',
@@ -434,8 +497,17 @@ function createRecorder(opts, key, endpoint) {
434
497
  }
435
498
  const resumed = openSession(false)
436
499
  if (!session.sampled) return api.stop('not-sampled')
500
+ // what was captured early follows the project's settings: masked where
501
+ // they're stricter, dropped where they turn a capture off — and the DOM
502
+ // starts over from a fresh snapshot when its masking must change
503
+ const stricter = cfg.strict && !local.strict
504
+ const freshDom = stricter || domOverflow
437
505
  started = true
438
- for (const [kind, payload] of early.splice(0)) push(kind, payload)
506
+ for (const [kind, payload] of early.splice(0)) {
507
+ const kept = settle(kind, payload, stricter, freshDom)
508
+ if (kept) push(kind, kept)
509
+ }
510
+ if (freshDom) { try { stopDom?.() } catch { /* already stopped */ } stopDom = startDom() }
439
511
 
440
512
  try {
441
513
  worker = opts.createWorker ? opts.createWorker() : null
@@ -453,47 +525,58 @@ function createRecorder(opts, key, endpoint) {
453
525
  } catch { worker = null }
454
526
  if (!worker) mainUploader = createUploader({ endpoint, onEvent: onUploader })
455
527
 
456
- instrument(resumed)
528
+ instrumentSession(resumed)
457
529
  const timer = setInterval(handoff, 2000)
458
530
  restore.push(() => clearInterval(timer))
459
531
  },
460
532
  }
461
533
 
462
- // resumed: this page load continues a session started on an earlier page
463
- function instrument(resumed) {
464
- // ---- DOM via rrweb ----
465
- stopDom = record({
466
- emit: (e) => push('dom', scrubEvent(e, cfg.strict)),
534
+ // the replay's DOM capture, masked by the settings in force
535
+ function startDom() {
536
+ const strict = now().strict
537
+ return record({
538
+ emit: (e) => push('dom', scrubEvent(e, now().strict)),
467
539
  maskAllInputs: true,
468
540
  maskInputOptions: { password: true, email: true, tel: true, color: false },
469
541
  maskTextClass: 'specto-mask',
470
- maskTextSelector: cfg.strict ? '*' : undefined,
542
+ maskTextSelector: strict ? '*' : undefined,
471
543
  blockClass: 'specto-block',
472
544
  recordCanvas: false,
473
545
  collectFonts: false,
474
546
  checkoutEveryNms: 5 * 60_000,
475
547
  sampling: { mousemove: 50, scroll: 150, input: 'last' },
476
548
  })
549
+ }
477
550
 
478
- // ---- activity → session liveness; idle past the timeout → new session
479
- const bump = () => {
480
- const now = Date.now()
481
- if (now - lastActive > SESSION_IDLE_MS) { lastActive = now; rotate(); return }
482
- lastActive = now
483
- }
484
- for (const ev of ['click', 'keydown', 'scroll', 'pointerdown']) {
485
- window.addEventListener(ev, bump, { capture: true, passive: true })
486
- restore.push(() => window.removeEventListener(ev, bump, { capture: true }))
551
+ // an early capture under the project's settings: null drops it
552
+ function settle(kind, p, stricter, freshDom) {
553
+ if (kind === 'dom') return freshDom ? null : p
554
+ if (!p || typeof p !== 'object') return p
555
+ if (kind === 'console') {
556
+ if (!cfg.console) return null
557
+ if (stricter) p.text = '[masked]'
558
+ } else if (kind === 'network') {
559
+ if (stricter && p.url) p.url = scrubUrl(p.url, true)
560
+ if (!cfg.networkDetails) delete p.detail
561
+ } else if (kind === 'event' && p.type === 'nav' && stricter && p.path) {
562
+ p.path = scrubUrl(p.path, true).slice(0, 300)
487
563
  }
564
+ return p
565
+ }
566
+
567
+ // ---- from the first moment: DOM, console, network, errors, navigations
568
+ function capture() {
569
+ // ---- DOM via rrweb ----
570
+ stopDom = startDom()
488
571
 
489
572
  // ---- console ----
490
- if (cfg.console) {
573
+ if (local.console) {
491
574
  for (const level of ['log', 'info', 'warn', 'error']) {
492
575
  const orig = console[level]
493
576
  console[level] = (...args) => {
494
577
  try {
495
578
  // strict privacy: keep the signal (a warning/error happened), not its text
496
- push('console', { t: rel(), level, text: cfg.strict ? '[masked]' : scrubText(args.map(fmt).join(' ')).slice(0, 2000) })
579
+ if (now().console) push('console', { t: rel(), level, text: now().strict ? '[masked]' : scrubText(args.map(fmt).join(' ')).slice(0, 2000) })
497
580
  } catch { /* never break the app */ }
498
581
  orig.apply(console, args)
499
582
  }
@@ -502,13 +585,16 @@ function createRecorder(opts, key, endpoint) {
502
585
  }
503
586
 
504
587
  // ---- network: fetch ----
505
- if (cfg.networkDetails) { try { performance.setResourceTimingBufferSize?.(1000) } catch { /* older engines */ } }
588
+ if (local.networkDetails) { try { performance.setResourceTimingBufferSize?.(1000) } catch { /* older engines */ } }
589
+ const details = () => now().networkDetails
506
590
  const origFetch = window.fetch
507
- // the SDK's own uploads (the page uploader when no worker runs) are not
508
- // the app's traffic: recording them made every upload trigger the next
509
- let ingestUrl = null
510
- try { ingestUrl = new URL(endpoint, location.href).href.split(/[?#]/)[0] } catch { /* relative-only engines */ }
511
- const isOwn = (u) => { try { return ingestUrl != null && new URL(u, location.href).href.split(/[?#]/)[0] === ingestUrl } catch { return false } }
591
+ // the SDK's own requests (the page uploader when no worker runs, the
592
+ // settings check) are not the app's traffic: recording them made every
593
+ // upload trigger the next
594
+ const bare = (u) => new URL(u, location.href).href.split(/[?#]/)[0]
595
+ const own = new Set()
596
+ for (const u of [endpoint, dest.configUrl]) { try { if (u) own.add(bare(u)) } catch { /* relative-only engines */ } }
597
+ const isOwn = (u) => { try { return own.has(bare(u)) } catch { return false } }
512
598
  // backend traces (opt-in): which requests carry a traceparent
513
599
  const traceOrigins = new Set((Array.isArray(opts.traceOrigins) ? opts.traceOrigins : []).map((o) => { try { return new URL(o).origin } catch { return null } }).filter(Boolean))
514
600
  const tracing = Boolean(opts.traces) || traceOrigins.size > 0
@@ -533,7 +619,7 @@ function createRecorder(opts, key, endpoint) {
533
619
  if (isOwn(urlOf(args[0]))) return origFetch.apply(window, args)
534
620
  const t = performance.now()
535
621
  const rawUrl = urlOf(args[0])
536
- const url = scrubUrl(rawUrl, cfg.strict)
622
+ const url = scrubUrl(rawUrl, now().strict)
537
623
  const method = (args[1]?.method || (typeof args[0] !== 'string' && args[0]?.method) || 'GET').toUpperCase()
538
624
  let sentTrace
539
625
  if (traced(rawUrl)) [args, sentTrace] = withTraceparent(args)
@@ -542,7 +628,7 @@ function createRecorder(opts, key, endpoint) {
542
628
  let traceId = sentTrace
543
629
  try { traceId = traceId || res.headers.get('x-trace-id') || undefined } catch { /* opaque */ }
544
630
  const payload = { t: rel(), method, url, status: res.status, dur: Math.round(performance.now() - t), ...(traceId ? { traceId } : {}) }
545
- if (cfg.networkDetails) {
631
+ if (details()) {
546
632
  const detail = { initiator: 'fetch' }
547
633
  try {
548
634
  if (res.statusText) detail.statusText = String(res.statusText).slice(0, 80)
@@ -558,14 +644,14 @@ function createRecorder(opts, key, endpoint) {
558
644
  if (reqSize != null) detail.reqSize = reqSize
559
645
  } catch { /* detail is best-effort */ }
560
646
  payload.detail = detail
561
- attachTiming(payload, absoluteUrl(rawUrl), t)
647
+ attachTiming(payload, absoluteUrl(rawUrl), t, details)
562
648
  }
563
649
  push('network', payload)
564
650
  return res
565
651
  } catch (err) {
566
652
  push('network', {
567
653
  t: rel(), method, url, status: 0, dur: Math.round(performance.now() - t), error: true,
568
- ...(cfg.networkDetails ? { detail: { initiator: 'fetch', message: scrubText(String(err?.message || err)).slice(0, 200) } } : {}),
654
+ ...(details() ? { detail: { initiator: 'fetch', message: scrubText(String(err?.message || err)).slice(0, 200) } } : {}),
569
655
  })
570
656
  throw err
571
657
  }
@@ -578,7 +664,7 @@ function createRecorder(opts, key, endpoint) {
578
664
  const origSend = XHR.prototype.send
579
665
  const origSetHeader = XHR.prototype.setRequestHeader
580
666
  XHR.prototype.open = function (method, url) {
581
- this.__specto = { method: String(method).toUpperCase(), url: scrubUrl(url, cfg.strict), rawUrl: absoluteUrl(url), started: 0, trace: traced(url) }
667
+ this.__specto = { method: String(method).toUpperCase(), url: scrubUrl(url, now().strict), rawUrl: absoluteUrl(url), started: 0, trace: traced(url) }
582
668
  return origOpen.apply(this, arguments)
583
669
  }
584
670
  XHR.prototype.setRequestHeader = function (name, value) {
@@ -597,13 +683,13 @@ function createRecorder(opts, key, endpoint) {
597
683
  } catch { /* never break the app's request */ }
598
684
  }
599
685
  this.__specto.started = performance.now()
600
- if (cfg.networkDetails) this.__specto.reqSize = bodySize(body)
686
+ if (details()) this.__specto.reqSize = bodySize(body)
601
687
  this.addEventListener('loadend', () => {
602
688
  const m = this.__specto
603
689
  let traceId = m.traceId
604
690
  try { traceId = traceId || this.getResponseHeader('x-trace-id') || undefined } catch { /* ignore */ }
605
691
  const payload = { t: rel(), method: m.method, url: m.url, status: this.status, dur: Math.round(performance.now() - m.started), ...(traceId ? { traceId } : {}), ...(this.status === 0 ? { error: true } : {}) }
606
- if (cfg.networkDetails) {
692
+ if (details()) {
607
693
  const detail = { initiator: 'xhr' }
608
694
  try {
609
695
  if (this.statusText) detail.statusText = String(this.statusText).slice(0, 80)
@@ -616,7 +702,7 @@ function createRecorder(opts, key, endpoint) {
616
702
  if (m.reqSize != null) detail.reqSize = m.reqSize
617
703
  } catch { /* best-effort */ }
618
704
  payload.detail = detail
619
- attachTiming(payload, m.rawUrl, m.started)
705
+ attachTiming(payload, m.rawUrl, m.started, details)
620
706
  }
621
707
  push('network', payload)
622
708
  })
@@ -626,30 +712,55 @@ function createRecorder(opts, key, endpoint) {
626
712
  restore.push(() => { XHR.prototype.open = origOpen; XHR.prototype.send = origSend; XHR.prototype.setRequestHeader = origSetHeader })
627
713
 
628
714
  // ---- JS errors (message + a few scrubbed stack frames) ----
715
+ // reported a tick later: in React 18 development an error a boundary
716
+ // catches reaches window first, and the boundary's report (with the
717
+ // component stack) should be the one kept
629
718
  const onError = (e) => {
630
719
  const err = e.error || e.reason
631
- const stack = err?.stack ? scrubText(String(err.stack)).split('\n').slice(0, 6).map((l) => l.replace(/\?[^\s:)]*/g, '').slice(0, 300)).join('\n') : undefined
632
- push('event', { t: rel(), type: 'error', message: scrubText(String(e.message || err?.message || e.reason || 'error')).slice(0, 500), ...(stack ? { stack } : {}) })
720
+ 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 } : {}) }
722
+ setTimeout(() => {
723
+ if (err && typeof err === 'object' && seen) { if (seen.has(err)) return; seen.add(err) }
724
+ push('event', payload)
725
+ }, 0)
633
726
  }
634
727
  window.addEventListener('error', onError)
635
728
  window.addEventListener('unhandledrejection', onError)
636
729
  restore.push(() => { window.removeEventListener('error', onError); window.removeEventListener('unhandledrejection', onError) })
637
730
 
638
731
  // ---- SPA navigations (history API + hash) — powers funnels/paths ----
639
- let viewChanged = () => {} // heatmaps: a new path is a new page view (below)
640
- const pushNav = () => {
732
+ pushNav = () => {
641
733
  viewChanged()
642
- push('event', { t: rel(), type: 'nav', path: scrubUrl(location.pathname + location.search + location.hash, cfg.strict).slice(0, 300) })
734
+ push('event', { t: rel(), type: 'nav', path: scrubUrl(location.pathname + location.search + location.hash, now().strict).slice(0, 300) })
643
735
  }
644
736
  const origPush = history.pushState, origReplace = history.replaceState
645
737
  history.pushState = function (...a) { const r = origPush.apply(this, a); try { pushNav() } catch { /* never break nav */ } return r }
646
738
  history.replaceState = function (...a) { const r = origReplace.apply(this, a); try { pushNav() } catch { /* never break nav */ } return r }
647
- window.addEventListener('popstate', pushNav)
648
- window.addEventListener('hashchange', pushNav)
739
+ const onNav = () => pushNav()
740
+ window.addEventListener('popstate', onNav)
741
+ window.addEventListener('hashchange', onNav)
649
742
  restore.push(() => {
650
743
  history.pushState = origPush; history.replaceState = origReplace
651
- window.removeEventListener('popstate', pushNav); window.removeEventListener('hashchange', pushNav)
744
+ window.removeEventListener('popstate', onNav); window.removeEventListener('hashchange', onNav)
652
745
  })
746
+ }
747
+ let pushNav = () => {}
748
+
749
+ // ---- once the session is known: liveness, page views, rage clicks,
750
+ // heatmaps, delivery on hide. resumed: this page load continues a session
751
+ // started on an earlier page
752
+ function instrumentSession(resumed) {
753
+ // ---- activity → session liveness; idle past the timeout → new session
754
+ const bump = () => {
755
+ const t = Date.now()
756
+ if (t - lastActive > SESSION_IDLE_MS) { lastActive = t; rotate(); return }
757
+ lastActive = t
758
+ }
759
+ for (const ev of ['click', 'keydown', 'scroll', 'pointerdown']) {
760
+ window.addEventListener(ev, bump, { capture: true, passive: true })
761
+ restore.push(() => window.removeEventListener(ev, bump, { capture: true }))
762
+ }
763
+
653
764
  // a page load inside a running session is a navigation too (multi-page
654
765
  // sites), and so is a hash route on the first page — the session's page
655
766
  // is only the path
@@ -679,13 +790,13 @@ function createRecorder(opts, key, endpoint) {
679
790
  const h = docHeight()
680
791
  if (view && h > 0) view.depth = Math.max(view.depth, Math.min(1, (window.scrollY + window.innerHeight) / h))
681
792
  }
682
- const newView = () => { view = { id: Math.random().toString(36).slice(2, 10), path: scrubUrl(location.pathname, cfg.strict).slice(0, 300), depth: 0, clicks: 0 }; measure() }
793
+ const newView = () => { view = { id: Math.random().toString(36).slice(2, 10), path: scrubUrl(location.pathname, now().strict).slice(0, 300), depth: 0, clicks: 0 }; measure() }
683
794
  const flushView = () => {
684
795
  if (view) push('event', { t: rel(), type: 'scroll', path: view.path, pv: view.id, depth: Math.round(view.depth * 1000) / 1000, vw: window.innerWidth, dh: docHeight() })
685
796
  }
686
797
  newView()
687
798
  viewChanged = () => {
688
- if (scrubUrl(location.pathname, cfg.strict).slice(0, 300) === view?.path) return
799
+ if (scrubUrl(location.pathname, now().strict).slice(0, 300) === view?.path) return
689
800
  flushView()
690
801
  newView()
691
802
  }
@@ -718,9 +829,16 @@ function createRecorder(opts, key, endpoint) {
718
829
  })
719
830
  }
720
831
 
832
+ capture()
721
833
  return api
722
834
  }
723
835
 
836
+ // a few scrubbed stack frames, without query strings
837
+ function framesOf(stack) {
838
+ if (!stack) return undefined
839
+ return scrubText(String(stack)).split('\n').slice(0, 6).map((l) => l.replace(/\?[^\s:)]*/g, '').slice(0, 300)).join('\n')
840
+ }
841
+
724
842
  // W3C trace context: a fresh trace for each request the app makes
725
843
  const randomHex = (bytes) => {
726
844
  const a = new Uint8Array(bytes)
@@ -0,0 +1,9 @@
1
+ // Types for @spectosh/browser/destination — where a key's recordings go.
2
+
3
+ export const DEFAULT_HOST: string
4
+ export function parseKey(key: string): { key: string; host: string | null }
5
+ export function normalizeHost(host: string): string
6
+ export function resolveDestination(
7
+ options: { key: string; host?: string; endpoint?: string; configUrl?: string | false },
8
+ defaults?: { fallback?: string | null; guessed?: boolean },
9
+ ): { key: string; endpoint: string; configUrl: string | null; host: string | null; guessed: boolean }
@@ -0,0 +1,113 @@
1
+ // Types for @spectosh/browser — the Specto session-replay recorder.
2
+
3
+ export interface RecordingOptions {
4
+ /**
5
+ * The project's publishable key from its Install page. `pk_…` belongs to
6
+ * the hosted service; `pk_…@eu.specto.sh` (EU region) or
7
+ * `pk_…@replay.example.com` (self-hosted) carries where the project lives.
8
+ */
9
+ key: string
10
+ /** Where the project lives, overriding the key's — e.g. your own domain proxying to Specto. */
11
+ host?: string
12
+ /** Full ingest URL (legacy; overrides `host`). */
13
+ endpoint?: string
14
+ /** Project settings URL; `false` skips it. Defaults to the host's `/api/sdk/config`. */
15
+ configUrl?: string | false
16
+ /** `'strict'` masks all text (inputs are always masked) and keeps only the path of URLs. */
17
+ privacy?: 'balanced' | 'strict'
18
+ /** Fraction of sessions recorded, decided once per session (0–1). */
19
+ sampleRate?: number
20
+ /** `'required'`: record and store nothing until `grantConsent()`. */
21
+ consent?: 'granted' | 'required'
22
+ /** Capture console output (default true). */
23
+ console?: boolean
24
+ /** Devtools-style request details: headers, sizes, timing (default true). Bodies are never captured. */
25
+ networkDetails?: boolean
26
+ /** Send a W3C `traceparent` with same-origin requests so backend spans join the replay. */
27
+ traces?: boolean
28
+ /** More origins to send `traceparent` to (their CORS must allow the header). */
29
+ traceOrigins?: string[]
30
+ /** Called as events are captured. */
31
+ onUpdate?: (info: { total: number; kind: string }) => void
32
+ /** Called for upload outcomes (ack, drop, stop, rotate). */
33
+ onDelivery?: (event: { t: string; [k: string]: unknown }) => void
34
+ }
35
+
36
+ export type StopReason =
37
+ | 'stopped' | 'dnt' | 'opted-out' | 'consent-required' | 'not-sampled'
38
+ | 'recording-disabled' | 'unknown-key' | 'unconfirmed' | 'no window' | 'starting' | (string & {})
39
+
40
+ /** Flat, JSON-safe user traits. */
41
+ export type Traits = Record<string, string | number | boolean | null | undefined>
42
+
43
+ export interface ErrorInfo {
44
+ /** React's component stack (from an error boundary or a root error handler). */
45
+ componentStack?: string | null
46
+ /** Where the error was caught, e.g. `'react-boundary'`. */
47
+ source?: string
48
+ }
49
+
50
+ export interface Recorder {
51
+ /** True once recording stopped, or when it never started (see `reason`). */
52
+ readonly disabled: boolean
53
+ readonly reason?: StopReason
54
+ /** The current session's id, once recording has begun. */
55
+ readonly sessionId: string | null
56
+ /** Events captured so far on this page. */
57
+ count(): number
58
+ /** Send what's buffered now instead of at the next interval. */
59
+ flushNow(): void
60
+ identify(id: string | number, traits?: Traits): void
61
+ track(name: string, props?: Record<string, unknown>): void
62
+ captureError(error: unknown, info?: ErrorInfo): void
63
+ /** A link to this session's replay. */
64
+ sessionUrl(): string | null
65
+ /** Stop recording; every patched browser API is restored. */
66
+ stop(reason?: string): void
67
+ }
68
+
69
+ /**
70
+ * Start recording — once per page; later calls return the running recorder.
71
+ * Call it before your app renders: capture begins at once, so a page load's
72
+ * first requests and errors are in the replay. Nothing is sent until the
73
+ * project's host confirms the key and its settings arrive.
74
+ */
75
+ export function startRecording(options: RecordingOptions): Recorder
76
+ /** Attach your user id (and a few flat traits) to the session. */
77
+ export function identify(id: string | number, traits?: Traits): void
78
+ /** Record a custom product event on the session's timeline. */
79
+ export function track(name: string, props?: Record<string, unknown>): void
80
+ /** Report an error your app caught itself. */
81
+ export function captureError(error: unknown, info?: ErrorInfo): void
82
+ /** A link to the current session's replay, if recording. */
83
+ export function sessionUrl(): string | null
84
+ export function stopRecording(): void
85
+ /** Consent mode: store the visitor's consent and start recording. */
86
+ export function grantConsent(): Recorder | null
87
+ export function revokeConsent(): void
88
+ /** Remember in this browser not to record it. */
89
+ export function optOut(): void
90
+ export function optIn(): void
91
+ export function isOptedOut(): boolean
92
+ export function hasConsent(): boolean
93
+ /** The browser-side PII scrubber (emails, tokens, card numbers). */
94
+ export function scrubText(text: unknown): string
95
+ /** `'pk_x@host'` → `{ key: 'pk_x', host: 'host' }`. */
96
+ export function parseKey(key: string): { key: string; host: string | null }
97
+ /** The hosted service a key without a host belongs to. */
98
+ export const DEFAULT_HOST: string
99
+ export const SDK_VERSION: string
100
+
101
+ declare const Specto: {
102
+ startRecording: typeof startRecording
103
+ identify: typeof identify
104
+ track: typeof track
105
+ captureError: typeof captureError
106
+ sessionUrl: typeof sessionUrl
107
+ stopRecording: typeof stopRecording
108
+ grantConsent: typeof grantConsent
109
+ revokeConsent: typeof revokeConsent
110
+ optOut: typeof optOut
111
+ optIn: typeof optIn
112
+ }
113
+ export default Specto