@amplitude/amp-semantic 0.2.0-codexsemantic-review-integration.0 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +8 -237
- package/lib/cjs/capture.d.ts +5 -5
- package/lib/cjs/capture.d.ts.map +1 -1
- package/lib/cjs/capture.js +48 -56
- package/lib/cjs/capture.js.map +1 -1
- package/lib/cjs/index.d.ts +4 -13
- package/lib/cjs/index.d.ts.map +1 -1
- package/lib/cjs/index.js +7 -32
- package/lib/cjs/index.js.map +1 -1
- package/lib/cjs/types.d.ts +33 -235
- package/lib/cjs/types.d.ts.map +1 -1
- package/lib/cjs/types.js.map +1 -1
- package/lib/esm/capture.d.ts +5 -5
- package/lib/esm/capture.d.ts.map +1 -1
- package/lib/esm/capture.js +47 -55
- package/lib/esm/capture.js.map +1 -1
- package/lib/esm/index.d.ts +4 -13
- package/lib/esm/index.d.ts.map +1 -1
- package/lib/esm/index.js +6 -22
- package/lib/esm/index.js.map +1 -1
- package/lib/esm/types.d.ts +33 -235
- package/lib/esm/types.d.ts.map +1 -1
- package/lib/esm/types.js.map +1 -1
- package/package.json +8 -10
- package/lib/cjs/helpers.d.ts +0 -9
- package/lib/cjs/helpers.d.ts.map +0 -1
- package/lib/cjs/helpers.js +0 -469
- package/lib/cjs/helpers.js.map +0 -1
- package/lib/cjs/recorders/analytics.d.ts +0 -7
- package/lib/cjs/recorders/analytics.d.ts.map +0 -1
- package/lib/cjs/recorders/analytics.js +0 -95
- package/lib/cjs/recorders/analytics.js.map +0 -1
- package/lib/cjs/recorders/feedback.d.ts +0 -4
- package/lib/cjs/recorders/feedback.d.ts.map +0 -1
- package/lib/cjs/recorders/feedback.js +0 -611
- package/lib/cjs/recorders/feedback.js.map +0 -1
- package/lib/cjs/recorders/interactions.d.ts +0 -4
- package/lib/cjs/recorders/interactions.d.ts.map +0 -1
- package/lib/cjs/recorders/interactions.js +0 -320
- package/lib/cjs/recorders/interactions.js.map +0 -1
- package/lib/cjs/recorders/keys.d.ts +0 -4
- package/lib/cjs/recorders/keys.d.ts.map +0 -1
- package/lib/cjs/recorders/keys.js +0 -64
- package/lib/cjs/recorders/keys.js.map +0 -1
- package/lib/cjs/recorders/lifecycle.d.ts +0 -4
- package/lib/cjs/recorders/lifecycle.d.ts.map +0 -1
- package/lib/cjs/recorders/lifecycle.js +0 -86
- package/lib/cjs/recorders/lifecycle.js.map +0 -1
- package/lib/cjs/recorders/navigation.d.ts +0 -4
- package/lib/cjs/recorders/navigation.d.ts.map +0 -1
- package/lib/cjs/recorders/navigation.js +0 -18
- package/lib/cjs/recorders/navigation.js.map +0 -1
- package/lib/cjs/recorders/resource-error.d.ts +0 -4
- package/lib/cjs/recorders/resource-error.d.ts.map +0 -1
- package/lib/cjs/recorders/resource-error.js +0 -159
- package/lib/cjs/recorders/resource-error.js.map +0 -1
- package/lib/esm/helpers.d.ts +0 -9
- package/lib/esm/helpers.d.ts.map +0 -1
- package/lib/esm/helpers.js +0 -461
- package/lib/esm/helpers.js.map +0 -1
- package/lib/esm/recorders/analytics.d.ts +0 -7
- package/lib/esm/recorders/analytics.d.ts.map +0 -1
- package/lib/esm/recorders/analytics.js +0 -92
- package/lib/esm/recorders/analytics.js.map +0 -1
- package/lib/esm/recorders/feedback.d.ts +0 -4
- package/lib/esm/recorders/feedback.d.ts.map +0 -1
- package/lib/esm/recorders/feedback.js +0 -608
- package/lib/esm/recorders/feedback.js.map +0 -1
- package/lib/esm/recorders/interactions.d.ts +0 -4
- package/lib/esm/recorders/interactions.d.ts.map +0 -1
- package/lib/esm/recorders/interactions.js +0 -317
- package/lib/esm/recorders/interactions.js.map +0 -1
- package/lib/esm/recorders/keys.d.ts +0 -4
- package/lib/esm/recorders/keys.d.ts.map +0 -1
- package/lib/esm/recorders/keys.js +0 -61
- package/lib/esm/recorders/keys.js.map +0 -1
- package/lib/esm/recorders/lifecycle.d.ts +0 -4
- package/lib/esm/recorders/lifecycle.d.ts.map +0 -1
- package/lib/esm/recorders/lifecycle.js +0 -83
- package/lib/esm/recorders/lifecycle.js.map +0 -1
- package/lib/esm/recorders/navigation.d.ts +0 -4
- package/lib/esm/recorders/navigation.d.ts.map +0 -1
- package/lib/esm/recorders/navigation.js +0 -15
- package/lib/esm/recorders/navigation.js.map +0 -1
- package/lib/esm/recorders/resource-error.d.ts +0 -4
- package/lib/esm/recorders/resource-error.d.ts.map +0 -1
- package/lib/esm/recorders/resource-error.js +0 -156
- package/lib/esm/recorders/resource-error.js.map +0 -1
- package/schema.json +0 -1110
package/README.md
CHANGED
|
@@ -1,246 +1,17 @@
|
|
|
1
1
|
# @amplitude/amp-semantic
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Internal, composable semantic capture runtime for Amplitude. This increment installs no production event recorders and is not connected to Session Replay.
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
The host supplies a document, window, and transport callback. `createSemanticCapture` accepts typed recorder factories and optional per-family budgets (200 events per session by default). With no recorders supplied it emits nothing and installs no browser listeners.
|
|
6
6
|
|
|
7
|
-
|
|
7
|
+
The runtime owns opt-in sampling, start/stop and session reset, event version/timestamp/identity stamping, host signals, subscriptions, exception isolation, and cleanup rollback. Sampling and caps survive stop/start and reset only for a new session. Identity is allocated lazily when an event is accepted; its fallback is document-scoped memory, with no storage access.
|
|
8
8
|
|
|
9
|
-
|
|
9
|
+
Recorders register teardown immediately with `onCleanup` when setup can fail. `canEmit` lets them avoid expensive payload work at capacity. `dropped` returns delivery-cap diagnostics; recorders acknowledge successfully delivered diagnostics with `clearDropped`.
|
|
10
10
|
|
|
11
|
-
|
|
11
|
+
The `snapshot` host signal describes an accepted full snapshot; the runtime does not subscribe to rrweb itself. The host remains responsible for privacy-safe payloads, recording consent, transport, and any persisted tab identity.
|
|
12
12
|
|
|
13
|
-
|
|
14
|
-
sessionReplay.init(API_KEY, {
|
|
15
|
-
deviceId,
|
|
16
|
-
sessionId,
|
|
17
|
-
semanticCapture: {
|
|
18
|
-
enabled: true,
|
|
19
|
-
sampleRate: 1,
|
|
20
|
-
families: { keys: false },
|
|
21
|
-
},
|
|
22
|
-
});
|
|
23
|
-
```
|
|
13
|
+
Context, Session Replay integration, and visibility are added in separate follow-up PRs. No analytics SDK depends on this package in this increment.
|
|
24
14
|
|
|
25
|
-
|
|
15
|
+
## Development
|
|
26
16
|
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
Notice/dialog capture consumes the accepted rrweb full snapshots and mutation batches through
|
|
30
|
-
`notify('dom', change)`, resolving relevant elements with `host.getNode(id)`. It does not install a
|
|
31
|
-
MutationObserver or perform an initial dialog selector query. Standalone hosts must provide both
|
|
32
|
-
this signal and resolver for these two families; there is no independent observation fallback.
|
|
33
|
-
Full snapshots seed existing dialogs silently, while later changes produce the same wire payloads.
|
|
34
|
-
The adapter queues startup input until capture starts and ignores custom events to prevent feedback.
|
|
35
|
-
|
|
36
|
-
## Semantic identity and visibility
|
|
37
|
-
|
|
38
|
-
Click `states` includes `mixed` (native checkbox indeterminate or ARIA checked/pressed mixed),
|
|
39
|
-
`busy` (the target's aria-busy), and `open` (native details/dialog), alongside existing states.
|
|
40
|
-
Mixed observations omit the checked token. Field events include optional `checked: true | false`
|
|
41
|
-
for native checkbox/radio controls, including masked controls; blocked controls remain excluded.
|
|
42
|
-
Other field types omit it, and older events without it mean unknown. These reads use existing
|
|
43
|
-
event handlers, with no extra observers, scans, or layout checks. Radio peers and silent programmatic
|
|
44
|
-
state changes are not continuously tracked. `value_state` is not checkbox selection state.
|
|
45
|
-
|
|
46
|
-
Every new semantic payload includes `tab_id` and `document_id`. The capture runtime stamps these
|
|
47
|
-
fields centrally, including when the context family is disabled. The host can inject `getIdentity()`;
|
|
48
|
-
without it, the package uses shared in-memory IDs for its host document, with no storage or listeners.
|
|
49
|
-
|
|
50
|
-
The Session Replay host lazily creates identity only when a semantic event is accepted. In a top-level
|
|
51
|
-
page it stores an opaque tab ID and document owner in sessionStorage (`AMP_semantic_tab_v1`).
|
|
52
|
-
Actual `pagehide` releases ownership so normal same-origin reloads/navigation reuse the tab ID;
|
|
53
|
-
each newly loaded document gets a new document ID. A copied record with a live owner gets a fresh
|
|
54
|
-
tab ID. A bfcache restore preserves the original document identity and reclaims ownership.
|
|
55
|
-
SPA navigation, stop/resume, and session resets preserve both IDs within the current document.
|
|
56
|
-
These IDs are unrelated to the replay event store's internal ownership ID.
|
|
57
|
-
|
|
58
|
-
Storage unavailable, corrupt, or a missing navigation boundary can break tab continuity. Capture
|
|
59
|
-
falls back to document-scoped in-memory IDs when storage is blocked; it never requires storage to
|
|
60
|
-
emit. Child-frame hosts use document-scoped IDs without modifying top-level tab storage; they are
|
|
61
|
-
not correlated to the parent's tab. The lightweight identity ownership listeners last for the
|
|
62
|
-
page lifetime once initialized, while recorder listeners are removed on stop. Disabled or
|
|
63
|
-
sampled-out capture does not initialize identity storage or listeners.
|
|
64
|
-
|
|
65
|
-
Context includes `visibility_state`, `focused` (`document.hasFocus()`), and `user_agent`.
|
|
66
|
-
Visibility emits `{ state }` plus the shared version and identity fields only when the document changes
|
|
67
|
-
between hidden and visible. Both transitions emit immediately, with no settling timer. Duplicate
|
|
68
|
-
visibility notifications and standalone window/element focus or blur events emit nothing.
|
|
69
|
-
Visibility payloads omit `focused`: focus may arrive after the visibility boundary, and a one-time
|
|
70
|
-
snapshot would be misleading as the focus state for the visible interval. Initial visibility is
|
|
71
|
-
included in context. The visibility listener is removed on stop or family disabling. Visibility
|
|
72
|
-
is an observation, not proof of attention or a reason for leaving the page.
|
|
73
|
-
The redundant `trigger` field is no longer emitted. The wire schema still accepts legacy
|
|
74
|
-
`focused` and `trigger` fields (`visibilitychange`, `focus`, or `blur`) from earlier recordings.
|
|
75
|
-
Context retains its observation-time `focused` snapshot; local diagnostics also show
|
|
76
|
-
raw focus notifications, but neither is continuous semantic focus tracking.
|
|
77
|
-
|
|
78
|
-
The local replay inspector displays millisecond timestamps and separate visibility diagnostics for
|
|
79
|
-
browser event creation, handler execution, and batch decoding. These diagnostics stay local and
|
|
80
|
-
are not semantic payload fields. A reported embedded-browser switch produced hidden/visible
|
|
81
|
-
observations only 4 ms apart despite several seconds away; the cause is still under investigation.
|
|
82
|
-
Do not treat that pair as a measured absence interval. Synthetic visibility tests do not establish
|
|
83
|
-
native browser tab-switch behavior.
|
|
84
|
-
|
|
85
|
-
The wire version remains `v: 1`; the schema accepts legacy payloads without these fields. Missing
|
|
86
|
-
identity/focus/visibility means unknown. These additions only identify semantic events. They do not
|
|
87
|
-
attribute interleaved raw rrweb events, link an opener to its child, or implement multi-tab DOM replay.
|
|
88
|
-
|
|
89
|
-
## Host API and extensions
|
|
90
|
-
|
|
91
|
-
```ts
|
|
92
|
-
const capture = createSemanticCapture(config, host);
|
|
93
|
-
capture.start();
|
|
94
|
-
capture.notify('recording', { state: 'start', reason: 'init' });
|
|
95
|
-
capture.notify('snapshot', undefined);
|
|
96
|
-
// Forward a URL observation after applying the host URL privacy rules:
|
|
97
|
-
// This also invalidates cached interaction headings.
|
|
98
|
-
capture.notify('url', { url: filteredUrl, timestamp: Date.now() });
|
|
99
|
-
capture.notify('recording', { state: 'stop', reason: 'customer_stop' });
|
|
100
|
-
capture.stop();
|
|
101
|
-
```
|
|
102
|
-
|
|
103
|
-
Pass a third argument containing recorder factories to replace the default recorder set. Built-in factories and `defaultRecorders` are exported so hosts can compose a subset. A `SemanticRecorder` declares its families and implements `setup(context)`, returning complete cleanup. Call `context.onCleanup()` immediately after acquiring a resource when setup could subsequently fail; the runtime unwinds those resources if setup throws. Context signal subscriptions are automatically scoped to their recorder. Cleanup should be idempotent.
|
|
104
|
-
|
|
105
|
-
To add an event family, add its payload to `SemanticPayloads`, its session limit to `SEMANTIC_CAPS`, its wire variant to `schema.json`, and its factory to the desired recorder set. Wire tags and payload `v` are stable contracts. Breaking payload changes require a new version; avoid encoding application classification into capture facts.
|
|
106
|
-
|
|
107
|
-
`SemanticHost.externalClicks` lets hosts reuse existing native click hooks. Session Replay routes primary clicks through its existing heatmap `ClickHandler` and rrweb's `mouseInteraction` hook, including when heatmaps are disabled. The hook receives the original event in memory, preserving modifiers, keyboard activation, trust and composed-path targeting. Native events are never added to recorded rrweb data. Selector lookup is shared for the same element within one click; an actionable ancestor gets its own lookup when it differs from the raw target. Consumer failures are isolated.
|
|
108
|
-
|
|
109
|
-
The published `@amplitude/rrweb-record@2.1.5` provides the optional native-event hook argument and `record.supportsNativeMouseInteraction`; no workspace patch is required. Older recorders retain the independent native listener as a compatibility fallback. `externalAuxClicks: false` keeps the middle-button `auxclick` listener because rrweb does not forward auxiliary clicks. Standalone semantic capture still installs its own native listeners.
|
|
110
|
-
|
|
111
|
-
Recorder processing timestamps are supplied to generic hosts. rrweb's `addCustomEvent` controls its own wire timestamp, so exact ±1 ms alignment with MouseInteraction remains a browser integration requirement.
|
|
112
|
-
|
|
113
|
-
## Privacy and limits
|
|
114
|
-
|
|
115
|
-
All captured text uses the replay privacy policy, including referenced labels and nested text sources. Blocked elements are skipped, masked text is `null`, and browser validation messages are never included. Field events include an optional `value` for native inputs and textareas only when the input policy permits it, with no length limit or whitespace normalization. Passwords (including `data-rr-is-password`), hidden fields and blocked fields emit nothing. Files, checkbox/radio submitted values, selects and contenteditable contents are excluded from `value`; selection labels and checked state retain their existing contracts. Text traversal is bounded and fails closed when its budget is exceeded. Unsupported URL schemes are discarded; HTTP(S) paths and hash routes are templated without queries or secondary fragments. Detached dialog names are cleared because their former masking ancestry cannot safely be reconstructed.
|
|
116
|
-
|
|
117
|
-
The page event and its title observer, scheduled checks, and page-wide scans remain deferred.
|
|
118
|
-
`amp-semantic/navigation` emits `{ url }` plus shared version/identity fields from accepted
|
|
119
|
-
`amplitude/url-tracking@1` plugin events. This covers the initial URL, history/hash changes (or the
|
|
120
|
-
plugin's configured polling), and the current URL when recording resumes. No second URL listener,
|
|
121
|
-
history wrapper, polling timer, title observer, or page scan is added. Plugin observations also
|
|
122
|
-
invalidate cached interaction headings even when the navigation family is disabled.
|
|
123
|
-
|
|
124
|
-
The existing URL plugin applies configured UGC URL rules first. Semantic normalization then removes
|
|
125
|
-
origins and query values and templates ID-shaped path segments, preserving hash routes. Literal path
|
|
126
|
-
segments remain: sensitive path content still requires appropriate UGC rules. No title or navigation
|
|
127
|
-
reason is emitted. Separate navigations may produce the same template; consumers should retain the
|
|
128
|
-
boundaries. The limit is 200 events per session. Set `families: { navigation: false }` to disable it.
|
|
129
|
-
Standalone hosts can provide accepted input using `capture.notify('url', { url, timestamp })`.
|
|
130
|
-
|
|
131
|
-
Recorders include context, clicks, keys, resource load failures, field state, form submissions, notices, dialogs, navigation, recording state, visibility, lifecycle, and an accepted-analytics-event mirror.
|
|
132
|
-
|
|
133
|
-
Field events and key targets include the same event-time `states` as clicks, including native disabled fieldset inheritance (with the first-legend exception) and native/ARIA invalid state. Reading native validity does not dispatch validation events. Fields, key targets and dialogs include `name_source`; excluded editable names and detached dialog names report `masked`. These additive v1 fields remain optional in the wire schema for older recordings. No new listeners, observers, scans or timers are introduced; states describe the observation, not a post-action outcome.
|
|
134
|
-
|
|
135
|
-
## Work limits
|
|
136
|
-
|
|
137
|
-
Recorders call `context.canEmit(family)` before expensive payload construction when possible.
|
|
138
|
-
A cap-rejected candidate increments the dropped count without resolving its text, selector, or
|
|
139
|
-
layout; `emit()` still enforces the cap independently. This is not a reservation. Recorders retain
|
|
140
|
-
shared subscriptions while another family still has capacity. `hasCapacity()` checks capacity without
|
|
141
|
-
incrementing dropped counts; feedback disconnects once both families are exhausted, including on
|
|
142
|
-
same-session resume, and reattaches after a session reset.
|
|
143
|
-
Field candidates rejected before deduplication can contribute to the dropped count.
|
|
144
|
-
|
|
145
|
-
Notice/dialog processing retains at most 128 replay batches, 256 notice candidates (ready plus
|
|
146
|
-
trailing timers), 256 dialog candidates, and 256 tracked dialogs (including closed/hidden dialogs).
|
|
147
|
-
Serialized trees are traversed incrementally without building a second tree or walking live DOM
|
|
148
|
-
subtrees. Ordinary serialized elements need no live-node lookup; repeated parent lookups in a
|
|
149
|
-
mutation batch are deduplicated with a bounded set. References to queued serialized batches retain
|
|
150
|
-
their source data until consumed. Overflow drops excess work and reports a payload-free diagnostic
|
|
151
|
-
through `host.onError`, once per limit per recorder setup; these are not exact dropped-event counts.
|
|
152
|
-
|
|
153
|
-
Each frame gives ready events the first 2 ms, alternating notices and dialogs, before inspecting
|
|
154
|
-
recorded changes. It processes at most 1,000 work items and 50 payload candidates within a cooperative
|
|
155
|
-
4 ms frame budget. Trailing notice timers only enqueue work. Detached notice work is discarded;
|
|
156
|
-
removal checks the bounded dialog registry without traversing removed subtrees. Privacy helpers
|
|
157
|
-
still recheck live text, names and blocking before emission; detached dialog names stay null.
|
|
158
|
-
|
|
159
|
-
State and timestamps reflect processing time. rrweb batching and deferred enrichment can coalesce
|
|
160
|
-
or omit transient states, including nodes removed before discovery. Masked/blocked or otherwise
|
|
161
|
-
unrecorded DOM changes cannot be recovered from this input. Snapshot baseline processing is also
|
|
162
|
-
incremental. CSS-only visibility and full-page visibility tracking remain out of scope. These are
|
|
163
|
-
cooperative limits, not hard deadlines for individual DOM or host callbacks. No production CPU
|
|
164
|
-
improvement is claimed without a representative browser benchmark.
|
|
165
|
-
|
|
166
|
-
Heading discovery traverses at most 2,000 elements with a cooperative 2 ms budget and reuses only the
|
|
167
|
-
DOM candidate for up to 250 ms. Text, masking and visibility are re-read when emitted; no private text
|
|
168
|
-
is cached. Navigation, snapshots, disconnected candidates and hidden candidates invalidate discovery.
|
|
169
|
-
New higher-priority headings may take up to 250 ms to be selected, and over-budget discovery can omit
|
|
170
|
-
a heading. These budgets are checked between DOM operations, not hard deadlines for browser calls.
|
|
171
|
-
|
|
172
|
-
The SDK still has separate autocapture/replay observers; this package does not introduce a shared observer across those packages.
|
|
173
|
-
|
|
174
|
-
## Remaining integration and release work
|
|
175
|
-
|
|
176
|
-
- The analytics mirror requires a host signal after analytics enrichment/filtering accepts an event for delivery. The existing Session Replay plugin `execute()` runs too early; SDK forwarding is intentionally not wired there.
|
|
177
|
-
- Coordinated cross-origin child iframe capture bypasses the ordinary snapshot callback and needs an additional rrweb lifecycle bridge. Semantic recorders currently operate on their host document, not a shadow-root/iframe forest.
|
|
178
|
-
- Within-frame dialog open/close transitions can coalesce in the observer batch.
|
|
179
|
-
- The inherited 100% unit-coverage threshold is retained and is not yet met. Do not treat passing tests with coverage disabled as a passing release gate.
|
|
180
|
-
- The real-browser smoke fixture checks shapes, privacy, teardown, reconfiguration, and click dispatch overhead. It does not establish the ≤5% replay-byte budget or exact rrweb timestamp/ID alignment on production journeys. Actionable-ancestor click IDs can differ from rrweb's raw target IDs; that spec tension needs explicit resolution before release.
|
|
181
|
-
|
|
182
|
-
## Validation
|
|
183
|
-
|
|
184
|
-
Build dependencies first, then run the package's build, test, and lint scripts. `schema.json` validates complete rrweb custom-event envelopes and is shipped with the package for downstream consumers. Fixture tests cover each specified family and reject extra raw-value fields.
|
|
185
|
-
|
|
186
|
-
### Local Session Replay inspector
|
|
187
|
-
|
|
188
|
-
From the repository root, run:
|
|
189
|
-
|
|
190
|
-
```sh
|
|
191
|
-
pnpm dev:semantic
|
|
192
|
-
```
|
|
193
|
-
|
|
194
|
-
This builds Session Replay and its workspace dependencies, then opens `http://127.0.0.1:5174/session-replay-browser/sr-semantic-test.html` in the existing Vite test server. After package source changes, run `pnpm build:semantic` again and reload. The page also works with the repository's normal `pnpm dev` watch workflow.
|
|
195
|
-
|
|
196
|
-
Interact with the checkout form, dialog, notice, navigation, and privacy fixtures. The inspector decodes actual Session Replay transport batches, validates every `amp-semantic/*` rrweb envelope against `schema.json`, and displays its payload. Use **Flush batches** to inspect the current recording immediately, filter by family, or **Export semantic JSON** to save the captured envelopes.
|
|
197
|
-
|
|
198
|
-
Controls let you change replay masking, semantic sampling, family switches, and worker transport. **Stop recording** and **Resume recording** exercise the public SDK lifecycle. Disabled or sampled-out semantic capture should leave ordinary replay events flowing. The inspector lives in a blocked shadow tree to keep its own controls and log updates outside recorded content.
|
|
199
|
-
|
|
200
|
-
No real API key is needed. Custom config and transport callbacks handle data locally in memory; the fixture does not upload to Amplitude. Reloading clears its log, which retains up to 10,000 replay events. The analytics mirror is not connected to this SDK path yet.
|
|
201
|
-
|
|
202
|
-
### Browser integration tests
|
|
203
|
-
|
|
204
|
-
```sh
|
|
205
|
-
pnpm test:semantic
|
|
206
|
-
```
|
|
207
|
-
|
|
208
|
-
This builds the dependencies and runs the package's Chromium Playwright suite, starting the local Vite server automatically. If Chromium is not installed, run `pnpm exec playwright install chromium` first. After a build, use `pnpm --filter @amplitude/amp-semantic test:playwright --ui` for interactive debugging.
|
|
209
|
-
|
|
210
|
-
The suite covers real SDK → rrweb → serialized transport delivery, schema validation, direct-button click node ID matching, fields/submits, notices/dialogs, post-navigation click context, masking, disabled capture, sampling, the remote kill switch, individual family switches, stop/resume, JSON export, and worker transport. It also checks ordinary clicks without a page change. These fixture checks do not establish production byte budgets or exact timestamp alignment.
|
|
211
|
-
|
|
212
|
-
For an isolated Chromium recorder smoke check, from the repository root:
|
|
213
|
-
|
|
214
|
-
```sh
|
|
215
|
-
node packages/amp-semantic/test/e2e/smoke.cjs
|
|
216
|
-
```
|
|
217
|
-
|
|
218
|
-
The smoke check uses the workspace's Vite and Playwright installations. It validates actual emitted events against the schema and reports measured click-dispatch p95 for its fixture.
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
## Keys and resource errors
|
|
222
|
-
|
|
223
|
-
`keys` emits `{ key, target: { id, role, name } }` with common identity/version fields. It allows
|
|
224
|
-
Escape, Enter, Tab, arrows, Home/End, PageUp/PageDown, F1–F12 and Ctrl/Meta+K/P/F (optionally Shift).
|
|
225
|
-
Modifier prefixes are canonical. Ordinary typing, Backspace/Delete, repeat, IME/composition,
|
|
226
|
-
AltGraph, password/hidden inputs, and blocked targets are excluded. Names use shared masking;
|
|
227
|
-
control values and editable text are never names. Browser/OS-intercepted shortcuts are unavailable.
|
|
228
|
-
The target is the actual DOM key target, not an inferred cause of a dialog transition.
|
|
229
|
-
|
|
230
|
-
`resource-error` emits `{ rt, count, container?, path? }`, where `rt` is img/css/font/script. Only
|
|
231
|
-
observed load failures are captured, not runtime exceptions or fetch/XHR. Identical resource type,
|
|
232
|
-
templated path, and container are aggregated over 500 ms; 100 pending groups force an early flush.
|
|
233
|
-
Counts saturate at 65,535. Hidden/pagehide flushes immediately; stop/disable discards pending groups.
|
|
234
|
-
The rrweb timestamp is batch emission time. Do not infer exact click attribution from that timestamp.
|
|
235
|
-
Paths omit origins, queries and fragments; data/blob/invalid/over-200-character paths are omitted.
|
|
236
|
-
Detached/blocked elements are dropped and container masking is checked again at emission.
|
|
237
|
-
|
|
238
|
-
FontFaceSet loadingerror supplies a failed-face count; font URLs and affected containers are not
|
|
239
|
-
available, so those fields are omitted. Font family names are never sent. Document-level font counts
|
|
240
|
-
cannot attribute or exclude a failure specific to a blocked region. Element errors in shadow roots
|
|
241
|
-
and other frame documents, and failures before capture starts, are outside this recorder's coverage.
|
|
242
|
-
There are no retrospective requests, polling, or DOM/CSS scans.
|
|
243
|
-
|
|
244
|
-
Caps are 1,000 keys and 200 resource-error groups per session. Disable either independently with
|
|
245
|
-
`families: { keys: false, 'resource-error': false }`. The local playground has a command palette
|
|
246
|
-
(Ctrl/Cmd+K, Escape) and a button that triggers real missing local image/CSS/script/font requests.
|
|
17
|
+
From the repository root, install dependencies and build with Node 24, `pnpm install`, and `pnpm build`. Run `pnpm --filter @amplitude/amp-semantic test` for runtime lifecycle and public contract tests.
|
package/lib/cjs/capture.d.ts
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
|
-
import { HostSignals, SemanticCaptureConfig, SemanticFamily, SemanticHost, SemanticRecorder } from './types';
|
|
2
|
-
export declare const
|
|
3
|
-
export interface SemanticCapture {
|
|
1
|
+
import { HostSignals, SemanticCaptureConfig, SemanticFamily, SemanticHost, SemanticPayloads, SemanticRecorder } from './types';
|
|
2
|
+
export declare const DEFAULT_SEMANTIC_CAP = 200;
|
|
3
|
+
export interface SemanticCapture<P extends object = SemanticPayloads> {
|
|
4
4
|
isActive: () => boolean;
|
|
5
5
|
start: () => void;
|
|
6
6
|
stop: () => void;
|
|
7
|
-
updateConfig: (config: SemanticCaptureConfig) => void;
|
|
7
|
+
updateConfig: (config: SemanticCaptureConfig<P>) => void;
|
|
8
8
|
resetSession: () => void;
|
|
9
9
|
notify: <K extends keyof HostSignals>(signal: K, value: HostSignals[K]) => void;
|
|
10
10
|
}
|
|
11
11
|
/** Composable runtime. Sampling and caps belong to a session, listeners to a recording. */
|
|
12
|
-
export declare function createCapture(config: SemanticCaptureConfig
|
|
12
|
+
export declare function createCapture<P extends object = SemanticPayloads>(config: SemanticCaptureConfig<P>, host: SemanticHost<P>, recorders: readonly SemanticRecorder<P>[], caps?: Partial<Record<SemanticFamily<P>, number>>): SemanticCapture<P>;
|
|
13
13
|
//# sourceMappingURL=capture.d.ts.map
|
package/lib/cjs/capture.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"capture.d.ts","sourceRoot":"","sources":["../../src/capture.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"capture.d.ts","sourceRoot":"","sources":["../../src/capture.ts"],"names":[],"mappings":"AACA,OAAO,EAEL,WAAW,EAEX,qBAAqB,EAErB,cAAc,EACd,YAAY,EACZ,gBAAgB,EAChB,gBAAgB,EACjB,MAAM,SAAS,CAAC;AAEjB,eAAO,MAAM,oBAAoB,MAAM,CAAC;AAExC,MAAM,WAAW,eAAe,CAAC,CAAC,SAAS,MAAM,GAAG,gBAAgB;IAClE,QAAQ,EAAE,MAAM,OAAO,CAAC;IACxB,KAAK,EAAE,MAAM,IAAI,CAAC;IAClB,IAAI,EAAE,MAAM,IAAI,CAAC;IACjB,YAAY,EAAE,CAAC,MAAM,EAAE,qBAAqB,CAAC,CAAC,CAAC,KAAK,IAAI,CAAC;IACzD,YAAY,EAAE,MAAM,IAAI,CAAC;IACzB,MAAM,EAAE,CAAC,CAAC,SAAS,MAAM,WAAW,EAAE,MAAM,EAAE,CAAC,EAAE,KAAK,EAAE,WAAW,CAAC,CAAC,CAAC,KAAK,IAAI,CAAC;CACjF;AAED,2FAA2F;AAC3F,wBAAgB,aAAa,CAAC,CAAC,SAAS,MAAM,GAAG,gBAAgB,EAC/D,MAAM,EAAE,qBAAqB,CAAC,CAAC,CAAC,EAChC,IAAI,EAAE,YAAY,CAAC,CAAC,CAAC,EACrB,SAAS,EAAE,SAAS,gBAAgB,CAAC,CAAC,CAAC,EAAE,EACzC,IAAI,GAAE,OAAO,CAAC,MAAM,CAAC,cAAc,CAAC,CAAC,CAAC,EAAE,MAAM,CAAC,CAAM,GACpD,eAAe,CAAC,CAAC,CAAC,CA4KpB"}
|
package/lib/cjs/capture.js
CHANGED
|
@@ -1,37 +1,22 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.createCapture = exports.
|
|
3
|
+
exports.createCapture = exports.DEFAULT_SEMANTIC_CAP = void 0;
|
|
4
4
|
var tslib_1 = require("tslib");
|
|
5
|
-
var helpers_1 = require("./helpers");
|
|
6
5
|
var identity_1 = require("./identity");
|
|
7
|
-
exports.
|
|
8
|
-
click: 2000,
|
|
9
|
-
keys: 1000,
|
|
10
|
-
'resource-error': 200,
|
|
11
|
-
field: 1000,
|
|
12
|
-
submit: 300,
|
|
13
|
-
notice: 300,
|
|
14
|
-
dialog: 300,
|
|
15
|
-
'amp-event': 500,
|
|
16
|
-
context: 200,
|
|
17
|
-
recording: 200,
|
|
18
|
-
navigation: 200,
|
|
19
|
-
visibility: 200,
|
|
20
|
-
lifecycle: 200,
|
|
21
|
-
};
|
|
6
|
+
exports.DEFAULT_SEMANTIC_CAP = 200;
|
|
22
7
|
/** Composable runtime. Sampling and caps belong to a session, listeners to a recording. */
|
|
23
|
-
function createCapture(config, host, recorders) {
|
|
8
|
+
function createCapture(config, host, recorders, caps) {
|
|
24
9
|
var _a;
|
|
10
|
+
if (caps === void 0) { caps = {}; }
|
|
25
11
|
var settings = copyConfig(config);
|
|
26
12
|
var active = false;
|
|
27
13
|
var requested = false;
|
|
28
|
-
var
|
|
14
|
+
var attachGeneration = 0;
|
|
29
15
|
var sample;
|
|
30
16
|
var cleanups = [];
|
|
31
17
|
var counts = {};
|
|
32
18
|
var dropped = {};
|
|
33
19
|
var signals = new Map();
|
|
34
|
-
var subscribers = new Set();
|
|
35
20
|
var now = (_a = host.now) !== null && _a !== void 0 ? _a : Date.now;
|
|
36
21
|
var report = function (error) {
|
|
37
22
|
var _a;
|
|
@@ -51,7 +36,7 @@ function createCapture(config, host, recorders) {
|
|
|
51
36
|
}
|
|
52
37
|
};
|
|
53
38
|
var enabled = function (family) { var _a; return active && ((_a = settings.families) === null || _a === void 0 ? void 0 : _a[family]) !== false; };
|
|
54
|
-
var hasCapacity = function (family) { var _a; return enabled(family) && ((_a = counts[family]) !== null && _a !== void 0 ? _a : 0) <
|
|
39
|
+
var hasCapacity = function (family) { var _a, _b; return enabled(family) && ((_a = counts[family]) !== null && _a !== void 0 ? _a : 0) < ((_b = caps[family]) !== null && _b !== void 0 ? _b : exports.DEFAULT_SEMANTIC_CAP); };
|
|
55
40
|
var canEmit = function (family) {
|
|
56
41
|
var _a;
|
|
57
42
|
if (!enabled(family))
|
|
@@ -63,13 +48,12 @@ function createCapture(config, host, recorders) {
|
|
|
63
48
|
};
|
|
64
49
|
var context = {
|
|
65
50
|
host: host,
|
|
66
|
-
helpers: (0, helpers_1.createHelpers)(host),
|
|
67
51
|
now: now,
|
|
68
|
-
enabled: enabled,
|
|
69
52
|
canEmit: canEmit,
|
|
70
|
-
hasCapacity: hasCapacity,
|
|
71
53
|
dropped: function () { return (tslib_1.__assign({}, dropped)); },
|
|
72
|
-
|
|
54
|
+
clearDropped: function () {
|
|
55
|
+
dropped = {};
|
|
56
|
+
},
|
|
73
57
|
emit: function (family, payload, timestamp) {
|
|
74
58
|
var _a, _b;
|
|
75
59
|
if (timestamp === void 0) { timestamp = now(); }
|
|
@@ -88,17 +72,17 @@ function createCapture(config, host, recorders) {
|
|
|
88
72
|
payload: tslib_1.__assign(tslib_1.__assign({}, payload), { v: 1, tab_id: identity.tab_id, document_id: identity.document_id }),
|
|
89
73
|
timestamp: timestamp,
|
|
90
74
|
};
|
|
91
|
-
|
|
75
|
+
// Reserve capacity before calling a host that may emit reentrantly.
|
|
76
|
+
var reservedCounts = counts;
|
|
77
|
+
reservedCounts[family] = ((_b = reservedCounts[family]) !== null && _b !== void 0 ? _b : 0) + 1;
|
|
92
78
|
try {
|
|
93
79
|
host.emit(event);
|
|
94
80
|
}
|
|
95
81
|
catch (error) {
|
|
82
|
+
reservedCounts[family] = reservedCounts[family] - 1;
|
|
96
83
|
report(error);
|
|
97
84
|
return false;
|
|
98
85
|
}
|
|
99
|
-
if (family === 'context')
|
|
100
|
-
dropped = {};
|
|
101
|
-
subscribers.forEach(function (subscriber) { return safely(function () { return subscriber(event); }); });
|
|
102
86
|
return true;
|
|
103
87
|
},
|
|
104
88
|
on: function (signal, callback) {
|
|
@@ -114,20 +98,14 @@ function createCapture(config, host, recorders) {
|
|
|
114
98
|
registered.delete(listener);
|
|
115
99
|
};
|
|
116
100
|
},
|
|
117
|
-
subscribe: function (callback) {
|
|
118
|
-
subscribers.add(callback);
|
|
119
|
-
return function () {
|
|
120
|
-
subscribers.delete(callback);
|
|
121
|
-
};
|
|
122
|
-
},
|
|
123
101
|
};
|
|
124
102
|
var detach = function () {
|
|
125
103
|
active = false;
|
|
104
|
+
attachGeneration += 1;
|
|
126
105
|
var previous = cleanups;
|
|
127
106
|
cleanups = [];
|
|
128
107
|
previous.reverse().forEach(function (cleanup) { return safely(cleanup); });
|
|
129
108
|
signals.clear();
|
|
130
|
-
subscribers.clear();
|
|
131
109
|
};
|
|
132
110
|
var attach = function () {
|
|
133
111
|
var e_1, _a;
|
|
@@ -141,41 +119,61 @@ function createCapture(config, host, recorders) {
|
|
|
141
119
|
sample = ((_c = host.random) !== null && _c !== void 0 ? _c : Math.random)();
|
|
142
120
|
if (sample >= rate)
|
|
143
121
|
return;
|
|
122
|
+
var myGeneration = attachGeneration + 1;
|
|
123
|
+
attachGeneration = myGeneration;
|
|
144
124
|
active = true;
|
|
145
125
|
var _loop_1 = function (recorder) {
|
|
146
126
|
if (recorder.families.some(enabled)) {
|
|
147
127
|
var acquired_1 = [];
|
|
148
|
-
var
|
|
128
|
+
var registerCleanup_1 = function (cleanup) {
|
|
129
|
+
if (!acquired_1.includes(cleanup))
|
|
149
130
|
acquired_1.push(cleanup);
|
|
150
|
-
|
|
131
|
+
};
|
|
132
|
+
var scoped = tslib_1.__assign(tslib_1.__assign({}, context), { onCleanup: registerCleanup_1, on: function (signal, callback) {
|
|
151
133
|
var cleanup = context.on(signal, callback);
|
|
152
|
-
|
|
153
|
-
return cleanup;
|
|
154
|
-
}, subscribe: function (callback) {
|
|
155
|
-
var cleanup = context.subscribe(callback);
|
|
156
|
-
acquired_1.push(cleanup);
|
|
134
|
+
registerCleanup_1(cleanup);
|
|
157
135
|
return cleanup;
|
|
158
136
|
} });
|
|
159
|
-
var
|
|
137
|
+
var rollback_1 = function () {
|
|
160
138
|
acquired_1
|
|
161
139
|
.splice(0)
|
|
162
140
|
.reverse()
|
|
163
141
|
.forEach(function (cleanup) { return safely(cleanup); });
|
|
164
142
|
};
|
|
143
|
+
var unregisterRollback = function () {
|
|
144
|
+
var index = cleanups.lastIndexOf(rollback_1);
|
|
145
|
+
if (index >= 0)
|
|
146
|
+
cleanups.splice(index, 1);
|
|
147
|
+
};
|
|
165
148
|
try {
|
|
166
|
-
|
|
167
|
-
cleanups.push(
|
|
149
|
+
// Register rollback before setup so reentrant stop/reset can tear listeners down.
|
|
150
|
+
cleanups.push(rollback_1);
|
|
151
|
+
var setupCleanup = recorder.setup(scoped);
|
|
152
|
+
if (active && myGeneration === attachGeneration) {
|
|
153
|
+
registerCleanup_1(setupCleanup);
|
|
154
|
+
}
|
|
155
|
+
if (!active || myGeneration !== attachGeneration) {
|
|
156
|
+
unregisterRollback();
|
|
157
|
+
rollback_1();
|
|
158
|
+
if (myGeneration !== attachGeneration)
|
|
159
|
+
return "break";
|
|
160
|
+
}
|
|
168
161
|
}
|
|
169
162
|
catch (error) {
|
|
170
|
-
|
|
163
|
+
unregisterRollback();
|
|
164
|
+
rollback_1();
|
|
171
165
|
report(error);
|
|
166
|
+
if (myGeneration !== attachGeneration)
|
|
167
|
+
return "break";
|
|
172
168
|
}
|
|
173
169
|
}
|
|
174
170
|
};
|
|
175
171
|
try {
|
|
176
172
|
for (var recorders_1 = tslib_1.__values(recorders), recorders_1_1 = recorders_1.next(); !recorders_1_1.done; recorders_1_1 = recorders_1.next()) {
|
|
177
173
|
var recorder = recorders_1_1.value;
|
|
178
|
-
_loop_1(recorder);
|
|
174
|
+
var state_1 = _loop_1(recorder);
|
|
175
|
+
if (state_1 === "break")
|
|
176
|
+
break;
|
|
179
177
|
}
|
|
180
178
|
}
|
|
181
179
|
catch (e_1_1) { e_1 = { error: e_1_1 }; }
|
|
@@ -194,7 +192,6 @@ function createCapture(config, host, recorders) {
|
|
|
194
192
|
},
|
|
195
193
|
stop: function () {
|
|
196
194
|
requested = false;
|
|
197
|
-
snapshotSeen = false;
|
|
198
195
|
detach();
|
|
199
196
|
},
|
|
200
197
|
updateConfig: function (next) {
|
|
@@ -205,20 +202,15 @@ function createCapture(config, host, recorders) {
|
|
|
205
202
|
resetSession: function () {
|
|
206
203
|
detach();
|
|
207
204
|
sample = undefined;
|
|
208
|
-
snapshotSeen = false;
|
|
209
205
|
counts = {};
|
|
210
206
|
dropped = {};
|
|
211
207
|
attach();
|
|
212
208
|
},
|
|
213
209
|
notify: function (signal, value) {
|
|
214
|
-
var _a
|
|
215
|
-
if (signal === 'snapshot')
|
|
216
|
-
snapshotSeen = true;
|
|
217
|
-
if (signal === 'snapshot' || signal === 'navigation' || signal === 'url')
|
|
218
|
-
(_b = (_a = context.helpers).invalidateHeading) === null || _b === void 0 ? void 0 : _b.call(_a);
|
|
210
|
+
var _a;
|
|
219
211
|
if (!active)
|
|
220
212
|
return;
|
|
221
|
-
(
|
|
213
|
+
(_a = signals.get(signal)) === null || _a === void 0 ? void 0 : _a.forEach(function (callback) { return callback(value); });
|
|
222
214
|
},
|
|
223
215
|
};
|
|
224
216
|
}
|
package/lib/cjs/capture.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"capture.js","sourceRoot":"","sources":["../../src/capture.ts"],"names":[],"mappings":";;;;AAAA,qCAA0C;AAC1C,uCAAiD;AAapC,QAAA,aAAa,GAAmC;IAC3D,KAAK,EAAE,IAAI;IACX,IAAI,EAAE,IAAI;IACV,gBAAgB,EAAE,GAAG;IACrB,KAAK,EAAE,IAAI;IACX,MAAM,EAAE,GAAG;IACX,MAAM,EAAE,GAAG;IACX,MAAM,EAAE,GAAG;IACX,WAAW,EAAE,GAAG;IAChB,OAAO,EAAE,GAAG;IACZ,SAAS,EAAE,GAAG;IACd,UAAU,EAAE,GAAG;IACf,UAAU,EAAE,GAAG;IACf,SAAS,EAAE,GAAG;CACf,CAAC;AAWF,2FAA2F;AAC3F,SAAgB,aAAa,CAC3B,MAA6B,EAC7B,IAAkB,EAClB,SAAsC;;IAEtC,IAAI,QAAQ,GAAG,UAAU,CAAC,MAAM,CAAC,CAAC;IAClC,IAAI,MAAM,GAAG,KAAK,CAAC;IACnB,IAAI,SAAS,GAAG,KAAK,CAAC;IACtB,IAAI,YAAY,GAAG,KAAK,CAAC;IACzB,IAAI,MAA0B,CAAC;IAC/B,IAAI,QAAQ,GAAc,EAAE,CAAC;IAC7B,IAAI,MAAM,GAA4C,EAAE,CAAC;IACzD,IAAI,OAAO,GAA4C,EAAE,CAAC;IAC1D,IAAM,OAAO,GAAG,IAAI,GAAG,EAAkD,CAAC;IAC1E,IAAM,WAAW,GAAG,IAAI,GAAG,EAAkC,CAAC;IAC9D,IAAM,GAAG,GAAG,MAAA,IAAI,CAAC,GAAG,mCAAI,IAAI,CAAC,GAAG,CAAC;IACjC,IAAM,M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,OAAA,QAAQ,CAAC,KAAc,CAAC,EAAxB,CAAwB,CAAC,CAAC;QACvE,CAAC;KACF,CAAC;AACJ,CAAC;AA7KD,sCA6KC;AAED,SAAS,UAAU,CAAC,MAA6B;IAC/C,6CAAY,MAAM,KAAE,QAAQ,EAAE,MAAM,CAAC,QAAQ,CAAC,CAAC,sBAAM,MAAM,CAAC,QAAQ,EAAG,CAAC,CAAC,SAAS,IAAG;AACvF,CAAC","sourcesContent":["import { createHelpers } from './helpers';\nimport { getDocumentIdentity } from './identity';\nimport {\n Cleanup,\n HostSignals,\n RecorderContext,\n SemanticCaptureConfig,\n SemanticEvent,\n SemanticFamily,\n SemanticHost,\n SemanticPayloads,\n SemanticRecorder,\n} from './types';\n\nexport const SEMANTIC_CAPS: Record<SemanticFamily, number> = {\n click: 2000,\n keys: 1000,\n 'resource-error': 200,\n field: 1000,\n submit: 300,\n notice: 300,\n dialog: 300,\n 'amp-event': 500,\n context: 200,\n recording: 200,\n navigation: 200,\n visibility: 200,\n lifecycle: 200,\n};\n\nexport interface SemanticCapture {\n isActive: () => boolean;\n start: () => void;\n stop: () => void;\n updateConfig: (config: SemanticCaptureConfig) => void;\n resetSession: () => void;\n notify: <K extends keyof HostSignals>(signal: K, value: HostSignals[K]) => void;\n}\n\n/** Composable runtime. Sampling and caps belong to a session, listeners to a recording. */\nexport function createCapture(\n config: SemanticCaptureConfig,\n host: SemanticHost,\n recorders: readonly SemanticRecorder[],\n): SemanticCapture {\n let settings = copyConfig(config);\n let active = false;\n let requested = false;\n let snapshotSeen = false;\n let sample: number | undefined;\n let cleanups: Cleanup[] = [];\n let counts: Partial<Record<SemanticFamily, number>> = {};\n let dropped: Partial<Record<SemanticFamily, number>> = {};\n const signals = new Map<keyof HostSignals, Set<(value: never) => void>>();\n const subscribers = new Set<(event: SemanticEvent) => void>();\n const now = host.now ?? Date.now;\n const report = (error: unknown) => {\n try {\n host.onError?.(error);\n } catch {\n /* Diagnostics must not affect the host. */\n }\n };\n const safely = (fn: () => void) => {\n try {\n fn();\n } catch (error) {\n report(error);\n }\n };\n const enabled = (family: SemanticFamily) => active && settings.families?.[family] !== false;\n const hasCapacity = (family: SemanticFamily) => enabled(family) && (counts[family] ?? 0) < SEMANTIC_CAPS[family];\n const canEmit = (family: SemanticFamily): boolean => {\n if (!enabled(family)) return false;\n if (hasCapacity(family)) return true;\n dropped[family] = (dropped[family] ?? 0) + 1;\n return false;\n };\n const context: Omit<RecorderContext, 'onCleanup'> = {\n host,\n helpers: createHelpers(host),\n now,\n enabled,\n canEmit,\n hasCapacity,\n dropped: () => ({ ...dropped }),\n hasSnapshot: () => snapshotSeen,\n emit: <K extends SemanticFamily>(family: K, payload: SemanticPayloads[K], timestamp = now()): boolean => {\n if (!canEmit(family)) return false;\n let identity;\n try {\n identity = host.getIdentity?.();\n } catch (error) {\n report(error);\n }\n identity ??= getDocumentIdentity(host.document, host.window);\n const event = {\n name: family,\n payload: { ...payload, v: 1, tab_id: identity.tab_id, document_id: identity.document_id },\n timestamp,\n } as SemanticEvent;\n counts[family] = (counts[family] ?? 0) + 1;\n try {\n host.emit(event);\n } catch (error) {\n report(error);\n return false;\n }\n if (family === 'context') dropped = {};\n subscribers.forEach((subscriber) => safely(() => subscriber(event)));\n return true;\n },\n on: (signal, callback) => {\n let listeners = signals.get(signal);\n if (!listeners) {\n listeners = new Set();\n signals.set(signal, listeners);\n }\n const listener = (value: never) => safely(() => callback(value));\n listeners.add(listener);\n const registered = listeners;\n return () => {\n registered.delete(listener);\n };\n },\n subscribe: (callback) => {\n subscribers.add(callback);\n return () => {\n subscribers.delete(callback);\n };\n },\n };\n const detach = () => {\n active = false;\n const previous = cleanups;\n cleanups = [];\n previous.reverse().forEach((cleanup) => safely(cleanup));\n signals.clear();\n subscribers.clear();\n };\n const attach = () => {\n if (active || !requested || !settings.enabled) return;\n const rate = settings.sampleRate ?? 1;\n if (!Number.isFinite(rate) || rate <= 0 || rate > 1) return;\n if (sample === undefined) sample = (host.random ?? Math.random)();\n if (sample >= rate) return;\n active = true;\n for (const recorder of recorders) {\n if (recorder.families.some(enabled)) {\n const acquired: Cleanup[] = [];\n const scoped: RecorderContext = {\n ...context,\n onCleanup: (cleanup) => {\n acquired.push(cleanup);\n },\n on: (signal, callback) => {\n const cleanup = context.on(signal, callback);\n acquired.push(cleanup);\n return cleanup;\n },\n subscribe: (callback) => {\n const cleanup = context.subscribe(callback);\n acquired.push(cleanup);\n return cleanup;\n },\n };\n const rollback = () => {\n acquired\n .splice(0)\n .reverse()\n .forEach((cleanup) => safely(cleanup));\n };\n try {\n acquired.push(recorder.setup(scoped));\n cleanups.push(rollback);\n } catch (error) {\n rollback();\n report(error);\n }\n }\n }\n };\n return {\n isActive: () => active,\n start: () => {\n requested = true;\n attach();\n },\n stop: () => {\n requested = false;\n snapshotSeen = false;\n detach();\n },\n updateConfig: (next) => {\n detach();\n settings = copyConfig(next);\n attach();\n },\n resetSession: () => {\n detach();\n sample = undefined;\n snapshotSeen = false;\n counts = {};\n dropped = {};\n attach();\n },\n notify: (signal, value) => {\n if (signal === 'snapshot') snapshotSeen = true;\n if (signal === 'snapshot' || signal === 'navigation' || signal === 'url') context.helpers.invalidateHeading?.();\n if (!active) return;\n signals.get(signal)?.forEach((callback) => callback(value as never));\n },\n };\n}\n\nfunction copyConfig(config: SemanticCaptureConfig): SemanticCaptureConfig {\n return { ...config, families: config.families ? { ...config.families } : undefined };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"capture.js","sourceRoot":"","sources":["../../src/capture.ts"],"names":[],"mappings":";;;;AAAA,uCAAiD;AAapC,QAAA,oBAAoB,GAAG,GAAG,CAAC;AAWxC,2FAA2F;AAC3F,SAAgB,aAAa,CAC3B,MAAgC,EAChC,IAAqB,EACrB,SAAyC,EACzC,IAAqD;;IAArD,qBAAA,EAAA,SAAqD;IAErD,IAAI,QAAQ,GAAG,UAAU,CAAC,MAAM,CAAC,CAAC;IAClC,IAAI,MAAM,GAAG,KAAK,CAAC;IACnB,IAAI,SA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E;YACZ,MAAM,EAAE,CAAC;YACT,MAAM,GAAG,SAAS,CAAC;YACnB,MAAM,GAAG,EAAE,CAAC;YACZ,OAAO,GAAG,EAAE,CAAC;YACb,MAAM,EAAE,CAAC;QACX,CAAC;QACD,MAAM,EAAE,UAAC,MAAM,EAAE,KAAK;;YACpB,IAAI,CAAC,MAAM;gBAAE,OAAO;YACpB,MAAA,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,0CAAE,OAAO,CAAC,UAAC,QAAQ,IAAK,OAAA,QAAQ,CAAC,KAAc,CAAC,EAAxB,CAAwB,CAAC,CAAC;QACvE,CAAC;KACF,CAAC;AACJ,CAAC;AAjLD,sCAiLC;AAED,SAAS,UAAU,CAAmB,MAAgC;IACpE,6CAAY,MAAM,KAAE,QAAQ,EAAE,MAAM,CAAC,QAAQ,CAAC,CAAC,sBAAM,MAAM,CAAC,QAAQ,EAAG,CAAC,CAAC,SAAS,IAAG;AACvF,CAAC","sourcesContent":["import { getDocumentIdentity } from './identity';\nimport {\n Cleanup,\n HostSignals,\n RecorderContext,\n SemanticCaptureConfig,\n SemanticEvent,\n SemanticFamily,\n SemanticHost,\n SemanticPayloads,\n SemanticRecorder,\n} from './types';\n\nexport const DEFAULT_SEMANTIC_CAP = 200;\n\nexport interface SemanticCapture<P extends object = SemanticPayloads> {\n isActive: () => boolean;\n start: () => void;\n stop: () => void;\n updateConfig: (config: SemanticCaptureConfig<P>) => void;\n resetSession: () => void;\n notify: <K extends keyof HostSignals>(signal: K, value: HostSignals[K]) => void;\n}\n\n/** Composable runtime. Sampling and caps belong to a session, listeners to a recording. */\nexport function createCapture<P extends object = SemanticPayloads>(\n config: SemanticCaptureConfig<P>,\n host: SemanticHost<P>,\n recorders: readonly SemanticRecorder<P>[],\n caps: Partial<Record<SemanticFamily<P>, number>> = {},\n): SemanticCapture<P> {\n let settings = copyConfig(config);\n let active = false;\n let requested = false;\n let attachGeneration = 0;\n let sample: number | undefined;\n let cleanups: Cleanup[] = [];\n let counts: Partial<Record<SemanticFamily<P>, number>> = {};\n let dropped: Partial<Record<SemanticFamily<P>, number>> = {};\n const signals = new Map<keyof HostSignals, Set<(value: never) => void>>();\n const now = host.now ?? Date.now;\n const report = (error: unknown) => {\n try {\n host.onError?.(error);\n } catch {\n /* Diagnostics must not affect the host. */\n }\n };\n const safely = (fn: () => void) => {\n try {\n fn();\n } catch (error) {\n report(error);\n }\n };\n const enabled = (family: SemanticFamily<P>) => active && settings.families?.[family] !== false;\n const hasCapacity = (family: SemanticFamily<P>) =>\n enabled(family) && (counts[family] ?? 0) < (caps[family] ?? DEFAULT_SEMANTIC_CAP);\n const canEmit = (family: SemanticFamily<P>): boolean => {\n if (!enabled(family)) return false;\n if (hasCapacity(family)) return true;\n dropped[family] = (dropped[family] ?? 0) + 1;\n return false;\n };\n const context: Omit<RecorderContext<P>, 'onCleanup'> = {\n host,\n now,\n canEmit,\n dropped: () => ({ ...dropped }),\n clearDropped: () => {\n dropped = {};\n },\n emit: <K extends SemanticFamily<P>>(family: K, payload: P[K], timestamp = now()): boolean => {\n if (!canEmit(family)) return false;\n let identity;\n try {\n identity = host.getIdentity?.();\n } catch (error) {\n report(error);\n }\n identity ??= getDocumentIdentity(host.document, host.window);\n const event = {\n name: family,\n payload: { ...payload, v: 1, tab_id: identity.tab_id, document_id: identity.document_id },\n timestamp,\n } as SemanticEvent<P>;\n // Reserve capacity before calling a host that may emit reentrantly.\n const reservedCounts = counts;\n reservedCounts[family] = (reservedCounts[family] ?? 0) + 1;\n try {\n host.emit(event);\n } catch (error) {\n reservedCounts[family] = (reservedCounts[family] as number) - 1;\n report(error);\n return false;\n }\n return true;\n },\n on: (signal, callback) => {\n let listeners = signals.get(signal);\n if (!listeners) {\n listeners = new Set();\n signals.set(signal, listeners);\n }\n const listener = (value: never) => safely(() => callback(value));\n listeners.add(listener);\n const registered = listeners;\n return () => {\n registered.delete(listener);\n };\n },\n };\n const detach = () => {\n active = false;\n attachGeneration += 1;\n const previous = cleanups;\n cleanups = [];\n previous.reverse().forEach((cleanup) => safely(cleanup));\n signals.clear();\n };\n const attach = () => {\n if (active || !requested || !settings.enabled) return;\n const rate = settings.sampleRate ?? 1;\n if (!Number.isFinite(rate) || rate <= 0 || rate > 1) return;\n if (sample === undefined) sample = (host.random ?? Math.random)();\n if (sample >= rate) return;\n const myGeneration = attachGeneration + 1;\n attachGeneration = myGeneration;\n active = true;\n for (const recorder of recorders) {\n if (recorder.families.some(enabled)) {\n const acquired: Cleanup[] = [];\n const registerCleanup = (cleanup: Cleanup) => {\n if (!acquired.includes(cleanup)) acquired.push(cleanup);\n };\n const scoped: RecorderContext<P> = {\n ...context,\n onCleanup: registerCleanup,\n on: (signal, callback) => {\n const cleanup = context.on(signal, callback);\n registerCleanup(cleanup);\n return cleanup;\n },\n };\n const rollback = () => {\n acquired\n .splice(0)\n .reverse()\n .forEach((cleanup) => safely(cleanup));\n };\n const unregisterRollback = () => {\n const index = cleanups.lastIndexOf(rollback);\n if (index >= 0) cleanups.splice(index, 1);\n };\n try {\n // Register rollback before setup so reentrant stop/reset can tear listeners down.\n cleanups.push(rollback);\n const setupCleanup = recorder.setup(scoped);\n if (active && myGeneration === attachGeneration) {\n registerCleanup(setupCleanup);\n }\n if (!active || myGeneration !== attachGeneration) {\n unregisterRollback();\n rollback();\n if (myGeneration !== attachGeneration) break;\n }\n } catch (error) {\n unregisterRollback();\n rollback();\n report(error);\n if (myGeneration !== attachGeneration) break;\n }\n }\n }\n };\n return {\n isActive: () => active,\n start: () => {\n requested = true;\n attach();\n },\n stop: () => {\n requested = false;\n detach();\n },\n updateConfig: (next) => {\n detach();\n settings = copyConfig(next);\n attach();\n },\n resetSession: () => {\n detach();\n sample = undefined;\n counts = {};\n dropped = {};\n attach();\n },\n notify: (signal, value) => {\n if (!active) return;\n signals.get(signal)?.forEach((callback) => callback(value as never));\n },\n };\n}\n\nfunction copyConfig<P extends object>(config: SemanticCaptureConfig<P>): SemanticCaptureConfig<P> {\n return { ...config, families: config.families ? { ...config.families } : undefined };\n}\n"]}
|
package/lib/cjs/index.d.ts
CHANGED
|
@@ -1,17 +1,8 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { feedbackRecorder } from './recorders/feedback';
|
|
3
|
-
import { navigationRecorder } from './recorders/navigation';
|
|
4
|
-
import { lifecycleRecorder } from './recorders/lifecycle';
|
|
5
|
-
import { keysRecorder } from './recorders/keys';
|
|
6
|
-
import { resourceErrorRecorder } from './recorders/resource-error';
|
|
7
|
-
import { analyticsRecorder } from './recorders/analytics';
|
|
8
|
-
import type { SemanticCaptureConfig, SemanticHost, SemanticRecorder } from './types';
|
|
9
|
-
export { interactionsRecorder, feedbackRecorder, lifecycleRecorder, navigationRecorder, analyticsRecorder, keysRecorder, resourceErrorRecorder, };
|
|
10
|
-
export declare const defaultRecorders: readonly SemanticRecorder[];
|
|
1
|
+
import type { SemanticCaptureConfig, SemanticHost, SemanticPayloads, SemanticRecorder } from './types';
|
|
11
2
|
export * from './types';
|
|
12
3
|
export type { SemanticCapture } from './capture';
|
|
13
|
-
export {
|
|
14
|
-
export { createHelpers, roleOf, urlTemplate } from './helpers';
|
|
4
|
+
export { DEFAULT_SEMANTIC_CAP } from './capture';
|
|
15
5
|
export { getDocumentIdentity } from './identity';
|
|
16
|
-
|
|
6
|
+
/** Starts only the supplied recorders; no event families are installed by default. */
|
|
7
|
+
export declare function createSemanticCapture<P extends object = SemanticPayloads>(config: SemanticCaptureConfig<P>, host: SemanticHost<P>, recorders?: readonly SemanticRecorder<P>[], caps?: Partial<Record<Extract<keyof P, string>, number>>): import("./capture").SemanticCapture<P>;
|
|
17
8
|
//# sourceMappingURL=index.d.ts.map
|
package/lib/cjs/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,qBAAqB,EAAE,YAAY,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,MAAM,SAAS,CAAC;AAEvG,cAAc,SAAS,CAAC;AACxB,YAAY,EAAE,eAAe,EAAE,MAAM,WAAW,CAAC;AACjD,OAAO,EAAE,oBAAoB,EAAE,MAAM,WAAW,CAAC;AACjD,OAAO,EAAE,mBAAmB,EAAE,MAAM,YAAY,CAAC;AAEjD,sFAAsF;AACtF,wBAAgB,qBAAqB,CAAC,CAAC,SAAS,MAAM,GAAG,gBAAgB,EACvE,MAAM,EAAE,qBAAqB,CAAC,CAAC,CAAC,EAChC,IAAI,EAAE,YAAY,CAAC,CAAC,CAAC,EACrB,SAAS,GAAE,SAAS,gBAAgB,CAAC,CAAC,CAAC,EAAO,EAC9C,IAAI,GAAE,OAAO,CAAC,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,EAAE,MAAM,CAAC,EAAE,MAAM,CAAC,CAAM,0CAG7D"}
|