@posthog/browser 0.0.0-stage → 0.1.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 (121) hide show
  1. package/ARCHITECTURE.md +559 -0
  2. package/LICENSE +417 -0
  3. package/README.md +302 -2
  4. package/dist/analytics-buffer.d.ts +4 -0
  5. package/dist/analytics-buffer.js +200 -0
  6. package/dist/analytics-buffer.mjs +162 -0
  7. package/dist/analytics-delivery.d.ts +3 -0
  8. package/dist/analytics-delivery.js +231 -0
  9. package/dist/analytics-delivery.mjs +193 -0
  10. package/dist/analytics-internal.d.ts +64 -0
  11. package/dist/analytics-internal.js +52 -0
  12. package/dist/analytics-internal.mjs +5 -0
  13. package/dist/analytics-options.d.ts +14 -0
  14. package/dist/analytics-options.js +18 -0
  15. package/dist/analytics-options.mjs +1 -0
  16. package/dist/analytics.d.ts +5 -0
  17. package/dist/analytics.js +42 -0
  18. package/dist/analytics.mjs +4 -0
  19. package/dist/autocapture-options.d.ts +32 -0
  20. package/dist/autocapture-options.js +49 -0
  21. package/dist/autocapture-options.mjs +11 -0
  22. package/dist/autocapture.d.ts +5 -0
  23. package/dist/autocapture.js +108 -0
  24. package/dist/autocapture.mjs +70 -0
  25. package/dist/automatic-analytics.d.ts +3 -0
  26. package/dist/automatic-analytics.js +44 -0
  27. package/dist/automatic-analytics.mjs +6 -0
  28. package/dist/automatic-surveys.d.ts +2 -0
  29. package/dist/automatic-surveys.js +41 -0
  30. package/dist/automatic-surveys.mjs +3 -0
  31. package/dist/bot-filter.d.ts +2 -0
  32. package/dist/bot-filter.js +87 -0
  33. package/dist/bot-filter.mjs +49 -0
  34. package/dist/browser-client.d.ts +30 -0
  35. package/dist/browser-client.js +18 -0
  36. package/dist/browser-client.mjs +1 -0
  37. package/dist/capture-summary.d.ts +3 -0
  38. package/dist/capture-summary.js +63 -0
  39. package/dist/capture-summary.mjs +22 -0
  40. package/dist/capture-v1.d.ts +105 -0
  41. package/dist/capture-v1.js +781 -0
  42. package/dist/capture-v1.mjs +722 -0
  43. package/dist/core.d.ts +7 -0
  44. package/dist/core.js +49 -0
  45. package/dist/core.mjs +5 -0
  46. package/dist/event-buffer.d.ts +41 -0
  47. package/dist/event-buffer.js +158 -0
  48. package/dist/event-buffer.mjs +120 -0
  49. package/dist/extensions/registry.d.ts +16 -0
  50. package/dist/extensions/registry.js +128 -0
  51. package/dist/extensions/registry.mjs +90 -0
  52. package/dist/flags-internal.d.ts +8 -0
  53. package/dist/flags-internal.js +18 -0
  54. package/dist/flags-internal.mjs +1 -0
  55. package/dist/flags-options.d.ts +22 -0
  56. package/dist/flags-options.js +18 -0
  57. package/dist/flags-options.mjs +1 -0
  58. package/dist/flags-token.d.ts +15 -0
  59. package/dist/flags-token.js +40 -0
  60. package/dist/flags-token.mjs +2 -0
  61. package/dist/flags.d.ts +6 -0
  62. package/dist/flags.js +163 -0
  63. package/dist/flags.mjs +122 -0
  64. package/dist/id.d.ts +1 -0
  65. package/dist/id.js +61 -0
  66. package/dist/id.mjs +23 -0
  67. package/dist/index.d.ts +11 -0
  68. package/dist/index.js +119 -0
  69. package/dist/index.mjs +75 -0
  70. package/dist/lane.d.ts +57 -0
  71. package/dist/lane.js +363 -0
  72. package/dist/lane.mjs +325 -0
  73. package/dist/logger.d.ts +4 -0
  74. package/dist/logger.js +57 -0
  75. package/dist/logger.mjs +19 -0
  76. package/dist/logs-internal.d.ts +7 -0
  77. package/dist/logs-internal.js +18 -0
  78. package/dist/logs-internal.mjs +1 -0
  79. package/dist/logs-options.d.ts +11 -0
  80. package/dist/logs-options.js +57 -0
  81. package/dist/logs-options.mjs +19 -0
  82. package/dist/logs.d.ts +6 -0
  83. package/dist/logs.js +140 -0
  84. package/dist/logs.mjs +102 -0
  85. package/dist/named-error.d.ts +7 -0
  86. package/dist/named-error.js +49 -0
  87. package/dist/named-error.mjs +11 -0
  88. package/dist/posthog.d.ts +3 -0
  89. package/dist/posthog.js +823 -0
  90. package/dist/posthog.mjs +785 -0
  91. package/dist/rate-limiter.d.ts +19 -0
  92. package/dist/rate-limiter.js +89 -0
  93. package/dist/rate-limiter.mjs +51 -0
  94. package/dist/remote-config.d.ts +3 -0
  95. package/dist/remote-config.js +47 -0
  96. package/dist/remote-config.mjs +9 -0
  97. package/dist/request.d.ts +14 -0
  98. package/dist/request.js +130 -0
  99. package/dist/request.mjs +89 -0
  100. package/dist/state.d.ts +82 -0
  101. package/dist/state.js +625 -0
  102. package/dist/state.mjs +581 -0
  103. package/dist/surveys-extension.d.ts +9 -0
  104. package/dist/surveys-extension.js +272 -0
  105. package/dist/surveys-extension.mjs +234 -0
  106. package/dist/surveys-internal.d.ts +12 -0
  107. package/dist/surveys-internal.js +18 -0
  108. package/dist/surveys-internal.mjs +1 -0
  109. package/dist/surveys-options.d.ts +18 -0
  110. package/dist/surveys-options.js +42 -0
  111. package/dist/surveys-options.mjs +4 -0
  112. package/dist/surveys.d.ts +7 -0
  113. package/dist/surveys.js +48 -0
  114. package/dist/surveys.mjs +7 -0
  115. package/dist/types.d.ts +114 -0
  116. package/dist/types.js +18 -0
  117. package/dist/types.mjs +1 -0
  118. package/dist/version.d.ts +1 -0
  119. package/dist/version.js +40 -0
  120. package/dist/version.mjs +2 -0
  121. package/package.json +88 -3
package/README.md CHANGED
@@ -1,3 +1,303 @@
1
- # Temporary Holding Version
1
+ # @posthog/browser
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ An experimental PostHog client for modern browsers. The API is not yet stable.
4
+
5
+ ```sh
6
+ npm install @posthog/browser
7
+ ```
8
+
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
+ ```ts
12
+ import { createPostHog } from '@posthog/browser'
13
+
14
+ const posthog = await createPostHog({ projectToken: '<project-token>' })
15
+ posthog.capture('signed_up')
16
+ await posthog.flush()
17
+ ```
18
+
19
+ Configure automatic scheduling or load delivery while the client initializes:
20
+
21
+ ```ts
22
+ const posthog = await createPostHog({
23
+ projectToken: '<project-token>',
24
+ analytics: { load: 'eager', flushAt: 20, flushInterval: 3_000 },
25
+ })
26
+ ```
27
+
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
+
30
+ ```ts
31
+ import { analytics } from '@posthog/browser/analytics'
32
+
33
+ const posthog = await createPostHog({
34
+ projectToken: '<project-token>',
35
+ extensions: [analytics({ flushAt: 5, flushInterval: 0 })],
36
+ })
37
+ ```
38
+
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
+
41
+ ## Classic script installation (draft CDN distribution)
42
+
43
+ The CDN build supports a plain external classic script in ordinary, `async`, or `defer` placement. The proposed asset namespace is `/static/browser/<exact-version-or-major>/`; availability depends on CDN deployment. For example, once deployed:
44
+
45
+ ```html
46
+ <script async src="https://us-assets.i.posthog.com/static/browser/0/script.js?projectToken=YOUR_PROJECT_TOKEN"></script>
47
+ ```
48
+
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.
50
+
51
+ Only these query options are supported; omitted options use the existing factory defaults:
52
+
53
+ | Option | Values |
54
+ | -------------------------------------------------------------------- | ------------------------------------------------------------------------------------------- |
55
+ | `projectToken` | Required, nonempty project token |
56
+ | `apiHost` | Absolute HTTP(S) API base, optionally with a proxy path; no credentials, query, or fragment |
57
+ | `capturePageview`, `optOutByDefault`, `debug`, `disableBotDetection` | Literal `true` or `false` |
58
+ | `storage`, `flags`, `logs`, `surveys`, `autocapture` | Literal `false` to disable the corresponding default |
59
+
60
+ Unknown parameters are ignored. Invalid recognized values prevent installation and log a generic diagnostic without the URL or token. This query interface does not accept objects, callbacks, or extensions; use the npm factory for those configurations.
61
+
62
+ After the existing `createPostHog()` factory resolves, the script assigns `window.posthog` and dispatches `posthog:ready` on `window`, with the client in `event.detail`. Readiness includes extension setup, not remote configuration, flag evaluation, or successful event delivery. An early consumer subscribes to the event; a late consumer checks the global:
63
+
64
+ ```js
65
+ function onPostHogReady(client) {
66
+ client.capture('signed_up')
67
+ }
68
+ if (window.posthog) {
69
+ onPostHogReady(window.posthog)
70
+ } else {
71
+ window.addEventListener('posthog:ready', (event) => onPostHogReady(event.detail), { once: true })
72
+ }
73
+ ```
74
+
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.
76
+
77
+ Build and validate locally after building workspace dependencies:
78
+
79
+ ```sh
80
+ pnpm --filter @posthog/browser build:cdn
81
+ pnpm --filter @posthog/browser bundle-size:cdn
82
+ pnpm --filter @posthog/browser test:snippet
83
+ ```
84
+
85
+ `dist-cdn/script.js`, its hashed `chunks/`, and source maps are CDN-only artifacts, outside the npm package's `dist` graph. `test:snippet` serves the exact generated scripts in plain HTML from a separate nested asset origin, and verifies real Capture V1 delivery against the checked-in SDK mock server in Chromium, Firefox, and WebKit. All browser requests are restricted to the local fixture origins. Attribution reports distinguish actual minified/compressed artifact sizes from transformed module sizes before minification.
86
+
87
+ ## Autocapture
88
+
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.
90
+
91
+ ```ts
92
+ const posthog = await createPostHog({
93
+ projectToken: '<project-token>',
94
+ autocapture: { maskAllText: true, cssSelectorAllowlist: ['button', 'a'] },
95
+ })
96
+ ```
97
+
98
+ For static inclusion without a runtime module request:
99
+
100
+ ```ts
101
+ import { autocapture } from '@posthog/browser/autocapture'
102
+
103
+ const posthog = await createPostHog({
104
+ projectToken: '<project-token>',
105
+ extensions: [autocapture({ maskAllText: true })],
106
+ })
107
+ ```
108
+
109
+ An explicit instance takes precedence over the top-level option. The manual core entrypoint never imports autocapture automatically. Both paths use the same options and shared DOM implementation:
110
+
111
+ - `urlAllowlist` / `urlIgnorelist` accept strings or regular expressions; `getCurrentUrl` supplies the URL used for matching. Ignore rules override allow rules.
112
+ - `domEventAllowlist`, `elementAllowlist`, `cssSelectorAllowlist`, `cssSelectorIgnorelist`, and `elementAttributeIgnorelist` restrict capture. A custom CSS ignorelist replaces the `.ph-no-autocapture` / `[data-ph-no-autocapture]` defaults; include them explicitly to retain those exclusions. `.ph-no-capture` remains an unconditional exclusion.
113
+ - `maskAllText` and `maskAllElementAttributes` default to false; sensitive value filtering remains active. `disableCaptureUrlHashes` defaults to true.
114
+ - `captureCopiedText` defaults to false. Enabling it captures cut/copy/paste interactions; pasted text is never included.
115
+ - `rageclick` accepts false, true, or an options object. Enabled by default, it ignores text-selection surfaces and navigation/stepper content (`next`, `previous`, `prev`, `>`, `<`, `+`, `-`, `−`, `–`). Options are `cssSelectorIgnorelist`, `contentIgnorelist`, `ignoreTextSelection`, `thresholdPx` (30), `clickCount` (3), and `timeoutMs` (1000). Explicit true uses these same defaults.
116
+
117
+ Configuration arrays and regular expressions are snapshotted before asynchronous loading; callbacks remain callable. Disposal removes all DOM listeners. Survey selector metadata follows the same consent, masking, and exclusion checks as ordinary autocapture; it does not bypass them.
118
+
119
+ ## Feature flags
120
+
121
+ Flags dynamically load during `createPostHog()` by default. Initialization waits for the module and extension setup, not the network response. Use `flags: false` to omit automatic flags, or configure the extension through `flags`:
122
+
123
+ ```ts
124
+ import { createPostHog, FeatureFlagsExtension } from '@posthog/browser'
125
+
126
+ const posthog = await createPostHog({
127
+ projectToken: '<project-token>',
128
+ flags: { evaluationContexts: ['web'], requestTimeoutMs: 3_000 },
129
+ })
130
+ const featureFlags = posthog.getExtension(FeatureFlagsExtension)
131
+ const subscription = featureFlags?.onFeatureFlags((results, errorsLoading) => {
132
+ if (!errorsLoading) console.log(results)
133
+ })
134
+ const result = featureFlags?.getFeatureFlag('new-onboarding')
135
+ if (result?.enabled) console.log(result.variant, result.payload)
136
+ subscription?.dispose()
137
+ ```
138
+
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.
140
+
141
+ Use `reloadFeatureFlags()` to request a remote evaluation and await its outcome before reading again:
142
+
143
+ ```ts
144
+ if (featureFlags) {
145
+ const outcome = await featureFlags.reloadFeatureFlags()
146
+ if (outcome.status === 'loaded') {
147
+ console.log(featureFlags.getFeatureFlag('new-onboarding'))
148
+ }
149
+ }
150
+ ```
151
+
152
+ The promise resolves with `loaded`, `error`, `skipped` (evaluation is disabled or unavailable), or `cancelled` (reset or disposal). It does not reject on request failures. Calls made before a request starts share that evaluation; calls during an active request wait for a follow-up evaluation. Cached values and `updateFlags()` do not complete a reload. `onFeatureFlags` remains a subscription to value changes, separate from reload completion.
153
+
154
+ For static inclusion, import the factory explicitly and pass the same configuration:
155
+
156
+ ```ts
157
+ import { flags } from '@posthog/browser/flags'
158
+
159
+ const posthog = await createPostHog({
160
+ projectToken: '<project-token>',
161
+ extensions: [flags({ featureFlagEvaluation: false, bootstrap: { featureFlags: { preview: true } } })],
162
+ })
163
+ ```
164
+
165
+ An explicit extension takes precedence over the top-level option, including `flags: false`. `featureFlagEvaluation: false` keeps local/bootstrap values without requesting remote evaluation; remote configuration remains available. Other options are `bootstrap.featureFlagPayloads`, `flagKeys`, `cacheTtlMs`, `refreshIntervalMs`, `deduplicateCallsPerSession`, and `onlyEvaluateSurveyFeatureFlags`. Refresh defaults to five minutes with idle backoff; `refreshIntervalMs: 0` disables automatic refresh. The manual `@posthog/browser/core` entrypoint supports explicit flags without referencing the automatic loader.
166
+
167
+ Flags uses the client's key-value store and configured persistence. With `storage: false`, values remain in memory. Reset clears flag state along with the client's other persisted state.
168
+
169
+ ## Extension lifecycle
170
+
171
+ Creating an extension does not initialize it. Pass it in the `extensions` option to `createPostHog()` and await the returned promise before using its controls.
172
+
173
+ ### Lifecycle notifications
174
+
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.
176
+
177
+ ```ts
178
+ import type { BrowserClient, Disposable } from '@posthog/browser'
179
+
180
+ let subscription: Disposable | undefined
181
+ const extension = {
182
+ name: 'identity-observer',
183
+ setup(client: BrowserClient) {
184
+ subscription = client.onIdentify(({ distinctId, previousDistinctId }) => {
185
+ console.log(previousDistinctId, distinctId)
186
+ })
187
+ },
188
+ dispose() {
189
+ subscription?.dispose()
190
+ },
191
+ }
192
+ ```
193
+
194
+ ## Logs
195
+
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:
197
+
198
+ ```ts
199
+ import type { LogsExtension } from '@posthog/browser/logs'
200
+
201
+ const posthog = await createPostHog({
202
+ projectToken: '<project-token>',
203
+ logs: { captureConsoleLogs: true, serviceName: 'storefront', flushIntervalMs: 3_000 },
204
+ })
205
+ const logger = posthog.getExtension<LogsExtension>('logs')!
206
+ logger.captureLog({ body: 'Checkout completed', level: 'info', attributes: { orderId: '123' } })
207
+ await logger.flush()
208
+ ```
209
+
210
+ Use `logs: false` to disable automatic inclusion. For static inclusion without a runtime module request:
211
+
212
+ ```ts
213
+ import { logs } from '@posthog/browser/logs'
214
+
215
+ const logger = logs({ serviceName: 'storefront' })
216
+ const posthog = await createPostHog({
217
+ projectToken: '<project-token>',
218
+ extensions: [logger],
219
+ })
220
+ logger.captureLog({ body: 'Checkout completed' })
221
+ ```
222
+
223
+ An explicit logs extension takes precedence over the top-level option, including `false`. The manual core entrypoint never loads logs automatically. Both paths accept the same options: `captureConsoleLogs`, `serviceName`, `serviceVersion`, `environment`, `resourceAttributes`, `beforeSend`, `flushIntervalMs`, `maxBufferSize`, and `maxLogsPerInterval`. Defaults match the legacy browser SDK: a 3,000ms flush interval, 100-record flush trigger, and 1,000 programmatic logs per interval. Console logs have a separate bounded queue and `console` scope, without the programmatic rate cap. Console service defaults to `posthog-browser-logs`; programmatic service defaults to `unknown_service`.
224
+
225
+ Logs includes the current URL as `url.full`. Configure `logs: { urlCapture: { path: true, search: false, hash: false } }` or pass the same `urlCapture` option to `logs()` to select which URL components are retained. These are the defaults, including for omitted fields: the origin and pathname are retained, while query parameters and fragments are removed. With `path: false`, the pathname becomes `/`. Invalid URLs are omitted. Component selection does not redact sensitive values within retained components.
226
+
227
+ The logs extension's `flush()` awaits both log queues. `posthog.flush()` awaits all installed extensions' flush methods, including analytics and logs. Consent denial and reset discard queued logs; later opt-in does not revive them. Shutdown awaits normal log delivery within its timeout before cleanup. On pagehide, logs attempt best-effort Beacon delivery with keepalive Fetch fallback. Console hooks and page lifecycle listeners are removed on disposal. Logs use their own `/i/v1/logs` endpoint, JSON payload, and project-token query authentication, never the analytics queue. The existing SDK `logger` remains diagnostic output; application logs use the logs extension's `captureLog()`.
228
+
229
+ ## Surveys
230
+
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.
232
+
233
+ ```ts
234
+ import type { SurveysExtension } from '@posthog/browser/surveys'
235
+
236
+ const posthog = await createPostHog({
237
+ projectToken: '<project-token>',
238
+ surveys: { automaticDisplay: false, requestTimeoutMs: 10_000 },
239
+ })
240
+ const feedback = posthog.getExtension<SurveysExtension>('surveys')
241
+ feedback?.getSurveys((surveys, context) => {
242
+ if (context?.isLoaded && surveys[0]) feedback.displaySurvey(surveys[0].id)
243
+ })
244
+ const eligibility = await feedback?.canRenderSurvey('feedback')
245
+ ```
246
+
247
+ The options are `automaticDisplay` (default `true`), `requestTimeoutMs` (default `10_000`), `prefillFromUrl` (default `false`), `overrideDisplayLanguage`, `prepareStylesheet`, and `getCurrentUrl`. `getActiveMatchingSurveys(callback, forceReload?)` applies targeting; `onSurveysLoaded(callback)` returns a disposable subscription; `cancelPendingSurvey(id)` cancels pending display. Capture consent still gates rendering and responses.
248
+
249
+ Use `surveys: false` to omit automatic inclusion. An explicitly supplied instance takes precedence, including over `false`. To include orchestration, rendering, and styles statically without runtime module loading:
250
+
251
+ ```ts
252
+ import { surveys } from '@posthog/browser/surveys'
253
+
254
+ const feedback = surveys({ automaticDisplay: false })
255
+ const posthog = await createPostHog({
256
+ projectToken: '<project-token>',
257
+ extensions: [feedback],
258
+ })
259
+ feedback.displaySurvey('feedback')
260
+ ```
261
+
262
+ Await client creation before using extension controls.
263
+
264
+ The manual core entrypoint never loads surveys automatically. Extension lookup returns undefined when surveys is omitted or fails setup. Without a document, rendering is unavailable. Disposal removes renderer listeners, polling, pending displays, and rendered elements. Survey abandonment uses analytics' existing pagehide keepalive handoff when delivery is initialized; an analytics module still loading during pagehide cannot send it.
265
+
266
+ Definitions and event activation state use the host-provided surveys KV namespace in the core persistence record. Survey interaction state—seen markers, partial answers, and abandonment markers—uses dedicated browser localStorage, independently of configured SDK persistence, including `storage: false`. Partial answers fall back to memory when localStorage writes fail; abandonment is skipped when its marker cannot be read. Client reset clears persisted extension data, runtime state, and localStorage seen markers, partial answers, and the last-seen date. Abandonment markers are retained, matching legacy survey reset behavior. Event targeting works through admitted captures; DOM-action selector targeting uses the installed autocapture extension, including the default dynamic instance. Cached definitions hydrate their triggers without requiring a refresh. Selectors registered before autocapture setup are retained; later successful definition snapshots replace the selector set, while failed refreshes retain it. Both extension orders are supported. Matching retains the shared exact-target semantics, including SVG attribution to its enclosing control. URL-constrained actions use survey targeting context when the event has no URL; this local fallback does not add URL data to the captured event.
267
+
268
+ ## Capture and delivery
269
+
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.
271
+
272
+ 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
+
274
+ Use `captureImmediate()` only when the caller needs a terminal delivery outcome before continuing:
275
+
276
+ ```ts
277
+ const summary = await posthog.captureImmediate('import_completed', { source: 'warehouse' })
278
+ if (summary.error) {
279
+ console.warn('Immediate capture failed', summary.error)
280
+ } else if (summary.submitted !== 1 || !summary.allPersisted) {
281
+ // Capture V1 did not confirm persistence of this event.
282
+ }
283
+ ```
284
+
285
+ 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
+
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.
288
+
289
+ 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
+
291
+ Both factories start one JSON remote-config request during initialization, without waiting for it before capture or factory completion. `remoteConfig` supplies an inline result instead of making a request. The default loader uses Fetch and `GET /array/{projectToken}/config`. Recognized PostHog US/EU hosts resolve to the corresponding assets host; custom hosts retain their configured base, including path prefixes. Loading is independent of capture consent. `fetch: false` disables built-in loading. Failure or the default 10-second `remoteConfigTimeoutMs` publishes `{ ok: false }` once, with no automatic retry; shutdown cancels the wait and suppresses late publication.
292
+
293
+ When remote configuration advertises gzip, eligible normal batches use native `CompressionStream`; delivery remains uncompressed while configuration is unresolved or compression is unavailable, invalid, stalled, or larger than the JSON body. While offline, finalized events remain admitted and avoid network attempts until an `online` notification. On `pagehide`, or `unload` where `pagehide` is unavailable, queued analytics receive one synchronous uncompressed handoff through headered keepalive Fetch under one conservative aggregate body budget. Beacon remains disabled until Capture V1 supports the required metadata without request headers.
294
+
295
+ One initial `$pageview` is admitted through the same queue after configured extensions install. Set `capturePageview: false` to disable it. Navigation tracking, URL/title enrichment, and page-leave capture remain optional product behavior.
296
+
297
+ Consent is stored separately from identity under `__ph_opt_in_out_<project-token>`. Use `consentPersistenceName` to supply a shared key verbatim. The client reads established `1`/`true`/`yes` and `0`/`false`/`no` values, including raw boolean and numeric compatibility values, and writes `1` or `0`. Configured extensions still initialize under prior denial. Identity, key-value persistence, and remote configuration remain available, while analytics capture and request transmission are consent-gated.
298
+
299
+ Session and window IDs are created on the first successfully admitted capture. Rejected work does not create or advance them. Idle timeout, maximum length, and reset rotate both IDs. Same-origin tabs share the active session while retaining distinct window IDs; ordinary reloads preserve the window ID and copied tab storage receives a new one. Session rotation is activity-driven and starts no core timer.
300
+
301
+ A compact in-memory token bucket admits 10 events per second with a burst of 100 and emits a bypassed aggregate ingestion warning when a runaway loop first reaches the limit. `shutdown(timeoutMs)` stops new work, makes one bounded normal flush attempt, removes timers and lifecycle listeners, and is idempotent. `dispose()` uses the same shutdown path.
302
+
303
+ See [Bundle architecture](./ARCHITECTURE.md) for package boundaries, tree-shaking rules, and bundle review.
@@ -0,0 +1,4 @@
1
+ import { type AnalyticsDeliveryFactory, type AnalyticsExtension } from './analytics-internal';
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;
@@ -0,0 +1,200 @@
1
+ "use strict";
2
+ var __webpack_require__ = {};
3
+ (()=>{
4
+ __webpack_require__.d = (exports1, getters, values)=>{
5
+ var define = (defs, kind)=>{
6
+ for(var key in defs)if (__webpack_require__.o(defs, key) && !__webpack_require__.o(exports1, key)) Object.defineProperty(exports1, key, {
7
+ enumerable: true,
8
+ [kind]: defs[key]
9
+ });
10
+ };
11
+ define(getters, "get");
12
+ define(values, "value");
13
+ };
14
+ })();
15
+ (()=>{
16
+ __webpack_require__.o = (obj, prop)=>Object.prototype.hasOwnProperty.call(obj, prop);
17
+ })();
18
+ (()=>{
19
+ __webpack_require__.r = (exports1)=>{
20
+ if ("u" > typeof Symbol && Symbol.toStringTag) Object.defineProperty(exports1, Symbol.toStringTag, {
21
+ value: 'Module'
22
+ });
23
+ Object.defineProperty(exports1, '__esModule', {
24
+ value: true
25
+ });
26
+ };
27
+ })();
28
+ var __webpack_exports__ = {};
29
+ __webpack_require__.r(__webpack_exports__);
30
+ __webpack_require__.d(__webpack_exports__, {
31
+ createAnalyticsExtension: ()=>createAnalyticsExtension
32
+ });
33
+ const external_analytics_internal_js_namespaceObject = require("./analytics-internal.js");
34
+ const external_event_buffer_js_namespaceObject = require("./event-buffer.js");
35
+ const external_capture_summary_js_namespaceObject = require("./capture-summary.js");
36
+ const numberOption = (read, fallback, minimum, maximum)=>{
37
+ try {
38
+ const value = read();
39
+ return Math.max(minimum, Math.min(maximum, Math.floor(Number.isFinite(value) ? value : fallback)));
40
+ } catch {
41
+ return fallback;
42
+ }
43
+ };
44
+ const createAnalyticsExtension = (options = {}, load, deliveryFactory)=>{
45
+ let eager = false;
46
+ if (load) try {
47
+ eager = 'eager' === options.load;
48
+ } catch {}
49
+ const scheduling = {
50
+ flushAt: numberOption(()=>options.flushAt, 20, 1, external_analytics_internal_js_namespaceObject.MAX_ANALYTICS_BATCH_EVENTS),
51
+ flushInterval: numberOption(()=>options.flushInterval, 3000, 0, Number.MAX_SAFE_INTEGER)
52
+ };
53
+ let client;
54
+ let host;
55
+ let driver;
56
+ let loading;
57
+ let disposed = false;
58
+ const disposalWaiters = new Set();
59
+ const teardownCallbacks = new Set();
60
+ let isTearingDown = false;
61
+ const beforeTeardown = ()=>{
62
+ isTearingDown = true;
63
+ try {
64
+ for (const callback of teardownCallbacks)try {
65
+ callback();
66
+ } catch (error) {
67
+ try {
68
+ host.reportFailure(error);
69
+ } catch {}
70
+ }
71
+ } finally{
72
+ isTearingDown = false;
73
+ }
74
+ };
75
+ let failures = 0;
76
+ const buffer = new external_event_buffer_js_namespaceObject.EventBuffer(1000, (total, count = 1, reason = 'overflow')=>host.reportWarning(`Analytics queue dropped ${count} ${reason} event${1 === count ? '' : 's'} (${total} total)`), external_analytics_internal_js_namespaceObject.MAX_ANALYTICS_BYTES, 3600000);
77
+ const ensureDelivery = async (reason, retryAfterPending = true)=>{
78
+ if (!load || disposed || driver) return;
79
+ if (loading) {
80
+ if ('capture' === reason || !retryAfterPending) return loading;
81
+ const previousFailures = failures;
82
+ await loading;
83
+ if (failures > previousFailures && buffer.hasPending()) await ensureDelivery(reason, false);
84
+ return;
85
+ }
86
+ if ('capture' === reason && failures > 0) return;
87
+ const loadDelivery = async ()=>{
88
+ await Promise.resolve();
89
+ try {
90
+ const createDelivery = await load();
91
+ if (disposed) return;
92
+ driver = createDelivery(buffer, client, host, scheduling, beforeTeardown);
93
+ } catch (error) {
94
+ if (!driver) {
95
+ failures++;
96
+ client.logger.error('Automatic analytics loading failed', error);
97
+ }
98
+ } finally{
99
+ if (loading === pending) loading = void 0;
100
+ }
101
+ };
102
+ const pending = loadDelivery();
103
+ loading = pending;
104
+ return pending;
105
+ };
106
+ return {
107
+ name: external_analytics_internal_js_namespaceObject.Analytics,
108
+ get isTearingDown () {
109
+ return isTearingDown;
110
+ },
111
+ setup (value) {
112
+ client = value;
113
+ },
114
+ initialize (value) {
115
+ host = value;
116
+ if (deliveryFactory) driver = deliveryFactory(buffer, client, host, scheduling, beforeTeardown);
117
+ },
118
+ enqueue: (message, bytes)=>buffer.enqueue(message, bytes),
119
+ discardQueued: (message)=>{
120
+ buffer.discardQueued(message);
121
+ },
122
+ admitted () {
123
+ ensureDelivery('capture');
124
+ },
125
+ start: ()=>eager ? ensureDelivery('eager') : Promise.resolve(),
126
+ onBeforeTeardown (callback) {
127
+ if (!disposed) teardownCallbacks.add(callback);
128
+ return {
129
+ get deliveryAvailable () {
130
+ return !disposed && !!driver;
131
+ },
132
+ dispose () {
133
+ teardownCallbacks.delete(callback);
134
+ }
135
+ };
136
+ },
137
+ async flush (reason = 'flush') {
138
+ if (disposed) return;
139
+ if ('shutdown' === reason && loading) await loading;
140
+ else if (buffer.hasPending()) await ensureDelivery(reason);
141
+ await driver?.flush();
142
+ },
143
+ async deliverImmediate (message, canContinue) {
144
+ let release;
145
+ const disposal = new Promise((resolve)=>{
146
+ release = resolve;
147
+ disposalWaiters.add(resolve);
148
+ });
149
+ try {
150
+ await Promise.race([
151
+ ensureDelivery('immediate'),
152
+ disposal
153
+ ]);
154
+ } finally{
155
+ disposalWaiters.delete(release);
156
+ }
157
+ let deliverImmediate;
158
+ try {
159
+ deliverImmediate = driver?.deliverImmediate;
160
+ } catch {
161
+ deliverImmediate = void 0;
162
+ }
163
+ if (!canContinue()) return (0, external_capture_summary_js_namespaceObject.captureFailure)(new Error('Immediate analytics delivery was cancelled'));
164
+ if (!driver || 'function' != typeof deliverImmediate || disposed) return (0, external_capture_summary_js_namespaceObject.captureFailure)(new Error('Immediate analytics delivery is unavailable'));
165
+ return deliverImmediate.call(driver, [
166
+ message
167
+ ], canContinue);
168
+ },
169
+ deliverUnload (message, canContinue) {
170
+ const send = ()=>{
171
+ if (disposed || !canContinue()) return;
172
+ try {
173
+ driver?.deliverUnload([
174
+ message
175
+ ]);
176
+ } catch (error) {
177
+ host.reportFailure(error);
178
+ }
179
+ };
180
+ if (driver) send();
181
+ else ensureDelivery('immediate').then(send, (error)=>host.reportFailure(error));
182
+ },
183
+ purge: ()=>buffer.purge(),
184
+ dispose () {
185
+ disposed = true;
186
+ for (const release of disposalWaiters)release();
187
+ disposalWaiters.clear();
188
+ teardownCallbacks.clear();
189
+ if (driver) return driver.dispose();
190
+ buffer.dispose();
191
+ }
192
+ };
193
+ };
194
+ exports.createAnalyticsExtension = __webpack_exports__.createAnalyticsExtension;
195
+ for(var __rspack_i in __webpack_exports__)if (-1 === [
196
+ "createAnalyticsExtension"
197
+ ].indexOf(__rspack_i)) exports[__rspack_i] = __webpack_exports__[__rspack_i];
198
+ Object.defineProperty(exports, '__esModule', {
199
+ value: true
200
+ });