@posthog/browser 0.1.1 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/ARCHITECTURE.md +28 -22
- package/README.md +94 -29
- package/dist/analytics-api.d.ts +32 -0
- package/dist/analytics-api.js +18 -0
- package/dist/analytics-api.mjs +1 -0
- package/dist/analytics-buffer.d.ts +3 -3
- package/dist/analytics-buffer.js +2 -161
- package/dist/analytics-buffer.mjs +2 -161
- package/dist/analytics-extension.d.ts +87 -0
- package/dist/analytics-extension.js +649 -0
- package/dist/analytics-extension.mjs +611 -0
- package/dist/analytics-internal.d.ts +33 -18
- package/dist/analytics-options.d.ts +7 -2
- package/dist/analytics-options.js +38 -1
- package/dist/analytics-options.mjs +17 -1
- package/dist/analytics-properties.d.ts +12 -0
- package/dist/analytics-properties.js +88 -0
- package/dist/analytics-properties.mjs +46 -0
- package/dist/analytics-session-properties.d.ts +12 -0
- package/dist/analytics-session-properties.js +84 -0
- package/dist/analytics-session-properties.mjs +46 -0
- package/dist/analytics.d.ts +4 -3
- package/dist/autocapture.d.ts +2 -2
- package/dist/autocapture.js +21 -10
- package/dist/autocapture.mjs +21 -10
- package/dist/automatic-analytics.d.ts +2 -2
- package/dist/browser-client.d.ts +44 -4
- package/dist/capture-properties.d.ts +15 -0
- package/dist/capture-properties.js +101 -0
- package/dist/capture-properties.mjs +57 -0
- package/dist/capture-v1.js +7 -19
- package/dist/capture-v1.mjs +1 -13
- package/dist/core.d.ts +7 -5
- package/dist/extensions/registry.d.ts +42 -7
- package/dist/extensions/registry.js +194 -37
- package/dist/extensions/registry.mjs +194 -37
- package/dist/flags-token.d.ts +4 -4
- package/dist/flags.js +15 -2
- package/dist/flags.mjs +15 -2
- package/dist/immutable.d.ts +1 -0
- package/dist/immutable.js +46 -0
- package/dist/immutable.mjs +8 -0
- package/dist/index.d.ts +7 -5
- package/dist/index.js +3 -67
- package/dist/index.mjs +3 -67
- package/dist/key-value-store.d.ts +21 -0
- package/dist/key-value-store.js +117 -0
- package/dist/key-value-store.mjs +72 -0
- package/dist/logs-internal.d.ts +2 -2
- package/dist/logs.js +5 -2
- package/dist/logs.mjs +5 -2
- package/dist/person-processing.d.ts +11 -0
- package/dist/person-processing.js +84 -0
- package/dist/person-processing.mjs +37 -0
- package/dist/posthog.d.ts +4 -3
- package/dist/posthog.js +154 -353
- package/dist/posthog.mjs +154 -353
- package/dist/root-composition.d.ts +11 -0
- package/dist/root-composition.js +138 -0
- package/dist/root-composition.mjs +100 -0
- package/dist/state.d.ts +6 -0
- package/dist/state.js +50 -56
- package/dist/state.mjs +50 -56
- package/dist/surveys-extension.js +11 -6
- package/dist/surveys-extension.mjs +11 -6
- package/dist/surveys-internal.d.ts +3 -2
- package/dist/types.d.ts +13 -19
- package/dist/utf8.d.ts +1 -0
- package/dist/utf8.js +52 -0
- package/dist/utf8.mjs +14 -0
- package/dist/version.js +1 -1
- package/dist/version.mjs +1 -1
- package/package.json +3 -3
package/ARCHITECTURE.md
CHANGED
|
@@ -6,7 +6,7 @@ This document defines the bundle architecture for `@posthog/browser`.
|
|
|
6
6
|
|
|
7
7
|
The goal is a behavior-complete core in the smallest practical bundle. Core behavior is a fixed constraint. Bundle size is the optimization objective.
|
|
8
8
|
|
|
9
|
-
The root package must provide a useful capture host. It must preserve required capture admission, consent, identity, session, cross-context, no-throw, and extension-isolation behavior.
|
|
9
|
+
The root package must provide a useful capture host. It must preserve required capture admission, consent, identity, session, cross-context, no-throw, and extension-isolation behavior. The root acquires the complete analytics product when an application resolves it, an enabled initial pageview needs it, or a capture-producing product resolves its dependency. Once acquired, analytics owns a bounded buffer and lazily loads queue scheduling and Capture V1 delivery after admission; an explicitly supplied analytics extension includes delivery statically. Feature flags initialize by default. Logs, surveys orchestration and autocapture load from explicit configuration, saved-state or remote-configuration signals, or explicit resolution. The `@posthog/browser/core` entrypoint omits automatic product dynamic-import references for deliberate manual composition. Do not reduce bundle size by removing an invariant. Reimplement the invariant with a smaller mechanism or move only the policy that can safely begin after admission.
|
|
10
10
|
|
|
11
11
|
Optional feature implementations must stay outside the initial root graph. Each public optional feature must remain in a removable chunk or explicit entrypoint, and the core entrypoint must not reference it. Application bundlers must be able to remove each unused module.
|
|
12
12
|
|
|
@@ -85,10 +85,9 @@ The core contains these responsibilities:
|
|
|
85
85
|
- Compact bot filtering.
|
|
86
86
|
- Device, anonymous, and identified state.
|
|
87
87
|
- Session, window, and cross-context correctness.
|
|
88
|
-
-
|
|
89
|
-
-
|
|
90
|
-
-
|
|
91
|
-
- Core-generated `$pageview` admission through the same buffer without waiting for remote configuration or analytics delivery.
|
|
88
|
+
- Conflict-safe persistence and session-admission authority.
|
|
89
|
+
- A scoped shared-client adapter that routes shared capture into analytics.
|
|
90
|
+
- Coordination of one initial `$pageview` through the analytics owner without waiting for remote configuration or analytics delivery.
|
|
92
91
|
- A small control-plane Fetch path for immediate remote configuration and extension requests.
|
|
93
92
|
- Consent and lifecycle authority for analytics dispatch, independent of delivery loading.
|
|
94
93
|
- Extension lifecycle and isolation.
|
|
@@ -96,9 +95,13 @@ The core contains these responsibilities:
|
|
|
96
95
|
|
|
97
96
|
Keep the capture pipeline fixed and direct. Use compact explicit state machines. Do not add a generic middleware framework or a general dependency-injection framework.
|
|
98
97
|
|
|
99
|
-
The root `createPostHog`
|
|
98
|
+
The root `createPostHog` composition wrapper snapshots product options, keeps supplied instances, and injects literal dynamic product loaders into `createPostHogCore`. Core does not statically construct analytics, its buffer, rate limiter or property normalizers. The manual core entrypoint installs only supplied extensions and has no implicit analytics instance or automatic product imports. Owner properties are synchronous ready-only lookups; `resolveExtension()` starts an eligible loader, shares concurrent acquisition and waits for setup. `analytics: false` disables implicit acquisition, while an explicit analytics instance takes precedence.
|
|
100
99
|
|
|
101
|
-
|
|
100
|
+
Supplied analytics initializes before other supplied extensions. Flags, surveys and autocapture await analytics resolution before exposing shared implementations that capture synchronously; their controls still work when analytics is explicitly disabled. An enabled initial pageview requests analytics separately. The factory awaits visible pageview admission before readiness; a hidden document waits on its visibility listener. Eager analytics configuration acquires the product and delivery during initialization. Once acquired, analytics interprets its own loading and scheduling options, with `automatic-analytics.ts` providing the separate deferred-delivery loader.
|
|
101
|
+
|
|
102
|
+
Analytics owns capture finalization, admission, rate limiting, immediate delivery, identity/group operations, and dynamic event-property producers. Core supplies retained state, session admission, consent/lifecycle authority, requests and diagnostics through `AnalyticsCaptureHost`; consent transitions purge the installed analytics owner. The registry flushes installed owners once and isolates failed acquisition/setup without publishing an unusable owner.
|
|
103
|
+
|
|
104
|
+
First-party analytics receives package-private `AnalyticsCaptureHost` initialization with the bound request runtime, dispatch-time consent/lifecycle authority, diagnostic reporting, and a capacity-availability notification for pending initial pageviews. This preserves raw gzip bodies, abort signals, keepalive, and shutdown delivery without changing the shared `Client.sendRequest()` contract. Core neither constructs a delivery object nor supplies queue-control callbacks. Browser-next extensions receive a scoped `IPostHogInternal` during setup; shared implementations receive its separate narrow `sharedClient` adapter.
|
|
102
105
|
|
|
103
106
|
Analytics owns one `EventBuffer` throughout its lifetime; `analytics-buffer.ts` contains admission and loading coordination, while `analytics-delivery.ts` creates the deferred `Lane` driver for that existing buffer. The driver owns scheduling, finite flush barriers, transport, and retry coordination. It is ordinary implementation code within analytics, not a registered extension.
|
|
104
107
|
|
|
@@ -130,9 +133,9 @@ The analytics delivery capability must use Capture Analytics V1 at `POST /i/v1/a
|
|
|
130
133
|
|
|
131
134
|
When remote configuration advertises `gzip-js`, analytics compresses exact request envelopes of at least 1 KiB through native `CompressionStream('gzip')`. It sends gzip only when the result is smaller and has a valid header, CRC, and input-size trailer. Missing, hostile, malformed, stalled, or expanding compression falls back to the unchanged JSON body without consuming a delivery attempt. Delivery proceeds uncompressed while remote configuration is unresolved, so the initial pageview and queued work do not wait for negotiation. These thresholds are measured browser policy, not Capture V1 server limits.
|
|
132
135
|
|
|
133
|
-
Analytics exposes a stable typed admission capability and owns its buffer independently of delivery loading. The buffer retains at most 1,000 queued events and 8 MiB across active and queued UTF-8 serialized finalized messages. An individual finalized core message has the same 8 MiB local limit. Queue pressure evicts the oldest queued prefix when enough queued work is reclaimable; active work cannot be recalled, so active bytes can reject a new event without evicting valid queued work. Queue residence expires strictly after one hour at the next admission, installation, drain, flush, or retry handoff; expiry uses monotonic local admission time and starts no expiry timer. Retry-exhausted transient messages remain byte- and count-accounted at their original FIFO position, become ineligible for the current drive, and can be redriven by the next interval, reconnect, count trigger, or explicit flush. A flush barrier resolves after its admitted snapshot receives one delivery drive; it does not hot-loop retained failures or wait indefinitely for server acceptance. These package-private values bound browser memory and stale delivery and do not claim the deployed V1 event or batch limits. The policy owns one endpoint, event/batch serializer, server payload limits, compression, transport, response classification, retry policy, and teardown policy. Events with different policies must not share a batch. A failure in one lane must not requeue or resend events accepted in another lane. The composition root creates the analytics extension with usable buffering before delivery attaches.
|
|
136
|
+
Analytics exposes a stable typed admission capability and owns its buffer independently of delivery loading. The buffer retains at most 1,000 queued events and 8 MiB across active and queued UTF-8 serialized finalized messages. An individual finalized core message has the same 8 MiB local limit. Queue pressure evicts the oldest queued prefix when enough queued work is reclaimable; active work cannot be recalled, so active bytes can reject a new event without evicting valid queued work. Queue residence expires strictly after one hour at the next admission, installation, drain, flush, or retry handoff; expiry uses monotonic local admission time and starts no expiry timer. Retry-exhausted transient messages remain byte- and count-accounted at their original FIFO position, become ineligible for the current drive, and can be redriven by the next interval, reconnect, count trigger, or explicit flush. A flush barrier resolves after its admitted snapshot receives one delivery drive; it does not hot-loop retained failures or wait indefinitely for server acceptance. These package-private values bound browser memory and stale delivery and do not claim the deployed V1 event or batch limits. The policy owns one endpoint, event/batch serializer, server payload limits, compression, transport, response classification, retry policy, and teardown policy. Events with different policies must not share a batch. A failure in one lane must not requeue or resend events accepted in another lane. The composition root creates the analytics extension with usable buffering before delivery attaches. Analytics `capture()` performs bounded admission, commits Core's session authority only after acceptance, and rolls back queued work when session admission fails. Delivery loading starts only after successful admission. The default entrypoint supplies a literal dynamic-import reference; its initial chunk and the core entrypoint exclude the queue driver and analytics delivery policy. Attaching a policy must preserve queued event UUIDs, timestamps, identity, session, ordering, measured bytes, admission time, and retry multiplicity. Optional product entry points create their lanes only when imported; the root must not contain their implementations or a product catalog.
|
|
134
137
|
|
|
135
|
-
`captureImmediate()` is the explicit exception to queued delivery.
|
|
138
|
+
`captureImmediate()` is the explicit exception to queued delivery. Analytics finalizes and commits one event through the same admission boundaries, then sends it inline. The capability's package-private immediate primitive accepts a readonly message array so single capture wraps the same batch-oriented Capture V1 sender and result classifier used by lane delivery. Immediate messages never enter the lane, are not retained for a later flush, can overtake buffered work, and may run concurrently. Unlike the general point-in-time consent rule, an observed denial permanently cancels pending immediate dispatch and retries; later opt-in does not revive them. Already-dispatched requests may finish. A valid `2xx` resolves to a terminal summary: only `ok` and `warning` count as persisted, while `drop`, final `retry`, and missing results do not. Request-level terminal failures, exhausted transport retries, malformed responses, cancellation, and unavailable delivery resolve with an operation-level `error` in the summary, retaining known partial outcomes and setting `allPersisted` to `false` even when nothing was submitted. The public immediate-capture boundary contains unexpected exceptions and rejected delivery promises as failure summaries. Local non-admission resolves an empty summary and callers requiring durability must verify both submitted count and persistence. The default entrypoint may satisfy an immediate call through its injected lazy loader; the core entrypoint contains no delivery import and requires an explicitly installed analytics capability. Analytics must degrade gracefully when a loaded delivery driver implements queued delivery without the immediate method.
|
|
136
139
|
|
|
137
140
|
After configured extensions install, core admits one enabled initial `$pageview` through ordinary capture before the factory resolves. `capturePageview: false` disables it. Hidden documents wait on one disposable visibility listener. Consent and bot filtering are enforced only when ordinary capture begins, and a later explicit opt-in can admit a pageview that prior denial held pending. The core event has no title, URL, referrer, page-view identifier, history patching, or page-leave behavior; those remain in an optional page-view/browser-context product.
|
|
138
141
|
|
|
@@ -173,15 +176,18 @@ Cross-context conflict safety is also a core invariant. Same-origin local-storag
|
|
|
173
176
|
|
|
174
177
|
## 5. Root entry point
|
|
175
178
|
|
|
176
|
-
The root
|
|
179
|
+
The initial root graph contains Core and product-composition glue, not analytics admission, buffering or delivery implementations. Resolving analytics acquires its API and buffer first; an admitted capture then starts its separate delivery import. `analytics.load: 'eager'` acquires both during initialization. `analytics: false` blocks implicit acquisition, but not an explicitly supplied instance. The manual core entrypoint has no implicit analytics product. Once acquired, the analytics owner remains the same instance before and after delivery loads.
|
|
177
180
|
|
|
178
181
|
The root entry point must use named exports. It must not create a default client singleton.
|
|
179
182
|
|
|
180
183
|
Use a narrow root wrapper with a literal dynamic loader and a separate core entry:
|
|
181
184
|
|
|
182
185
|
```ts
|
|
183
|
-
//
|
|
184
|
-
const
|
|
186
|
+
// Root composition: acquire the whole product.
|
|
187
|
+
const loadAnalytics = () => import('./automatic-analytics').then(({ analytics }) => analytics({}))
|
|
188
|
+
|
|
189
|
+
// Inside the acquired product: load delivery separately.
|
|
190
|
+
const loadDelivery = () => import('./analytics-delivery').then(({ createAnalyticsDelivery }) => createAnalyticsDelivery)
|
|
185
191
|
|
|
186
192
|
// @posthog/browser/core
|
|
187
193
|
export { createPostHog } from './core'
|
|
@@ -194,7 +200,7 @@ export * from './products'
|
|
|
194
200
|
export { default } from './singleton'
|
|
195
201
|
```
|
|
196
202
|
|
|
197
|
-
The root entry point must not re-export optional runtime features. Its
|
|
203
|
+
The root entry point must not re-export optional runtime features. Its loaders acquire whole products; analytics delivery and survey rendering remain further deferred imports. Flags initializes by default. Logs, surveys and autocapture activate from explicit options, saved-state or remote-configuration signals, or explicit resolution. You can re-export types when the compiler produces no JavaScript import.
|
|
198
204
|
|
|
199
205
|
Treat `createPostHog` and its static imports as one size unit.
|
|
200
206
|
A bundler cannot remove an internal module when the factory always needs that module.
|
|
@@ -205,7 +211,7 @@ Use an extension or an adapter instead.
|
|
|
205
211
|
|
|
206
212
|
### Autocapture
|
|
207
213
|
|
|
208
|
-
|
|
214
|
+
Explicit autocapture options, saved-state or remote-configuration opt-in, or explicit resolution trigger a literal dynamic import and setup, unless disabled or an explicit instance exists. `/autocapture` statically includes the same browser-common implementation; the manual core has no automatic import. Configuration uses camelCase, maps inside the optional module, and snapshots arrays/regular expressions without losing callbacks. The latest staged browser defaults apply: URL hashes are redacted, rageclick ignores stepper content and text-selection surfaces, clipboard capture is opt-in, and text/attribute masking remains false by default. Remote-config/cached opt-out policy, consent, DOM privacy filters, and event wire properties remain shared. No new core method or host contract is needed.
|
|
209
215
|
|
|
210
216
|
Survey action selectors are owned by the optional surveys module. It returns copied snapshots to autocapture at setup and forwards replacements when definitions register later. Receiver creation hydrates running triggers from the existing cached definitions without adding requests or bypassing TTL/backoff. Successful full definition refreshes replace next's trigger maps, including empty snapshots; failed fetches retain them. The shared orchestration also replaces trigger maps for legacy clients. Survey disposal clears its selector set. For URL-constrained actions, the surveys observation adapter supplies a missing URL from its existing targeting URL capability only to local matching; explicit event URL values are preserved and observed/wire events are not modified. There is no generic extension-registration observer or core selector catalog. Matching keeps existing exact-target and SVG-control attribution rather than broadening ancestor matches.
|
|
211
217
|
|
|
@@ -213,15 +219,15 @@ Survey action selectors are owned by the optional surveys module. It returns cop
|
|
|
213
219
|
|
|
214
220
|
`flags` accepts the same `FlagsOptions` as `flags(options)` from `@posthog/browser/flags`. With no explicit `featureFlags` extension, the root awaits a literal flags import and extension setup before resolving. It does not await remote evaluation. `flags: false` disables automatic inclusion; an explicit instance takes precedence. Failed loading/setup is isolated from core capture. The manual core entrypoint never imports flags automatically.
|
|
215
221
|
|
|
216
|
-
Applications access flag controls through `
|
|
222
|
+
Applications access flag controls through `await posthog.resolveExtension(FeatureFlagsExtension)`. The typed token is lightweight and does not import the implementation. Result conversion, subscriptions, bootstrap, and evaluation stay in the optional module. Missing or failed extensions return undefined from lookup. Callbacks enumerate results without emitting flag-called events.
|
|
217
223
|
|
|
218
|
-
Browser-next supplies
|
|
224
|
+
Browser-next supplies an `IPostHogInternal` scoped host with a separate shared `Client` adapter. Identification publishes `onIdentify`; local person-property updates publish the product-host `onChangeProperties` notification with `set`, `setOnce` and `unset` fields. Property setters do not publish identification, while identification with properties publishes both notifications. Core also supplies `onGroup`, `onGroupsReset` and `onReset`. Notifications run synchronously, independently of capture admission. Publishers isolate listener failures and do not replay earlier operations. Extensions subscribe during setup and dispose their subscriptions during teardown. Flags uses identification to update identity-dependent tracking and property changes to update evaluation context; core does not look up product-specific hooks.
|
|
219
225
|
|
|
220
226
|
Flags passes the shared `Client` directly to the shared feature-flags implementation and stores its values through `Client.kv`. The host owns storage selection, serialization, and durable writes. Core reset clears persisted extension data before notifying flags to clear its in-memory evaluation state and reload. Flag values follow the client's configured persistence, including memory-only operation with `storage: false`.
|
|
221
227
|
|
|
222
228
|
### Logs
|
|
223
229
|
|
|
224
|
-
Logs follows the flags composition pattern:
|
|
230
|
+
Logs follows the flags composition pattern: explicit configuration or resolution loads the literal module import and awaits setup, not remote configuration. `logs: false` omits automatic inclusion; an explicit `logs(options)` extension owns its configuration and takes precedence. The manual core entrypoint contains no logs import. Applications call `captureLog()` on the logs extension; SDK diagnostics retain the existing `logger`.
|
|
225
231
|
|
|
226
232
|
The optional module adapts the shared browser-common logs implementation. It owns programmatic and console queues, OTLP resources/scopes, the console runtime, persisted console enablement hints, and pagehide handoff. Console capture follows existing local/remote gates, not module loading. The generic console serialization and patching runtime is shared with legacy browser bundles; historical ABI routing and global registration stay exclusively in the legacy entrypoint.
|
|
227
233
|
|
|
@@ -231,7 +237,7 @@ The logs extension subscribes to the browser client's reset and consent-change n
|
|
|
231
237
|
|
|
232
238
|
### Surveys
|
|
233
239
|
|
|
234
|
-
|
|
240
|
+
Explicit surveys options, a remote-configuration gate, or explicit resolution acquire only optional surveys orchestration; acquisition awaits setup, not remote configuration, renderer loading, or survey definitions. The orchestration module owns the literal dynamic import of the shared renderer. A successful remote configuration with a truthy surveys gate loads UI automatically. A false or unavailable gate leaves it deferred, while explicit survey APIs may initialize a non-automatic manager. If enabled remote configuration arrives later, that same manager starts its idempotent automatic-display loop unless automatic display is disabled; it is not replaced or duplicated. The explicit `@posthog/browser/surveys` factory includes orchestration only and defers the same renderer through a literal dynamic import. Preact, CSS, and DOMPurify belong behind that boundary; DOMPurify initializes browser capabilities when its module loads, so it must not enter the import-pure factory graph. An explicit instance wins over `surveys`, and `surveys: false` omits automatic inclusion.
|
|
235
241
|
|
|
236
242
|
Application-facing survey controls belong to the extension reference, obtained from the explicit factory or `getExtension()`. The extension receives host capabilities through ordinary setup and subscribes to `BrowserClient.onReset` for runtime cleanup. Renderer waiting and call coordination stay in the optional module; no post-init public registry installation is introduced. Manual `canRenderSurvey` resolves unavailable when disposed during loading or fetch. Callback delivery is suppressed after disposal.
|
|
237
243
|
|
|
@@ -371,7 +377,7 @@ The change must include measurements that support this decision.
|
|
|
371
377
|
|
|
372
378
|
The extension registry stores configured instances and automatic instances selected by the root factory. Explicit analytics, feature-flags, logs, surveys, and autocapture instances take precedence over their corresponding top-level options. Analytics delivery loading does not add a registry entry; flags register the same extension implementation used by static inclusion.
|
|
373
379
|
|
|
374
|
-
|
|
380
|
+
Keep product factories, option interpretation and literal imports in composition code. Core may store injected named loaders and dependency bookkeeping, but must not import a static catalog of product implementations. Other products require explicit composition until their automatic loading contract is implemented.
|
|
375
381
|
|
|
376
382
|
Do not put this code in the root graph:
|
|
377
383
|
|
|
@@ -410,12 +416,12 @@ The client owns every configured or internally created extension for its lifetim
|
|
|
410
416
|
An extension must release owned resources in its final `dispose()`.
|
|
411
417
|
Cleanup must be safe after partial setup.
|
|
412
418
|
|
|
413
|
-
The host must give each extension a narrow `
|
|
414
|
-
|
|
419
|
+
The host must give each browser-next extension a scoped `IPostHogInternal` view, with its own narrow `sharedClient` adapter for shared implementations.
|
|
420
|
+
These views must expose capabilities, not the concrete host implementation.
|
|
415
421
|
|
|
416
422
|
The host must keep extension state separate. The host must dispose extensions in reverse installation order.
|
|
417
423
|
|
|
418
|
-
|
|
424
|
+
Owner names and shared binding names are separate namespaces. Browser product properties and awaited `resolveExtension()` return successfully initialized lifecycle owners. An extension's `bindings` map supplies targets only for the shared adapter's synchronous `getExtension()` lookup; owner names are not implicit shared bindings. For example, `client.featureFlags` returns the browser facade, while `client.sharedClient.getExtension('featureFlags')` returns its shared implementation. The registered extension is the sole lifecycle owner: binding targets are not independently set up, flushed or disposed. Shared bindings are reserved before setup and removed when the owner fails setup, is rolled back, or is disposed.
|
|
419
425
|
|
|
420
426
|
An extension failure must not stop core capture. A failed setup must remove all reserved registry state.
|
|
421
427
|
|
package/README.md
CHANGED
|
@@ -2,21 +2,22 @@
|
|
|
2
2
|
|
|
3
3
|
An experimental PostHog client for modern browsers. The API is not yet stable.
|
|
4
4
|
|
|
5
|
+
Moving from `posthog-js`? See the [draft migration guide](./MIGRATION.md) for public API call-site changes and remaining gaps.
|
|
6
|
+
|
|
5
7
|
```sh
|
|
6
8
|
npm install @posthog/browser
|
|
7
9
|
```
|
|
8
10
|
|
|
9
|
-
The client installs one analytics extension with a bounded in-memory buffer during initialization. By default, the first successfully admitted event lazily loads its queue scheduling and Capture Analytics V1 delivery machinery. Consent-denied, bot-filtered, and rejected events do not load delivery. Feature flags, logs, surveys orchestration, and autocapture dynamically load during initialization by default; their capture and display behavior retains its own consent and remote-configuration gates. Survey rendering is a further deferred chunk.
|
|
10
|
-
|
|
11
11
|
```ts
|
|
12
12
|
import { createPostHog } from '@posthog/browser'
|
|
13
13
|
|
|
14
14
|
const posthog = await createPostHog({ projectToken: '<project-token>' })
|
|
15
|
-
posthog.
|
|
15
|
+
await posthog.resolveExtension('analytics')
|
|
16
|
+
posthog.analytics?.capture('signed_up')
|
|
16
17
|
await posthog.flush()
|
|
17
18
|
```
|
|
18
19
|
|
|
19
|
-
Configure
|
|
20
|
+
Configure scheduling or acquire analytics and start delivery while the client initializes:
|
|
20
21
|
|
|
21
22
|
```ts
|
|
22
23
|
const posthog = await createPostHog({
|
|
@@ -25,7 +26,7 @@ const posthog = await createPostHog({
|
|
|
25
26
|
})
|
|
26
27
|
```
|
|
27
28
|
|
|
28
|
-
Importing `@posthog/browser/analytics` statically includes both buffering and delivery. Supplying its extension selects that instance and its constructor options instead of automatic
|
|
29
|
+
Importing `@posthog/browser/analytics` statically includes both buffering and delivery. Supplying its extension selects that instance and its constructor options instead of automatic product acquisition:
|
|
29
30
|
|
|
30
31
|
```ts
|
|
31
32
|
import { analytics } from '@posthog/browser/analytics'
|
|
@@ -36,7 +37,70 @@ const posthog = await createPostHog({
|
|
|
36
37
|
})
|
|
37
38
|
```
|
|
38
39
|
|
|
39
|
-
Use `analytics: false` to
|
|
40
|
+
Use `analytics: false` to block implicit analytics acquisition, including requests from other products. An explicitly supplied analytics instance takes precedence. The manual `@posthog/browser/core` entrypoint installs only supplied products and has no automatic product imports. Installed namespaces are synchronous lookups; `await posthog.resolveExtension('analytics')` acquires an eligible unloaded product and returns its installed instance, or undefined if disabled or unavailable. Concurrent requests share loading and setup. Supplied analytics initializes before other configured extensions; extensions needing a capture dependency resolve it before exposing synchronous operations.
|
|
41
|
+
|
|
42
|
+
Product namespaces expose owners only after successful setup. Reading a namespace never initiates loading. Use `await posthog.resolveExtension(token)` for typed custom-extension access; resolution waits for readiness and returns `undefined` when the extension is unavailable. Shared implementations receive a separate `Client` adapter with shared binding lookup.
|
|
43
|
+
|
|
44
|
+
Analytics owns person-profile policy through `personProfiles: 'always' | 'never' | 'identified_only'`, defaulting to `identified_only`. Anonymous events carry `process_person_profile: false` in Capture V1 options until identification, group registration or explicit profile enablement. Configure it through `analytics: { personProfiles: 'always' }` or an explicit `analytics({ personProfiles: 'always' })` instance. SDK-computed processing metadata takes precedence over caller properties; `$process_person_profile` does not change the SDK's underlying processing state.
|
|
45
|
+
|
|
46
|
+
Use the analytics product's `createPersonProfile()`, `setPersonProperties(set?, setOnce?)`, `unsetPersonProperties(names)` and `setInternalOrTestUser()` controls for explicit person updates. Profile creation and property updates preserve the current anonymous identity; they do not identify the user. Set, set-once and unset also update local feature-flag person context. Exact repeated property updates are deduplicated only after local event admission. Reset clears explicit profile enablement and deduplication, without rewriting queued events. In `never` mode, person helpers, identify and group registration are no-ops; ordinary capture continues without person processing.
|
|
47
|
+
|
|
48
|
+
Resolve or explicitly compose analytics before using its identity controls. `alias(targetId)` links the current ID without changing the current identity or marking it identified; it enables person processing unless disabled by policy. Use `identify()` to switch the ambient identity.
|
|
49
|
+
|
|
50
|
+
`group(type, key, properties?)` persists ambient membership. `groupIdentify(type, key, properties?, options?)` sends a group-profile update without changing membership or local flag-evaluation context; its key can be a string or finite number, and its options use the ordinary capture pipeline. Alias and group-profile events require capture consent and are suppressed in `never` mode. `resetGroups()` clears memberships, retaining identity, sessions, person properties and other stored state. When flags is installed it also clears group properties used for evaluation and requests a reload. Persisted group flag properties can remain when flags is absent ([tracked in #5673](https://github.com/PostHog/posthog-js/issues/5673)). It remains available for cleanup when capture is denied or person processing is disabled. Previously queued events retain their captured group context.
|
|
51
|
+
|
|
52
|
+
```ts
|
|
53
|
+
const analytics = await posthog.resolveExtension('analytics')
|
|
54
|
+
analytics?.alias('account-123')
|
|
55
|
+
await analytics?.group('organization', 'current-group')
|
|
56
|
+
analytics?.groupIdentify('organization', 'another-group', { plan: 'enterprise' })
|
|
57
|
+
analytics?.resetGroups()
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
## Persistent event properties
|
|
61
|
+
|
|
62
|
+
Use the installed analytics product to register context for future events:
|
|
63
|
+
|
|
64
|
+
```ts
|
|
65
|
+
const analytics = await posthog.resolveExtension('analytics')
|
|
66
|
+
analytics?.register({ plan: 'pro', region: 'eu' })
|
|
67
|
+
analytics?.registerOnce({ acquisitionSource: 'website' })
|
|
68
|
+
analytics?.capture('dashboard', { plan: 'enterprise' })
|
|
69
|
+
const region = analytics?.getProperty('region')
|
|
70
|
+
analytics?.unregister('region')
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
`register(properties)` merges JSON-serializable properties into analytics' Core-owned persistent storage. `registerOnce(properties, defaultValue = 'None')` adds missing keys or replaces existing values strictly equal to the sentinel; other existing values, including `false`, `0`, `''` and `null`, are retained. `getProperty(key)` returns an isolated stored value, or `undefined` for a missing key. Registration inputs and captured events are snapshotted, so later input or stored-property changes do not rewrite queued events.
|
|
74
|
+
|
|
75
|
+
Persistent properties are overridden by session properties, then dynamic event-property producers, then caller properties and capture options. SDK identity, group, session, library and person-processing metadata remains authoritative. Registration and removal only change local context, do not emit events, and remain available when capture consent is denied or person processing is disabled. Properties survive reload with persistent storage, until overwritten, unregistered or cleared by full `reset()`; `resetGroups()` retains them.
|
|
76
|
+
|
|
77
|
+
## Session event properties
|
|
78
|
+
|
|
79
|
+
```ts
|
|
80
|
+
const analytics = await posthog.resolveExtension('analytics')
|
|
81
|
+
analytics?.registerForSession({ checkoutFlow: 'express' })
|
|
82
|
+
analytics?.unregisterForSession('checkoutFlow')
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
With default browser storage, session properties use Core-owned per-tab storage, surviving reloads in the same SDK session. Independent tabs are isolated; copied tabs inherit a snapshot and then diverge. With a custom `storage` adapter, `storage: false` or unavailable native session storage, properties remain in per-instance memory. They override persistent defaults, but dynamic producers, caller properties, capture options and protected SDK metadata take precedence.
|
|
86
|
+
|
|
87
|
+
Registration and removal are local, do not create a session, and remain available under capture denial or `personProfiles: 'never'`. Properties registered before the first event or after the current session expires remain pending for the next admitted session. Registration does not extend session activity. On Core session rotation or adoption, old properties are excluded from the new session's events and cleared only after successful admission; rejected events retain the old scope. Full `reset()` clears session properties; `resetGroups()` retains them. Already-admitted events retain their finalized properties.
|
|
88
|
+
|
|
89
|
+
## Migrating to analytics-owned operations
|
|
90
|
+
|
|
91
|
+
Analytics operations now belong to `posthog.analytics`, not the Core client:
|
|
92
|
+
|
|
93
|
+
| Previous client API | Replacement |
|
|
94
|
+
| ---------------------------------- | ----------------------------------------------------------------------- |
|
|
95
|
+
| `capture()`, `captureImmediate()` | `posthog.analytics?.capture()`, `posthog.analytics?.captureImmediate()` |
|
|
96
|
+
| `identify()`, `group()`, `reset()` | The corresponding method on `posthog.analytics` |
|
|
97
|
+
| `onEvent`, `isRateLimited` | The corresponding member on `posthog.analytics` |
|
|
98
|
+
| `registerDynamicEventProperties()` | `posthog.analytics?.registerDynamicEventProperties()` |
|
|
99
|
+
| Synchronous `getExtension(token)` | `await posthog.resolveExtension(token)` |
|
|
100
|
+
|
|
101
|
+
Product namespaces are optional: they expose successfully initialized owners, not availability of network delivery. Resolve a product before using it when initialization may still be pending, and handle `undefined` when it is unavailable. `flush()` and `dispose()` remain on the client, alongside consent, identity/session getters, remote configuration and scoped key-value storage.
|
|
102
|
+
|
|
103
|
+
Replace the removed application type export `PostHog` with `IPostHog`. For extension authors, replace the removed `BrowserClient` type export with `IPostHogInternal`. `BrowserExtension` (also exported as `Extension`) is the browser-next extension contract; shared implementations continue using `Client` from `@posthog/browser-common`. The setup host exposes browser product owners directly. Its `sharedClient` adapter supplies shared implementations with their binding lookup and capture surface; it is not the application client.
|
|
40
104
|
|
|
41
105
|
## Classic script installation (draft CDN distribution)
|
|
42
106
|
|
|
@@ -46,7 +110,7 @@ The CDN build supports a plain external classic script in ordinary, `async`, or
|
|
|
46
110
|
<script async src="https://us-assets.i.posthog.com/static/browser/0/script.js?projectToken=YOUR_PROJECT_TOKEN"></script>
|
|
47
111
|
```
|
|
48
112
|
|
|
49
|
-
The first response embeds
|
|
113
|
+
The first response embeds core and full analytics, including Capture V1 delivery. Queued and immediate analytics do not require another JavaScript request. Optional implementations load through native bundler-generated script chunks relative to that script's directory, including when assets and the page have different origins. Publish the entire `dist-cdn` tree together, keeping hashed chunks available during alias updates. Query parameters and fragments are not forwarded to chunk URLs. When the installing script has a CSP nonce, deferred chunk scripts inherit it. The asset host is not the ingestion host: the SDK's US ingestion default still applies. Set `apiHost` explicitly for EU ingestion or a proxy, URL-encoding its value, for example `&apiHost=https%3A%2F%2Feu.i.posthog.com` in HTML.
|
|
50
114
|
|
|
51
115
|
Only these query options are supported; omitted options use the existing factory defaults:
|
|
52
116
|
|
|
@@ -63,7 +127,7 @@ After the existing `createPostHog()` factory resolves, the script assigns `windo
|
|
|
63
127
|
|
|
64
128
|
```js
|
|
65
129
|
function onPostHogReady(client) {
|
|
66
|
-
client.capture('signed_up')
|
|
130
|
+
client.analytics?.capture('signed_up')
|
|
67
131
|
}
|
|
68
132
|
if (window.posthog) {
|
|
69
133
|
onPostHogReady(window.posthog)
|
|
@@ -72,7 +136,7 @@ if (window.posthog) {
|
|
|
72
136
|
}
|
|
73
137
|
```
|
|
74
138
|
|
|
75
|
-
There is no pre-load capture queue. Concurrent tags share an in-flight installation reservation: the first valid tag wins, even if later tags specify different options. Any existing `posthog` property (including a reserved undefined property or a legacy stub) prevents installation, without initialization or a new ready event. If another installer claims the global during initialization, the unpublished client is disposed rather than overwriting it. A failed installation releases its reservation so a subsequent tag can retry. Failed optional chunks retain the factory's existing failure isolation; ready can still expose
|
|
139
|
+
There is no pre-load capture queue. Concurrent tags share an in-flight installation reservation: the first valid tag wins, even if later tags specify different options. Any existing `posthog` property (including a reserved undefined property or a legacy stub) prevents installation, without initialization or a new ready event. If another installer claims the global during initialization, the unpublished client is disposed rather than overwriting it. A failed installation releases its reservation so a subsequent tag can retry. Failed optional chunks retain the factory's existing failure isolation; ready can still expose working embedded analytics. Consent and capture admission remain unchanged.
|
|
76
140
|
|
|
77
141
|
Build and validate locally after building workspace dependencies:
|
|
78
142
|
|
|
@@ -86,7 +150,7 @@ pnpm --filter @posthog/browser test:snippet
|
|
|
86
150
|
|
|
87
151
|
## Autocapture
|
|
88
152
|
|
|
89
|
-
|
|
153
|
+
With no explicit autocapture configuration, its implementation loads when saved state or remote configuration indicates a server opt-in. Supplying an autocapture options object loads it during initialization. Code loading alone does not enable collection: it waits for the initial remote configuration outcome and a known server opt-in (or a retained opt-in after a failed refresh). Consent, bot filtering, and local privacy exclusions still apply. `autocapture: false` omits automatic inclusion; it does not disable another product's configuration or an explicitly supplied autocapture instance.
|
|
90
154
|
|
|
91
155
|
```ts
|
|
92
156
|
const posthog = await createPostHog({
|
|
@@ -127,7 +191,7 @@ const posthog = await createPostHog({
|
|
|
127
191
|
projectToken: '<project-token>',
|
|
128
192
|
flags: { evaluationContexts: ['web'], requestTimeoutMs: 3_000 },
|
|
129
193
|
})
|
|
130
|
-
const featureFlags = posthog.
|
|
194
|
+
const featureFlags = await posthog.resolveExtension(FeatureFlagsExtension)
|
|
131
195
|
const subscription = featureFlags?.onFeatureFlags((results, errorsLoading) => {
|
|
132
196
|
if (!errorsLoading) console.log(results)
|
|
133
197
|
})
|
|
@@ -136,7 +200,7 @@ if (result?.enabled) console.log(result.variant, result.payload)
|
|
|
136
200
|
subscription?.dispose()
|
|
137
201
|
```
|
|
138
202
|
|
|
139
|
-
`FeatureFlagsExtension` is a lightweight typed lookup token, exported from the root, core, and flags entrypoints. `
|
|
203
|
+
`FeatureFlagsExtension` is a lightweight typed lookup token, exported from the root, core, and flags entrypoints. `resolveExtension(FeatureFlagsExtension)` resolves to undefined when flags is disabled or failed to install. The extension's `getFeatureFlag()` returns undefined until a value is available. A disabled flag returns an object with `enabled: false`. Reads emit deduplicated flag-called analytics through ordinary capture; subscriptions do not. `updateFlags(values, payloads?, { merge })` injects flag values.
|
|
140
204
|
|
|
141
205
|
Use `reloadFeatureFlags()` to request a remote evaluation and await its outcome before reading again:
|
|
142
206
|
|
|
@@ -172,15 +236,15 @@ Creating an extension does not initialize it. Pass it in the `extensions` option
|
|
|
172
236
|
|
|
173
237
|
### Lifecycle notifications
|
|
174
238
|
|
|
175
|
-
Browser-next supplies
|
|
239
|
+
Browser-next supplies an `IPostHogInternal` scoped host to extension setup. It exposes browser namespaces, asynchronous dependency resolution, and `onIdentify`, `onGroup`, `onGroupsReset` and `onReset` listeners. Identification uses `onIdentify`; person-property setters use the separate product-host `onChangeProperties` notification with `set`, `setOnce` and `unset` fields. Identification with properties publishes both kinds of notification. Group-only reset uses `onGroupsReset`; full identity reset uses `onReset`. These notifications fire synchronously after local state updates, independently of capture consent, and do not replay earlier operations. Listener errors are logged without stopping other listeners. Dispose subscriptions when the extension is disposed.
|
|
176
240
|
|
|
177
241
|
```ts
|
|
178
|
-
import type {
|
|
242
|
+
import type { IPostHogInternal, Disposable } from '@posthog/browser'
|
|
179
243
|
|
|
180
244
|
let subscription: Disposable | undefined
|
|
181
245
|
const extension = {
|
|
182
246
|
name: 'identity-observer',
|
|
183
|
-
setup(client:
|
|
247
|
+
setup(client: IPostHogInternal) {
|
|
184
248
|
subscription = client.onIdentify(({ distinctId, previousDistinctId }) => {
|
|
185
249
|
console.log(previousDistinctId, distinctId)
|
|
186
250
|
})
|
|
@@ -193,18 +257,16 @@ const extension = {
|
|
|
193
257
|
|
|
194
258
|
## Logs
|
|
195
259
|
|
|
196
|
-
|
|
260
|
+
With no explicit logs configuration, logs loads from a saved console-capture hint, remote console enablement or `resolveExtension('logs')`. Supplying a logs options object loads it during initialization. Console collection starts after the implementation loads. `captureLog()` explicitly queues an OTLP log; loading the extension alone does not turn on console capture. Console capture follows remote configuration or a local `captureConsoleLogs` opt-in:
|
|
197
261
|
|
|
198
262
|
```ts
|
|
199
|
-
import type { LogsExtension } from '@posthog/browser/logs'
|
|
200
|
-
|
|
201
263
|
const posthog = await createPostHog({
|
|
202
264
|
projectToken: '<project-token>',
|
|
203
265
|
logs: { captureConsoleLogs: true, serviceName: 'storefront', flushIntervalMs: 3_000 },
|
|
204
266
|
})
|
|
205
|
-
const logger = posthog.
|
|
206
|
-
logger
|
|
207
|
-
await logger
|
|
267
|
+
const logger = await posthog.resolveExtension('logs')
|
|
268
|
+
logger?.captureLog({ body: 'Checkout completed', level: 'info', attributes: { orderId: '123' } })
|
|
269
|
+
await logger?.flush()
|
|
208
270
|
```
|
|
209
271
|
|
|
210
272
|
Use `logs: false` to disable automatic inclusion. For static inclusion without a runtime module request:
|
|
@@ -228,16 +290,14 @@ The logs extension's `flush()` awaits both log queues. `posthog.flush()` awaits
|
|
|
228
290
|
|
|
229
291
|
## Surveys
|
|
230
292
|
|
|
231
|
-
|
|
293
|
+
With no explicit surveys configuration, orchestration loads from cached definitions, remote survey enablement or `resolveExtension('surveys')`. Supplying a surveys options object loads orchestration during initialization. Its UI is a separate dynamic chunk: a successful remote configuration with surveys enabled loads it automatically; otherwise an explicit survey call can load it for manual use. Definitions come from a separate `/api/surveys/` request and are cached for five minutes. Client creation does not wait for the renderer or definitions.
|
|
232
294
|
|
|
233
295
|
```ts
|
|
234
|
-
import type { SurveysExtension } from '@posthog/browser/surveys'
|
|
235
|
-
|
|
236
296
|
const posthog = await createPostHog({
|
|
237
297
|
projectToken: '<project-token>',
|
|
238
298
|
surveys: { automaticDisplay: false, requestTimeoutMs: 10_000 },
|
|
239
299
|
})
|
|
240
|
-
const feedback = posthog.
|
|
300
|
+
const feedback = await posthog.resolveExtension('surveys')
|
|
241
301
|
feedback?.getSurveys((surveys, context) => {
|
|
242
302
|
if (context?.isLoaded && surveys[0]) feedback.displaySurvey(surveys[0].id)
|
|
243
303
|
})
|
|
@@ -267,15 +327,20 @@ Definitions and event activation state use the host-provided surveys KV namespac
|
|
|
267
327
|
|
|
268
328
|
## Capture and delivery
|
|
269
329
|
|
|
270
|
-
|
|
330
|
+
Capture, immediate capture, identity and group controls, reset and event-property registration live on the analytics extension. Core owns shared identity, sessions, groups, consent, persistence and lifecycle. The npm root acquires the complete analytics API through asynchronous resolution; delivery remains a separate lazy chunk until an admitted capture or an operation needs it. An enabled initial pageview or capture-producing product also acquires it. Feature flags initialize during startup. When their options are omitted, logs, surveys orchestration and autocapture load on existing saved-state or remote-config signals, or explicit asynchronous acquisition. Their collection and display retain their own consent and remote-configuration gates; survey rendering is a further deferred chunk.
|
|
331
|
+
|
|
332
|
+
`analytics.capture()` runs synchronously. Its `false` result is a rate-limit backpressure signal, not a general rejection signal. `true` is neither an admission nor a delivery acknowledgement: consent, lifecycle, filtering, invalid properties or queue limits can suppress an event while it still returns `true`. Use `captureImmediate()` and check its summary when persistence matters. Capture never waits for code or network delivery. With pending queued work, `flush()` joins an in-progress delivery load and can retry failed automatic loading; without available delivery it resolves without discarding unexpired queued events. Analytics retains at most 1,000 queued events and 8 MiB of active-plus-queued finalized analytics messages; queued work expires strictly after one hour on the next queue interaction. Queue overflow evicts the oldest queued prefix, while active bytes cannot be recalled and can cause a new event to be rejected.
|
|
271
333
|
|
|
272
334
|
Queued and immediate capture omit null or undefined object properties from delivered events, including nested objects and objects inside arrays. Array positions are preserved; null and undefined array entries are sent as JSON `null`. Events with no remaining custom properties are still delivered with their SDK metadata.
|
|
273
335
|
|
|
274
336
|
Use `captureImmediate()` only when the caller needs a terminal delivery outcome before continuing:
|
|
275
337
|
|
|
276
338
|
```ts
|
|
277
|
-
const
|
|
278
|
-
|
|
339
|
+
const analytics = await posthog.resolveExtension('analytics')
|
|
340
|
+
const summary = await analytics?.captureImmediate('import_completed', { source: 'warehouse' })
|
|
341
|
+
if (!summary) {
|
|
342
|
+
console.warn('Analytics is unavailable')
|
|
343
|
+
} else if (summary.error) {
|
|
279
344
|
console.warn('Immediate capture failed', summary.error)
|
|
280
345
|
} else if (summary.submitted !== 1 || !summary.allPersisted) {
|
|
281
346
|
// Capture V1 did not confirm persistence of this event.
|
|
@@ -284,7 +349,7 @@ if (summary.error) {
|
|
|
284
349
|
|
|
285
350
|
Immediate capture finalizes the event through the same consent, identity, session, protected-property, size, and rate-limit boundaries, then bypasses the lane and sends inline through the same Capture V1 sender. A valid `2xx` resolves to a `CaptureSummary`; `drop`, final `retry`, and missing outcomes set `allPersisted` to `false`, while `warning` counts as persisted. Terminal HTTP failures, exhausted transport retries, malformed responses, cancellation, and unavailable delivery resolve with `summary.error` and `allPersisted: false`, retaining any known partial outcomes. These failures do not reject the promise. Local non-admission resolves an empty summary, so durability-sensitive callers must check both `submitted` and `allPersisted`. Immediate requests can overtake buffered events and run concurrently with each other; they are never retained for a later `flush()`. An observed consent denial permanently cancels pending immediate dispatch and retries, even if the user opts in again; already-dispatched requests may finish.
|
|
286
351
|
|
|
287
|
-
|
|
352
|
+
Acquire analytics before making an immediate call. The manual core exposes analytics only when explicitly supplied through `extensions`. Analytics admission and its bounded buffer remain independent of the inner delivery loader; delayed delivery retains finalized event snapshots, cancellation and retries, not raw calls to replay.
|
|
288
353
|
|
|
289
354
|
The analytics extension sends FIFO Capture V1 batches of at most 100 events and partitions large backlogs by exact uncompressed envelope size. `flushAt` defaults to 20 and triggers delivery by queued count; `flushInterval` defaults to 3,000 milliseconds and triggers delivery by age. Set `flushInterval: 0` to disable timer delivery. Explicit `flush()` and shutdown bypass both thresholds. Retry-exhausted transient failures remain in the bounded lane for a later interval, reconnect, or explicit flush rather than hot-looping or being discarded.
|
|
290
355
|
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import type { CaptureOptions, CapturedEventInfo, Disposable, Listener } from '@posthog/browser-common';
|
|
2
|
+
import type { BrowserExtension } from './browser-client';
|
|
3
|
+
import type { CaptureSummary } from './types';
|
|
4
|
+
/** Application-facing analytics operations on one installed product instance. */
|
|
5
|
+
export interface IAnalytics extends BrowserExtension {
|
|
6
|
+
readonly isRateLimited: boolean;
|
|
7
|
+
readonly onEvent: Listener<CapturedEventInfo>;
|
|
8
|
+
/**
|
|
9
|
+
* Synchronous capture. False signals rate-limit backpressure; true does not acknowledge admission or delivery.
|
|
10
|
+
* Consent, filtering, invalid properties and queue limits can suppress an event while returning true.
|
|
11
|
+
*/
|
|
12
|
+
capture(event: string, properties?: Record<string, unknown> | null, options?: CaptureOptions): boolean;
|
|
13
|
+
captureImmediate(event: string, properties?: Record<string, unknown> | null, options?: CaptureOptions): Promise<CaptureSummary>;
|
|
14
|
+
identify(distinctId: string, set?: Record<string, unknown>, setOnce?: Record<string, unknown>): Promise<void>;
|
|
15
|
+
alias(alias: string): void;
|
|
16
|
+
group(type: string, key: string, properties?: Record<string, unknown>): Promise<void>;
|
|
17
|
+
groupIdentify(type: string, key: string | number, properties?: Record<string, unknown>, options?: CaptureOptions): void;
|
|
18
|
+
resetGroups(): void;
|
|
19
|
+
reset(): void;
|
|
20
|
+
createPersonProfile(): void;
|
|
21
|
+
setPersonProperties(set?: Record<string, unknown>, setOnce?: Record<string, unknown>): void;
|
|
22
|
+
unsetPersonProperties(names: string | readonly string[]): void;
|
|
23
|
+
setInternalOrTestUser(): void;
|
|
24
|
+
register(properties: Record<string, unknown>): void;
|
|
25
|
+
registerOnce(properties: Record<string, unknown>, defaultValue?: unknown): void;
|
|
26
|
+
registerForSession(properties: Record<string, unknown>): void;
|
|
27
|
+
unregisterForSession(property: string): void;
|
|
28
|
+
unregister(property: string): void;
|
|
29
|
+
getProperty(property: string): unknown;
|
|
30
|
+
registerDynamicEventProperties(producer: () => Record<string, unknown>): Disposable;
|
|
31
|
+
flush(): Promise<void>;
|
|
32
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __webpack_require__ = {};
|
|
3
|
+
(()=>{
|
|
4
|
+
__webpack_require__.r = (exports1)=>{
|
|
5
|
+
if ("u" > typeof Symbol && Symbol.toStringTag) Object.defineProperty(exports1, Symbol.toStringTag, {
|
|
6
|
+
value: 'Module'
|
|
7
|
+
});
|
|
8
|
+
Object.defineProperty(exports1, '__esModule', {
|
|
9
|
+
value: true
|
|
10
|
+
});
|
|
11
|
+
};
|
|
12
|
+
})();
|
|
13
|
+
var __webpack_exports__ = {};
|
|
14
|
+
__webpack_require__.r(__webpack_exports__);
|
|
15
|
+
for(var __rspack_i in __webpack_exports__)exports[__rspack_i] = __webpack_exports__[__rspack_i];
|
|
16
|
+
Object.defineProperty(exports, '__esModule', {
|
|
17
|
+
value: true
|
|
18
|
+
});
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { };
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import type { AnalyticsDeliveryFactory, IAnalyticsExtension } from './analytics-internal';
|
|
2
2
|
import type { AutomaticAnalyticsOptions } from './analytics-options';
|
|
3
|
-
/**
|
|
4
|
-
export declare const createAnalyticsExtension: (options?: AutomaticAnalyticsOptions, load?: () => Promise<AnalyticsDeliveryFactory>, deliveryFactory?: AnalyticsDeliveryFactory) =>
|
|
3
|
+
/** Creates one analytics instance, with delivery supplied statically or loaded later. */
|
|
4
|
+
export declare const createAnalyticsExtension: (options?: AutomaticAnalyticsOptions, load?: () => Promise<AnalyticsDeliveryFactory>, deliveryFactory?: AnalyticsDeliveryFactory) => IAnalyticsExtension;
|