@shware/analytics 16.0.0 → 16.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (200) hide show
  1. package/README.md +90 -5
  2. package/dist/native/fbsdk.cjs +1 -2
  3. package/dist/native/fbsdk.cjs.map +1 -1
  4. package/dist/native/fbsdk.d.cts.map +1 -1
  5. package/dist/native/fbsdk.d.mts.map +1 -1
  6. package/dist/native/fbsdk.mjs +3 -4
  7. package/dist/native/fbsdk.mjs.map +1 -1
  8. package/dist/react/index.cjs +11 -2
  9. package/dist/react/index.cjs.map +1 -1
  10. package/dist/react/index.d.cts +3 -2
  11. package/dist/react/index.d.cts.map +1 -1
  12. package/dist/react/index.d.mts +3 -2
  13. package/dist/react/index.d.mts.map +1 -1
  14. package/dist/react/index.mjs +3 -2
  15. package/dist/react/index.mjs.map +1 -1
  16. package/dist/react/posthog-error-boundary.cjs +119 -0
  17. package/dist/react/posthog-error-boundary.cjs.map +1 -0
  18. package/dist/react/posthog-error-boundary.d.cts +60 -0
  19. package/dist/react/posthog-error-boundary.d.cts.map +1 -0
  20. package/dist/react/posthog-error-boundary.d.mts +60 -0
  21. package/dist/react/posthog-error-boundary.d.mts.map +1 -0
  22. package/dist/react/posthog-error-boundary.mjs +117 -0
  23. package/dist/react/posthog-error-boundary.mjs.map +1 -0
  24. package/dist/react/posthog.cjs +97 -0
  25. package/dist/react/posthog.cjs.map +1 -0
  26. package/dist/react/posthog.d.cts +41 -0
  27. package/dist/react/posthog.d.cts.map +1 -0
  28. package/dist/react/posthog.d.mts +41 -0
  29. package/dist/react/posthog.d.mts.map +1 -0
  30. package/dist/react/posthog.mjs +90 -0
  31. package/dist/react/posthog.mjs.map +1 -0
  32. package/dist/server/conversions-api-error.cjs +20 -0
  33. package/dist/server/conversions-api-error.cjs.map +1 -0
  34. package/dist/server/conversions-api-error.d.cts +17 -0
  35. package/dist/server/conversions-api-error.d.cts.map +1 -0
  36. package/dist/server/conversions-api-error.d.mts +17 -0
  37. package/dist/server/conversions-api-error.d.mts.map +1 -0
  38. package/dist/server/conversions-api-error.mjs +19 -0
  39. package/dist/server/conversions-api-error.mjs.map +1 -0
  40. package/dist/server/google-data-manager.cjs +24 -26
  41. package/dist/server/google-data-manager.cjs.map +1 -1
  42. package/dist/server/google-data-manager.d.cts +13 -5
  43. package/dist/server/google-data-manager.d.cts.map +1 -1
  44. package/dist/server/google-data-manager.d.mts +13 -5
  45. package/dist/server/google-data-manager.d.mts.map +1 -1
  46. package/dist/server/google-data-manager.mjs +24 -27
  47. package/dist/server/google-data-manager.mjs.map +1 -1
  48. package/dist/server/index.cjs +11 -0
  49. package/dist/server/index.d.cts +10 -7
  50. package/dist/server/index.d.mts +10 -7
  51. package/dist/server/index.mjs +9 -7
  52. package/dist/server/linkedin-conversions-api.cjs +29 -23
  53. package/dist/server/linkedin-conversions-api.cjs.map +1 -1
  54. package/dist/server/linkedin-conversions-api.d.cts +7 -2
  55. package/dist/server/linkedin-conversions-api.d.cts.map +1 -1
  56. package/dist/server/linkedin-conversions-api.d.mts +7 -2
  57. package/dist/server/linkedin-conversions-api.d.mts.map +1 -1
  58. package/dist/server/linkedin-conversions-api.mjs +29 -24
  59. package/dist/server/linkedin-conversions-api.mjs.map +1 -1
  60. package/dist/server/meta-capi.cjs +32 -31
  61. package/dist/server/meta-capi.cjs.map +1 -1
  62. package/dist/server/meta-capi.d.cts +12 -3
  63. package/dist/server/meta-capi.d.cts.map +1 -1
  64. package/dist/server/meta-capi.d.mts +12 -3
  65. package/dist/server/meta-capi.d.mts.map +1 -1
  66. package/dist/server/meta-capi.mjs +33 -33
  67. package/dist/server/meta-capi.mjs.map +1 -1
  68. package/dist/server/microsoft-conversions-api.cjs +33 -28
  69. package/dist/server/microsoft-conversions-api.cjs.map +1 -1
  70. package/dist/server/microsoft-conversions-api.d.cts +14 -2
  71. package/dist/server/microsoft-conversions-api.d.cts.map +1 -1
  72. package/dist/server/microsoft-conversions-api.d.mts +14 -2
  73. package/dist/server/microsoft-conversions-api.d.mts.map +1 -1
  74. package/dist/server/microsoft-conversions-api.mjs +33 -29
  75. package/dist/server/microsoft-conversions-api.mjs.map +1 -1
  76. package/dist/server/openai-conversions-api.cjs +20 -18
  77. package/dist/server/openai-conversions-api.cjs.map +1 -1
  78. package/dist/server/openai-conversions-api.d.cts +7 -0
  79. package/dist/server/openai-conversions-api.d.cts.map +1 -1
  80. package/dist/server/openai-conversions-api.d.mts +7 -0
  81. package/dist/server/openai-conversions-api.d.mts.map +1 -1
  82. package/dist/server/openai-conversions-api.mjs +21 -20
  83. package/dist/server/openai-conversions-api.mjs.map +1 -1
  84. package/dist/server/reddit-conversions-api.cjs +20 -18
  85. package/dist/server/reddit-conversions-api.cjs.map +1 -1
  86. package/dist/server/reddit-conversions-api.d.cts +7 -0
  87. package/dist/server/reddit-conversions-api.d.cts.map +1 -1
  88. package/dist/server/reddit-conversions-api.d.mts +7 -0
  89. package/dist/server/reddit-conversions-api.d.mts.map +1 -1
  90. package/dist/server/reddit-conversions-api.mjs +21 -20
  91. package/dist/server/reddit-conversions-api.mjs.map +1 -1
  92. package/dist/server/setup-conversions.cjs +62 -0
  93. package/dist/server/setup-conversions.cjs.map +1 -0
  94. package/dist/server/setup-conversions.d.cts +97 -0
  95. package/dist/server/setup-conversions.d.cts.map +1 -0
  96. package/dist/server/setup-conversions.d.mts +97 -0
  97. package/dist/server/setup-conversions.d.mts.map +1 -0
  98. package/dist/server/setup-conversions.mjs +60 -0
  99. package/dist/server/setup-conversions.mjs.map +1 -0
  100. package/dist/third-parties/index.d.cts +3 -3
  101. package/dist/third-parties/index.d.mts +3 -3
  102. package/dist/third-parties/integration.cjs +13 -6
  103. package/dist/third-parties/integration.cjs.map +1 -1
  104. package/dist/third-parties/integration.d.cts +12 -8
  105. package/dist/third-parties/integration.d.cts.map +1 -1
  106. package/dist/third-parties/integration.d.mts +12 -8
  107. package/dist/third-parties/integration.d.mts.map +1 -1
  108. package/dist/third-parties/integration.mjs +13 -7
  109. package/dist/third-parties/integration.mjs.map +1 -1
  110. package/dist/third-parties/linkedin-insight-tag.cjs +0 -4
  111. package/dist/third-parties/linkedin-insight-tag.cjs.map +1 -1
  112. package/dist/third-parties/linkedin-insight-tag.d.cts +4 -2
  113. package/dist/third-parties/linkedin-insight-tag.d.cts.map +1 -1
  114. package/dist/third-parties/linkedin-insight-tag.d.mts +4 -2
  115. package/dist/third-parties/linkedin-insight-tag.d.mts.map +1 -1
  116. package/dist/third-parties/linkedin-insight-tag.mjs +0 -4
  117. package/dist/third-parties/linkedin-insight-tag.mjs.map +1 -1
  118. package/dist/third-parties/meta-pixel.cjs +1 -3
  119. package/dist/third-parties/meta-pixel.cjs.map +1 -1
  120. package/dist/third-parties/meta-pixel.d.cts +4 -2
  121. package/dist/third-parties/meta-pixel.d.cts.map +1 -1
  122. package/dist/third-parties/meta-pixel.d.mts +4 -2
  123. package/dist/third-parties/meta-pixel.d.mts.map +1 -1
  124. package/dist/third-parties/meta-pixel.mjs +3 -5
  125. package/dist/third-parties/meta-pixel.mjs.map +1 -1
  126. package/dist/third-parties/microsoft-uet.cjs +7 -2
  127. package/dist/third-parties/microsoft-uet.cjs.map +1 -1
  128. package/dist/third-parties/microsoft-uet.d.cts +10 -3
  129. package/dist/third-parties/microsoft-uet.d.cts.map +1 -1
  130. package/dist/third-parties/microsoft-uet.d.mts +10 -3
  131. package/dist/third-parties/microsoft-uet.d.mts.map +1 -1
  132. package/dist/third-parties/microsoft-uet.mjs +8 -4
  133. package/dist/third-parties/microsoft-uet.mjs.map +1 -1
  134. package/dist/third-parties/openai-pixel.cjs +1 -3
  135. package/dist/third-parties/openai-pixel.cjs.map +1 -1
  136. package/dist/third-parties/openai-pixel.d.cts +4 -2
  137. package/dist/third-parties/openai-pixel.d.cts.map +1 -1
  138. package/dist/third-parties/openai-pixel.d.mts +4 -2
  139. package/dist/third-parties/openai-pixel.d.mts.map +1 -1
  140. package/dist/third-parties/openai-pixel.mjs +3 -5
  141. package/dist/third-parties/openai-pixel.mjs.map +1 -1
  142. package/dist/third-parties/posthog.cjs +3 -3
  143. package/dist/third-parties/posthog.cjs.map +1 -1
  144. package/dist/third-parties/posthog.d.cts +3 -3
  145. package/dist/third-parties/posthog.d.mts +3 -3
  146. package/dist/third-parties/posthog.mjs +3 -3
  147. package/dist/third-parties/posthog.mjs.map +1 -1
  148. package/dist/third-parties/reddit-pixel.cjs +1 -3
  149. package/dist/third-parties/reddit-pixel.cjs.map +1 -1
  150. package/dist/third-parties/reddit-pixel.d.cts +4 -2
  151. package/dist/third-parties/reddit-pixel.d.cts.map +1 -1
  152. package/dist/third-parties/reddit-pixel.d.mts +4 -2
  153. package/dist/third-parties/reddit-pixel.d.mts.map +1 -1
  154. package/dist/third-parties/reddit-pixel.mjs +3 -5
  155. package/dist/third-parties/reddit-pixel.mjs.map +1 -1
  156. package/dist/track/fbq.cjs +5 -0
  157. package/dist/track/fbq.cjs.map +1 -1
  158. package/dist/track/fbq.d.cts +2 -0
  159. package/dist/track/fbq.d.cts.map +1 -1
  160. package/dist/track/fbq.d.mts +2 -0
  161. package/dist/track/fbq.d.mts.map +1 -1
  162. package/dist/track/fbq.mjs +5 -1
  163. package/dist/track/fbq.mjs.map +1 -1
  164. package/dist/track/oaiq.cjs +5 -0
  165. package/dist/track/oaiq.cjs.map +1 -1
  166. package/dist/track/oaiq.d.cts +2 -0
  167. package/dist/track/oaiq.d.cts.map +1 -1
  168. package/dist/track/oaiq.d.mts +2 -0
  169. package/dist/track/oaiq.d.mts.map +1 -1
  170. package/dist/track/oaiq.mjs +5 -1
  171. package/dist/track/oaiq.mjs.map +1 -1
  172. package/dist/track/rdt.cjs +5 -0
  173. package/dist/track/rdt.cjs.map +1 -1
  174. package/dist/track/rdt.d.cts +2 -0
  175. package/dist/track/rdt.d.cts.map +1 -1
  176. package/dist/track/rdt.d.mts +2 -0
  177. package/dist/track/rdt.d.mts.map +1 -1
  178. package/dist/track/rdt.mjs +5 -1
  179. package/dist/track/rdt.mjs.map +1 -1
  180. package/package.json +1 -16
  181. package/dist/react/use-feature-flag.cjs +0 -23
  182. package/dist/react/use-feature-flag.cjs.map +0 -1
  183. package/dist/react/use-feature-flag.d.cts +0 -10
  184. package/dist/react/use-feature-flag.d.cts.map +0 -1
  185. package/dist/react/use-feature-flag.d.mts +0 -10
  186. package/dist/react/use-feature-flag.d.mts.map +0 -1
  187. package/dist/react/use-feature-flag.mjs +0 -22
  188. package/dist/react/use-feature-flag.mjs.map +0 -1
  189. package/dist/server/legacy.cjs +0 -3
  190. package/dist/server/legacy.d.cts +0 -2
  191. package/dist/server/legacy.d.mts +0 -2
  192. package/dist/server/legacy.mjs +0 -1
  193. package/dist/server/meta-conversions-api.cjs +0 -205
  194. package/dist/server/meta-conversions-api.cjs.map +0 -1
  195. package/dist/server/meta-conversions-api.d.cts +0 -8
  196. package/dist/server/meta-conversions-api.d.cts.map +0 -1
  197. package/dist/server/meta-conversions-api.d.mts +0 -8
  198. package/dist/server/meta-conversions-api.d.mts.map +0 -1
  199. package/dist/server/meta-conversions-api.mjs +0 -201
  200. package/dist/server/meta-conversions-api.mjs.map +0 -1
package/README.md CHANGED
@@ -33,7 +33,6 @@ modules for `/native`, `react-native-fbsdk-next` for `/native/fbsdk`, and so on)
33
33
  | `@shware/analytics/tanstack` | both | `createClickIdMiddleware` for TanStack Start |
34
34
  | `@shware/analytics/third-parties` | browser | GA4, Meta Pixel, Reddit, LinkedIn, OpenAI and UET trackers and setters |
35
35
  | `@shware/analytics/server` | server | Conversions APIs: Meta, Google Ads, Microsoft, Reddit, LinkedIn, OpenAI |
36
- | `@shware/analytics/server/legacy` | server | The old Meta sender built on `facebook-nodejs-business-sdk` |
37
36
  | `@shware/analytics/attribution` | server | `classifyTouch` and the channel vocabulary for reading sessions |
38
37
  | `@shware/analytics/ads` | server | Pulling spend and performance from Google Ads and Meta |
39
38
 
@@ -106,10 +105,10 @@ export const integrations = [
106
105
  | `ads` | `linkedInAds` | the events in `conversions`, each as its conversion id |
107
106
  | `ads` | `microsoftAds` | `events` (the GA4 conversion events, `CONVERSION_EVENTS`, by default), plus `customEvents` |
108
107
 
109
- An ad platform needs conversions to optimize and build audiences, not the product's day-to-day events, which are behavior analysis for GA4 and PostHog. `excludeFromIntegrations` applies to every integration, analytics included. PostHog loads from its HTML snippet like the pixels, so `posthog-js` is not bundled: the library comes from PostHog's assets host after the page loads, and `config` (only its JSON survives) goes to `posthog.init`. Until it loads, `window.posthog` is a stub that queues calls returning nothing (`capture`, `identify`, `onFeatureFlags`) and replays them, while calls returning a value (`getFeatureFlag`) return `undefined`. So: `getPosthog()` for queued calls, `getLoadedPosthog()` (undefined until loaded) for values, and `useFeatureFlag(key)` from `@shware/analytics/react` in components. `useFeatureFlag` renders the default until flags arrive, then the variant. To show a `<Suspense>` fallback until then instead, wait for them with React 19.3's `browser()` (so the server renders the fallback) and `posthogFlagsReady()` (one promise per page, resolving when flags load or after a 3 s timeout, for when an ad blocker stops the library):
108
+ An ad platform needs conversions to optimize and build audiences, not the product's day-to-day events, which are behavior analysis for GA4 and PostHog. `excludeFromIntegrations` applies to every integration, analytics included. PostHog loads from its HTML snippet like the pixels, so `posthog-js` is not bundled: the library comes from PostHog's assets host after the page loads, and `config` (only its JSON survives) goes to `posthog.init`. Until it loads, `window.posthog` is a stub that queues calls returning nothing (`capture`, `identify`, `onFeatureFlags`) and replays them, while calls returning a value (`getFeatureFlag`) return `undefined`. So: `getPosthog()` for queued calls, `getLoadedPosthog()` (undefined until loaded) for values, and in components the flag hooks of `posthog-js/react`, with its names and signatures, from `@shware/analytics/react`: `useFeatureFlagVariantKey`, `useFeatureFlagEnabled`, `useFeatureFlagPayload`, `useFeatureFlagResult` and `useActiveFeatureFlags`, and `usePostHog` for the instance (the stub until the library loads). The flag hooks render the default until flags arrive, then the variant. To show a `<Suspense>` fallback until then instead, wait for them with React 19.3's `browser()` (so the server renders the fallback) and `posthogFlagsReady()` (one promise per page, resolving when flags load or after a 3 s timeout, for when an ad blocker stops the library):
110
109
 
111
110
  ```tsx
112
- import { useFeatureFlag } from '@shware/analytics/react';
111
+ import { useFeatureFlagVariantKey } from '@shware/analytics/react';
113
112
  import { posthogFlagsReady } from '@shware/analytics/third-parties';
114
113
  import { use } from 'react';
115
114
  import { browser } from 'react-dom';
@@ -117,11 +116,21 @@ import { browser } from 'react-dom';
117
116
  function Checkout() {
118
117
  use(browser());
119
118
  use(posthogFlagsReady());
120
- return useFeatureFlag('new-checkout') === 'test' ? <NewCheckout /> : <OldCheckout />;
119
+ return useFeatureFlagVariantKey('new-checkout') === 'test' ? <NewCheckout /> : <OldCheckout />;
121
120
  }
122
121
  ```
123
122
 
124
- With server-evaluated flags in `config.bootstrap` the wait ends as soon as the library loads. On Next.js its snippet uses `next/script`'s `beforeInteractive`, so the stub exists before hydration tracks anything; render `<Analytics>` in the root layout for that. `<Analytics>` also preconnects to PostHog's assets host (`Integration.preconnect`, through `react-dom`'s `preconnect`), so `array.js` starts sooner. The `PostHog` and `PostHogConfig` types come from `posthog-js`: install it as a dev dependency for them. In an app, `firebaseAnalytics()` (every event) and `metaAppEvents({ customEvents })` (the conversions Meta maps, like `metaAds`) are the `integrations`. A platform the SDK does not cover is an object implementing `Integration` (`type`, `track`, and optionally `setUser` and `script`).
123
+ With server-evaluated flags, skip the wait: pass them in `config.bootstrap` and wrap the app in `<PosthogProvider bootstrap={bootstrap}>` with the same object (it initializes nothing: the snippet does), and the hooks render the server's value on the server, through hydration and until the library loads — the variant from the first frame, with no hydration mismatch. The exposure (`$feature_flag_called`) is sent once the library reads the flag.
124
+
125
+ ```tsx
126
+ <PosthogProvider bootstrap={bootstrap}>
127
+ <Outlet />
128
+ </PosthogProvider>
129
+ ```
130
+
131
+ For error tracking, `<PosthogErrorBoundary fallback={…}>` (with `posthog-js/react`'s props) sends a render error to PostHog with its component stack, tied to the session's replay, and renders `fallback` instead; an error before the library loads is queued on the stub. Errors outside render (event handlers, unhandled rejections) are the library's own exception autocapture: `capture_exceptions: true` in `config`. What no boundary of yours sees — an uncaught error, one a framework's boundary caught (TanStack Router's `errorComponent`), a hydration mismatch React recovered from — `setupReactErrorHandler()` reports from React 19's root options, in the client entry: `hydrateRoot(document, <StartClient />, { onUncaughtError: setupReactErrorHandler(), onCaughtError: setupReactErrorHandler(), onRecoverableError: setupReactErrorHandler() })`.
132
+
133
+ Under `posthogFlagsReady()` with `config.bootstrap` the wait ends as soon as the library loads. On Next.js its snippet uses `next/script`'s `beforeInteractive`, so the stub exists before hydration tracks anything; render `<Analytics>` in the root layout for that. `<Analytics>` also preconnects to PostHog's assets host (`Integration.preconnect`, through `react-dom`'s `preconnect`), so `array.js` starts sooner. The `PostHog` and `PostHogConfig` types come from `posthog-js`: install it as a dev dependency for them. In an app, `firebaseAnalytics()` (every event) and `metaAppEvents({ customEvents })` (the conversions Meta maps, like `metaAds`) are the `integrations`. A platform the SDK does not cover is an object implementing `Integration` (`type`, `track`, and optionally `setUser` and `script`).
125
134
 
126
135
  `getHeaders` is also accepted, for a backend that wants extra headers on the analytics requests.
127
136
 
@@ -261,6 +270,82 @@ The server's conversions API, sending the stored event under the same id, then d
261
270
 
262
271
  Nothing waits for the server: `track` fires the pixels at once and the batch reaches the server within 2 s or by beacon when the page is left, so there is no `trackAsync` (removed in 13.0). A step that must not run before the server has the event does not belong in the client; record it server-side.
263
272
 
273
+ ### Conversions APIs on the server (`setupConversions`)
274
+
275
+ The server's counterpart of `setupAnalytics({ integrations })`, configured on the server alone:
276
+ each ad platform's Conversions API once, sent what its browser integration is sent — the
277
+ platform's standard events and the `customEvents` it lists, nothing else. The options are the
278
+ browser integrations' (`MetaAdsOptions`, …) plus a token; give a platform the same
279
+ `customEvents` on both sides for the tag and the API to report the same events.
280
+
281
+ ```ts
282
+ import {
283
+ linkedinConversions,
284
+ metaConversions,
285
+ redditConversions,
286
+ setupConversions,
287
+ } from '@shware/analytics/server';
288
+
289
+ export const conversions = setupConversions({
290
+ destinations: [
291
+ metaConversions({
292
+ accessToken: env.META_CONVERSIONS_API_ACCESS_TOKEN,
293
+ pixelId: '1234567890',
294
+ customEvents: ['onboarding_completed'],
295
+ }),
296
+ redditConversions({ accessToken: env.REDDIT_CONVERSIONS_API_ACCESS_TOKEN, pixelId: 'a2_xxx' }),
297
+ linkedinConversions({
298
+ accessToken: env.LINKEDIN_CONVERSIONS_API_ACCESS_TOKEN,
299
+ conversions: { sign_up: 7654321, purchase: 7654322 },
300
+ }),
301
+ // a CRM or the host's own workflows: any `{ send(events, data) }`
302
+ { send: (events, data) => sendToCrm(events, data) },
303
+ ],
304
+ // Only for conversions.track(), which is returned only with it; forward needs none of it.
305
+ track: {
306
+ resolveUser: async (userId) => latestSessionOf(userId),
307
+ store: async (event) => (await insertEvents([event])).length > 0,
308
+ },
309
+ });
310
+
311
+ // POST /events, after storing the batch
312
+ ctx.waitUntil(conversions.forward(events, userProvidedData));
313
+
314
+ // a webhook: Stripe's invoice.paid, once the account is credited
315
+ ctx.waitUntil(
316
+ conversions.track({
317
+ id: invoice.id,
318
+ name: 'purchase',
319
+ userId,
320
+ properties: { transaction_id: invoice.id, value: 9.99, currency: 'usd', items: [] },
321
+ createdAt: new Date(invoice.created * 1000).toISOString(),
322
+ })
323
+ );
324
+ ```
325
+
326
+ - `forward(events, data)`: the events a client sent, as stored, to every destination at once.
327
+ - `track(event)`: an event the server reports on its own — a webhook's purchase, renewal or
328
+ refund — with `id` the transaction id. `track.resolveUser(userId)` returns what a client event
329
+ would have carried, from the host's records: the user's latest session's `tags` (cookies, page,
330
+ user agent) with the click ids of the touch the conversion is credited to, that session's
331
+ `visitor_id`, `session_id`, `platform` (which decides website or app) and `environment`, and the
332
+ user's identity as `data`. `track.store` stores the event — in the events table, so the
333
+ server's conversions count wherever the client's do — and says whether it was new: only a new
334
+ one is sent, so a webhook delivered again is not reported twice. That matters: the platforms
335
+ document deduplicating a server event against a browser one, and only Microsoft (on `eventId`)
336
+ and Google Ads (on `transaction_id`) a server event sent twice. A user with no session is
337
+ skipped.
338
+
339
+ Neither throws, so reporting a conversion cannot fail the request it runs in — least of all a
340
+ payment webhook, which its provider would deliver again and again. A failure is logged with the
341
+ ids of the events it lost (`Conversions not sent, events: …`), to be found and sent later: a
342
+ missed conversion costs less than a duplicate one or a failing webhook. The `send…Events`
343
+ functions underneath reject instead (`ConversionsApiError` for an error status, the fetch error
344
+ for a network failure; neither carries a token), for a caller using them directly to handle.
345
+
346
+ List events the server reports itself in `setupAnalytics({ excludeFromIntegrations })` so the
347
+ browser does not send them too.
348
+
264
349
  ### Tracking an occurrence once (`trackOnce`)
265
350
 
266
351
  A payment result page can be reloaded or reopened from history, and a store transaction can be delivered again; each would report the same `purchase` again. `trackOnce` takes the key that identifies the occurrence and tracks it at most once per key:
@@ -44,10 +44,9 @@ function setFBUser({ user_id, user_data }) {
44
44
  * — the app's counterpart of `metaAds`.
45
45
  */
46
46
  function metaAppEvents(options = {}) {
47
- const isStandard = (name) => require_track_fbq.mapFBEvent(name)[0] === "track";
48
47
  return {
49
48
  type: "ads",
50
- track: require_third_parties_integration.adsTracker(sendFBEvent, isStandard, options.customEvents ?? []),
49
+ track: require_third_parties_integration.adsTracker(sendFBEvent, require_third_parties_integration.adEvents(require_track_fbq.isStandardFBEvent, options.customEvents)),
51
50
  setUser: setFBUser
52
51
  };
53
52
  }
@@ -1 +1 @@
1
- {"version":3,"file":"fbsdk.cjs","names":["mapFBEvent","getFirst","adsTracker"],"sources":["../../src/native/fbsdk.ts"],"sourcesContent":["import { AppEventsLogger, type Params } from 'react-native-fbsdk-next';\nimport type { UpdateVisitorDTO } from '../schema/index';\nimport { type AdsOptions, type Integration, adsTracker } from '../third-parties/integration';\nimport { mapFBEvent } from '../track/fbq';\nimport type { EventName, TrackName, TrackProperties } from '../track/types';\nimport { getFirst } from '../utils/field';\n\n/**\n * ref: https://developers.facebook.com/docs/app-events/guides/maximize-in-app-ad-revenue/\n *\n * Synchronous, like `logEvent`: a tracker returns `void | boolean`, which an `async` function's\n * promise would not satisfy. Callers that still `await` it keep compiling.\n */\nexport function sendFBEvent<T extends EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>\n) {\n const [_, fbEventName, fbEventProperties] = mapFBEvent(name, properties);\n AppEventsLogger.logEvent(fbEventName, fbEventProperties as Params);\n}\n\n/**\n * Hands the signed-in user to Facebook App Events, as `setFBUser` does the Pixel: the user id\n * (`external_id`) and the advanced matching fields, which the SDK hashes on the device. No user is\n * sign-out (`reset()`): the user id is cleared, but the matching fields may not be.\n *\n * Known gap, kept on purpose: the fields go to the native `setUserData`, which on Android only\n * updates the fields it is given, so the empty ones sent at sign-out leave the previous user's\n * email and phone in place, and later anonymous events (or another user's without an email) can\n * still carry them. `react-native-fbsdk-next` does not expose the native `clearUserData`. Dropping\n * the fields would avoid it, but cost more in ad conversion matching than the gap does.\n */\nexport function setFBUser({ user_id, user_data }: Omit<UpdateVisitorDTO, 'tags'>) {\n AppEventsLogger.setUserID(user_id || null);\n const address = getFirst(user_data?.address);\n AppEventsLogger.setUserData({\n email: getFirst(user_data?.email),\n phone: getFirst(user_data?.phone_number),\n firstName: address?.first_name,\n lastName: address?.last_name,\n city: address?.city,\n state: address?.region,\n zip: address?.postal_code,\n country: address?.country,\n });\n}\n\n/**\n * Facebook App Events: the events `mapFBEvent` maps to a Meta standard event, and `customEvents`\n * — the app's counterpart of `metaAds`.\n */\nexport function metaAppEvents(options: AdsOptions = {}): Integration {\n const isStandard = (name: string) => mapFBEvent(name as TrackName)[0] === 'track';\n return {\n type: 'ads',\n track: adsTracker(sendFBEvent, isStandard, options.customEvents ?? []),\n setUser: setFBUser,\n };\n}\n"],"mappings":";;;;;;;;;;;;AAaA,SAAgB,YACd,MACA,YACA;CACA,MAAM,CAAC,GAAG,aAAa,qBAAqBA,kBAAAA,WAAW,MAAM,UAAU;CACvE,wBAAA,gBAAgB,SAAS,aAAa,iBAA2B;AACnE;;;;;;;;;;;;AAaA,SAAgB,UAAU,EAAE,SAAS,aAA6C;CAChF,wBAAA,gBAAgB,UAAU,WAAW,IAAI;CACzC,MAAM,UAAUC,oBAAAA,SAAS,WAAW,OAAO;CAC3C,wBAAA,gBAAgB,YAAY;EAC1B,OAAOA,oBAAAA,SAAS,WAAW,KAAK;EAChC,OAAOA,oBAAAA,SAAS,WAAW,YAAY;EACvC,WAAW,SAAS;EACpB,UAAU,SAAS;EACnB,MAAM,SAAS;EACf,OAAO,SAAS;EAChB,KAAK,SAAS;EACd,SAAS,SAAS;CACpB,CAAC;AACH;;;;;AAMA,SAAgB,cAAc,UAAsB,CAAC,GAAgB;CACnE,MAAM,cAAc,SAAiBD,kBAAAA,WAAW,IAAiB,CAAC,CAAC,OAAO;CAC1E,OAAO;EACL,MAAM;EACN,OAAOE,kCAAAA,WAAW,aAAa,YAAY,QAAQ,gBAAgB,CAAC,CAAC;EACrE,SAAS;CACX;AACF"}
1
+ {"version":3,"file":"fbsdk.cjs","names":["mapFBEvent","getFirst","adsTracker","adEvents","isStandardFBEvent"],"sources":["../../src/native/fbsdk.ts"],"sourcesContent":["import { AppEventsLogger, type Params } from 'react-native-fbsdk-next';\nimport type { UpdateVisitorDTO } from '../schema/index';\nimport {\n type AdsOptions,\n type Integration,\n adEvents,\n adsTracker,\n} from '../third-parties/integration';\nimport { isStandardFBEvent, mapFBEvent } from '../track/fbq';\nimport type { EventName, TrackName, TrackProperties } from '../track/types';\nimport { getFirst } from '../utils/field';\n\n/**\n * ref: https://developers.facebook.com/docs/app-events/guides/maximize-in-app-ad-revenue/\n *\n * Synchronous, like `logEvent`: a tracker returns `void | boolean`, which an `async` function's\n * promise would not satisfy. Callers that still `await` it keep compiling.\n */\nexport function sendFBEvent<T extends EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>\n) {\n const [_, fbEventName, fbEventProperties] = mapFBEvent(name, properties);\n AppEventsLogger.logEvent(fbEventName, fbEventProperties as Params);\n}\n\n/**\n * Hands the signed-in user to Facebook App Events, as `setFBUser` does the Pixel: the user id\n * (`external_id`) and the advanced matching fields, which the SDK hashes on the device. No user is\n * sign-out (`reset()`): the user id is cleared, but the matching fields may not be.\n *\n * Known gap, kept on purpose: the fields go to the native `setUserData`, which on Android only\n * updates the fields it is given, so the empty ones sent at sign-out leave the previous user's\n * email and phone in place, and later anonymous events (or another user's without an email) can\n * still carry them. `react-native-fbsdk-next` does not expose the native `clearUserData`. Dropping\n * the fields would avoid it, but cost more in ad conversion matching than the gap does.\n */\nexport function setFBUser({ user_id, user_data }: Omit<UpdateVisitorDTO, 'tags'>) {\n AppEventsLogger.setUserID(user_id || null);\n const address = getFirst(user_data?.address);\n AppEventsLogger.setUserData({\n email: getFirst(user_data?.email),\n phone: getFirst(user_data?.phone_number),\n firstName: address?.first_name,\n lastName: address?.last_name,\n city: address?.city,\n state: address?.region,\n zip: address?.postal_code,\n country: address?.country,\n });\n}\n\n/**\n * Facebook App Events: the events `mapFBEvent` maps to a Meta standard event, and `customEvents`\n * — the app's counterpart of `metaAds`.\n */\nexport function metaAppEvents(options: AdsOptions = {}): Integration {\n return {\n type: 'ads',\n track: adsTracker(sendFBEvent, adEvents(isStandardFBEvent, options.customEvents)),\n setUser: setFBUser,\n };\n}\n"],"mappings":";;;;;;;;;;;;AAkBA,SAAgB,YACd,MACA,YACA;CACA,MAAM,CAAC,GAAG,aAAa,qBAAqBA,kBAAAA,WAAW,MAAM,UAAU;CACvE,wBAAA,gBAAgB,SAAS,aAAa,iBAA2B;AACnE;;;;;;;;;;;;AAaA,SAAgB,UAAU,EAAE,SAAS,aAA6C;CAChF,wBAAA,gBAAgB,UAAU,WAAW,IAAI;CACzC,MAAM,UAAUC,oBAAAA,SAAS,WAAW,OAAO;CAC3C,wBAAA,gBAAgB,YAAY;EAC1B,OAAOA,oBAAAA,SAAS,WAAW,KAAK;EAChC,OAAOA,oBAAAA,SAAS,WAAW,YAAY;EACvC,WAAW,SAAS;EACpB,UAAU,SAAS;EACnB,MAAM,SAAS;EACf,OAAO,SAAS;EAChB,KAAK,SAAS;EACd,SAAS,SAAS;CACpB,CAAC;AACH;;;;;AAMA,SAAgB,cAAc,UAAsB,CAAC,GAAgB;CACnE,OAAO;EACL,MAAM;EACN,OAAOC,kCAAAA,WAAW,aAAaC,kCAAAA,SAASC,kBAAAA,mBAAmB,QAAQ,YAAY,CAAC;EAChF,SAAS;CACX;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"fbsdk.d.cts","names":[],"sources":["../../src/native/fbsdk.ts"],"mappings":";;;;;;;;;wBAagB,YAAY,UAAU,WACpC,MAAM,UAAU,IAChB,aAAa,gBAAgB;;;;;;;;;;;;wBAiBf,YAAY,SAAS,aAAa,KAAK;;;;;wBAmBvC,cAAc,UAAS,aAAkB"}
1
+ {"version":3,"file":"fbsdk.d.cts","names":[],"sources":["../../src/native/fbsdk.ts"],"mappings":";;;;;;;;;wBAkBgB,YAAY,UAAU,WACpC,MAAM,UAAU,IAChB,aAAa,gBAAgB;;;;;;;;;;;;wBAiBf,YAAY,SAAS,aAAa,KAAK;;;;;wBAmBvC,cAAc,UAAS,aAAkB"}
@@ -1 +1 @@
1
- {"version":3,"file":"fbsdk.d.mts","names":[],"sources":["../../src/native/fbsdk.ts"],"mappings":";;;;;;;;;wBAagB,YAAY,UAAU,WACpC,MAAM,UAAU,IAChB,aAAa,gBAAgB;;;;;;;;;;;;wBAiBf,YAAY,SAAS,aAAa,KAAK;;;;;wBAmBvC,cAAc,UAAS,aAAkB"}
1
+ {"version":3,"file":"fbsdk.d.mts","names":[],"sources":["../../src/native/fbsdk.ts"],"mappings":";;;;;;;;;wBAkBgB,YAAY,UAAU,WACpC,MAAM,UAAU,IAChB,aAAa,gBAAgB;;;;;;;;;;;;wBAiBf,YAAY,SAAS,aAAa,KAAK;;;;;wBAmBvC,cAAc,UAAS,aAAkB"}
@@ -1,6 +1,6 @@
1
1
  import { getFirst } from "../utils/field.mjs";
2
- import { adsTracker } from "../third-parties/integration.mjs";
3
- import { mapFBEvent } from "../track/fbq.mjs";
2
+ import { adEvents, adsTracker } from "../third-parties/integration.mjs";
3
+ import { isStandardFBEvent, mapFBEvent } from "../track/fbq.mjs";
4
4
  import { AppEventsLogger } from "react-native-fbsdk-next";
5
5
  // src/native/fbsdk.ts
6
6
  /**
@@ -43,10 +43,9 @@ function setFBUser({ user_id, user_data }) {
43
43
  * — the app's counterpart of `metaAds`.
44
44
  */
45
45
  function metaAppEvents(options = {}) {
46
- const isStandard = (name) => mapFBEvent(name)[0] === "track";
47
46
  return {
48
47
  type: "ads",
49
- track: adsTracker(sendFBEvent, isStandard, options.customEvents ?? []),
48
+ track: adsTracker(sendFBEvent, adEvents(isStandardFBEvent, options.customEvents)),
50
49
  setUser: setFBUser
51
50
  };
52
51
  }
@@ -1 +1 @@
1
- {"version":3,"file":"fbsdk.mjs","names":[],"sources":["../../src/native/fbsdk.ts"],"sourcesContent":["import { AppEventsLogger, type Params } from 'react-native-fbsdk-next';\nimport type { UpdateVisitorDTO } from '../schema/index';\nimport { type AdsOptions, type Integration, adsTracker } from '../third-parties/integration';\nimport { mapFBEvent } from '../track/fbq';\nimport type { EventName, TrackName, TrackProperties } from '../track/types';\nimport { getFirst } from '../utils/field';\n\n/**\n * ref: https://developers.facebook.com/docs/app-events/guides/maximize-in-app-ad-revenue/\n *\n * Synchronous, like `logEvent`: a tracker returns `void | boolean`, which an `async` function's\n * promise would not satisfy. Callers that still `await` it keep compiling.\n */\nexport function sendFBEvent<T extends EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>\n) {\n const [_, fbEventName, fbEventProperties] = mapFBEvent(name, properties);\n AppEventsLogger.logEvent(fbEventName, fbEventProperties as Params);\n}\n\n/**\n * Hands the signed-in user to Facebook App Events, as `setFBUser` does the Pixel: the user id\n * (`external_id`) and the advanced matching fields, which the SDK hashes on the device. No user is\n * sign-out (`reset()`): the user id is cleared, but the matching fields may not be.\n *\n * Known gap, kept on purpose: the fields go to the native `setUserData`, which on Android only\n * updates the fields it is given, so the empty ones sent at sign-out leave the previous user's\n * email and phone in place, and later anonymous events (or another user's without an email) can\n * still carry them. `react-native-fbsdk-next` does not expose the native `clearUserData`. Dropping\n * the fields would avoid it, but cost more in ad conversion matching than the gap does.\n */\nexport function setFBUser({ user_id, user_data }: Omit<UpdateVisitorDTO, 'tags'>) {\n AppEventsLogger.setUserID(user_id || null);\n const address = getFirst(user_data?.address);\n AppEventsLogger.setUserData({\n email: getFirst(user_data?.email),\n phone: getFirst(user_data?.phone_number),\n firstName: address?.first_name,\n lastName: address?.last_name,\n city: address?.city,\n state: address?.region,\n zip: address?.postal_code,\n country: address?.country,\n });\n}\n\n/**\n * Facebook App Events: the events `mapFBEvent` maps to a Meta standard event, and `customEvents`\n * — the app's counterpart of `metaAds`.\n */\nexport function metaAppEvents(options: AdsOptions = {}): Integration {\n const isStandard = (name: string) => mapFBEvent(name as TrackName)[0] === 'track';\n return {\n type: 'ads',\n track: adsTracker(sendFBEvent, isStandard, options.customEvents ?? []),\n setUser: setFBUser,\n };\n}\n"],"mappings":";;;;;;;;;;;AAaA,SAAgB,YACd,MACA,YACA;CACA,MAAM,CAAC,GAAG,aAAa,qBAAqB,WAAW,MAAM,UAAU;CACvE,gBAAgB,SAAS,aAAa,iBAA2B;AACnE;;;;;;;;;;;;AAaA,SAAgB,UAAU,EAAE,SAAS,aAA6C;CAChF,gBAAgB,UAAU,WAAW,IAAI;CACzC,MAAM,UAAU,SAAS,WAAW,OAAO;CAC3C,gBAAgB,YAAY;EAC1B,OAAO,SAAS,WAAW,KAAK;EAChC,OAAO,SAAS,WAAW,YAAY;EACvC,WAAW,SAAS;EACpB,UAAU,SAAS;EACnB,MAAM,SAAS;EACf,OAAO,SAAS;EAChB,KAAK,SAAS;EACd,SAAS,SAAS;CACpB,CAAC;AACH;;;;;AAMA,SAAgB,cAAc,UAAsB,CAAC,GAAgB;CACnE,MAAM,cAAc,SAAiB,WAAW,IAAiB,CAAC,CAAC,OAAO;CAC1E,OAAO;EACL,MAAM;EACN,OAAO,WAAW,aAAa,YAAY,QAAQ,gBAAgB,CAAC,CAAC;EACrE,SAAS;CACX;AACF"}
1
+ {"version":3,"file":"fbsdk.mjs","names":[],"sources":["../../src/native/fbsdk.ts"],"sourcesContent":["import { AppEventsLogger, type Params } from 'react-native-fbsdk-next';\nimport type { UpdateVisitorDTO } from '../schema/index';\nimport {\n type AdsOptions,\n type Integration,\n adEvents,\n adsTracker,\n} from '../third-parties/integration';\nimport { isStandardFBEvent, mapFBEvent } from '../track/fbq';\nimport type { EventName, TrackName, TrackProperties } from '../track/types';\nimport { getFirst } from '../utils/field';\n\n/**\n * ref: https://developers.facebook.com/docs/app-events/guides/maximize-in-app-ad-revenue/\n *\n * Synchronous, like `logEvent`: a tracker returns `void | boolean`, which an `async` function's\n * promise would not satisfy. Callers that still `await` it keep compiling.\n */\nexport function sendFBEvent<T extends EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>\n) {\n const [_, fbEventName, fbEventProperties] = mapFBEvent(name, properties);\n AppEventsLogger.logEvent(fbEventName, fbEventProperties as Params);\n}\n\n/**\n * Hands the signed-in user to Facebook App Events, as `setFBUser` does the Pixel: the user id\n * (`external_id`) and the advanced matching fields, which the SDK hashes on the device. No user is\n * sign-out (`reset()`): the user id is cleared, but the matching fields may not be.\n *\n * Known gap, kept on purpose: the fields go to the native `setUserData`, which on Android only\n * updates the fields it is given, so the empty ones sent at sign-out leave the previous user's\n * email and phone in place, and later anonymous events (or another user's without an email) can\n * still carry them. `react-native-fbsdk-next` does not expose the native `clearUserData`. Dropping\n * the fields would avoid it, but cost more in ad conversion matching than the gap does.\n */\nexport function setFBUser({ user_id, user_data }: Omit<UpdateVisitorDTO, 'tags'>) {\n AppEventsLogger.setUserID(user_id || null);\n const address = getFirst(user_data?.address);\n AppEventsLogger.setUserData({\n email: getFirst(user_data?.email),\n phone: getFirst(user_data?.phone_number),\n firstName: address?.first_name,\n lastName: address?.last_name,\n city: address?.city,\n state: address?.region,\n zip: address?.postal_code,\n country: address?.country,\n });\n}\n\n/**\n * Facebook App Events: the events `mapFBEvent` maps to a Meta standard event, and `customEvents`\n * — the app's counterpart of `metaAds`.\n */\nexport function metaAppEvents(options: AdsOptions = {}): Integration {\n return {\n type: 'ads',\n track: adsTracker(sendFBEvent, adEvents(isStandardFBEvent, options.customEvents)),\n setUser: setFBUser,\n };\n}\n"],"mappings":";;;;;;;;;;;AAkBA,SAAgB,YACd,MACA,YACA;CACA,MAAM,CAAC,GAAG,aAAa,qBAAqB,WAAW,MAAM,UAAU;CACvE,gBAAgB,SAAS,aAAa,iBAA2B;AACnE;;;;;;;;;;;;AAaA,SAAgB,UAAU,EAAE,SAAS,aAA6C;CAChF,gBAAgB,UAAU,WAAW,IAAI;CACzC,MAAM,UAAU,SAAS,WAAW,OAAO;CAC3C,gBAAgB,YAAY;EAC1B,OAAO,SAAS,WAAW,KAAK;EAChC,OAAO,SAAS,WAAW,YAAY;EACvC,WAAW,SAAS;EACpB,UAAU,SAAS;EACnB,MAAM,SAAS;EACf,OAAO,SAAS;EAChB,KAAK,SAAS;EACd,SAAS,SAAS;CACpB,CAAC;AACH;;;;;AAMA,SAAgB,cAAc,UAAsB,CAAC,GAAgB;CACnE,OAAO;EACL,MAAM;EACN,OAAO,WAAW,aAAa,SAAS,mBAAmB,QAAQ,YAAY,CAAC;EAChF,SAAS;CACX;AACF"}
@@ -6,7 +6,8 @@ const require_third_parties_microsoft_uet = require("../third-parties/microsoft-
6
6
  const require_hooks_use_uet_id_sync = require("../hooks/use-uet-id-sync.cjs");
7
7
  const require_hooks_use_web_analytics = require("../hooks/use-web-analytics.cjs");
8
8
  const require_third_parties_analytics_props = require("../third-parties/analytics-props.cjs");
9
- const require_react_use_feature_flag = require("./use-feature-flag.cjs");
9
+ const require_react_posthog = require("./posthog.cjs");
10
+ const require_react_posthog_error_boundary = require("./posthog-error-boundary.cjs");
10
11
  let react_jsx_runtime = require("react/jsx-runtime");
11
12
  // src/react/index.tsx
12
13
  /**
@@ -40,6 +41,14 @@ function Analytics({ pathname, search, integrations, facebookAppId, nonce, repor
40
41
  })] });
41
42
  }
42
43
  exports.Analytics = Analytics;
43
- exports.useFeatureFlag = require_react_use_feature_flag.useFeatureFlag;
44
+ exports.PosthogErrorBoundary = require_react_posthog_error_boundary.PosthogErrorBoundary;
45
+ exports.PosthogProvider = require_react_posthog.PosthogProvider;
46
+ exports.setupReactErrorHandler = require_react_posthog_error_boundary.setupReactErrorHandler;
47
+ exports.useActiveFeatureFlags = require_react_posthog.useActiveFeatureFlags;
48
+ exports.useFeatureFlagEnabled = require_react_posthog.useFeatureFlagEnabled;
49
+ exports.useFeatureFlagPayload = require_react_posthog.useFeatureFlagPayload;
50
+ exports.useFeatureFlagResult = require_react_posthog.useFeatureFlagResult;
51
+ exports.useFeatureFlagVariantKey = require_react_posthog.useFeatureFlagVariantKey;
52
+ exports.usePostHog = require_react_posthog.usePostHog;
44
53
 
45
54
  //# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["uetCustomerIdOf","IntegrationScripts"],"sources":["../../src/react/index.tsx"],"sourcesContent":["import { useOutboundClickAnalytics } from '../hooks/use-outbound-click-analytics';\nimport { useReportWebVitals } from '../hooks/use-report-web-vitals';\nimport { useUETIdSync } from '../hooks/use-uet-id-sync';\nimport { useWebAnalytics } from '../hooks/use-web-analytics';\nimport {\n type AnalyticsProps,\n IntegrationScripts,\n preconnectIntegrations,\n} from '../third-parties/analytics-props';\nimport { uetCustomerIdOf } from '../third-parties/microsoft-uet';\nimport { track } from '../track/index';\n\ninterface Props extends AnalyticsProps {\n /** The router's current path; a change reports a page view. */\n pathname: string;\n /** The router's current query string, with or without the leading `?`. */\n search: string;\n}\n\n/**\n * `<Analytics>` for any React router (TanStack Router, React Router, …): the host passes the\n * current location, e.g. `useLocation()`'s `pathname` and `searchStr` / `search`.\n */\nexport function Analytics({\n pathname,\n search,\n integrations,\n facebookAppId,\n nonce,\n reportWebVitals = true,\n}: Props) {\n useWebAnalytics(pathname, search);\n useOutboundClickAnalytics();\n useUETIdSync(uetCustomerIdOf(integrations));\n preconnectIntegrations(integrations);\n\n useReportWebVitals((metric) => {\n if (!reportWebVitals) return;\n const properties = {\n value: metric.delta,\n metric_id: metric.id,\n metric_value: metric.value,\n metric_delta: metric.delta,\n metric_rating: metric.rating,\n metric_navigation_type: metric.navigationType,\n non_interaction: true, // avoids affecting bounce rate.\n };\n track(metric.name, properties);\n });\n\n return (\n <>\n {facebookAppId && <meta property=\"fb:app_id\" content={facebookAppId} />}\n <IntegrationScripts integrations={integrations} nonce={nonce} />\n </>\n );\n}\n\nexport { useFeatureFlag } from './use-feature-flag';\n"],"mappings":";;;;;;;;;;;;;;;AAuBA,SAAgB,UAAU,EACxB,UACA,QACA,cACA,eACA,OACA,kBAAkB,QACV;CACR,gCAAA,gBAAgB,UAAU,MAAM;CAChC,2CAAA,0BAA0B;CAC1B,8BAAA,aAAaA,oCAAAA,gBAAgB,YAAY,CAAC;CAC1C,sCAAA,uBAAuB,YAAY;CAEnC,oCAAA,oBAAoB,WAAW;EAC7B,IAAI,CAAC,iBAAiB;EACtB,MAAM,aAAa;GACjB,OAAO,OAAO;GACd,WAAW,OAAO;GAClB,cAAc,OAAO;GACrB,cAAc,OAAO;GACrB,eAAe,OAAO;GACtB,wBAAwB,OAAO;GAC/B,iBAAiB;EACnB;EACA,oBAAA,MAAM,OAAO,MAAM,UAAU;CAC/B,CAAC;CAED,OACE,iBAAA,GAAA,kBAAA,KAAA,CAAA,kBAAA,UAAA,EAAA,UAAA,CACG,iBAAiB,iBAAA,GAAA,kBAAA,IAAA,CAAC,QAAD;EAAM,UAAS;EAAY,SAAS;CAAgB,CAAA,GACtE,iBAAA,GAAA,kBAAA,IAAA,CAACC,sCAAAA,oBAAD;EAAkC;EAAqB;CAAQ,CAAA,CAC/D,EAAA,CAAA;AAEN"}
1
+ {"version":3,"file":"index.cjs","names":["uetCustomerIdOf","IntegrationScripts"],"sources":["../../src/react/index.tsx"],"sourcesContent":["import { useOutboundClickAnalytics } from '../hooks/use-outbound-click-analytics';\nimport { useReportWebVitals } from '../hooks/use-report-web-vitals';\nimport { useUETIdSync } from '../hooks/use-uet-id-sync';\nimport { useWebAnalytics } from '../hooks/use-web-analytics';\nimport {\n type AnalyticsProps,\n IntegrationScripts,\n preconnectIntegrations,\n} from '../third-parties/analytics-props';\nimport { uetCustomerIdOf } from '../third-parties/microsoft-uet';\nimport { track } from '../track/index';\n\ninterface Props extends AnalyticsProps {\n /** The router's current path; a change reports a page view. */\n pathname: string;\n /** The router's current query string, with or without the leading `?`. */\n search: string;\n}\n\n/**\n * `<Analytics>` for any React router (TanStack Router, React Router, …): the host passes the\n * current location, e.g. `useLocation()`'s `pathname` and `searchStr` / `search`.\n */\nexport function Analytics({\n pathname,\n search,\n integrations,\n facebookAppId,\n nonce,\n reportWebVitals = true,\n}: Props) {\n useWebAnalytics(pathname, search);\n useOutboundClickAnalytics();\n useUETIdSync(uetCustomerIdOf(integrations));\n preconnectIntegrations(integrations);\n\n useReportWebVitals((metric) => {\n if (!reportWebVitals) return;\n const properties = {\n value: metric.delta,\n metric_id: metric.id,\n metric_value: metric.value,\n metric_delta: metric.delta,\n metric_rating: metric.rating,\n metric_navigation_type: metric.navigationType,\n non_interaction: true, // avoids affecting bounce rate.\n };\n track(metric.name, properties);\n });\n\n return (\n <>\n {facebookAppId && <meta property=\"fb:app_id\" content={facebookAppId} />}\n <IntegrationScripts integrations={integrations} nonce={nonce} />\n </>\n );\n}\n\nexport {\n PosthogProvider,\n useActiveFeatureFlags,\n useFeatureFlagEnabled,\n useFeatureFlagPayload,\n useFeatureFlagResult,\n useFeatureFlagVariantKey,\n usePostHog,\n} from './posthog';\nexport {\n PosthogErrorBoundary,\n type PosthogErrorBoundaryFallbackProps,\n type PosthogErrorBoundaryProps,\n setupReactErrorHandler,\n} from './posthog-error-boundary';\n"],"mappings":";;;;;;;;;;;;;;;;AAuBA,SAAgB,UAAU,EACxB,UACA,QACA,cACA,eACA,OACA,kBAAkB,QACV;CACR,gCAAA,gBAAgB,UAAU,MAAM;CAChC,2CAAA,0BAA0B;CAC1B,8BAAA,aAAaA,oCAAAA,gBAAgB,YAAY,CAAC;CAC1C,sCAAA,uBAAuB,YAAY;CAEnC,oCAAA,oBAAoB,WAAW;EAC7B,IAAI,CAAC,iBAAiB;EACtB,MAAM,aAAa;GACjB,OAAO,OAAO;GACd,WAAW,OAAO;GAClB,cAAc,OAAO;GACrB,cAAc,OAAO;GACrB,eAAe,OAAO;GACtB,wBAAwB,OAAO;GAC/B,iBAAiB;EACnB;EACA,oBAAA,MAAM,OAAO,MAAM,UAAU;CAC/B,CAAC;CAED,OACE,iBAAA,GAAA,kBAAA,KAAA,CAAA,kBAAA,UAAA,EAAA,UAAA,CACG,iBAAiB,iBAAA,GAAA,kBAAA,IAAA,CAAC,QAAD;EAAM,UAAS;EAAY,SAAS;CAAgB,CAAA,GACtE,iBAAA,GAAA,kBAAA,IAAA,CAACC,sCAAAA,oBAAD;EAAkC;EAAqB;CAAQ,CAAA,CAC/D,EAAA,CAAA;AAEN"}
@@ -1,5 +1,6 @@
1
1
  import { AnalyticsProps } from "../third-parties/analytics-props.cjs";
2
- import { useFeatureFlag } from "./use-feature-flag.cjs";
2
+ import { PosthogProvider, useActiveFeatureFlags, useFeatureFlagEnabled, useFeatureFlagPayload, useFeatureFlagResult, useFeatureFlagVariantKey, usePostHog } from "./posthog.cjs";
3
+ import { PosthogErrorBoundary, PosthogErrorBoundaryFallbackProps, PosthogErrorBoundaryProps, setupReactErrorHandler } from "./posthog-error-boundary.cjs";
3
4
  interface Props extends AnalyticsProps {
4
5
  /** The router's current path; a change reports a page view. */
5
6
  pathname: string;
@@ -11,5 +12,5 @@ interface Props extends AnalyticsProps {
11
12
  * current location, e.g. `useLocation()`'s `pathname` and `searchStr` / `search`.
12
13
  */
13
14
  export declare function Analytics({ pathname, search, integrations, facebookAppId, nonce, reportWebVitals }: Props): import("react").JSX.Element;
14
- export { useFeatureFlag };
15
+ export { PosthogErrorBoundary, type PosthogErrorBoundaryFallbackProps, type PosthogErrorBoundaryProps, PosthogProvider, setupReactErrorHandler, useActiveFeatureFlags, useFeatureFlagEnabled, useFeatureFlagPayload, useFeatureFlagResult, useFeatureFlagVariantKey, usePostHog };
15
16
  //# sourceMappingURL=index.d.cts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.cts","names":[],"sources":["../../src/react/index.tsx"],"mappings":";;UAYU,cAAc;;EAEtB;;EAEA;;;;;;wBAOc,YACd,UACA,QACA,cACA,eACA,OACA,mBACC,wBAAK,IAAA"}
1
+ {"version":3,"file":"index.d.cts","names":[],"sources":["../../src/react/index.tsx"],"mappings":";;;UAYU,cAAc;;EAEtB;;EAEA;;;;;;wBAOc,YACd,UACA,QACA,cACA,eACA,OACA,mBACC,wBAAK,IAAA"}
@@ -1,5 +1,6 @@
1
1
  import { AnalyticsProps } from "../third-parties/analytics-props.mjs";
2
- import { useFeatureFlag } from "./use-feature-flag.mjs";
2
+ import { PosthogProvider, useActiveFeatureFlags, useFeatureFlagEnabled, useFeatureFlagPayload, useFeatureFlagResult, useFeatureFlagVariantKey, usePostHog } from "./posthog.mjs";
3
+ import { PosthogErrorBoundary, PosthogErrorBoundaryFallbackProps, PosthogErrorBoundaryProps, setupReactErrorHandler } from "./posthog-error-boundary.mjs";
3
4
  interface Props extends AnalyticsProps {
4
5
  /** The router's current path; a change reports a page view. */
5
6
  pathname: string;
@@ -11,5 +12,5 @@ interface Props extends AnalyticsProps {
11
12
  * current location, e.g. `useLocation()`'s `pathname` and `searchStr` / `search`.
12
13
  */
13
14
  export declare function Analytics({ pathname, search, integrations, facebookAppId, nonce, reportWebVitals }: Props): import("react").JSX.Element;
14
- export { useFeatureFlag };
15
+ export { PosthogErrorBoundary, type PosthogErrorBoundaryFallbackProps, type PosthogErrorBoundaryProps, PosthogProvider, setupReactErrorHandler, useActiveFeatureFlags, useFeatureFlagEnabled, useFeatureFlagPayload, useFeatureFlagResult, useFeatureFlagVariantKey, usePostHog };
15
16
  //# sourceMappingURL=index.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","names":[],"sources":["../../src/react/index.tsx"],"mappings":";;UAYU,cAAc;;EAEtB;;EAEA;;;;;;wBAOc,YACd,UACA,QACA,cACA,eACA,OACA,mBACC,wBAAK,IAAA"}
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../../src/react/index.tsx"],"mappings":";;;UAYU,cAAc;;EAEtB;;EAEA;;;;;;wBAOc,YACd,UACA,QACA,cACA,eACA,OACA,mBACC,wBAAK,IAAA"}
@@ -5,7 +5,8 @@ import { uetCustomerIdOf } from "../third-parties/microsoft-uet.mjs";
5
5
  import { useUETIdSync } from "../hooks/use-uet-id-sync.mjs";
6
6
  import { useWebAnalytics } from "../hooks/use-web-analytics.mjs";
7
7
  import { IntegrationScripts, preconnectIntegrations } from "../third-parties/analytics-props.mjs";
8
- import { useFeatureFlag } from "./use-feature-flag.mjs";
8
+ import { PosthogProvider, useActiveFeatureFlags, useFeatureFlagEnabled, useFeatureFlagPayload, useFeatureFlagResult, useFeatureFlagVariantKey, usePostHog } from "./posthog.mjs";
9
+ import { PosthogErrorBoundary, setupReactErrorHandler } from "./posthog-error-boundary.mjs";
9
10
  import { Fragment, jsx, jsxs } from "react/jsx-runtime";
10
11
  // src/react/index.tsx
11
12
  /**
@@ -38,6 +39,6 @@ function Analytics({ pathname, search, integrations, facebookAppId, nonce, repor
38
39
  nonce
39
40
  })] });
40
41
  }
41
- export { Analytics, useFeatureFlag };
42
+ export { Analytics, PosthogErrorBoundary, PosthogProvider, setupReactErrorHandler, useActiveFeatureFlags, useFeatureFlagEnabled, useFeatureFlagPayload, useFeatureFlagResult, useFeatureFlagVariantKey, usePostHog };
42
43
 
43
44
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":[],"sources":["../../src/react/index.tsx"],"sourcesContent":["import { useOutboundClickAnalytics } from '../hooks/use-outbound-click-analytics';\nimport { useReportWebVitals } from '../hooks/use-report-web-vitals';\nimport { useUETIdSync } from '../hooks/use-uet-id-sync';\nimport { useWebAnalytics } from '../hooks/use-web-analytics';\nimport {\n type AnalyticsProps,\n IntegrationScripts,\n preconnectIntegrations,\n} from '../third-parties/analytics-props';\nimport { uetCustomerIdOf } from '../third-parties/microsoft-uet';\nimport { track } from '../track/index';\n\ninterface Props extends AnalyticsProps {\n /** The router's current path; a change reports a page view. */\n pathname: string;\n /** The router's current query string, with or without the leading `?`. */\n search: string;\n}\n\n/**\n * `<Analytics>` for any React router (TanStack Router, React Router, …): the host passes the\n * current location, e.g. `useLocation()`'s `pathname` and `searchStr` / `search`.\n */\nexport function Analytics({\n pathname,\n search,\n integrations,\n facebookAppId,\n nonce,\n reportWebVitals = true,\n}: Props) {\n useWebAnalytics(pathname, search);\n useOutboundClickAnalytics();\n useUETIdSync(uetCustomerIdOf(integrations));\n preconnectIntegrations(integrations);\n\n useReportWebVitals((metric) => {\n if (!reportWebVitals) return;\n const properties = {\n value: metric.delta,\n metric_id: metric.id,\n metric_value: metric.value,\n metric_delta: metric.delta,\n metric_rating: metric.rating,\n metric_navigation_type: metric.navigationType,\n non_interaction: true, // avoids affecting bounce rate.\n };\n track(metric.name, properties);\n });\n\n return (\n <>\n {facebookAppId && <meta property=\"fb:app_id\" content={facebookAppId} />}\n <IntegrationScripts integrations={integrations} nonce={nonce} />\n </>\n );\n}\n\nexport { useFeatureFlag } from './use-feature-flag';\n"],"mappings":";;;;;;;;;;;;;;AAuBA,SAAgB,UAAU,EACxB,UACA,QACA,cACA,eACA,OACA,kBAAkB,QACV;CACR,gBAAgB,UAAU,MAAM;CAChC,0BAA0B;CAC1B,aAAa,gBAAgB,YAAY,CAAC;CAC1C,uBAAuB,YAAY;CAEnC,oBAAoB,WAAW;EAC7B,IAAI,CAAC,iBAAiB;EACtB,MAAM,aAAa;GACjB,OAAO,OAAO;GACd,WAAW,OAAO;GAClB,cAAc,OAAO;GACrB,cAAc,OAAO;GACrB,eAAe,OAAO;GACtB,wBAAwB,OAAO;GAC/B,iBAAiB;EACnB;EACA,MAAM,OAAO,MAAM,UAAU;CAC/B,CAAC;CAED,OACE,qBAAA,UAAA,EAAA,UAAA,CACG,iBAAiB,oBAAC,QAAD;EAAM,UAAS;EAAY,SAAS;CAAgB,CAAA,GACtE,oBAAC,oBAAD;EAAkC;EAAqB;CAAQ,CAAA,CAC/D,EAAA,CAAA;AAEN"}
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../../src/react/index.tsx"],"sourcesContent":["import { useOutboundClickAnalytics } from '../hooks/use-outbound-click-analytics';\nimport { useReportWebVitals } from '../hooks/use-report-web-vitals';\nimport { useUETIdSync } from '../hooks/use-uet-id-sync';\nimport { useWebAnalytics } from '../hooks/use-web-analytics';\nimport {\n type AnalyticsProps,\n IntegrationScripts,\n preconnectIntegrations,\n} from '../third-parties/analytics-props';\nimport { uetCustomerIdOf } from '../third-parties/microsoft-uet';\nimport { track } from '../track/index';\n\ninterface Props extends AnalyticsProps {\n /** The router's current path; a change reports a page view. */\n pathname: string;\n /** The router's current query string, with or without the leading `?`. */\n search: string;\n}\n\n/**\n * `<Analytics>` for any React router (TanStack Router, React Router, …): the host passes the\n * current location, e.g. `useLocation()`'s `pathname` and `searchStr` / `search`.\n */\nexport function Analytics({\n pathname,\n search,\n integrations,\n facebookAppId,\n nonce,\n reportWebVitals = true,\n}: Props) {\n useWebAnalytics(pathname, search);\n useOutboundClickAnalytics();\n useUETIdSync(uetCustomerIdOf(integrations));\n preconnectIntegrations(integrations);\n\n useReportWebVitals((metric) => {\n if (!reportWebVitals) return;\n const properties = {\n value: metric.delta,\n metric_id: metric.id,\n metric_value: metric.value,\n metric_delta: metric.delta,\n metric_rating: metric.rating,\n metric_navigation_type: metric.navigationType,\n non_interaction: true, // avoids affecting bounce rate.\n };\n track(metric.name, properties);\n });\n\n return (\n <>\n {facebookAppId && <meta property=\"fb:app_id\" content={facebookAppId} />}\n <IntegrationScripts integrations={integrations} nonce={nonce} />\n </>\n );\n}\n\nexport {\n PosthogProvider,\n useActiveFeatureFlags,\n useFeatureFlagEnabled,\n useFeatureFlagPayload,\n useFeatureFlagResult,\n useFeatureFlagVariantKey,\n usePostHog,\n} from './posthog';\nexport {\n PosthogErrorBoundary,\n type PosthogErrorBoundaryFallbackProps,\n type PosthogErrorBoundaryProps,\n setupReactErrorHandler,\n} from './posthog-error-boundary';\n"],"mappings":";;;;;;;;;;;;;;;AAuBA,SAAgB,UAAU,EACxB,UACA,QACA,cACA,eACA,OACA,kBAAkB,QACV;CACR,gBAAgB,UAAU,MAAM;CAChC,0BAA0B;CAC1B,aAAa,gBAAgB,YAAY,CAAC;CAC1C,uBAAuB,YAAY;CAEnC,oBAAoB,WAAW;EAC7B,IAAI,CAAC,iBAAiB;EACtB,MAAM,aAAa;GACjB,OAAO,OAAO;GACd,WAAW,OAAO;GAClB,cAAc,OAAO;GACrB,cAAc,OAAO;GACrB,eAAe,OAAO;GACtB,wBAAwB,OAAO;GAC/B,iBAAiB;EACnB;EACA,MAAM,OAAO,MAAM,UAAU;CAC/B,CAAC;CAED,OACE,qBAAA,UAAA,EAAA,UAAA,CACG,iBAAiB,oBAAC,QAAD;EAAM,UAAS;EAAY,SAAS;CAAgB,CAAA,GACtE,oBAAC,oBAAD;EAAkC;EAAqB;CAAQ,CAAA,CAC/D,EAAA,CAAA;AAEN"}
@@ -0,0 +1,119 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ const require_third_parties_posthog = require("../third-parties/posthog.cjs");
3
+ let react = require("react");
4
+ // src/react/posthog-error-boundary.tsx
5
+ const INITIAL_STATE = {
6
+ error: null,
7
+ componentStack: null,
8
+ exceptionEvent: void 0
9
+ };
10
+ /**
11
+ * The error as PostHog's own boundary reports it: the React component stack added as a cause, so
12
+ * the issue shows which components it was thrown in.
13
+ */
14
+ function withComponentStack(error, componentStack) {
15
+ if (!componentStack) return error;
16
+ const isError = error instanceof Error;
17
+ const stackError = new Error(isError ? error.message : `Primitive value captured as exception: ${String(error)}`);
18
+ stackError.name = `React ErrorBoundary ${isError ? error.name : "Error"}`;
19
+ stackError.stack = componentStack;
20
+ if (!isError) return stackError;
21
+ const seen = /* @__PURE__ */ new WeakSet();
22
+ let current = error;
23
+ while (!seen.has(current)) {
24
+ seen.add(current);
25
+ if (!(current.cause instanceof Error)) {
26
+ if (current.cause !== void 0) stackError.cause = current.cause;
27
+ current.cause = stackError;
28
+ break;
29
+ }
30
+ current = current.cause;
31
+ }
32
+ return error;
33
+ }
34
+ /**
35
+ * `posthog-js/react`'s `PostHogErrorBoundary`, with its props, for the snippet-loaded library: a
36
+ * render error in `children` is sent to PostHog's error tracking (`captureException`, as an
37
+ * `$exception` event tied to the session's replay) and `fallback` renders instead — a
38
+ * component gets the error and `resetError`. An error thrown before the library has loaded is
39
+ * queued on the stub and sent once it has.
40
+ *
41
+ * The boundary itself never throws: a failure to report (no PostHog, an ad blocker that stopped the
42
+ * library, a throwing `additionalProperties`) is logged and the fallback still renders. It
43
+ * catches render errors only, as any error boundary; errors outside React's render (event
44
+ * handlers, unhandled rejections) are the library's exception autocapture's, enabled in the
45
+ * snippet's `config` (`capture_exceptions`).
46
+ */
47
+ var PosthogErrorBoundary = class extends react.Component {
48
+ constructor(..._args) {
49
+ super(..._args);
50
+ this.state = INITIAL_STATE;
51
+ this.resetError = () => {
52
+ this.setState(INITIAL_STATE);
53
+ };
54
+ }
55
+ componentDidCatch(error, errorInfo) {
56
+ const componentStack = errorInfo.componentStack ?? "";
57
+ let exceptionEvent;
58
+ try {
59
+ const { additionalProperties } = this.props;
60
+ const properties = typeof additionalProperties === "function" ? additionalProperties(error, errorInfo) : additionalProperties;
61
+ exceptionEvent = require_third_parties_posthog.getPosthog()?.captureException(withComponentStack(error, componentStack), properties);
62
+ } catch (e) {
63
+ console.error("PosthogErrorBoundary: the error was not reported", e);
64
+ }
65
+ this.setState({
66
+ error,
67
+ componentStack,
68
+ exceptionEvent
69
+ });
70
+ }
71
+ render() {
72
+ const { children, fallback } = this.props;
73
+ const { error, componentStack, exceptionEvent } = this.state;
74
+ if (componentStack === null) return typeof children === "function" ? children() : children;
75
+ const element = typeof fallback === "function" ? fallback({
76
+ error,
77
+ componentStack,
78
+ exceptionEvent,
79
+ resetError: this.resetError
80
+ }) : fallback;
81
+ if ((0, react.isValidElement)(element)) return element;
82
+ console.warn("PosthogErrorBoundary: fallback is not a React element; rendering nothing");
83
+ return null;
84
+ }
85
+ };
86
+ /**
87
+ * `posthog-js/react`'s `setupReactErrorHandler`, for the snippet-loaded library, so without its
88
+ * `client`: a handler for React 19's root options, which report what no `PosthogErrorBoundary`
89
+ * sees — `onUncaughtError` (no boundary caught it), `onCaughtError` (a framework's boundary did,
90
+ * e.g. TanStack Router's `errorComponent`) and `onRecoverableError` (a hydration mismatch React
91
+ * recovered from). The error goes to PostHog with its component stack; `callback` gets the event
92
+ * (`undefined` while only the stub is there), as React's own logging does not run once a handler
93
+ * is set.
94
+ *
95
+ * ```tsx
96
+ * hydrateRoot(document, <StartClient />, {
97
+ * onUncaughtError: setupReactErrorHandler(),
98
+ * onCaughtError: setupReactErrorHandler(),
99
+ * onRecoverableError: setupReactErrorHandler(),
100
+ * });
101
+ * ```
102
+ *
103
+ * Never throws, as `PosthogErrorBoundary`: a failure to report is logged.
104
+ */
105
+ function setupReactErrorHandler(callback) {
106
+ return (error, errorInfo) => {
107
+ let event;
108
+ try {
109
+ event = require_third_parties_posthog.getPosthog()?.captureException(withComponentStack(error, errorInfo.componentStack));
110
+ } catch (e) {
111
+ console.error("setupReactErrorHandler: the error was not reported", e);
112
+ }
113
+ callback?.(event, error, errorInfo);
114
+ };
115
+ }
116
+ exports.PosthogErrorBoundary = PosthogErrorBoundary;
117
+ exports.setupReactErrorHandler = setupReactErrorHandler;
118
+
119
+ //# sourceMappingURL=posthog-error-boundary.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"posthog-error-boundary.cjs","names":["Component","getPosthog","isValidElement"],"sources":["../../src/react/posthog-error-boundary.tsx"],"sourcesContent":["import type { CaptureResult, Properties } from 'posthog-js';\nimport {\n Component,\n type ErrorInfo,\n type FunctionComponent,\n type ReactNode,\n isValidElement,\n} from 'react';\nimport { getPosthog } from '../third-parties/posthog';\n\nexport interface PosthogErrorBoundaryFallbackProps {\n error: unknown;\n /** The `$exception` event sent; `undefined` while only the stub is there, which queues it. */\n exceptionEvent: CaptureResult | undefined;\n componentStack: string;\n resetError: () => void;\n}\n\nexport interface PosthogErrorBoundaryProps {\n children?: ReactNode | (() => ReactNode);\n fallback?: ReactNode | FunctionComponent<PosthogErrorBoundaryFallbackProps>;\n additionalProperties?: Properties | ((error: unknown, errorInfo: ErrorInfo) => Properties);\n}\n\ninterface State {\n error: unknown;\n componentStack: string | null;\n exceptionEvent: CaptureResult | undefined;\n}\n\nconst INITIAL_STATE: State = { error: null, componentStack: null, exceptionEvent: undefined };\n\n/**\n * The error as PostHog's own boundary reports it: the React component stack added as a cause, so\n * the issue shows which components it was thrown in.\n */\nfunction withComponentStack(error: unknown, componentStack: string | null | undefined): unknown {\n if (!componentStack) return error;\n const isError = error instanceof Error;\n const stackError = new Error(\n isError ? error.message : `Primitive value captured as exception: ${String(error)}`\n );\n stackError.name = `React ErrorBoundary ${isError ? error.name : 'Error'}`;\n stackError.stack = componentStack;\n if (!isError) return stackError;\n // At the end of the error's cause chain, keeping a last cause that is not an error under it.\n const seen = new WeakSet<Error>();\n let current = error;\n while (!seen.has(current)) {\n seen.add(current);\n if (!(current.cause instanceof Error)) {\n if (current.cause !== undefined) stackError.cause = current.cause;\n current.cause = stackError;\n break;\n }\n current = current.cause;\n }\n return error;\n}\n\n/**\n * `posthog-js/react`'s `PostHogErrorBoundary`, with its props, for the snippet-loaded library: a\n * render error in `children` is sent to PostHog's error tracking (`captureException`, as an\n * `$exception` event tied to the session's replay) and `fallback` renders instead — a\n * component gets the error and `resetError`. An error thrown before the library has loaded is\n * queued on the stub and sent once it has.\n *\n * The boundary itself never throws: a failure to report (no PostHog, an ad blocker that stopped the\n * library, a throwing `additionalProperties`) is logged and the fallback still renders. It\n * catches render errors only, as any error boundary; errors outside React's render (event\n * handlers, unhandled rejections) are the library's exception autocapture's, enabled in the\n * snippet's `config` (`capture_exceptions`).\n */\nexport class PosthogErrorBoundary extends Component<PosthogErrorBoundaryProps, State> {\n override state = INITIAL_STATE;\n\n override componentDidCatch(error: unknown, errorInfo: ErrorInfo) {\n const componentStack = errorInfo.componentStack ?? '';\n let exceptionEvent: CaptureResult | undefined;\n // Reporting must never fail the boundary: an error thrown here would go to the boundary\n // above it, if any — `additionalProperties` throwing, or an error that cannot take a cause.\n try {\n const { additionalProperties } = this.props;\n const properties =\n typeof additionalProperties === 'function'\n ? additionalProperties(error, errorInfo)\n : additionalProperties;\n exceptionEvent = getPosthog()?.captureException(\n withComponentStack(error, componentStack),\n properties\n );\n } catch (e: unknown) {\n console.error('PosthogErrorBoundary: the error was not reported', e);\n }\n this.setState({ error, componentStack, exceptionEvent });\n }\n\n resetError = () => {\n this.setState(INITIAL_STATE);\n };\n\n override render() {\n const { children, fallback } = this.props;\n const { error, componentStack, exceptionEvent } = this.state;\n if (componentStack === null) return typeof children === 'function' ? children() : children;\n\n const element =\n typeof fallback === 'function'\n ? fallback({ error, componentStack, exceptionEvent, resetError: this.resetError })\n : fallback;\n if (isValidElement(element)) return element;\n console.warn('PosthogErrorBoundary: fallback is not a React element; rendering nothing');\n return null;\n }\n}\n\n/**\n * `posthog-js/react`'s `setupReactErrorHandler`, for the snippet-loaded library, so without its\n * `client`: a handler for React 19's root options, which report what no `PosthogErrorBoundary`\n * sees — `onUncaughtError` (no boundary caught it), `onCaughtError` (a framework's boundary did,\n * e.g. TanStack Router's `errorComponent`) and `onRecoverableError` (a hydration mismatch React\n * recovered from). The error goes to PostHog with its component stack; `callback` gets the event\n * (`undefined` while only the stub is there), as React's own logging does not run once a handler\n * is set.\n *\n * ```tsx\n * hydrateRoot(document, <StartClient />, {\n * onUncaughtError: setupReactErrorHandler(),\n * onCaughtError: setupReactErrorHandler(),\n * onRecoverableError: setupReactErrorHandler(),\n * });\n * ```\n *\n * Never throws, as `PosthogErrorBoundary`: a failure to report is logged.\n */\nexport function setupReactErrorHandler(\n callback?: (event: CaptureResult | undefined, error: unknown, errorInfo: ErrorInfo) => void\n): (error: unknown, errorInfo: ErrorInfo) => void {\n return (error, errorInfo) => {\n let event: CaptureResult | undefined;\n try {\n event = getPosthog()?.captureException(withComponentStack(error, errorInfo.componentStack));\n } catch (e: unknown) {\n console.error('setupReactErrorHandler: the error was not reported', e);\n }\n callback?.(event, error, errorInfo);\n };\n}\n"],"mappings":";;;;AA8BA,MAAM,gBAAuB;CAAE,OAAO;CAAM,gBAAgB;CAAM,gBAAgB,KAAA;AAAU;;;;;AAM5F,SAAS,mBAAmB,OAAgB,gBAAoD;CAC9F,IAAI,CAAC,gBAAgB,OAAO;CAC5B,MAAM,UAAU,iBAAiB;CACjC,MAAM,aAAa,IAAI,MACrB,UAAU,MAAM,UAAU,0CAA0C,OAAO,KAAK,GAClF;CACA,WAAW,OAAO,uBAAuB,UAAU,MAAM,OAAO;CAChE,WAAW,QAAQ;CACnB,IAAI,CAAC,SAAS,OAAO;CAErB,MAAM,uBAAO,IAAI,QAAe;CAChC,IAAI,UAAU;CACd,OAAO,CAAC,KAAK,IAAI,OAAO,GAAG;EACzB,KAAK,IAAI,OAAO;EAChB,IAAI,EAAE,QAAQ,iBAAiB,QAAQ;GACrC,IAAI,QAAQ,UAAU,KAAA,GAAW,WAAW,QAAQ,QAAQ;GAC5D,QAAQ,QAAQ;GAChB;EACF;EACA,UAAU,QAAQ;CACpB;CACA,OAAO;AACT;;;;;;;;;;;;;;AAeA,IAAa,uBAAb,cAA0CA,MAAAA,UAA4C;;;EACnE,KAAA,QAAA;EAuBE,KAAA,mBAAA;GACjB,KAAK,SAAS,aAAa;EAC7B;;CAvBA,kBAA2B,OAAgB,WAAsB;EAC/D,MAAM,iBAAiB,UAAU,kBAAkB;EACnD,IAAI;EAGJ,IAAI;GACF,MAAM,EAAE,yBAAyB,KAAK;GACtC,MAAM,aACJ,OAAO,yBAAyB,aAC5B,qBAAqB,OAAO,SAAS,IACrC;GACN,iBAAiBC,8BAAAA,WAAW,CAAC,EAAE,iBAC7B,mBAAmB,OAAO,cAAc,GACxC,UACF;EACF,SAAS,GAAY;GACnB,QAAQ,MAAM,oDAAoD,CAAC;EACrE;EACA,KAAK,SAAS;GAAE;GAAO;GAAgB;EAAe,CAAC;CACzD;CAMA,SAAkB;EAChB,MAAM,EAAE,UAAU,aAAa,KAAK;EACpC,MAAM,EAAE,OAAO,gBAAgB,mBAAmB,KAAK;EACvD,IAAI,mBAAmB,MAAM,OAAO,OAAO,aAAa,aAAa,SAAS,IAAI;EAElF,MAAM,UACJ,OAAO,aAAa,aAChB,SAAS;GAAE;GAAO;GAAgB;GAAgB,YAAY,KAAK;EAAW,CAAC,IAC/E;EACN,KAAA,GAAIC,MAAAA,eAAAA,CAAe,OAAO,GAAG,OAAO;EACpC,QAAQ,KAAK,0EAA0E;EACvF,OAAO;CACT;AACF;;;;;;;;;;;;;;;;;;;;AAqBA,SAAgB,uBACd,UACgD;CAChD,QAAQ,OAAO,cAAc;EAC3B,IAAI;EACJ,IAAI;GACF,QAAQD,8BAAAA,WAAW,CAAC,EAAE,iBAAiB,mBAAmB,OAAO,UAAU,cAAc,CAAC;EAC5F,SAAS,GAAY;GACnB,QAAQ,MAAM,sDAAsD,CAAC;EACvE;EACA,WAAW,OAAO,OAAO,SAAS;CACpC;AACF"}
@@ -0,0 +1,60 @@
1
+ import { Component, ErrorInfo, FunctionComponent, ReactNode } from "react";
2
+ import { CaptureResult, Properties } from "posthog-js";
3
+ export interface PosthogErrorBoundaryFallbackProps {
4
+ error: unknown;
5
+ /** The `$exception` event sent; `undefined` while only the stub is there, which queues it. */
6
+ exceptionEvent: CaptureResult | undefined;
7
+ componentStack: string;
8
+ resetError: () => void;
9
+ }
10
+ export interface PosthogErrorBoundaryProps {
11
+ children?: ReactNode | (() => ReactNode);
12
+ fallback?: ReactNode | FunctionComponent<PosthogErrorBoundaryFallbackProps>;
13
+ additionalProperties?: Properties | ((error: unknown, errorInfo: ErrorInfo) => Properties);
14
+ }
15
+ interface State {
16
+ error: unknown;
17
+ componentStack: string | null;
18
+ exceptionEvent: CaptureResult | undefined;
19
+ }
20
+ /**
21
+ * `posthog-js/react`'s `PostHogErrorBoundary`, with its props, for the snippet-loaded library: a
22
+ * render error in `children` is sent to PostHog's error tracking (`captureException`, as an
23
+ * `$exception` event tied to the session's replay) and `fallback` renders instead — a
24
+ * component gets the error and `resetError`. An error thrown before the library has loaded is
25
+ * queued on the stub and sent once it has.
26
+ *
27
+ * The boundary itself never throws: a failure to report (no PostHog, an ad blocker that stopped the
28
+ * library, a throwing `additionalProperties`) is logged and the fallback still renders. It
29
+ * catches render errors only, as any error boundary; errors outside React's render (event
30
+ * handlers, unhandled rejections) are the library's exception autocapture's, enabled in the
31
+ * snippet's `config` (`capture_exceptions`).
32
+ */
33
+ export declare class PosthogErrorBoundary extends Component<PosthogErrorBoundaryProps, State> {
34
+ state: State;
35
+ componentDidCatch(error: unknown, errorInfo: ErrorInfo): void;
36
+ resetError: () => void;
37
+ render(): ReactNode;
38
+ }
39
+ /**
40
+ * `posthog-js/react`'s `setupReactErrorHandler`, for the snippet-loaded library, so without its
41
+ * `client`: a handler for React 19's root options, which report what no `PosthogErrorBoundary`
42
+ * sees — `onUncaughtError` (no boundary caught it), `onCaughtError` (a framework's boundary did,
43
+ * e.g. TanStack Router's `errorComponent`) and `onRecoverableError` (a hydration mismatch React
44
+ * recovered from). The error goes to PostHog with its component stack; `callback` gets the event
45
+ * (`undefined` while only the stub is there), as React's own logging does not run once a handler
46
+ * is set.
47
+ *
48
+ * ```tsx
49
+ * hydrateRoot(document, <StartClient />, {
50
+ * onUncaughtError: setupReactErrorHandler(),
51
+ * onCaughtError: setupReactErrorHandler(),
52
+ * onRecoverableError: setupReactErrorHandler(),
53
+ * });
54
+ * ```
55
+ *
56
+ * Never throws, as `PosthogErrorBoundary`: a failure to report is logged.
57
+ */
58
+ export declare function setupReactErrorHandler(callback?: (event: CaptureResult | undefined, error: unknown, errorInfo: ErrorInfo) => void): (error: unknown, errorInfo: ErrorInfo) => void;
59
+ export {};
60
+ //# sourceMappingURL=posthog-error-boundary.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"posthog-error-boundary.d.cts","names":[],"sources":["../../src/react/posthog-error-boundary.tsx"],"mappings":";;iBAUiB;EACf;;EAEA,gBAAgB;EAChB;EACA;;iBAGe;EACf,WAAW,mBAAmB;EAC9B,WAAW,YAAY,kBAAkB;EACzC,uBAAuB,eAAe,gBAAgB,WAAW,cAAc;;UAGvE;EACR;EACA;EACA,gBAAgB;;;;;;;;;;;;;;;qBA8CL,6BAA6B,UAAU,2BAA2B;EACpE,OAAK;EAEL,kBAAkB,gBAAgB,WAAW;EAqBtD;EAIS,UAAM;;;;;;;;;;;;;;;;;;;;;wBAkCD,uBACd,YAAY,OAAO,2BAA2B,gBAAgB,WAAW,sBACvE,gBAAgB,WAAW"}
@@ -0,0 +1,60 @@
1
+ import { Component, ErrorInfo, FunctionComponent, ReactNode } from "react";
2
+ import { CaptureResult, Properties } from "posthog-js";
3
+ export interface PosthogErrorBoundaryFallbackProps {
4
+ error: unknown;
5
+ /** The `$exception` event sent; `undefined` while only the stub is there, which queues it. */
6
+ exceptionEvent: CaptureResult | undefined;
7
+ componentStack: string;
8
+ resetError: () => void;
9
+ }
10
+ export interface PosthogErrorBoundaryProps {
11
+ children?: ReactNode | (() => ReactNode);
12
+ fallback?: ReactNode | FunctionComponent<PosthogErrorBoundaryFallbackProps>;
13
+ additionalProperties?: Properties | ((error: unknown, errorInfo: ErrorInfo) => Properties);
14
+ }
15
+ interface State {
16
+ error: unknown;
17
+ componentStack: string | null;
18
+ exceptionEvent: CaptureResult | undefined;
19
+ }
20
+ /**
21
+ * `posthog-js/react`'s `PostHogErrorBoundary`, with its props, for the snippet-loaded library: a
22
+ * render error in `children` is sent to PostHog's error tracking (`captureException`, as an
23
+ * `$exception` event tied to the session's replay) and `fallback` renders instead — a
24
+ * component gets the error and `resetError`. An error thrown before the library has loaded is
25
+ * queued on the stub and sent once it has.
26
+ *
27
+ * The boundary itself never throws: a failure to report (no PostHog, an ad blocker that stopped the
28
+ * library, a throwing `additionalProperties`) is logged and the fallback still renders. It
29
+ * catches render errors only, as any error boundary; errors outside React's render (event
30
+ * handlers, unhandled rejections) are the library's exception autocapture's, enabled in the
31
+ * snippet's `config` (`capture_exceptions`).
32
+ */
33
+ export declare class PosthogErrorBoundary extends Component<PosthogErrorBoundaryProps, State> {
34
+ state: State;
35
+ componentDidCatch(error: unknown, errorInfo: ErrorInfo): void;
36
+ resetError: () => void;
37
+ render(): ReactNode;
38
+ }
39
+ /**
40
+ * `posthog-js/react`'s `setupReactErrorHandler`, for the snippet-loaded library, so without its
41
+ * `client`: a handler for React 19's root options, which report what no `PosthogErrorBoundary`
42
+ * sees — `onUncaughtError` (no boundary caught it), `onCaughtError` (a framework's boundary did,
43
+ * e.g. TanStack Router's `errorComponent`) and `onRecoverableError` (a hydration mismatch React
44
+ * recovered from). The error goes to PostHog with its component stack; `callback` gets the event
45
+ * (`undefined` while only the stub is there), as React's own logging does not run once a handler
46
+ * is set.
47
+ *
48
+ * ```tsx
49
+ * hydrateRoot(document, <StartClient />, {
50
+ * onUncaughtError: setupReactErrorHandler(),
51
+ * onCaughtError: setupReactErrorHandler(),
52
+ * onRecoverableError: setupReactErrorHandler(),
53
+ * });
54
+ * ```
55
+ *
56
+ * Never throws, as `PosthogErrorBoundary`: a failure to report is logged.
57
+ */
58
+ export declare function setupReactErrorHandler(callback?: (event: CaptureResult | undefined, error: unknown, errorInfo: ErrorInfo) => void): (error: unknown, errorInfo: ErrorInfo) => void;
59
+ export {};
60
+ //# sourceMappingURL=posthog-error-boundary.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"posthog-error-boundary.d.mts","names":[],"sources":["../../src/react/posthog-error-boundary.tsx"],"mappings":";;iBAUiB;EACf;;EAEA,gBAAgB;EAChB;EACA;;iBAGe;EACf,WAAW,mBAAmB;EAC9B,WAAW,YAAY,kBAAkB;EACzC,uBAAuB,eAAe,gBAAgB,WAAW,cAAc;;UAGvE;EACR;EACA;EACA,gBAAgB;;;;;;;;;;;;;;;qBA8CL,6BAA6B,UAAU,2BAA2B;EACpE,OAAK;EAEL,kBAAkB,gBAAgB,WAAW;EAqBtD;EAIS,UAAM;;;;;;;;;;;;;;;;;;;;;wBAkCD,uBACd,YAAY,OAAO,2BAA2B,gBAAgB,WAAW,sBACvE,gBAAgB,WAAW"}