@symbo.ls/analyze
v3.14.781
Published
Runtime audit logger for smbls apps. Errors, warnings, lifecycle traces, browser events, network calls, and session replay — designed for smbls's declarative model so the runtime is the source of truth.
Maintainers
Keywords
Readme
@symbo.ls/analyze
Runtime audit logger for smbls apps. Errors, warnings, lifecycle traces, browser events, network calls, and session replay — designed for smbls's declarative model so the runtime is the source of truth.
Think of it as Grafana Faro built for DOMQL: error collection by default, deep tracing in debug mode, and a clean transformer→sink pipeline for analytics, AI agents, and e2e replay.
At a glance
- Auto-registered by smbls when
analyze: true|{...}is set oncreate(). - Errors and warnings on by default, everything else opt-in.
- Dormant until hydration completes — no noise from initial render, no first-paint cost beyond registration. Pre-hydration errors are buffered and drained at activation.
- Transformer → sinks pipeline: events flow through pure transforms before reaching destinations. Default:
[enrich → redact → summarize] → [console, memory]. - Browser-event capture for clicks, keys, forms, scroll, viewport, performance, console — all opt-in, all redacted by default.
- Network capture chains with
@symbo.ls/fetch(smbls-aware events with cache key, mode, transform name) AND wrapswindow.fetch+ XHR for non-smbls traffic. - Session replay uses smbls's element-tree-derived rendering to record state + input events instead of DOM mutations. Tiny payload, perfect fidelity.
- Cached error ring buffer queryable at runtime via
context.analyze.query()— for in-app debug panels and AI agents.
Defaults
import { create } from 'smbls'
create(App, {
analyze: true // → errors + warnings, enrich → redact → summarize → [console, memory]
})In production, this captures window.onerror, unhandledrejection, lifecycle and event handler throws, and el.warn / el.error calls — nothing else.
Configuration
create(App, {
analyze: {
enabled: true,
level: 'warn', // error | warn | info | debug | trace
load: 'boot', // 'afterFirstView': the kit after the first view (below)
capture: {
// on by default
errors: true,
warnings: true,
// browser tracking — off by default
pointer: false,
keyboard: false,
forms: false,
scroll: false,
viewport: false,
network: false,
performance: false,
navigation: false,
console: false,
// smbls internals — debug-only
lifecycle: false,
state: false,
updates: false,
// presets — expand into combinations of the above
replay: false, // full session-replay set
telemetry: false // analytics-friendly subset
},
// throttling (ms)
throttle: {
pointermove: 80,
mousemove: 80,
scroll: 100,
resize: 200
},
// privacy (see Privacy below)
redact: ['password', 'token', /secret/i, /ssn/i],
maskFormValues: true,
maskStrategy: 'mask', // 'mask' | 'hash' | 'redact'
page: 'path', // each event's page: 'path' (no query, no hash) | 'url' (keeps the query) | false
stripQuery: true, // cut ?… and #… from URLs in message, stack, source and a network event's url
// ring-buffer cache for memory sink
cache: {
max: 500,
dedupeWindowMs: 1000
},
// pipeline
transformers: ['enrich', 'summarize'], // 'redact' runs right after 'enrich'
sinks: ['console', 'memory'],
// hydration gating
captureDuringHydration: false,
// debug overrides
debug: false, // or set ?analyze=debug in URL
urlOverride: undefined, // ?analyze=debug|off: honoured in development, ignored in a production build; true | false
debugKey: null, // a production build honours ?analyze=… with &analyzeKey=<debugKey>
onEvent: null // optional catch-all (ev) => void
}
})What gets captured
Always-on: errors and warnings
window.onerrorandunhandledrejection(after activation).- Lifecycle and event handler throws and rejections (
onUpdate,onRender,onClick,onSubmit,onDocumentKeydown,onInView, the router'sonRouteChanged/onRouteExit, etc.). Element-core and@symbo.ls/utilstriggerEventOnroute these through the pluginerrorhook as{ hook, error },hookbeing the handler's key, so analyze records anerrorevent with element context. Falls back toconsole.errorwhen no plugin records it: none is installed, or analyze is off (enabled: false,?analyze=off,capture.errors: false, paused). el.warn(...)andel.error(...)from element prototype.- A part of the page that failed to build and was left out, and a route whose content failed: the
renderErrorplugin hook, recorded as anerrorevent withhook: 'renderError',where('createChildren','children','child'with itskey, or'route'with itsroute), the element and the error. The framework still prints its own line.
Browser events (opt-in)
| Category | Captures | Notes |
|---|---|---|
| pointer | click, dblclick, pointermove, contextmenu | move events throttled |
| keyboard | keydown, keyup | key codes + modifiers only, never values |
| forms | input, change, submit | values masked by default |
| scroll | window + element scroll position | throttled |
| viewport | resize, orientationchange, visibilitychange | + initial snapshot at activation |
| network | fetch + XHR | URL, method, status, duration |
| performance | LCP, CLS, INP, longtasks, paint | PerformanceObserver |
| navigation | route changes via DOMQL renderRouter | no listeners — free |
| console | console.{log,warn,error,debug} proxy | console sink uses saved originals — no recursion |
Element targeting uses the DOMQL key path (e.g. App > Sidebar > MenuItem_3), built by walking up data-key DOM attributes. Stable across renders. Falls back to a CSS selector for events on non-DOMQL nodes.
smbls internals (debug-only)
lifecycle—init,create,render,complete,done,attachNode,lazyLoad,frame,beforeRemove,remove.state—stateInit,stateCreated,stateUpdate,beforeStateUpdate. Coarse-grained: which keys changed, by whom.updates— everyupdate()call. Only useful when actively debugging; high volume.
Network capture (chained with fetch plugin)
@symbo.ls/fetch calls context.analyze.emitNetwork(...) at the start, success, and error of every runFetch and runMutation. The call is a no-op when analyze isn't installed — so projects without analyze pay nothing.
Default-off, including in the
remotepreset. The analyzed server discards un-opted-inlogType=networkenvelopes at ingest (servercd64446f), so the emitter no longer captures or ships them by default — no fetch/XHR wrapping, no batching, no egress. Re-enable with the same levers the server honors:debug: true(or?analyze=debug), which also stampsapp.debugon every envelope so the server's per-envelope lever accepts the rows end-to-end; or an explicitcapture: { network: true }/ runtimestate.setCapture('network', true)— the client half of the per-workspaceOrganization.settings.analyzedNetworkCaptureopt-in.
When analyze IS installed and network: true is set, you get smbls-aware events with:
{
type: 'network',
hook: 'fetch.start' | 'fetch.success' | 'fetch.error',
source: 'symbo-fetch',
mode: 'query' | 'mutation',
from: 'users', method: 'select',
cacheKey: 'users:select:#5c1a9e07',
durationMs: 12.4,
ok: true,
status: 200,
code: null
}cacheKey names the query without its values: from:method: and a hash of the fetch cache key, salted once per page load. The same query keeps one value for the page's life (a refetch loop shows as one key), another query gets another value, and no param, page, cursor, scope or cache.key value reaches a sink. A query with cache: false has cacheKey: null.
fetch.success and fetch.error events carry status, the answer's HTTP status (null when no answer came or the adapter gives none), and code, the server's error code when it is a short token (letters, digits, ., _, -; 40 at most), else null, so a server cannot put free text in it. A failure's message goes only as error, through the redact pass, as before. In the app, the fetch plugin's fetchSettled hook gives the same per request, without analyze.
In addition, window.fetch and XMLHttpRequest are wrapped to catch any non-smbls traffic (third-party SDKs, raw fetches in user code). Beacon traffic is filtered out via the X-Analyze-Beacon header to avoid capturing analyze's own events.
Session replay (smbls-native)
Conventional session replay (rrweb, FullStory) records DOM mutations and replays them into a clean DOM. That's heavy, lossy with CSS-in-JS, and re-implements a rendering pipeline that smbls already owns.
Because every visible byte in a smbls app is derived from element tree + state, replay only needs:
replay payload = initial state snapshot
+ input event log (clicks, keys, forms, viewport, scroll)
+ state mutations (the stateUpdate hook)To replay: restart the app with the snapshot, then replay input events in order. The DOM regenerates itself.
Enable with:
analyze: {
level: 'info',
capture: { replay: true },
sinks: [{ type: 'memory', max: 5000 }]
}Then context.analyze.replay() returns { initialSnapshot, events } ready to ship.
Transformer pipeline
Every captured event flows through a single ordered pipeline:
hook fires → build event → transformers[] → sinks[]A transformer is (event) => event | null | event[]. Return null to drop. Return an array to fan out.
Built-in transformers
| Name | What it does |
|---|---|
| redact | The privacy pass (see Privacy). Masks keys matching redact config or a built-in sensitive name, cuts queries from URLs, clips messages and stacks, and turns el.warn / el.error arguments other than strings, numbers, booleans and null into their type. Runs right after enrich, before every other transformer — cannot be reordered. Disable with redact: false. |
| enrich | Adds session id, page path (page), route, viewport, app id, build hash (app.build: the buildHash config, else globalThis.__SMBLS_BUILD__, the build id a production smbls build sets: SMBLS_BUILD_ID, else a hash of the app's sources). Active by default. |
| summarize | Replaces raw element refs and Error instances with safe slices. Active by default. |
| dedupe | Drops events identical to one within dedupeWindowMs. |
| sample(rates) | Drops 1 - rate of events of a given type. |
Custom transformers are functions:
transformers: [
'enrich',
'summarize',
(ev) => ev.level === 'trace' ? null : ev,
(ev) => ({ ...ev, app: 'workspace' })
]Sinks
| Sink | Purpose |
|---|---|
| console | Pretty-printed, color by level. Default. Saves console.error/warn/log references at construction so the console proxy doesn't recurse. |
| memory | Ring buffer in-process. Queryable via context.analyze.query(). Default. |
| beacon | POST to a same-origin url with navigator.sendBeacon: by default each time the page turns hidden, what is new, with at most 20 sends and 20 distinct events per page (below). An event that cannot be serialized (a circular value) is left out and counted; the rest of its batch is sent. |
Custom sinks are functions: (event) => void.
sinks: [
'console',
{ type: 'memory', max: 1000 },
{ type: 'beacon', url: '/analyze' },
(ev) => myCustomSink(ev)
]The beacon sink
{
type: 'beacon',
url: '/api/err', // same origin
flush: 'hidden', // default; or 'timer'
maxSends: 20, // sends per document (default 20)
maxEvents: 20 // distinct events per document (default 20)
}- When.
flush: 'hidden'sends each time the page turns hidden (visibilitychange) and onpagehide, never on a timer: turning hidden is the last moment a page reliably sees, especially on mobile (MDN). A send carries what is new since the last one; a hide with nothing new sends nothing. So a single-page app, or a page restored from the back/forward cache, keeps reporting after a tab switch.context.analyze.flush()sends at once, and that send counts towardmaxSends. - Bounds. Per document, at most
maxSends(20) requests andmaxEvents(20) distinct events. What comes after either cap is only counted. - What.
{"events":[...],"more":N}."more", on every send, 0 too, counts the events kept from being sent since the last send: pastmaxEvents, after the last send, repeats of an event already sent, and those left out for size or because they cannot be serialized. When only that count is new, a hide sends it alone:{"events":[],"more":N}. A repeat of a queued event (sametype,hookandmessage) is not sent again and takes no place undermaxEvents: it adds one to its first event's"repeat"(only when above 0). Only an event with a message folds: a click, a fetch or a route has none, and each is its own event. - Size. The body stays under 60,000 bytes (UTF-8); an event that would take it over is left out and counted in
more. Browsers queue at most 64 KiB of beacon data. - A refused beacon. When
sendBeaconanswersfalse(over the browser's limit, or its queue is full) or throws, the sink posts the same body once withfetch,keepalive: trueand theX-Analyze-Beaconheader. flush: 'timer'is the sink as it was before these options: a batchbatchMs(5000) after its first event or atmaxBatch(50) events, and onpagehideandbeforeunload. Every event is sent, repeats too, with no caps unlessmaxSendsormaxEventsis set;maxEventsthen counts distinct events, as above."more"appears only when above 0, so a payload with nothing left out is the old one. The size limit and thefetchfallback apply in both modes.
Runtime API
Exposed on context.analyze:
context.analyze.query({ level: 'error', sinceMs: 60000 }) // ring buffer query
context.analyze.snapshot() // full current buffer
context.analyze.flush() // force-send pending beacons
context.analyze.replay() // export replay payload
context.analyze.activate(context) // (called by smbls after onCreate)
context.analyze.destroy() // (called by smbls destroy())
context.analyze.pause() / .resume() // toggle capture without unregistering
context.analyze.setLevel('debug') // change log level at runtime
context.analyze.setCapture('pointer', true) // toggle a category at runtime
context.analyze.emit(event) // raw emit (used by element-core)
context.analyze.emitNetwork(data) // helper used by @symbo.ls/fetchDebug mode
Three ways to enable:
// 1. Config
analyze: { debug: true }
// 2. URL parameter (no rebuild; in a production build only when the app allows it)
// https://app.localhost/?analyze=debug
// 3. Runtime toggle
context.analyze.setLevel('debug')
context.analyze.setCapture('updates', true)debug: true (or ?analyze=debug) flips on lifecycle, state, updates, and console capture, and sets level to debug. To turn analyze off entirely via URL: ?analyze=off.
In a production build both URL switches are ignored, so no visitor can turn on full capture or turn reports off. A production build is one that defines globalThis.__SMBLS_DEV_DIAGNOSTICS_OFF__ (smbls build; vite, webpack and Parcel production builds through smbls's production export condition; the production classic runtime). The app can allow them:
urlOverride: true: honoured for every visitor, as in development.debugKey: 'k7q2': honoured when the address also carries the key,?analyze=debug&analyzeKey=k7q2. The key ships in the page's script, so it is not a password; it keeps the switch from anyone who only knows?analyze=debug.
urlOverride: false turns the switches off in development too.
How it works
Plugin registration
Auto-registers in packages/smbls/src/createDomql.js when context.analyze is truthy:
if (context.analyze && !hasPlugin('analyze')) {
const analyzeConfig = context.analyze === true ? {} : context.analyze
context.analyze = createAnalyzeState(analyzeConfig)
context.plugins.push(analyzePlugin)
}So context.analyze IS the live state object — .emit, .query, .activate are all there.
Lifecycle hooks tapped
Hooks dispatched by triggerLifecycle() in packages/element/src/create.js and runPluginHook() in packages/element/src/update.js:
error— handler throws + explicit error reportsupdate,beforeUpdate(debug only)stateUpdate,beforeStateUpdate(debug only, also for replay)init,create,render,complete,done(debug only)beforeRemove,remove(debug only)renderRouter(always-on ifnavigationenabled)
Hydration gate
The plugin sits in context.plugins from creation, but every hook is a guarded no-op until context.analyze.__ready === true. The flag flips in one place: packages/smbls/src/index.js, immediately after app.onCreate fires.
A small pre-ready buffer keeps error events that fire during init — so first-paint crashes still surface, even though the plugin is technically dormant.
Loading after the first view (load)
load: 'boot' (the default) loads the kit before the first render: create() awaits it, and in smbls/core its file (about 7 KB Brotli) is on the first render's path.
load: 'afterFirstView' (opt-in) loads the kit a task after the first view is in, at the moment the afterFirstView create option runs. Until then a small capture core holds the errors from the start of create(): window error and unhandledrejection, the error and renderError hooks, and el.error(). The core is this package's @symbo.ls/analyze/capture subpath, which smbls imports statically; the kit stays a file of its own. The core builds each event with the functions the kit's listeners and hooks build it with (src/errorEvents.js), so a held error has the kit's fields exactly. It keeps 64 in a buffer, the kit's own size before activation, and sends nothing. When the kit is in, it takes the hooks and the listeners over in one step and gets what the core held, through its pipeline. It takes over the way it boots at load: 'boot': createAnalyzeState (given the core, it stops it and takes what it held as its pre-ready buffer), its plugin, its activation. When the buffer was full, it first gets one analyze.dropped event: dropped (errors not kept), held and ms (from create() to the hand-over).
smbls buildpreloads the kit only forload: 'boot'.- Until the kit is in,
context.analyzeis the core, withload,config,emit,shouldCaptureanddestroy. The runtime API (above) comes with the kit. - Warnings, the other categories and
captureDuringHydrationstart with the kit. - With
enabled: false,capture.errors: falseor?analyze=off, the core holds nothing and listens to nothing; the kit still loads after the first view.?analyze=offcounts only where the kit honours it (see Debug mode): a production build ignores it unlessurlOverrideor thedebugKeyallows it, and then the core holds the errors too. - A server render (
context.ssr) gets no core and loads no kit. - A boot that fails (
create()orcreateSync()rejects) has no first view to wait for: the kit loads at once and gets what the core held. This is the report of a failed first view. - A boot abandoned because its document went away stops the core: its listeners off, nothing held.
destroy(app)before the kit is in stops it too, and nothing takes over. - A kit that fails to load prints what the core held.
What an app pays, built with smbls build and build.treeShakeFeatures:
load: 'boot'(the default): none of the core. The featureanalyzeCapturestays only when the loaded configuration saysload: 'afterFirstView'; a boot app keeps one check, which logs oneconsole.errornaminganalyzeCaptureandbuild.treeShakeFeatures.keepwhen it meetsload: 'afterFirstView'anyway (a configuration the build could not see). That app then boots asload: 'boot': the kit before the first render, nothing lost.- Analyze off: none of the core, and no check (the kit is out:
DROP_K_analyze). load: 'afterFirstView': the core on the first view (about 3.2 KB minified, 0.8 KB Brotli), the kit after it.
Without build.treeShakeFeatures every app that keeps analyze carries the core, as it carries every other optional feature.
Element-core integration
Two small integrations in packages/element/src/:
pluginHooks.js— lifecycle handler throws (reportLifecycleError) and event handler throws (reportEventError, fromdelegate.js) go through the pluginerrorhook as{ hook, error }instead of bareconsole.error. The framework still falls back toconsole.errorwhen no plugin handles the hook; analyze's hook returnsfalsewhen it does not record the error, which counts as not handled.methods.js—el.warn()andel.error()emit throughcontext.analyzefirst, then fall through to the original env-gated console.warn / throw.
packages/utils/function.js — runPluginHook now returns true when at least one plugin handled the hook (its hook ran and did not return false), so callers can fall back to default behavior when no plugin captured.
Browser-event listeners
When opt-in browser categories are enabled, the plugin attaches passive listeners on window and document during activate(). Listeners are detached during destroy(app). All listeners are throttled or debounced per the throttle config and route through the same pipeline as lifecycle events.
Privacy
Browser-event capture without redaction is a compliance disaster. The plugin defaults are tuned for that:
redacttransformer runs right afterenrich, before every other transformer, and cannot be reordered. Disable explicitly withredact: falseif you mean it: that turns off the next four items too.- Keys: a key that names a secret has its value masked. The long names (
password,passcode,passphrase,token,secret,credential,cookie,bearer,email,apikey/api_key,authorization,authentication,authcode,oauth,totp,otpcode,pincode,card,cvv) match anywhere in the key; the short ones (pin,auth,authn,authz,ssn,otp,pwd) only as a whole word of it (userPin,PIN_CODE,auth_header,X-Authz), soauthor,spinner,shipping,classNameandsessionstay. Patterns inredactadd to them: a string matches anywhere in the key, a RegExp as written. - URLs: a URL with a scheme in
message, the error's message and stack,sourceor a string argument loses its query and hash; a stack frame keeps its:line:col. An event'surlfield (the network category's), relative or absolute, loses its query and hash too.stripQuery: falsekeeps them. - Lengths: a message is at most 300 characters, a stack at most 3,000, the cut marked with
…. el.warn/el.errorarguments: strings (300 characters at most), numbers, booleans and null keep their value; any other value becomes its type ([object Object]), so an object's content (form text, ids) never leaves the page. Theconsolecategory (opt-in) keeps its own arguments.- Page: each event carries
page, the path it came from, with no query and no hash.page: 'url'keeps the query;page: falseleaves it out. - URL switches: a production build ignores
?analyze=debug|offunless the app allows them (see Debug mode). - Form values: masked by default. Opt in per-field with
data-analyze="track"(data-analyze="skip"always skips). <input type="password">,<input type="hidden">, and fields matching/email|token|secret|ssn|card|cvv|pin|otp/iare never recorded.- Mask strategies:
'mask'(***),'hash'(32-bit hash with#prefix),'redact'(drop the field entirely).
Performance
- Plugin registration: zero cost (one object pushed to
context.plugins). - Hooks while dormant: one boolean check.
- Hooks after activation, with category off: one boolean check.
- Hooks after activation, category on: build event, run pipeline, write to sinks. Sub-microsecond on hot paths with sampling.
- Browser listeners: passive + throttled.
updates capture is the one hot-path category and is debug-only for that reason.
Comparison
| | rrweb | LogRocket | Sentry SR | analyze | |---|---|---|---|---| | Replay model | DOM mutations | DOM mutations | DOM mutations | state + events | | Payload size | MB | MB | MB | KB | | CSS-in-JS fidelity | partial | partial | partial | perfect | | smbls integration | none | none | none | native | | Privacy default | opt-out | mixed | mixed | opt-in everywhere |
Multi-app caveat
window.fetch and XMLHttpRequest wrappers are global. If multiple smbls apps mount on the same realm and each enables network: true, the wrappers nest. Destroy order matters — the last app destroyed correctly restores window.fetch, but interleaved destroys may leave a stale wrapper. For the multi-app case, install network capture on a single shell app and let nested apps emit through the same context.analyze.
License
CC-BY-NC-4.0
