@shware/analytics 16.1.0 → 16.2.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/README.md +14 -4
- package/dist/react/index.cjs +11 -2
- package/dist/react/index.cjs.map +1 -1
- package/dist/react/index.d.cts +3 -2
- package/dist/react/index.d.cts.map +1 -1
- package/dist/react/index.d.mts +3 -2
- package/dist/react/index.d.mts.map +1 -1
- package/dist/react/index.mjs +3 -2
- package/dist/react/index.mjs.map +1 -1
- package/dist/react/posthog-error-boundary.cjs +119 -0
- package/dist/react/posthog-error-boundary.cjs.map +1 -0
- package/dist/react/posthog-error-boundary.d.cts +60 -0
- package/dist/react/posthog-error-boundary.d.cts.map +1 -0
- package/dist/react/posthog-error-boundary.d.mts +60 -0
- package/dist/react/posthog-error-boundary.d.mts.map +1 -0
- package/dist/react/posthog-error-boundary.mjs +117 -0
- package/dist/react/posthog-error-boundary.mjs.map +1 -0
- package/dist/react/posthog.cjs +97 -0
- package/dist/react/posthog.cjs.map +1 -0
- package/dist/react/posthog.d.cts +41 -0
- package/dist/react/posthog.d.cts.map +1 -0
- package/dist/react/posthog.d.mts +41 -0
- package/dist/react/posthog.d.mts.map +1 -0
- package/dist/react/posthog.mjs +90 -0
- package/dist/react/posthog.mjs.map +1 -0
- package/dist/third-parties/google-analytics.cjs +1 -1
- package/dist/third-parties/google-analytics.cjs.map +1 -1
- package/dist/third-parties/google-analytics.mjs +1 -1
- package/dist/third-parties/google-analytics.mjs.map +1 -1
- package/dist/third-parties/integration.cjs.map +1 -1
- package/dist/third-parties/integration.d.cts +5 -1
- package/dist/third-parties/integration.d.cts.map +1 -1
- package/dist/third-parties/integration.d.mts +5 -1
- package/dist/third-parties/integration.d.mts.map +1 -1
- package/dist/third-parties/integration.mjs.map +1 -1
- package/dist/third-parties/posthog.cjs +4 -4
- package/dist/third-parties/posthog.cjs.map +1 -1
- package/dist/third-parties/posthog.d.cts +3 -3
- package/dist/third-parties/posthog.d.mts +3 -3
- package/dist/third-parties/posthog.mjs +4 -4
- package/dist/third-parties/posthog.mjs.map +1 -1
- package/package.json +1 -1
- package/dist/react/use-feature-flag.cjs +0 -23
- package/dist/react/use-feature-flag.cjs.map +0 -1
- package/dist/react/use-feature-flag.d.cts +0 -10
- package/dist/react/use-feature-flag.d.cts.map +0 -1
- package/dist/react/use-feature-flag.d.mts +0 -10
- package/dist/react/use-feature-flag.d.mts.map +0 -1
- package/dist/react/use-feature-flag.mjs +0 -22
- package/dist/react/use-feature-flag.mjs.map +0 -1
package/README.md
CHANGED
|
@@ -105,10 +105,10 @@ export const integrations = [
|
|
|
105
105
|
| `ads` | `linkedInAds` | the events in `conversions`, each as its conversion id |
|
|
106
106
|
| `ads` | `microsoftAds` | `events` (the GA4 conversion events, `CONVERSION_EVENTS`, by default), plus `customEvents` |
|
|
107
107
|
|
|
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 `
|
|
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):
|
|
109
109
|
|
|
110
110
|
```tsx
|
|
111
|
-
import {
|
|
111
|
+
import { useFeatureFlagVariantKey } from '@shware/analytics/react';
|
|
112
112
|
import { posthogFlagsReady } from '@shware/analytics/third-parties';
|
|
113
113
|
import { use } from 'react';
|
|
114
114
|
import { browser } from 'react-dom';
|
|
@@ -116,11 +116,21 @@ import { browser } from 'react-dom';
|
|
|
116
116
|
function Checkout() {
|
|
117
117
|
use(browser());
|
|
118
118
|
use(posthogFlagsReady());
|
|
119
|
-
return
|
|
119
|
+
return useFeatureFlagVariantKey('new-checkout') === 'test' ? <NewCheckout /> : <OldCheckout />;
|
|
120
120
|
}
|
|
121
121
|
```
|
|
122
122
|
|
|
123
|
-
With server-evaluated flags
|
|
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`).
|
|
124
134
|
|
|
125
135
|
`getHeaders` is also accepted, for a backend that wants extra headers on the analytics requests.
|
|
126
136
|
|
package/dist/react/index.cjs
CHANGED
|
@@ -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
|
|
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.
|
|
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
|
package/dist/react/index.cjs.map
CHANGED
|
@@ -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 {
|
|
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"}
|
package/dist/react/index.d.cts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { AnalyticsProps } from "../third-parties/analytics-props.cjs";
|
|
2
|
-
import {
|
|
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 {
|
|
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":"
|
|
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"}
|
package/dist/react/index.d.mts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { AnalyticsProps } from "../third-parties/analytics-props.mjs";
|
|
2
|
-
import {
|
|
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 {
|
|
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":"
|
|
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"}
|
package/dist/react/index.mjs
CHANGED
|
@@ -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 {
|
|
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,
|
|
42
|
+
export { Analytics, PosthogErrorBoundary, PosthogProvider, setupReactErrorHandler, useActiveFeatureFlags, useFeatureFlagEnabled, useFeatureFlagPayload, useFeatureFlagResult, useFeatureFlagVariantKey, usePostHog };
|
|
42
43
|
|
|
43
44
|
//# sourceMappingURL=index.mjs.map
|
package/dist/react/index.mjs.map
CHANGED
|
@@ -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 {
|
|
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"}
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
import { getPosthog } from "../third-parties/posthog.mjs";
|
|
2
|
+
import { Component, isValidElement } from "react";
|
|
3
|
+
// src/react/posthog-error-boundary.tsx
|
|
4
|
+
const INITIAL_STATE = {
|
|
5
|
+
error: null,
|
|
6
|
+
componentStack: null,
|
|
7
|
+
exceptionEvent: void 0
|
|
8
|
+
};
|
|
9
|
+
/**
|
|
10
|
+
* The error as PostHog's own boundary reports it: the React component stack added as a cause, so
|
|
11
|
+
* the issue shows which components it was thrown in.
|
|
12
|
+
*/
|
|
13
|
+
function withComponentStack(error, componentStack) {
|
|
14
|
+
if (!componentStack) return error;
|
|
15
|
+
const isError = error instanceof Error;
|
|
16
|
+
const stackError = new Error(isError ? error.message : `Primitive value captured as exception: ${String(error)}`);
|
|
17
|
+
stackError.name = `React ErrorBoundary ${isError ? error.name : "Error"}`;
|
|
18
|
+
stackError.stack = componentStack;
|
|
19
|
+
if (!isError) return stackError;
|
|
20
|
+
const seen = /* @__PURE__ */ new WeakSet();
|
|
21
|
+
let current = error;
|
|
22
|
+
while (!seen.has(current)) {
|
|
23
|
+
seen.add(current);
|
|
24
|
+
if (!(current.cause instanceof Error)) {
|
|
25
|
+
if (current.cause !== void 0) stackError.cause = current.cause;
|
|
26
|
+
current.cause = stackError;
|
|
27
|
+
break;
|
|
28
|
+
}
|
|
29
|
+
current = current.cause;
|
|
30
|
+
}
|
|
31
|
+
return error;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* `posthog-js/react`'s `PostHogErrorBoundary`, with its props, for the snippet-loaded library: a
|
|
35
|
+
* render error in `children` is sent to PostHog's error tracking (`captureException`, as an
|
|
36
|
+
* `$exception` event tied to the session's replay) and `fallback` renders instead — a
|
|
37
|
+
* component gets the error and `resetError`. An error thrown before the library has loaded is
|
|
38
|
+
* queued on the stub and sent once it has.
|
|
39
|
+
*
|
|
40
|
+
* The boundary itself never throws: a failure to report (no PostHog, an ad blocker that stopped the
|
|
41
|
+
* library, a throwing `additionalProperties`) is logged and the fallback still renders. It
|
|
42
|
+
* catches render errors only, as any error boundary; errors outside React's render (event
|
|
43
|
+
* handlers, unhandled rejections) are the library's exception autocapture's, enabled in the
|
|
44
|
+
* snippet's `config` (`capture_exceptions`).
|
|
45
|
+
*/
|
|
46
|
+
var PosthogErrorBoundary = class extends Component {
|
|
47
|
+
constructor(..._args) {
|
|
48
|
+
super(..._args);
|
|
49
|
+
this.state = INITIAL_STATE;
|
|
50
|
+
this.resetError = () => {
|
|
51
|
+
this.setState(INITIAL_STATE);
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
componentDidCatch(error, errorInfo) {
|
|
55
|
+
const componentStack = errorInfo.componentStack ?? "";
|
|
56
|
+
let exceptionEvent;
|
|
57
|
+
try {
|
|
58
|
+
const { additionalProperties } = this.props;
|
|
59
|
+
const properties = typeof additionalProperties === "function" ? additionalProperties(error, errorInfo) : additionalProperties;
|
|
60
|
+
exceptionEvent = getPosthog()?.captureException(withComponentStack(error, componentStack), properties);
|
|
61
|
+
} catch (e) {
|
|
62
|
+
console.error("PosthogErrorBoundary: the error was not reported", e);
|
|
63
|
+
}
|
|
64
|
+
this.setState({
|
|
65
|
+
error,
|
|
66
|
+
componentStack,
|
|
67
|
+
exceptionEvent
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
render() {
|
|
71
|
+
const { children, fallback } = this.props;
|
|
72
|
+
const { error, componentStack, exceptionEvent } = this.state;
|
|
73
|
+
if (componentStack === null) return typeof children === "function" ? children() : children;
|
|
74
|
+
const element = typeof fallback === "function" ? fallback({
|
|
75
|
+
error,
|
|
76
|
+
componentStack,
|
|
77
|
+
exceptionEvent,
|
|
78
|
+
resetError: this.resetError
|
|
79
|
+
}) : fallback;
|
|
80
|
+
if (isValidElement(element)) return element;
|
|
81
|
+
console.warn("PosthogErrorBoundary: fallback is not a React element; rendering nothing");
|
|
82
|
+
return null;
|
|
83
|
+
}
|
|
84
|
+
};
|
|
85
|
+
/**
|
|
86
|
+
* `posthog-js/react`'s `setupReactErrorHandler`, for the snippet-loaded library, so without its
|
|
87
|
+
* `client`: a handler for React 19's root options, which report what no `PosthogErrorBoundary`
|
|
88
|
+
* sees — `onUncaughtError` (no boundary caught it), `onCaughtError` (a framework's boundary did,
|
|
89
|
+
* e.g. TanStack Router's `errorComponent`) and `onRecoverableError` (a hydration mismatch React
|
|
90
|
+
* recovered from). The error goes to PostHog with its component stack; `callback` gets the event
|
|
91
|
+
* (`undefined` while only the stub is there), as React's own logging does not run once a handler
|
|
92
|
+
* is set.
|
|
93
|
+
*
|
|
94
|
+
* ```tsx
|
|
95
|
+
* hydrateRoot(document, <StartClient />, {
|
|
96
|
+
* onUncaughtError: setupReactErrorHandler(),
|
|
97
|
+
* onCaughtError: setupReactErrorHandler(),
|
|
98
|
+
* onRecoverableError: setupReactErrorHandler(),
|
|
99
|
+
* });
|
|
100
|
+
* ```
|
|
101
|
+
*
|
|
102
|
+
* Never throws, as `PosthogErrorBoundary`: a failure to report is logged.
|
|
103
|
+
*/
|
|
104
|
+
function setupReactErrorHandler(callback) {
|
|
105
|
+
return (error, errorInfo) => {
|
|
106
|
+
let event;
|
|
107
|
+
try {
|
|
108
|
+
event = getPosthog()?.captureException(withComponentStack(error, errorInfo.componentStack));
|
|
109
|
+
} catch (e) {
|
|
110
|
+
console.error("setupReactErrorHandler: the error was not reported", e);
|
|
111
|
+
}
|
|
112
|
+
callback?.(event, error, errorInfo);
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
export { PosthogErrorBoundary, setupReactErrorHandler };
|
|
116
|
+
|
|
117
|
+
//# sourceMappingURL=posthog-error-boundary.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"posthog-error-boundary.mjs","names":[],"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,cAA0C,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,iBAAiB,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,IAAI,eAAe,OAAO,GAAG,OAAO;EACpC,QAAQ,KAAK,0EAA0E;EACvF,OAAO;CACT;AACF;;;;;;;;;;;;;;;;;;;;AAqBA,SAAgB,uBACd,UACgD;CAChD,QAAQ,OAAO,cAAc;EAC3B,IAAI;EACJ,IAAI;GACF,QAAQ,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"}
|