@posthog/browser 0.0.0 → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/ARCHITECTURE.md +559 -0
- package/LICENSE +417 -0
- package/README.md +286 -28
- package/dist/analytics-buffer.d.ts +4 -0
- package/dist/analytics-buffer.js +200 -0
- package/dist/analytics-buffer.mjs +162 -0
- package/dist/analytics-delivery.d.ts +3 -0
- package/dist/analytics-delivery.js +231 -0
- package/dist/analytics-delivery.mjs +193 -0
- package/dist/analytics-internal.d.ts +64 -0
- package/dist/analytics-internal.js +52 -0
- package/dist/analytics-internal.mjs +5 -0
- package/dist/analytics-options.d.ts +14 -0
- package/dist/analytics-options.js +18 -0
- package/dist/analytics-options.mjs +1 -0
- package/dist/analytics.d.ts +5 -0
- package/dist/analytics.js +42 -0
- package/dist/analytics.mjs +4 -0
- package/dist/autocapture-options.d.ts +32 -0
- package/dist/autocapture-options.js +49 -0
- package/dist/autocapture-options.mjs +11 -0
- package/dist/autocapture.d.ts +5 -0
- package/dist/autocapture.js +108 -0
- package/dist/autocapture.mjs +70 -0
- package/dist/automatic-analytics.d.ts +3 -0
- package/dist/automatic-analytics.js +44 -0
- package/dist/automatic-analytics.mjs +6 -0
- package/dist/automatic-surveys.d.ts +2 -0
- package/dist/automatic-surveys.js +41 -0
- package/dist/automatic-surveys.mjs +3 -0
- package/dist/bot-filter.d.ts +2 -0
- package/dist/bot-filter.js +87 -0
- package/dist/bot-filter.mjs +49 -0
- package/dist/browser-client.d.ts +30 -0
- package/dist/browser-client.js +18 -0
- package/dist/browser-client.mjs +1 -0
- package/dist/capture-summary.d.ts +3 -0
- package/dist/capture-summary.js +63 -0
- package/dist/capture-summary.mjs +22 -0
- package/dist/capture-v1.d.ts +105 -0
- package/dist/capture-v1.js +781 -0
- package/dist/capture-v1.mjs +722 -0
- package/dist/core.d.ts +7 -0
- package/dist/core.js +49 -0
- package/dist/core.mjs +5 -0
- package/dist/event-buffer.d.ts +41 -0
- package/dist/event-buffer.js +158 -0
- package/dist/event-buffer.mjs +120 -0
- package/dist/extensions/registry.d.ts +16 -0
- package/dist/extensions/registry.js +128 -0
- package/dist/extensions/registry.mjs +90 -0
- package/dist/flags-internal.d.ts +8 -0
- package/dist/flags-internal.js +18 -0
- package/dist/flags-internal.mjs +1 -0
- package/dist/flags-options.d.ts +22 -0
- package/dist/flags-options.js +18 -0
- package/dist/flags-options.mjs +1 -0
- package/dist/flags-token.d.ts +15 -0
- package/dist/flags-token.js +40 -0
- package/dist/flags-token.mjs +2 -0
- package/dist/flags.d.ts +6 -0
- package/dist/flags.js +164 -0
- package/dist/flags.mjs +123 -0
- package/dist/id.d.ts +1 -0
- package/dist/id.js +61 -0
- package/dist/id.mjs +23 -0
- package/dist/index.d.ts +11 -0
- package/dist/index.js +119 -0
- package/dist/index.mjs +75 -0
- package/dist/lane.d.ts +57 -0
- package/dist/lane.js +363 -0
- package/dist/lane.mjs +325 -0
- package/dist/logger.d.ts +4 -0
- package/dist/logger.js +57 -0
- package/dist/logger.mjs +19 -0
- package/dist/logs-internal.d.ts +7 -0
- package/dist/logs-internal.js +18 -0
- package/dist/logs-internal.mjs +1 -0
- package/dist/logs-options.d.ts +11 -0
- package/dist/logs-options.js +57 -0
- package/dist/logs-options.mjs +19 -0
- package/dist/logs.d.ts +6 -0
- package/dist/logs.js +140 -0
- package/dist/logs.mjs +102 -0
- package/dist/named-error.d.ts +7 -0
- package/dist/named-error.js +49 -0
- package/dist/named-error.mjs +11 -0
- package/dist/posthog.d.ts +3 -0
- package/dist/posthog.js +829 -0
- package/dist/posthog.mjs +791 -0
- package/dist/rate-limiter.d.ts +24 -0
- package/dist/rate-limiter.js +95 -0
- package/dist/rate-limiter.mjs +57 -0
- package/dist/remote-config.d.ts +3 -0
- package/dist/remote-config.js +47 -0
- package/dist/remote-config.mjs +9 -0
- package/dist/request.d.ts +14 -0
- package/dist/request.js +130 -0
- package/dist/request.mjs +89 -0
- package/dist/state.d.ts +82 -0
- package/dist/state.js +625 -0
- package/dist/state.mjs +581 -0
- package/dist/surveys-extension.d.ts +9 -0
- package/dist/surveys-extension.js +272 -0
- package/dist/surveys-extension.mjs +234 -0
- package/dist/surveys-internal.d.ts +12 -0
- package/dist/surveys-internal.js +18 -0
- package/dist/surveys-internal.mjs +1 -0
- package/dist/surveys-options.d.ts +18 -0
- package/dist/surveys-options.js +42 -0
- package/dist/surveys-options.mjs +4 -0
- package/dist/surveys.d.ts +6 -0
- package/dist/surveys.js +45 -0
- package/dist/surveys.mjs +4 -0
- package/dist/types.d.ts +114 -0
- package/dist/types.js +18 -0
- package/dist/types.mjs +1 -0
- package/dist/version.d.ts +1 -0
- package/dist/version.js +40 -0
- package/dist/version.mjs +2 -0
- package/package.json +89 -8
package/ARCHITECTURE.md
ADDED
|
@@ -0,0 +1,559 @@
|
|
|
1
|
+
# `@posthog/browser` bundle architecture
|
|
2
|
+
|
|
3
|
+
## 1. Purpose
|
|
4
|
+
|
|
5
|
+
This document defines the bundle architecture for `@posthog/browser`.
|
|
6
|
+
|
|
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
|
+
|
|
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.
|
|
10
|
+
|
|
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
|
+
|
|
13
|
+
These rules apply to source files, package exports, dependencies, build output, and tests. Use the Capture Analytics V1 harness for exact analytics wire behavior.
|
|
14
|
+
|
|
15
|
+
## 2. Terms
|
|
16
|
+
|
|
17
|
+
This document uses these terms:
|
|
18
|
+
|
|
19
|
+
- **Core**: The minimum code for a useful capture client.
|
|
20
|
+
- **Root entry point**: The `@posthog/browser` export.
|
|
21
|
+
- **Root graph**: Runtime modules statically reachable from the root entry point before a dynamic-import boundary.
|
|
22
|
+
- **Optional feature**: Behavior that is not necessary for basic capture.
|
|
23
|
+
- **Import side effect**: Work that starts when JavaScript evaluates a module.
|
|
24
|
+
- **Initial chunk**: JavaScript that an application loads before optional dynamic imports.
|
|
25
|
+
- **Tree-shakable**: Removable by a bundler when no used export needs the code.
|
|
26
|
+
|
|
27
|
+
The words **must** and **must not** identify requirements.
|
|
28
|
+
The word **should** identifies a strong recommendation.
|
|
29
|
+
|
|
30
|
+
## 3. Main design rules
|
|
31
|
+
|
|
32
|
+
1. Preserve required core behavior.
|
|
33
|
+
2. Keep the compliant root graph small.
|
|
34
|
+
3. Keep every module free of import side effects.
|
|
35
|
+
4. Put optional features behind import boundaries.
|
|
36
|
+
5. Use explicit exports and exact runtime imports.
|
|
37
|
+
6. Preserve ES module boundaries in the published output.
|
|
38
|
+
7. Measure bundles from a package consumer.
|
|
39
|
+
8. Reject optional implementations when they enter the initial root graph.
|
|
40
|
+
|
|
41
|
+
An API boundary is also a size boundary. A runtime option is not a size boundary.
|
|
42
|
+
A minifier cannot correct a bad package boundary. An automatic dynamic import does not make required behavior optional.
|
|
43
|
+
|
|
44
|
+
## 4. Package layers
|
|
45
|
+
|
|
46
|
+
Use these layers:
|
|
47
|
+
|
|
48
|
+
```text
|
|
49
|
+
standard preset, optional features, compatibility modules
|
|
50
|
+
↓ can import
|
|
51
|
+
core capture host
|
|
52
|
+
↓ can import
|
|
53
|
+
small runtime primitives
|
|
54
|
+
↓ can import
|
|
55
|
+
contracts and types
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
A module can import its own layer or a lower layer.
|
|
59
|
+
A module must not import a higher layer.
|
|
60
|
+
|
|
61
|
+
### 4.1 Contracts and types
|
|
62
|
+
|
|
63
|
+
This layer defines TypeScript contracts. It must contain no runtime work.
|
|
64
|
+
|
|
65
|
+
Use `import type` and `export type` for this layer.
|
|
66
|
+
A type import must not become a JavaScript import.
|
|
67
|
+
|
|
68
|
+
Use the shared `Client` and `Extension` contracts from `@posthog/browser-common`.
|
|
69
|
+
Do not create a second extension contract.
|
|
70
|
+
|
|
71
|
+
### 4.2 Small runtime primitives
|
|
72
|
+
|
|
73
|
+
This layer contains small and general functions. Each function must have one clear purpose.
|
|
74
|
+
|
|
75
|
+
A primitive must not import a product feature. A primitive must not create a global singleton.
|
|
76
|
+
A primitive must not read browser state during module evaluation.
|
|
77
|
+
|
|
78
|
+
### 4.3 Core capture host
|
|
79
|
+
|
|
80
|
+
The core must contain all behavior that correct basic capture always needs, and no optional product implementation.
|
|
81
|
+
|
|
82
|
+
The core contains these responsibilities:
|
|
83
|
+
|
|
84
|
+
- Consent and privacy enforcement.
|
|
85
|
+
- Compact bot filtering.
|
|
86
|
+
- Device, anonymous, and identified state.
|
|
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.
|
|
92
|
+
- A small control-plane Fetch path for immediate remote configuration and extension requests.
|
|
93
|
+
- Consent and lifecycle authority for analytics dispatch, independent of delivery loading.
|
|
94
|
+
- Extension lifecycle and isolation.
|
|
95
|
+
- No-throw boundaries for customer-controlled and browser operations.
|
|
96
|
+
|
|
97
|
+
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
|
+
|
|
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.
|
|
100
|
+
|
|
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()`.
|
|
102
|
+
|
|
103
|
+
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
|
+
|
|
105
|
+
Review each core mechanism with compliance tests, bundle measurements, and module attribution. Move optional implementations out of core. Do not move a required invariant out only because it has a measurable cost.
|
|
106
|
+
|
|
107
|
+
Consent uses `__ph_opt_in_out_<project-token>` by default and accepts a verbatim `consentPersistenceName` override. Store interoperable `0`/`1` values and accept trimmed, case-insensitive `1`/`true`/`yes` and `0`/`false`/`no` forms, including raw boolean and numeric values from compatibility adapters. Keep this logical key independent of identity persistence and consistent across consent storage adapters. Default local storage uses native `storage` events plus a same-document SDK event; adapters can provide an optional keyed subscription for prompt external revocation. All listeners start during client initialization and stop during disposal. Deprecated prefix-derived keys and migration between storage backends belong in a compatibility entry point.
|
|
108
|
+
|
|
109
|
+
Consent is prospective point-in-time analytics authority, not a global client lifecycle lock or a transaction spanning an operation. Extension setup, registration, lookup, subscriptions, and cleanup always run. Check consent once when capture begins and immediately before each new analytics transport attempt or retry. An operation or request authorized at its boundary may finish after consent changes; except for pending immediate dispatch and retries described below, do not invalidate it using a historical consent generation. Denial purges work already queued at that transition and prevents new capture and analytics dispatch. Match `posthog-js` by retaining identity, group, session, and device state across capture denial; persistence restrictions are a separate policy. Client shutdown remains an independent terminal boundary.
|
|
110
|
+
|
|
111
|
+
Apply those boundaries method by method:
|
|
112
|
+
|
|
113
|
+
| Surface | Consent and lifecycle boundary |
|
|
114
|
+
| --------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
|
115
|
+
| Identity, group, device, and session getters | Prepare and return retained state without reinterpreting it from consent. `BrowserState` separately owns fresh compatible-consent observation. |
|
|
116
|
+
| `capture()` | Check once before evaluating caller properties. The synchronous capture operation then runs to completion; delivery applies its own dispatch-time gate. |
|
|
117
|
+
| `identify()` and `group()` | Valid calls update and persist state regardless of capture consent, matching `posthog-js`. Their generated analytics events pass through ordinary `capture()` admission. |
|
|
118
|
+
| `reset()` | Treat reset as cleanup, not an operation that a consent transition can invalidate. Lifecycle still prevents mutation after disposal. |
|
|
119
|
+
| `sendRequest()` | Check immediately before each actual transport dispatch. Do not prepare analytics identity state and do not reinterpret an already-started result after consent changes. |
|
|
120
|
+
| Remote configuration | Consent does not gate control-plane loading, caching, subscriptions, or publication. Lifecycle prevents new work after shutdown. |
|
|
121
|
+
| Initial `$pageview` | Rely on ordinary `capture()` admission. Do not duplicate consent checks around DOM access or listener setup. |
|
|
122
|
+
| Extension KV | Reads and writes are independent of capture consent, matching `posthog-js`. Lifecycle and state readiness still apply; any future durable-storage restriction belongs to a separate persistence policy. |
|
|
123
|
+
| Analytics initialization and delivery loading | Analytics initializes independently of consent. Eager or already-started delivery loading finishes under denial; lazy loading begins only after an admitted capture. Denial purges queued analytics and blocks dispatch. |
|
|
124
|
+
|
|
125
|
+
No general `canContinue` or `canUseState` predicate should coordinate these surfaces. State preparation belongs only to operations that consume persisted analytics state; requests, remote configuration, pageview listener setup, and delivery retries must not initialize identity state as a side effect of authorization.
|
|
126
|
+
|
|
127
|
+
Create session and window IDs lazily on the first successfully admitted capture. Preview session context while finalizing an event, but do not expose, persist, or install tab lifecycle state until bounded admission succeeds; rejected work must not create, rotate, or advance session state. Match `posthog-js` analytics semantics by rotating both IDs after reset, idle timeout, or maximum session length, and by adopting a sibling tab's active session while retaining the receiving tab's current window ID. Persist monotonic session revisions and explicit reset tombstones so sequential stale identity, group, or extension-data writes preserve the newest session authority; revalidate authority around admission commit, and discard stale finalized work rather than overwrite a newer session or reset. Missing or malformed optional session data is not a reset. With default storage, preserve ordinary reload windows and separate copied tab storage through tab-scoped storage; lifecycle cleanup and a no-throw navigation-type fallback cover browser reload differences. Core must not run a background timer solely to rotate sessions. Replay owns proactive recorder shutdown, interaction state, snapshot buffering, and recording-age limits; session rotation or notification alone must not start or flush a product. The alpha still documents perfectly simultaneous equal-revision whole-record writers after the final authoritative read as last-writer-wins.
|
|
128
|
+
|
|
129
|
+
The analytics delivery capability must use Capture Analytics V1 at `POST /i/v1/analytics/events`. It must not use the legacy `/e/` envelope. Normal analytics delivery must use Fetch so it can send required headers, observe the UUID-keyed result map, time out, rate limit, and retry only server-marked retry events. It receives the core's bound Fetch capability but owns analytics-specific batching, authentication, compression, response, retry, and teardown policy. `analytics({ flushAt, flushInterval })` configures count and timer triggers with defaults of 20 events and 3,000 milliseconds; `flushInterval: 0` disables the timer, while explicit flush and shutdown bypass both thresholds. It selects at most 100 FIFO events at a time, serializes transformed events once, and greedily partitions exact uncompressed V1 envelopes at a package-private soft 5 MiB target. A larger admitted event is sent alone, and `413` remains terminal rather than triggering response-driven splitting. Remote configuration uses the small core control-plane request path and must not wait for analytics delivery to load.
|
|
130
|
+
|
|
131
|
+
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
|
+
|
|
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.
|
|
134
|
+
|
|
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.
|
|
136
|
+
|
|
137
|
+
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
|
+
|
|
139
|
+
Select an optional lane through an explicit product API, such as `captureAi()`, not an event-name prefix or a caller-supplied lane string on general `capture()`. General `capture()` always uses analytics. The product module receives only its private lane sink. Install the lane lazily, then include it in client `flush()` and `dispose()`. Lane sinks, lane state, delivery policies, and the coordinator are package-private implementation details; do not export them from the package root or add them to the shared `Client` contract. This follows Python's `_capture_ai` lane and the unmerged Node `captureAi` design while keeping product code removable from the browser root.
|
|
140
|
+
|
|
141
|
+
Teardown delivery must use the Capture V1 header-less Beacon contract only after the target backend and proxy paths support it. Until then, use Fetch with `keepalive: true` and the normal V1 headers. The current conservative aggregate body budget is 80% of 64 KiB across the entire analytics handoff; requests walk active and queued source identities in FIFO order, and splitting does not replenish the browser's shared quota. Teardown does not mutate retained work because keepalive acceptance is not server acceptance. It does not parse responses, start asynchronous compression, or start retry timers. Register `pagehide`, or `unload` only when `pagehide` is unavailable, when delivery initializes and remove the listener during disposal. Online/offline listeners are scoped to the same delivery lifetime: offline is a scheduling hint that pauses avoidable sends, while online promptly redrives retained work. A compact in-memory token bucket runs before event construction with a default 10-event-per-second refill and 100-event burst; its aggregate warning bypasses the limiter without weakening consent or bounded admission. Explicit shutdown stops new work, makes one timeout-bounded normal flush drive, aborts remaining transport, and shares the idempotent disposal path.
|
|
142
|
+
|
|
143
|
+
### 4.4 Optional adapters and extensions
|
|
144
|
+
|
|
145
|
+
Put delivery or product behavior in an extension, capability, or adapter. Examples include analytics delivery, replay, surveys, and web vitals. The analytics extension owns its queue and loads its delivery implementation as needed. Optional products likewise own their buffers and delivery policies.
|
|
146
|
+
|
|
147
|
+
An optional module can import the core. The core must not import the optional module.
|
|
148
|
+
|
|
149
|
+
Application-facing log methods belong to the logs extension reference. Shared/core logs owns its queue, batching, retries, and flush implementation. An extension can observe reset and consent changes to clear its own queued data. The extension registry flushes each installed owner once, independently of its lookup bindings, and isolates failures. `client.flush()` awaits each optional `Extension.flush()`; shutdown passes the `shutdown` reason and awaits flushing within its timeout before releasing resources. Logs uses normal delivery for these flushes and Beacon for pagehide.
|
|
150
|
+
|
|
151
|
+
Each optional module must have an explicit entry point. A consumer must import that entry point directly.
|
|
152
|
+
|
|
153
|
+
### 4.5 Standard preset
|
|
154
|
+
|
|
155
|
+
A standard preset can select recommended features. The root entry point must not import the standard preset.
|
|
156
|
+
|
|
157
|
+
The preset must keep large features behind dynamic imports. Each large feature must create a separate chunk.
|
|
158
|
+
|
|
159
|
+
Measure the preset in two ways:
|
|
160
|
+
|
|
161
|
+
- Initial size.
|
|
162
|
+
- Total size after all dynamic imports.
|
|
163
|
+
|
|
164
|
+
### 4.6 Compatibility and migration modules
|
|
165
|
+
|
|
166
|
+
Put old-browser support, full historical-state migrations, and heavy fallbacks in separate entry points.
|
|
167
|
+
|
|
168
|
+
The root graph must not contain these modules. Importing the root must not run a general migration.
|
|
169
|
+
|
|
170
|
+
A supported upgrade path must still recognize a prior explicit denial before the first capture admission or transport dispatch. This narrow privacy compatibility rule is part of consent enforcement, not an optional historical-state migration; identity and KV persistence remain a separate policy.
|
|
171
|
+
|
|
172
|
+
Cross-context conflict safety is also a core invariant. Same-origin local-storage persistence must prevent stale writers. A selected cross-subdomain cookie adapter must provide equivalent reconciliation for shared cookie state.
|
|
173
|
+
|
|
174
|
+
## 5. Root entry point
|
|
175
|
+
|
|
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.
|
|
177
|
+
|
|
178
|
+
The root entry point must use named exports. It must not create a default client singleton.
|
|
179
|
+
|
|
180
|
+
Use a narrow root wrapper with a literal dynamic loader and a separate core entry:
|
|
181
|
+
|
|
182
|
+
```ts
|
|
183
|
+
// automatic-analytics.ts
|
|
184
|
+
const load = () => import('./analytics-delivery').then(({ createAnalyticsDelivery }) => createAnalyticsDelivery)
|
|
185
|
+
|
|
186
|
+
// @posthog/browser/core
|
|
187
|
+
export { createPostHog } from './core'
|
|
188
|
+
```
|
|
189
|
+
|
|
190
|
+
Do not use this form:
|
|
191
|
+
|
|
192
|
+
```ts
|
|
193
|
+
export * from './products'
|
|
194
|
+
export { default } from './singleton'
|
|
195
|
+
```
|
|
196
|
+
|
|
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.
|
|
198
|
+
|
|
199
|
+
Treat `createPostHog` and its static imports as one size unit.
|
|
200
|
+
A bundler cannot remove an internal module when the factory always needs that module.
|
|
201
|
+
|
|
202
|
+
Do not implement a large optional feature as a method on the core client class.
|
|
203
|
+
Bundlers usually retain all methods on a used class.
|
|
204
|
+
Use an extension or an adapter instead.
|
|
205
|
+
|
|
206
|
+
### Autocapture
|
|
207
|
+
|
|
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.
|
|
209
|
+
|
|
210
|
+
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
|
+
|
|
212
|
+
### Feature flags
|
|
213
|
+
|
|
214
|
+
`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
|
+
|
|
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.
|
|
217
|
+
|
|
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.
|
|
219
|
+
|
|
220
|
+
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
|
+
|
|
222
|
+
### Logs
|
|
223
|
+
|
|
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`.
|
|
225
|
+
|
|
226
|
+
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
|
+
|
|
228
|
+
Shared logs uses the SDK-provided `Client.sendRequest()` for JSON requests to `/i/v1/logs?token=...` with a 60-second timeout. Logs owns status classification and retry policy; requests retain their own timeouts, while the SDK bounds how long shutdown waits for extension flushing. Pagehide uses the existing logs Beacon contract with keepalive Fetch fallback. This does not enable Beacon for analytics. Product queues, serializers, and console instrumentation stay in the optional module. Logs reads session context through the shared `Client.session` property without creating or advancing a session. The property can be undefined; an existing `SessionContext` includes `lastActivityTimestamp`. The logs adapter shapes the current URL through the shared `sanitizeUrl()` helper using its snapshotted `urlCapture` options. By default it retains the origin and path, omits query parameters and fragments, and omits invalid URLs. URL component selection is configured per extension.
|
|
229
|
+
|
|
230
|
+
The logs extension subscribes to the browser client's reset and consent-change notifications to clear its queues on reset or observed consent denial. Capture stops when shutdown begins, but already admitted logs can flush while dispatch authority remains valid. `flush()` awaits analytics and both logs queues independently. Shutdown shares its existing timeout across delivery and disposal; an in-flight logs request can outlive that wait until its own timeout. Logs resolves `FeatureFlagsCommonExtension` through `Client.getExtension()` and reads `getFlags()` from the shared flags implementation to include flag keys without emitting exposure analytics. The host isolates extension setup, flush, and cleanup failures.
|
|
231
|
+
|
|
232
|
+
### Surveys
|
|
233
|
+
|
|
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.
|
|
235
|
+
|
|
236
|
+
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
|
+
|
|
238
|
+
The shared renderer, Preact components, CSS string, event/action receiver, and matching helpers are reused by legacy adapters. Capture, flags, submission IDs, configuration, and stylesheet preparation are explicit runtime capabilities, not a concrete PostHog facade. Legacy global routing, preview wrappers, and UUID behavior remain legacy-owned. Native capability reads occur at invocation/setup, preserving strict static-entry import purity.
|
|
239
|
+
|
|
240
|
+
The optional module stores definitions and event-activation state through its host-provided `Client.kv` namespace. Survey interaction history—seen markers, partial answers, and abandonment markers—uses dedicated browser localStorage with the existing survey keys, independently of SDK persistence, including `storage: false`. Failed partial-answer writes retain an in-memory fallback. Abandonment checks capture permission before writing its marker and skips capture if reading the marker fails. Client reset clears persisted extension data, and the extension's reset subscription delegates to the shared surveys reset implementation. This clears in-memory progress and activation state, plus localStorage seen markers, partial answers, and the last-seen date. Abandonment markers remain, matching legacy survey reset behavior. Existing capture consent gates still control eligibility and submission, while cleanup always runs. The renderer owns polling, language/visibility listeners, pending display timeouts, and Preact unmounting.
|
|
241
|
+
|
|
242
|
+
Survey abandonment uses a package-private analytics pre-teardown subscription: the analytics buffer retains callbacks across lazy delivery loading, and initialized delivery invokes them synchronously before its single keepalive queue handoff. Browser-native `pagehide` listener ordering is not portable (Chromium can invoke an earlier non-capture listener before a later capture listener), so capture phase alone cannot provide this ordering. Subscription failures are contained and disposal removes callbacks. A surveys-owned `pagehide` fallback admits abandonment when analytics delivery is unavailable, but cannot ensure delivery from a module still loading during unload.
|
|
243
|
+
|
|
244
|
+
Survey definitions are fetched separately at `/api/surveys/` with the existing token query, cache TTL, and failure backoff. The surveys extension resolves the browser-next flags facade through `Client.getExtension()` for configuration and person-property context; shared surveys resolves common flags through its common token. Event targets observe admitted captures. Action matching can register DOM selectors through an optional autocapture capability; that extension must be installed for selector-backed DOM events.
|
|
245
|
+
|
|
246
|
+
## 6. Import graph rules
|
|
247
|
+
|
|
248
|
+
### 6.1 Use exact runtime imports
|
|
249
|
+
|
|
250
|
+
Import the exact runtime module that the code needs.
|
|
251
|
+
|
|
252
|
+
Use this form:
|
|
253
|
+
|
|
254
|
+
```ts
|
|
255
|
+
import { Publisher } from '@posthog/browser-common/pubsub'
|
|
256
|
+
import type { Client, Extension } from '@posthog/browser-common'
|
|
257
|
+
```
|
|
258
|
+
|
|
259
|
+
Do not use a runtime root barrel when an exact subpath exists.
|
|
260
|
+
Do not use a utility barrel for runtime imports.
|
|
261
|
+
|
|
262
|
+
### 6.2 Keep barrels narrow
|
|
263
|
+
|
|
264
|
+
A barrel can export types. A runtime barrel must use explicit named exports.
|
|
265
|
+
|
|
266
|
+
Do not use `export *` across product boundaries.
|
|
267
|
+
Do not use `export *` across side-effect boundaries.
|
|
268
|
+
|
|
269
|
+
A root barrel must not import a module only to register it.
|
|
270
|
+
|
|
271
|
+
### 6.3 Prevent cycles
|
|
272
|
+
|
|
273
|
+
Keep the import graph acyclic. A cycle can prevent tree shaking and can change initialization order.
|
|
274
|
+
|
|
275
|
+
Move shared contracts to a lower layer when two modules need each other.
|
|
276
|
+
Do not fix a cycle with a runtime service locator.
|
|
277
|
+
|
|
278
|
+
### 6.4 Do not use internal deep imports
|
|
279
|
+
|
|
280
|
+
Publish each supported entry point in the `exports` map.
|
|
281
|
+
Do not require consumers to import a file from `dist`.
|
|
282
|
+
|
|
283
|
+
Internal emitted files are not public entry points.
|
|
284
|
+
|
|
285
|
+
## 7. Import purity
|
|
286
|
+
|
|
287
|
+
The package declares `sideEffects: false`. Every published entry point must satisfy that declaration.
|
|
288
|
+
|
|
289
|
+
Module evaluation must not do these operations:
|
|
290
|
+
|
|
291
|
+
- Read or write storage.
|
|
292
|
+
- Read the DOM.
|
|
293
|
+
- Add an event listener.
|
|
294
|
+
- Start a timer.
|
|
295
|
+
- Start a network request.
|
|
296
|
+
- Create a client.
|
|
297
|
+
- Register an extension.
|
|
298
|
+
- Modify a global object.
|
|
299
|
+
- Install a polyfill.
|
|
300
|
+
- Emit telemetry.
|
|
301
|
+
|
|
302
|
+
Start work only from a factory, a method, or `Extension.setup()`.
|
|
303
|
+
|
|
304
|
+
Use a function to read a browser capability:
|
|
305
|
+
|
|
306
|
+
```ts
|
|
307
|
+
const getDefaultFetch = () => globalThis.fetch?.bind(globalThis)
|
|
308
|
+
```
|
|
309
|
+
|
|
310
|
+
Do not capture a browser capability at module scope:
|
|
311
|
+
|
|
312
|
+
```ts
|
|
313
|
+
const defaultFetch = globalThis.fetch?.bind(globalThis)
|
|
314
|
+
```
|
|
315
|
+
|
|
316
|
+
A module can define constants and pure functions at module scope.
|
|
317
|
+
A module can create immutable data when that data has no external effect.
|
|
318
|
+
Keep large data tables outside core when basic capture does not need them.
|
|
319
|
+
|
|
320
|
+
If an import side effect is unavoidable, prefer a separate package. Otherwise, create an explicit side-effect entry point and change `package.json#sideEffects` from `false` to an array that lists only that entry. Do not set the whole package to `sideEffects: true`.
|
|
321
|
+
|
|
322
|
+
## 8. Optional feature rules
|
|
323
|
+
|
|
324
|
+
### 8.1 Use an import boundary
|
|
325
|
+
|
|
326
|
+
Use a separate export subpath for each substantial optional feature. Automatic analytics delivery, feature flags, logs, surveys orchestration, and autocapture use literal dynamic imports from the root entrypoint; the core entrypoint references none of their automatic loaders.
|
|
327
|
+
|
|
328
|
+
Example:
|
|
329
|
+
|
|
330
|
+
```text
|
|
331
|
+
@posthog/browser
|
|
332
|
+
@posthog/browser/standard
|
|
333
|
+
@posthog/browser/delivery/analytics
|
|
334
|
+
@posthog/browser/persistence/cookie
|
|
335
|
+
@posthog/browser/delivery/durable
|
|
336
|
+
@posthog/browser/flags
|
|
337
|
+
```
|
|
338
|
+
|
|
339
|
+
Add the source entry and the package export in the same change.
|
|
340
|
+
Add a consumer bundle test for each public runtime entry.
|
|
341
|
+
|
|
342
|
+
### 8.2 Do not use configuration as a bundle boundary
|
|
343
|
+
|
|
344
|
+
A boolean option changes runtime behavior. It usually does not remove imported code.
|
|
345
|
+
|
|
346
|
+
Do not use this pattern for a large feature:
|
|
347
|
+
|
|
348
|
+
```ts
|
|
349
|
+
import { largeFeature } from './large-feature'
|
|
350
|
+
|
|
351
|
+
if (options.enableLargeFeature) {
|
|
352
|
+
largeFeature()
|
|
353
|
+
}
|
|
354
|
+
```
|
|
355
|
+
|
|
356
|
+
Use an explicit import or a client-owned extension:
|
|
357
|
+
|
|
358
|
+
```ts
|
|
359
|
+
import { largeFeature } from '@posthog/browser/extensions/large-feature'
|
|
360
|
+
|
|
361
|
+
const posthog = await createPostHog({
|
|
362
|
+
projectToken,
|
|
363
|
+
extensions: [largeFeature()],
|
|
364
|
+
})
|
|
365
|
+
```
|
|
366
|
+
|
|
367
|
+
A small branch can stay in core when a separate boundary adds more bytes.
|
|
368
|
+
The change must include measurements that support this decision.
|
|
369
|
+
|
|
370
|
+
### 8.3 Register only selected extensions
|
|
371
|
+
|
|
372
|
+
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
|
+
|
|
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.
|
|
375
|
+
|
|
376
|
+
Do not put this code in the root graph:
|
|
377
|
+
|
|
378
|
+
```ts
|
|
379
|
+
import { replay } from './replay'
|
|
380
|
+
import { surveys } from './surveys'
|
|
381
|
+
|
|
382
|
+
const products = { replay, surveys }
|
|
383
|
+
```
|
|
384
|
+
|
|
385
|
+
A product-name catalog can exist in a separate preset entry point.
|
|
386
|
+
|
|
387
|
+
### 8.4 Use real dynamic imports
|
|
388
|
+
|
|
389
|
+
A generic loader function does not create a chunk by itself. The owner or a product-specific package API must contain a literal dynamic `import()`.
|
|
390
|
+
|
|
391
|
+
Use this form when the application selects an extension before client creation:
|
|
392
|
+
|
|
393
|
+
```ts
|
|
394
|
+
const { flags } = await import('@posthog/browser/flags')
|
|
395
|
+
const posthog = await createPostHog({
|
|
396
|
+
projectToken,
|
|
397
|
+
extensions: [flags()],
|
|
398
|
+
})
|
|
399
|
+
```
|
|
400
|
+
|
|
401
|
+
Use a literal module path. This lets the bundler create a stable chunk. Do not use a computed import path for a known product list.
|
|
402
|
+
|
|
403
|
+
## 9. Extension design
|
|
404
|
+
|
|
405
|
+
An extension must be a factory result or an application-supplied instance.
|
|
406
|
+
It must not be a shared mutable singleton.
|
|
407
|
+
|
|
408
|
+
An extension may start external work during `setup()` or through its own controls after setup.
|
|
409
|
+
The client owns every configured or internally created extension for its lifetime. Runtime installation, removal, and replacement are not public extension contracts; feature-level start and stop remain extension-owned controls.
|
|
410
|
+
An extension must release owned resources in its final `dispose()`.
|
|
411
|
+
Cleanup must be safe after partial setup.
|
|
412
|
+
|
|
413
|
+
The host must give each extension a narrow `Client` view.
|
|
414
|
+
The view must expose capabilities, not the concrete host implementation.
|
|
415
|
+
|
|
416
|
+
The host must keep extension state separate. The host must dispose extensions in reverse installation order.
|
|
417
|
+
|
|
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.
|
|
419
|
+
|
|
420
|
+
An extension failure must not stop core capture. A failed setup must remove all reserved registry state.
|
|
421
|
+
|
|
422
|
+
## 10. Dependency rules
|
|
423
|
+
|
|
424
|
+
The root graph must not import these packages:
|
|
425
|
+
|
|
426
|
+
- `posthog-js`.
|
|
427
|
+
- `@posthog/core`.
|
|
428
|
+
- `core-js`.
|
|
429
|
+
- `fflate`.
|
|
430
|
+
- Preact.
|
|
431
|
+
- DOMPurify.
|
|
432
|
+
- rrweb.
|
|
433
|
+
- `web-vitals`.
|
|
434
|
+
|
|
435
|
+
Put a heavy dependency behind an optional entry point. Prefer a browser capability before a JavaScript fallback.
|
|
436
|
+
|
|
437
|
+
Do not install a global polyfill from the root graph.
|
|
438
|
+
Use a local capability check and a local fallback when the fallback is small.
|
|
439
|
+
|
|
440
|
+
Check the `sideEffects` field of each runtime dependency.
|
|
441
|
+
Import a side-effect-free subpath when the dependency provides one.
|
|
442
|
+
|
|
443
|
+
Move code to `@posthog/browser-common` only when more than one SDK uses the code.
|
|
444
|
+
Shared location does not make code free. Measure the resulting consumer graph.
|
|
445
|
+
|
|
446
|
+
## 11. Build and package rules
|
|
447
|
+
|
|
448
|
+
Publish unbundled ES modules. Preserve the source module boundaries.
|
|
449
|
+
|
|
450
|
+
Also publish CommonJS only when a supported consumer needs it.
|
|
451
|
+
Modern bundlers must resolve the ES module output through the `import` condition.
|
|
452
|
+
|
|
453
|
+
Use modern JavaScript as the library target. Let the application bundler select older targets.
|
|
454
|
+
Do not add compatibility transforms to the root without browser-support evidence.
|
|
455
|
+
|
|
456
|
+
Keep an exact `exports` map. Do not expose all files with a wildcard export.
|
|
457
|
+
|
|
458
|
+
Keep `sideEffects: false` while all entry points remain import-pure. If an explicit side-effect entry becomes necessary, use a small array allowlist instead of `false`.
|
|
459
|
+
|
|
460
|
+
Do not combine all entry points into one prebuilt runtime bundle.
|
|
461
|
+
The package needs preserved ES module boundaries for consumer tree shaking.
|
|
462
|
+
|
|
463
|
+
### CDN-only classic entry
|
|
464
|
+
|
|
465
|
+
The standalone classic-script installer lives in `snippet/`, outside Rslib's `src` glob and the npm `files` allowlist. `build:cdn` emits `dist-cdn/script.js` with the complete initial core graph embedded, plus optional asynchronous chunks and source maps. Rspack's automatic public path captures the executing external script's directory synchronously and removes its query and fragment before loading chunks. There is no separate client download between the initial response and core construction.
|
|
466
|
+
|
|
467
|
+
This deployment artifact intentionally initializes a client; it is not an npm export and does not change the import-purity contract or `sideEffects: false`. Keep the root factory's extension setup order, override precedence, snapshots, consent, and failure isolation unchanged. The installer delegates readiness to that factory. See the [script installation guide](./README.md#classic-script-installation-draft-cdn-distribution) for query configuration, global ownership, and ready-event semantics. `bundle-size:cdn` checks the generated initial graph and reports initial/deferred artifact sizes and module attribution; `test:snippet` runs the generated classic artifacts in plain HTML against the SDK mock server.
|
|
468
|
+
|
|
469
|
+
## 12. Bundle tests
|
|
470
|
+
|
|
471
|
+
Measure code as a package consumer. Build the package before each measurement.
|
|
472
|
+
Do not use source-file size as a bundle metric.
|
|
473
|
+
Do not use npm unpacked size as a browser bundle metric.
|
|
474
|
+
|
|
475
|
+
Run the current core check from `packages/browser-next`:
|
|
476
|
+
|
|
477
|
+
```sh
|
|
478
|
+
pnpm bundle-size
|
|
479
|
+
```
|
|
480
|
+
|
|
481
|
+
The previous 12 KiB gzip threshold is not a binding budget. Set the release ceiling only after the core behavior suite passes and the compliant graph is optimized. This policy is not permission to omit required behavior.
|
|
482
|
+
|
|
483
|
+
After the first behavior-compliant baseline, set binding regression budgets from the optimized consumer bundle. If required behavior exceeds the working budget, inspect and simplify the implementation. Do not delete the invariant.
|
|
484
|
+
|
|
485
|
+
The current check reports these values for the core capture fixture:
|
|
486
|
+
|
|
487
|
+
- Minified bytes.
|
|
488
|
+
- Gzip bytes.
|
|
489
|
+
- Brotli bytes.
|
|
490
|
+
|
|
491
|
+
The current check also reads an esbuild metafile. It rejects known heavy modules in the root graph and prints minified-byte attribution. Pass `--analyze` for the full esbuild import-path report. It does not store a baseline.
|
|
492
|
+
|
|
493
|
+
Add these fixtures when the related public entry points exist:
|
|
494
|
+
|
|
495
|
+
| Fixture | Required check |
|
|
496
|
+
| ----------------------- | ----------------------------------------------------- |
|
|
497
|
+
| Root export only | An unused root export does not retain unrelated code. |
|
|
498
|
+
| Type-only consumer | Type imports produce no JavaScript. |
|
|
499
|
+
| Optional static import | Only the selected optional feature enters the graph. |
|
|
500
|
+
| Optional dynamic import | The feature stays outside the initial chunk. |
|
|
501
|
+
| Standard preset | Initial and total sizes stay separate. |
|
|
502
|
+
| Server import | Package import does not require browser globals. |
|
|
503
|
+
|
|
504
|
+
Each optional-feature check must report these values:
|
|
505
|
+
|
|
506
|
+
- Initial chunk bytes.
|
|
507
|
+
- Dynamic chunk bytes.
|
|
508
|
+
- Total loaded bytes.
|
|
509
|
+
- Module attribution.
|
|
510
|
+
|
|
511
|
+
Extend the bundle-size script when you add a new public entry point.
|
|
512
|
+
Fail the check when a forbidden product or dependency enters the root graph.
|
|
513
|
+
|
|
514
|
+
Review initial and total bundle measurements for runtime changes.
|
|
515
|
+
An increase needs a user benefit and a short size explanation.
|
|
516
|
+
|
|
517
|
+
## 13. Review procedure
|
|
518
|
+
|
|
519
|
+
Use this procedure for each runtime change:
|
|
520
|
+
|
|
521
|
+
1. Identify the durable behavior test, explicit decision, or Capture V1 compliance case.
|
|
522
|
+
2. Add or identify the parity, conformance, or fault-injection test that protects it.
|
|
523
|
+
3. Identify the new static imports.
|
|
524
|
+
4. Check the direction of each import.
|
|
525
|
+
5. Convert contract imports to `import type`.
|
|
526
|
+
6. Check all changed modules for import side effects.
|
|
527
|
+
7. Add an export only when a public import boundary is necessary.
|
|
528
|
+
8. Add or update a consumer fixture.
|
|
529
|
+
9. Run `pnpm bundle-size`.
|
|
530
|
+
10. Inspect module attribution when the runtime graph changes.
|
|
531
|
+
11. Report the behavioral decision and size change in the pull request.
|
|
532
|
+
|
|
533
|
+
Ask these questions during review:
|
|
534
|
+
|
|
535
|
+
- Does basic capture always need this code?
|
|
536
|
+
- Can an application omit this feature by omitting one import?
|
|
537
|
+
- Does a runtime option hide code that needs an import boundary?
|
|
538
|
+
- Does the root import an optional implementation?
|
|
539
|
+
- Does a barrel make the runtime graph unclear?
|
|
540
|
+
- Does module evaluation start work?
|
|
541
|
+
- Does the dynamic loader create a separate chunk?
|
|
542
|
+
- Does the package export match the intended public boundary?
|
|
543
|
+
- Do bundle tests prove the result?
|
|
544
|
+
|
|
545
|
+
If an answer is not clear, do not add the code to the root graph.
|
|
546
|
+
|
|
547
|
+
## 14. Decision priority
|
|
548
|
+
|
|
549
|
+
Use this priority when two designs have similar behavior:
|
|
550
|
+
|
|
551
|
+
1. Select the smaller root graph.
|
|
552
|
+
2. Select the design with the clearer import boundary.
|
|
553
|
+
3. Select the design with fewer import side effects.
|
|
554
|
+
4. Select the design with fewer framework abstractions.
|
|
555
|
+
5. Select the design that produces stable dynamic chunks.
|
|
556
|
+
6. Select the design that is easier to measure.
|
|
557
|
+
|
|
558
|
+
Do not trade correctness, privacy, or no-throw behavior for a smaller bundle.
|
|
559
|
+
Use bundle size as an architectural constraint, not as the only constraint.
|