@posthog/browser 0.1.1 → 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.
Files changed (64) hide show
  1. package/ARCHITECTURE.md +28 -22
  2. package/README.md +65 -29
  3. package/dist/analytics-api.d.ts +26 -0
  4. package/dist/analytics-api.js +18 -0
  5. package/dist/analytics-api.mjs +1 -0
  6. package/dist/analytics-buffer.d.ts +3 -3
  7. package/dist/analytics-buffer.js +2 -161
  8. package/dist/analytics-buffer.mjs +2 -161
  9. package/dist/analytics-extension.d.ts +76 -0
  10. package/dist/analytics-extension.js +589 -0
  11. package/dist/analytics-extension.mjs +551 -0
  12. package/dist/analytics-internal.d.ts +32 -18
  13. package/dist/analytics-options.d.ts +7 -2
  14. package/dist/analytics-options.js +38 -1
  15. package/dist/analytics-options.mjs +17 -1
  16. package/dist/analytics.d.ts +4 -3
  17. package/dist/autocapture.d.ts +2 -2
  18. package/dist/autocapture.js +21 -10
  19. package/dist/autocapture.mjs +21 -10
  20. package/dist/automatic-analytics.d.ts +2 -2
  21. package/dist/browser-client.d.ts +44 -4
  22. package/dist/capture-properties.d.ts +9 -0
  23. package/dist/capture-properties.js +68 -0
  24. package/dist/capture-properties.mjs +30 -0
  25. package/dist/capture-v1.js +7 -19
  26. package/dist/capture-v1.mjs +1 -13
  27. package/dist/core.d.ts +7 -5
  28. package/dist/extensions/registry.d.ts +42 -7
  29. package/dist/extensions/registry.js +194 -37
  30. package/dist/extensions/registry.mjs +194 -37
  31. package/dist/flags-token.d.ts +4 -4
  32. package/dist/flags.js +15 -2
  33. package/dist/flags.mjs +15 -2
  34. package/dist/immutable.d.ts +1 -0
  35. package/dist/immutable.js +46 -0
  36. package/dist/immutable.mjs +8 -0
  37. package/dist/index.d.ts +7 -5
  38. package/dist/index.js +3 -67
  39. package/dist/index.mjs +3 -67
  40. package/dist/logs-internal.d.ts +2 -2
  41. package/dist/logs.js +5 -2
  42. package/dist/logs.mjs +5 -2
  43. package/dist/person-processing.d.ts +11 -0
  44. package/dist/person-processing.js +84 -0
  45. package/dist/person-processing.mjs +37 -0
  46. package/dist/posthog.d.ts +4 -3
  47. package/dist/posthog.js +153 -353
  48. package/dist/posthog.mjs +153 -353
  49. package/dist/root-composition.d.ts +11 -0
  50. package/dist/root-composition.js +138 -0
  51. package/dist/root-composition.mjs +100 -0
  52. package/dist/state.d.ts +1 -0
  53. package/dist/state.js +4 -0
  54. package/dist/state.mjs +4 -0
  55. package/dist/surveys-extension.js +11 -6
  56. package/dist/surveys-extension.mjs +11 -6
  57. package/dist/surveys-internal.d.ts +3 -2
  58. package/dist/types.d.ts +13 -19
  59. package/dist/utf8.d.ts +1 -0
  60. package/dist/utf8.js +52 -0
  61. package/dist/utf8.mjs +14 -0
  62. package/dist/version.js +1 -1
  63. package/dist/version.mjs +1 -1
  64. package/package.json +5 -5
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. It installs one analytics extension that owns a bounded in-memory buffer from initialization. The first admitted event loads queue scheduling and Capture V1 delivery through a literal dynamic import by default; an explicitly supplied analytics extension includes delivery statically. The root also dynamically imports feature flags, logs, surveys orchestration, and autocapture during async initialization, unless disabled or explicitly supplied. 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.
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
- - Safe event normalization, copying, and admission.
89
- - Conflict-safe persistence.
90
- - Delegation of finalized analytics admission to the analytics extension's bounded buffer.
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` factory keeps explicitly supplied analytics or statically constructs a default instance using the caller's analytics configuration. The lightweight factory is included in the initial root graph; only delivery is dynamically loaded. Analytics interprets its own loading and scheduling options. `automatic-analytics.ts` supplies the literal deferred-delivery loader; the core entrypoint retains buffer-only defaults without that reference. The shared `createPostHogCore` helper receives the original client options and configured extensions. Analytics settings and extension order are snapshotted before client construction. The client's internal static `create` takes core options and the selected `CaptureSink` and returns the client. The factory installs analytics and initializes its host before installing other extensions, so they can capture during setup. It then awaits eager analytics loading when configured and starts core-generated pageview capture. Core uses its supplied capture sink for admission, immediate delivery, and consent purging. Flush coordination belongs to the extension registry, which invokes the installed analytics extension alongside other extension owners. If analytics setup fails, the factory disconnects that sink and rolls back its registration; other extensions retain their normal setup and failure isolation.
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
- First-party analytics receives package-private `CaptureHost` 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. All configured extensions receive the shared narrow `Client` view through normal `Extension.setup()`.
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. General `capture()` delegates bounded admission to that extension, commits 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.
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. Core finalizes and commits one event through the same admission boundaries, then asks the installed analytics capability to send 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.
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 entry point must provide a useful capture host with bounded analytics admission. It must not statically include analytics transmission or every PostHog product. By default, its first successfully admitted event starts one shared literal dynamic import of analytics delivery. `analytics.load: 'eager'` starts the same import during initialization, `analytics: false` disables automatic loading, and a preinstalled first-party analytics extension satisfies delivery without loading a duplicate. The `@posthog/browser/core` entrypoint retains buffer-only analytics without a delivery chunk reference. The registry returns the same analytics instance before and after delivery loads, including when automatic delivery is disabled.
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
- // automatic-analytics.ts
184
- const load = () => import('./analytics-delivery').then(({ createAnalyticsDelivery }) => createAnalyticsDelivery)
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 automatic analytics loader imports delivery only after runtime admission or explicit eager selection; flags, logs, surveys orchestration, and autocapture load during async initialization. You can re-export types when the compiler produces no JavaScript import.
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
- The root awaits a literal dynamic autocapture 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.
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 `getExtension(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.
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 a `BrowserClient` view extending the shared `Client` with `onIdentify`, `onGroup`, and `onReset` listeners. Core publishes synchronous notifications after local state updates, 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 these listeners to update evaluation context and reload; core does not look up product-specific identity hooks.
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: the root awaits the literal module import and 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`.
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
- The root loads only optional surveys orchestration during initialization; it 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.
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
- Do not add a static catalog of product implementations to core. The root selects automatic analytics, flags, logs, surveys, and autocapture through product-specific composition code, not a generic product-name loader registry. Other products require explicit composition until their automatic loading contract is implemented.
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 `Client` view.
414
- The view must expose capabilities, not the concrete host implementation.
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
- An extension may declare additional lookup targets through `bindings`. Its name and binding names share one namespace and are reserved together before setup. Application and extension clients resolve each token to the same target. The registered extension is the sole lifecycle owner: binding targets are not independently set up or disposed. All bindings are removed when the owner fails setup, is rolled back, or is disposed. Browser-next flags binds `FeatureFlagsCommonExtension` from browser-common to its wrapped implementation while its SDK token resolves to the facade.
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.capture('signed_up')
15
+ await posthog.resolveExtension('analytics')
16
+ posthog.analytics?.capture('signed_up')
16
17
  await posthog.flush()
17
18
  ```
18
19
 
19
- Configure automatic scheduling or load delivery while the client initializes:
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 delivery loading:
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,41 @@ const posthog = await createPostHog({
36
37
  })
37
38
  ```
38
39
 
39
- Use `analytics: false` to keep the default entrypoint buffer-only, or import `createPostHog` from `@posthog/browser/core` for a graph with no delivery dynamic-import reference. Both modes retain the analytics extension and its buffer. `getExtension('analytics')` returns the same instance before and after delivery loads; its presence alone does not indicate that delivery is available. Analytics initializes before other configured extensions so they can capture during setup. Other extensions retain their configured order.
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
+ ## Migrating to analytics-owned operations
61
+
62
+ Analytics operations now belong to `posthog.analytics`, not the Core client:
63
+
64
+ | Previous client API | Replacement |
65
+ | ---------------------------------- | ----------------------------------------------------------------------- |
66
+ | `capture()`, `captureImmediate()` | `posthog.analytics?.capture()`, `posthog.analytics?.captureImmediate()` |
67
+ | `identify()`, `group()`, `reset()` | The corresponding method on `posthog.analytics` |
68
+ | `onEvent`, `isRateLimited` | The corresponding member on `posthog.analytics` |
69
+ | `registerDynamicEventProperties()` | `posthog.analytics?.registerDynamicEventProperties()` |
70
+ | Synchronous `getExtension(token)` | `await posthog.resolveExtension(token)` |
71
+
72
+ 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.
73
+
74
+ 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
75
 
41
76
  ## Classic script installation (draft CDN distribution)
42
77
 
@@ -46,7 +81,7 @@ The CDN build supports a plain external classic script in ordinary, `async`, or
46
81
  <script async src="https://us-assets.i.posthog.com/static/browser/0/script.js?projectToken=YOUR_PROJECT_TOKEN"></script>
47
82
  ```
48
83
 
49
- The first response embeds the client core. 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 `&amp;apiHost=https%3A%2F%2Feu.i.posthog.com` in HTML.
84
+ 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 `&amp;apiHost=https%3A%2F%2Feu.i.posthog.com` in HTML.
50
85
 
51
86
  Only these query options are supported; omitted options use the existing factory defaults:
52
87
 
@@ -63,7 +98,7 @@ After the existing `createPostHog()` factory resolves, the script assigns `windo
63
98
 
64
99
  ```js
65
100
  function onPostHogReady(client) {
66
- client.capture('signed_up')
101
+ client.analytics?.capture('signed_up')
67
102
  }
68
103
  if (window.posthog) {
69
104
  onPostHogReady(window.posthog)
@@ -72,7 +107,7 @@ if (window.posthog) {
72
107
  }
73
108
  ```
74
109
 
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 a usable core. Consent and capture admission remain unchanged.
110
+ 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
111
 
77
112
  Build and validate locally after building workspace dependencies:
78
113
 
@@ -86,7 +121,7 @@ pnpm --filter @posthog/browser test:snippet
86
121
 
87
122
  ## Autocapture
88
123
 
89
- Autocapture loads dynamically during initialization by default. 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.
124
+ 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
125
 
91
126
  ```ts
92
127
  const posthog = await createPostHog({
@@ -127,7 +162,7 @@ const posthog = await createPostHog({
127
162
  projectToken: '<project-token>',
128
163
  flags: { evaluationContexts: ['web'], requestTimeoutMs: 3_000 },
129
164
  })
130
- const featureFlags = posthog.getExtension(FeatureFlagsExtension)
165
+ const featureFlags = await posthog.resolveExtension(FeatureFlagsExtension)
131
166
  const subscription = featureFlags?.onFeatureFlags((results, errorsLoading) => {
132
167
  if (!errorsLoading) console.log(results)
133
168
  })
@@ -136,7 +171,7 @@ if (result?.enabled) console.log(result.variant, result.payload)
136
171
  subscription?.dispose()
137
172
  ```
138
173
 
139
- `FeatureFlagsExtension` is a lightweight typed lookup token, exported from the root, core, and flags entrypoints. `getExtension(FeatureFlagsExtension)` returns 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.
174
+ `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
175
 
141
176
  Use `reloadFeatureFlags()` to request a remote evaluation and await its outcome before reading again:
142
177
 
@@ -172,15 +207,15 @@ Creating an extension does not initialize it. Pass it in the `extensions` option
172
207
 
173
208
  ### Lifecycle notifications
174
209
 
175
- Browser-next supplies a `BrowserClient` to extension setup. It extends the shared client with `onIdentify`, `onGroup`, and `onReset` listeners. These 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.
210
+ 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
211
 
177
212
  ```ts
178
- import type { BrowserClient, Disposable } from '@posthog/browser'
213
+ import type { IPostHogInternal, Disposable } from '@posthog/browser'
179
214
 
180
215
  let subscription: Disposable | undefined
181
216
  const extension = {
182
217
  name: 'identity-observer',
183
- setup(client: BrowserClient) {
218
+ setup(client: IPostHogInternal) {
184
219
  subscription = client.onIdentify(({ distinctId, previousDistinctId }) => {
185
220
  console.log(previousDistinctId, distinctId)
186
221
  })
@@ -193,18 +228,16 @@ const extension = {
193
228
 
194
229
  ## Logs
195
230
 
196
- Logs dynamically load during initialization by default, separately from analytics. `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:
231
+ 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
232
 
198
233
  ```ts
199
- import type { LogsExtension } from '@posthog/browser/logs'
200
-
201
234
  const posthog = await createPostHog({
202
235
  projectToken: '<project-token>',
203
236
  logs: { captureConsoleLogs: true, serviceName: 'storefront', flushIntervalMs: 3_000 },
204
237
  })
205
- const logger = posthog.getExtension<LogsExtension>('logs')!
206
- logger.captureLog({ body: 'Checkout completed', level: 'info', attributes: { orderId: '123' } })
207
- await logger.flush()
238
+ const logger = await posthog.resolveExtension('logs')
239
+ logger?.captureLog({ body: 'Checkout completed', level: 'info', attributes: { orderId: '123' } })
240
+ await logger?.flush()
208
241
  ```
209
242
 
210
243
  Use `logs: false` to disable automatic inclusion. For static inclusion without a runtime module request:
@@ -228,16 +261,14 @@ The logs extension's `flush()` awaits both log queues. `posthog.flush()` awaits
228
261
 
229
262
  ## Surveys
230
263
 
231
- Surveys orchestration loads dynamically during initialization by default. 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.
264
+ 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
265
 
233
266
  ```ts
234
- import type { SurveysExtension } from '@posthog/browser/surveys'
235
-
236
267
  const posthog = await createPostHog({
237
268
  projectToken: '<project-token>',
238
269
  surveys: { automaticDisplay: false, requestTimeoutMs: 10_000 },
239
270
  })
240
- const feedback = posthog.getExtension<SurveysExtension>('surveys')
271
+ const feedback = await posthog.resolveExtension('surveys')
241
272
  feedback?.getSurveys((surveys, context) => {
242
273
  if (context?.isLoaded && surveys[0]) feedback.displaySurvey(surveys[0].id)
243
274
  })
@@ -267,15 +298,20 @@ Definitions and event activation state use the host-provided surveys KV namespac
267
298
 
268
299
  ## Capture and delivery
269
300
 
270
- `capture()` admits an event to the queue synchronously and does not wait 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.
301
+ Capture, immediate capture, identity and group controls, reset and dynamic 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.
302
+
303
+ `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
304
 
272
305
  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
306
 
274
307
  Use `captureImmediate()` only when the caller needs a terminal delivery outcome before continuing:
275
308
 
276
309
  ```ts
277
- const summary = await posthog.captureImmediate('import_completed', { source: 'warehouse' })
278
- if (summary.error) {
310
+ const analytics = await posthog.resolveExtension('analytics')
311
+ const summary = await analytics?.captureImmediate('import_completed', { source: 'warehouse' })
312
+ if (!summary) {
313
+ console.warn('Analytics is unavailable')
314
+ } else if (summary.error) {
279
315
  console.warn('Immediate capture failed', summary.error)
280
316
  } else if (summary.submitted !== 1 || !summary.allPersisted) {
281
317
  // Capture V1 did not confirm persistence of this event.
@@ -284,7 +320,7 @@ if (summary.error) {
284
320
 
285
321
  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
322
 
287
- The default entrypoint loads delivery on the first admitted immediate call. The core entrypoint supports immediate capture only when `analytics()` was explicitly installed through `extensions`; otherwise it resolves with an unavailable-delivery error without adding a delivery import to the core graph.
323
+ 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
324
 
289
325
  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
326
 
@@ -0,0 +1,26 @@
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
+ registerDynamicEventProperties(producer: () => Record<string, unknown>): Disposable;
25
+ flush(): Promise<void>;
26
+ }
@@ -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 { type AnalyticsDeliveryFactory, type AnalyticsExtension } from './analytics-internal';
1
+ import type { AnalyticsDeliveryFactory, IAnalyticsExtension } from './analytics-internal';
2
2
  import type { AutomaticAnalyticsOptions } from './analytics-options';
3
- /** One analytics instance owns admission and storage before and after delivery loads. */
4
- export declare const createAnalyticsExtension: (options?: AutomaticAnalyticsOptions, load?: () => Promise<AnalyticsDeliveryFactory>, deliveryFactory?: AnalyticsDeliveryFactory) => AnalyticsExtension;
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;