@shware/analytics 16.1.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 (40) hide show
  1. package/README.md +14 -4
  2. package/dist/react/index.cjs +11 -2
  3. package/dist/react/index.cjs.map +1 -1
  4. package/dist/react/index.d.cts +3 -2
  5. package/dist/react/index.d.cts.map +1 -1
  6. package/dist/react/index.d.mts +3 -2
  7. package/dist/react/index.d.mts.map +1 -1
  8. package/dist/react/index.mjs +3 -2
  9. package/dist/react/index.mjs.map +1 -1
  10. package/dist/react/posthog-error-boundary.cjs +119 -0
  11. package/dist/react/posthog-error-boundary.cjs.map +1 -0
  12. package/dist/react/posthog-error-boundary.d.cts +60 -0
  13. package/dist/react/posthog-error-boundary.d.cts.map +1 -0
  14. package/dist/react/posthog-error-boundary.d.mts +60 -0
  15. package/dist/react/posthog-error-boundary.d.mts.map +1 -0
  16. package/dist/react/posthog-error-boundary.mjs +117 -0
  17. package/dist/react/posthog-error-boundary.mjs.map +1 -0
  18. package/dist/react/posthog.cjs +97 -0
  19. package/dist/react/posthog.cjs.map +1 -0
  20. package/dist/react/posthog.d.cts +41 -0
  21. package/dist/react/posthog.d.cts.map +1 -0
  22. package/dist/react/posthog.d.mts +41 -0
  23. package/dist/react/posthog.d.mts.map +1 -0
  24. package/dist/react/posthog.mjs +90 -0
  25. package/dist/react/posthog.mjs.map +1 -0
  26. package/dist/third-parties/posthog.cjs +3 -3
  27. package/dist/third-parties/posthog.cjs.map +1 -1
  28. package/dist/third-parties/posthog.d.cts +3 -3
  29. package/dist/third-parties/posthog.d.mts +3 -3
  30. package/dist/third-parties/posthog.mjs +3 -3
  31. package/dist/third-parties/posthog.mjs.map +1 -1
  32. package/package.json +1 -1
  33. package/dist/react/use-feature-flag.cjs +0 -23
  34. package/dist/react/use-feature-flag.cjs.map +0 -1
  35. package/dist/react/use-feature-flag.d.cts +0 -10
  36. package/dist/react/use-feature-flag.d.cts.map +0 -1
  37. package/dist/react/use-feature-flag.d.mts +0 -10
  38. package/dist/react/use-feature-flag.d.mts.map +0 -1
  39. package/dist/react/use-feature-flag.mjs +0 -22
  40. 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 `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):
109
109
 
110
110
  ```tsx
111
- import { useFeatureFlag } from '@shware/analytics/react';
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 useFeatureFlag('new-checkout') === 'test' ? <NewCheckout /> : <OldCheckout />;
119
+ return useFeatureFlagVariantKey('new-checkout') === 'test' ? <NewCheckout /> : <OldCheckout />;
120
120
  }
121
121
  ```
122
122
 
123
- 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`).
124
134
 
125
135
  `getHeaders` is also accepted, for a backend that wants extra headers on the analytics requests.
126
136
 
@@ -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"}
@@ -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,g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B;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"}
@@ -0,0 +1,97 @@
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.ts
5
+ const noop = () => {};
6
+ const Bootstrap = (0, react.createContext)(void 0);
7
+ /**
8
+ * The counterpart of `posthog-js/react`'s `PostHogProvider`, for the snippet-loaded library. It
9
+ * does not initialize PostHog — `posthogAnalytics` does — only carries what the hooks need from
10
+ * the server: the request's server-evaluated flags, the same object as the snippet's
11
+ * `config.bootstrap`, for the flag hooks to render with on the server, through hydration and until
12
+ * the library has loaded its flags — an experiment's variant renders at once, with no flicker and
13
+ * no hydration mismatch. Wrap the app in it, e.g. in the root route.
14
+ */
15
+ function PosthogProvider({ bootstrap, children }) {
16
+ return (0, react.createElement)(Bootstrap.Provider, { value: bootstrap }, children);
17
+ }
18
+ /** Subscribes to flag (re)loads; on the stub the subscription is queued and has no unsubscribe. */
19
+ function subscribe(onChange) {
20
+ return require_third_parties_posthog.getPosthog()?.onFeatureFlags(onChange) ?? noop;
21
+ }
22
+ /**
23
+ * What `read` returns once the library has loaded its flags, and `bootstrapped` until then and on
24
+ * the server, re-read when flags reload. The value is kept while its JSON is unchanged, as
25
+ * `useSyncExternalStore` needs: PostHog builds a new result or payload object on every read.
26
+ */
27
+ function useFlags(read, bootstrapped) {
28
+ const cache = (0, react.useRef)(void 0);
29
+ const stable = (value) => {
30
+ const json = JSON.stringify(value);
31
+ if (!cache.current || cache.current.json !== json) cache.current = {
32
+ json,
33
+ value
34
+ };
35
+ return cache.current.value;
36
+ };
37
+ return (0, react.useSyncExternalStore)(subscribe, () => {
38
+ const posthog = require_third_parties_posthog.getLoadedPosthog();
39
+ return stable(posthog?.featureFlags.hasLoadedFlags ? read(posthog) : bootstrapped);
40
+ }, () => stable(bootstrapped));
41
+ }
42
+ /** A flag's value: `true`/`false`, a multivariate flag's variant, or `undefined` until loaded. */
43
+ function useFeatureFlagVariantKey(flag) {
44
+ const bootstrapped = (0, react.use)(Bootstrap)?.featureFlags?.[flag];
45
+ return useFlags((posthog) => posthog.getFeatureFlag(flag), bootstrapped);
46
+ }
47
+ function useFeatureFlagEnabled(flag, defaultValue) {
48
+ const value = (0, react.use)(Bootstrap)?.featureFlags?.[flag];
49
+ return useFlags((posthog) => posthog.isFeatureEnabled(flag), value === void 0 ? void 0 : !!value) ?? defaultValue;
50
+ }
51
+ /** A flag's payload, read without recording an exposure. */
52
+ function useFeatureFlagPayload(flag) {
53
+ const bootstrapped = (0, react.use)(Bootstrap)?.featureFlagPayloads?.[flag];
54
+ return useFlags((posthog) => posthog.getFeatureFlagResult(flag, { send_event: false })?.payload, bootstrapped);
55
+ }
56
+ /** A flag's value, variant and payload together; `undefined` while it is unknown. */
57
+ function useFeatureFlagResult(flag) {
58
+ const bootstrap = (0, react.use)(Bootstrap);
59
+ const value = bootstrap?.featureFlags?.[flag];
60
+ return useFlags((posthog) => posthog.getFeatureFlagResult(flag), value === void 0 ? void 0 : {
61
+ key: flag,
62
+ enabled: typeof value === "string" ? true : value,
63
+ variant: typeof value === "string" ? value : void 0,
64
+ payload: bootstrap?.featureFlagPayloads?.[flag]
65
+ });
66
+ }
67
+ /**
68
+ * The keys of the flags: only those that are on while bootstrapped, every flag the library has
69
+ * once loaded — as `posthog-js/react`'s does.
70
+ */
71
+ function useActiveFeatureFlags() {
72
+ const flags = (0, react.use)(Bootstrap)?.featureFlags ?? {};
73
+ return useFlags((posthog) => posthog.featureFlags.getFlags(), Object.keys(flags).filter((key) => flags[key]));
74
+ }
75
+ /**
76
+ * `window.posthog`, as `posthog-js/react`'s `usePostHog`: the snippet's stub until the library
77
+ * loads — which queues the calls returning nothing (`capture`, `identify`, …) — then the library,
78
+ * re-rendering when it replaces the stub; `undefined` on the server. Use the value of the latest
79
+ * render rather than one kept from before (e.g. in a ref): calls on a stub kept past the load are
80
+ * lost. A method that returns a value returns `undefined` on the stub; read flags with the hooks.
81
+ *
82
+ * The re-render comes from the flags loading, as the library answers the stub's queued
83
+ * `onFeatureFlags`: with feature flags disabled it stays on the stub until something else
84
+ * re-renders.
85
+ */
86
+ function usePostHog() {
87
+ return (0, react.useSyncExternalStore)(subscribe, require_third_parties_posthog.getPosthog, () => void 0);
88
+ }
89
+ exports.PosthogProvider = PosthogProvider;
90
+ exports.useActiveFeatureFlags = useActiveFeatureFlags;
91
+ exports.useFeatureFlagEnabled = useFeatureFlagEnabled;
92
+ exports.useFeatureFlagPayload = useFeatureFlagPayload;
93
+ exports.useFeatureFlagResult = useFeatureFlagResult;
94
+ exports.useFeatureFlagVariantKey = useFeatureFlagVariantKey;
95
+ exports.usePostHog = usePostHog;
96
+
97
+ //# sourceMappingURL=posthog.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"posthog.cjs","names":["createContext","createElement","getPosthog","useRef","useSyncExternalStore","getLoadedPosthog","use"],"sources":["../../src/react/posthog.ts"],"sourcesContent":["import type { BootstrapConfig, FeatureFlagResult, JsonType, PostHog } from 'posthog-js';\nimport {\n type ReactNode,\n createContext,\n createElement,\n use,\n useRef,\n useSyncExternalStore,\n} from 'react';\nimport { getLoadedPosthog, getPosthog } from '../third-parties/posthog';\n\nconst noop = () => {};\n\nconst Bootstrap = createContext<BootstrapConfig | undefined>(undefined);\n\n/**\n * The counterpart of `posthog-js/react`'s `PostHogProvider`, for the snippet-loaded library. It\n * does not initialize PostHog — `posthogAnalytics` does — only carries what the hooks need from\n * the server: the request's server-evaluated flags, the same object as the snippet's\n * `config.bootstrap`, for the flag hooks to render with on the server, through hydration and until\n * the library has loaded its flags — an experiment's variant renders at once, with no flicker and\n * no hydration mismatch. Wrap the app in it, e.g. in the root route.\n */\nexport function PosthogProvider({\n bootstrap,\n children,\n}: {\n bootstrap: BootstrapConfig | undefined;\n children: ReactNode;\n}) {\n return createElement(Bootstrap.Provider, { value: bootstrap }, children);\n}\n\n/** Subscribes to flag (re)loads; on the stub the subscription is queued and has no unsubscribe. */\nfunction subscribe(onChange: () => void): () => void {\n const unsubscribe: (() => void) | undefined = getPosthog()?.onFeatureFlags(onChange);\n return unsubscribe ?? noop;\n}\n\n/**\n * What `read` returns once the library has loaded its flags, and `bootstrapped` until then and on\n * the server, re-read when flags reload. The value is kept while its JSON is unchanged, as\n * `useSyncExternalStore` needs: PostHog builds a new result or payload object on every read.\n */\nfunction useFlags<T>(read: (posthog: PostHog) => T, bootstrapped: T): T {\n const cache = useRef<{ json: string | undefined; value: T }>(undefined);\n const stable = (value: T) => {\n // Typed wider: `JSON.stringify(undefined)` is `undefined`, whatever its type says.\n const json: string | undefined = JSON.stringify(value);\n if (!cache.current || cache.current.json !== json) cache.current = { json, value };\n return cache.current.value;\n };\n return useSyncExternalStore(\n subscribe,\n () => {\n const posthog = getLoadedPosthog();\n // As `posthog-js/react`: the bootstrap until the flags request has answered, not only until\n // the library has loaded, so no flag is read (and no exposure recorded) before then.\n return stable(posthog?.featureFlags.hasLoadedFlags ? read(posthog) : bootstrapped);\n },\n () => stable(bootstrapped)\n );\n}\n\n/*\n * The hooks of `posthog-js/react`, with its names and signatures, for the snippet-loaded library.\n *\n * Under a `<PosthogProvider>` each is the server's value until the library has loaded its\n * flags, on the server too. Without one it is `undefined` on the server and through hydration, so\n * the default renders first and the variant once flags arrive; to wait for them instead, call\n * `use(browser())` and `use(posthogFlagsReady())` above it, under a `<Suspense>`.\n *\n * Reading a flag records the exposure (`$feature_flag_called`) once the flags have loaded, as\n * PostHog's do — except the payload's — not while only a bootstrapped value is shown.\n */\n\n/** A flag's value: `true`/`false`, a multivariate flag's variant, or `undefined` until loaded. */\nexport function useFeatureFlagVariantKey(flag: string): string | boolean | undefined {\n const bootstrapped = use(Bootstrap)?.featureFlags?.[flag];\n return useFlags((posthog) => posthog.getFeatureFlag(flag), bootstrapped);\n}\n\n/** Whether a flag is on (a variant counts as on); `defaultValue` while it is unknown. */\nexport function useFeatureFlagEnabled(flag: string): boolean | undefined;\nexport function useFeatureFlagEnabled(flag: string, defaultValue: boolean): boolean;\nexport function useFeatureFlagEnabled(flag: string, defaultValue?: boolean) {\n const value = use(Bootstrap)?.featureFlags?.[flag];\n const bootstrapped = value === undefined ? undefined : !!value;\n return useFlags((posthog) => posthog.isFeatureEnabled(flag), bootstrapped) ?? defaultValue;\n}\n\n/** A flag's payload, read without recording an exposure. */\nexport function useFeatureFlagPayload(flag: string): JsonType {\n const bootstrapped = use(Bootstrap)?.featureFlagPayloads?.[flag];\n return useFlags(\n (posthog) => posthog.getFeatureFlagResult(flag, { send_event: false })?.payload,\n bootstrapped\n );\n}\n\n/** A flag's value, variant and payload together; `undefined` while it is unknown. */\nexport function useFeatureFlagResult(flag: string): FeatureFlagResult | undefined {\n const bootstrap = use(Bootstrap);\n const value = bootstrap?.featureFlags?.[flag];\n const bootstrapped: FeatureFlagResult | undefined =\n value === undefined\n ? undefined\n : {\n key: flag,\n enabled: typeof value === 'string' ? true : value,\n variant: typeof value === 'string' ? value : undefined,\n payload: bootstrap?.featureFlagPayloads?.[flag],\n };\n return useFlags((posthog) => posthog.getFeatureFlagResult(flag), bootstrapped);\n}\n\n/**\n * The keys of the flags: only those that are on while bootstrapped, every flag the library has\n * once loaded — as `posthog-js/react`'s does.\n */\nexport function useActiveFeatureFlags(): string[] {\n const flags = use(Bootstrap)?.featureFlags ?? {};\n const bootstrapped = Object.keys(flags).filter((key) => flags[key]);\n return useFlags((posthog) => posthog.featureFlags.getFlags(), bootstrapped);\n}\n\n/**\n * `window.posthog`, as `posthog-js/react`'s `usePostHog`: the snippet's stub until the library\n * loads — which queues the calls returning nothing (`capture`, `identify`, …) — then the library,\n * re-rendering when it replaces the stub; `undefined` on the server. Use the value of the latest\n * render rather than one kept from before (e.g. in a ref): calls on a stub kept past the load are\n * lost. A method that returns a value returns `undefined` on the stub; read flags with the hooks.\n *\n * The re-render comes from the flags loading, as the library answers the stub's queued\n * `onFeatureFlags`: with feature flags disabled it stays on the stub until something else\n * re-renders.\n */\nexport function usePostHog(): PostHog | undefined {\n return useSyncExternalStore(subscribe, getPosthog, () => undefined);\n}\n"],"mappings":";;;;AAWA,MAAM,aAAa,CAAC;AAEpB,MAAM,aAAA,GAAYA,MAAAA,cAAAA,CAA2C,KAAA,CAAS;;;;;;;;;AAUtE,SAAgB,gBAAgB,EAC9B,WACA,YAIC;CACD,QAAA,GAAOC,MAAAA,cAAAA,CAAc,UAAU,UAAU,EAAE,OAAO,UAAU,GAAG,QAAQ;AACzE;;AAGA,SAAS,UAAU,UAAkC;CAEnD,OAD8CC,8BAAAA,WAAW,CAAC,EAAE,eAAe,QAAQ,KAC7D;AACxB;;;;;;AAOA,SAAS,SAAY,MAA+B,cAAoB;CACtE,MAAM,SAAA,GAAQC,MAAAA,OAAAA,CAA+C,KAAA,CAAS;CACtE,MAAM,UAAU,UAAa;EAE3B,MAAM,OAA2B,KAAK,UAAU,KAAK;EACrD,IAAI,CAAC,MAAM,WAAW,MAAM,QAAQ,SAAS,MAAM,MAAM,UAAU;GAAE;GAAM;EAAM;EACjF,OAAO,MAAM,QAAQ;CACvB;CACA,QAAA,GAAOC,MAAAA,qBAAAA,CACL,iBACM;EACJ,MAAM,UAAUC,8BAAAA,iBAAiB;EAGjC,OAAO,OAAO,SAAS,aAAa,iBAAiB,KAAK,OAAO,IAAI,YAAY;CACnF,SACM,OAAO,YAAY,CAC3B;AACF;;AAeA,SAAgB,yBA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AAS;AACpE"}
@@ -0,0 +1,41 @@
1
+ import { ReactNode } from "react";
2
+ import { BootstrapConfig, FeatureFlagResult, JsonType, PostHog } from "posthog-js";
3
+ /**
4
+ * The counterpart of `posthog-js/react`'s `PostHogProvider`, for the snippet-loaded library. It
5
+ * does not initialize PostHog — `posthogAnalytics` does — only carries what the hooks need from
6
+ * the server: the request's server-evaluated flags, the same object as the snippet's
7
+ * `config.bootstrap`, for the flag hooks to render with on the server, through hydration and until
8
+ * the library has loaded its flags — an experiment's variant renders at once, with no flicker and
9
+ * no hydration mismatch. Wrap the app in it, e.g. in the root route.
10
+ */
11
+ export declare function PosthogProvider({ bootstrap, children }: {
12
+ bootstrap: BootstrapConfig | undefined;
13
+ children: ReactNode;
14
+ }): import("react").FunctionComponentElement<import("react").ProviderProps<BootstrapConfig | undefined>>;
15
+ /** A flag's value: `true`/`false`, a multivariate flag's variant, or `undefined` until loaded. */
16
+ export declare function useFeatureFlagVariantKey(flag: string): string | boolean | undefined;
17
+ /** Whether a flag is on (a variant counts as on); `defaultValue` while it is unknown. */
18
+ export declare function useFeatureFlagEnabled(flag: string): boolean | undefined;
19
+ export declare function useFeatureFlagEnabled(flag: string, defaultValue: boolean): boolean;
20
+ /** A flag's payload, read without recording an exposure. */
21
+ export declare function useFeatureFlagPayload(flag: string): JsonType;
22
+ /** A flag's value, variant and payload together; `undefined` while it is unknown. */
23
+ export declare function useFeatureFlagResult(flag: string): FeatureFlagResult | undefined;
24
+ /**
25
+ * The keys of the flags: only those that are on while bootstrapped, every flag the library has
26
+ * once loaded — as `posthog-js/react`'s does.
27
+ */
28
+ export declare function useActiveFeatureFlags(): string[];
29
+ /**
30
+ * `window.posthog`, as `posthog-js/react`'s `usePostHog`: the snippet's stub until the library
31
+ * loads — which queues the calls returning nothing (`capture`, `identify`, …) — then the library,
32
+ * re-rendering when it replaces the stub; `undefined` on the server. Use the value of the latest
33
+ * render rather than one kept from before (e.g. in a ref): calls on a stub kept past the load are
34
+ * lost. A method that returns a value returns `undefined` on the stub; read flags with the hooks.
35
+ *
36
+ * The re-render comes from the flags loading, as the library answers the stub's queued
37
+ * `onFeatureFlags`: with feature flags disabled it stays on the stub until something else
38
+ * re-renders.
39
+ */
40
+ export declare function usePostHog(): PostHog | undefined;
41
+ //# sourceMappingURL=posthog.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"posthog.d.cts","names":[],"sources":["../../src/react/posthog.ts"],"mappings":";;;;;;;;;;wBAuBgB,kBACd,WACA;EAEA,WAAW;EACX,UAAU;oBACX,yCAAA,cAAA;;wBAgDe,yBAAyB;;wBAMzB,sBAAsB;wBACtB,sBAAsB,cAAc;;wBAQpC,sBAAsB,eAAe;;wBASrC,qBAAqB,eAAe;;;;;wBAmBpC;;;;;;;;;;;;wBAiBA,cAAc"}
@@ -0,0 +1,41 @@
1
+ import { ReactNode } from "react";
2
+ import { BootstrapConfig, FeatureFlagResult, JsonType, PostHog } from "posthog-js";
3
+ /**
4
+ * The counterpart of `posthog-js/react`'s `PostHogProvider`, for the snippet-loaded library. It
5
+ * does not initialize PostHog — `posthogAnalytics` does — only carries what the hooks need from
6
+ * the server: the request's server-evaluated flags, the same object as the snippet's
7
+ * `config.bootstrap`, for the flag hooks to render with on the server, through hydration and until
8
+ * the library has loaded its flags — an experiment's variant renders at once, with no flicker and
9
+ * no hydration mismatch. Wrap the app in it, e.g. in the root route.
10
+ */
11
+ export declare function PosthogProvider({ bootstrap, children }: {
12
+ bootstrap: BootstrapConfig | undefined;
13
+ children: ReactNode;
14
+ }): import("react").FunctionComponentElement<import("react").ProviderProps<BootstrapConfig | undefined>>;
15
+ /** A flag's value: `true`/`false`, a multivariate flag's variant, or `undefined` until loaded. */
16
+ export declare function useFeatureFlagVariantKey(flag: string): string | boolean | undefined;
17
+ /** Whether a flag is on (a variant counts as on); `defaultValue` while it is unknown. */
18
+ export declare function useFeatureFlagEnabled(flag: string): boolean | undefined;
19
+ export declare function useFeatureFlagEnabled(flag: string, defaultValue: boolean): boolean;
20
+ /** A flag's payload, read without recording an exposure. */
21
+ export declare function useFeatureFlagPayload(flag: string): JsonType;
22
+ /** A flag's value, variant and payload together; `undefined` while it is unknown. */
23
+ export declare function useFeatureFlagResult(flag: string): FeatureFlagResult | undefined;
24
+ /**
25
+ * The keys of the flags: only those that are on while bootstrapped, every flag the library has
26
+ * once loaded — as `posthog-js/react`'s does.
27
+ */
28
+ export declare function useActiveFeatureFlags(): string[];
29
+ /**
30
+ * `window.posthog`, as `posthog-js/react`'s `usePostHog`: the snippet's stub until the library
31
+ * loads — which queues the calls returning nothing (`capture`, `identify`, …) — then the library,
32
+ * re-rendering when it replaces the stub; `undefined` on the server. Use the value of the latest
33
+ * render rather than one kept from before (e.g. in a ref): calls on a stub kept past the load are
34
+ * lost. A method that returns a value returns `undefined` on the stub; read flags with the hooks.
35
+ *
36
+ * The re-render comes from the flags loading, as the library answers the stub's queued
37
+ * `onFeatureFlags`: with feature flags disabled it stays on the stub until something else
38
+ * re-renders.
39
+ */
40
+ export declare function usePostHog(): PostHog | undefined;
41
+ //# sourceMappingURL=posthog.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"posthog.d.mts","names":[],"sources":["../../src/react/posthog.ts"],"mappings":";;;;;;;;;;wBAuBgB,kBACd,WACA;EAEA,WAAW;EACX,UAAU;oBACX,yCAAA,cAAA;;wBAgDe,yBAAyB;;wBAMzB,sBAAsB;wBACtB,sBAAsB,cAAc;;wBAQpC,sBAAsB,eAAe;;wBASrC,qBAAqB,eAAe;;;;;wBAmBpC;;;;;;;;;;;;wBAiBA,cAAc"}
@@ -0,0 +1,90 @@
1
+ import { getLoadedPosthog, getPosthog } from "../third-parties/posthog.mjs";
2
+ import { createContext, createElement, use, useRef, useSyncExternalStore } from "react";
3
+ // src/react/posthog.ts
4
+ const noop = () => {};
5
+ const Bootstrap = createContext(void 0);
6
+ /**
7
+ * The counterpart of `posthog-js/react`'s `PostHogProvider`, for the snippet-loaded library. It
8
+ * does not initialize PostHog — `posthogAnalytics` does — only carries what the hooks need from
9
+ * the server: the request's server-evaluated flags, the same object as the snippet's
10
+ * `config.bootstrap`, for the flag hooks to render with on the server, through hydration and until
11
+ * the library has loaded its flags — an experiment's variant renders at once, with no flicker and
12
+ * no hydration mismatch. Wrap the app in it, e.g. in the root route.
13
+ */
14
+ function PosthogProvider({ bootstrap, children }) {
15
+ return createElement(Bootstrap.Provider, { value: bootstrap }, children);
16
+ }
17
+ /** Subscribes to flag (re)loads; on the stub the subscription is queued and has no unsubscribe. */
18
+ function subscribe(onChange) {
19
+ return getPosthog()?.onFeatureFlags(onChange) ?? noop;
20
+ }
21
+ /**
22
+ * What `read` returns once the library has loaded its flags, and `bootstrapped` until then and on
23
+ * the server, re-read when flags reload. The value is kept while its JSON is unchanged, as
24
+ * `useSyncExternalStore` needs: PostHog builds a new result or payload object on every read.
25
+ */
26
+ function useFlags(read, bootstrapped) {
27
+ const cache = useRef(void 0);
28
+ const stable = (value) => {
29
+ const json = JSON.stringify(value);
30
+ if (!cache.current || cache.current.json !== json) cache.current = {
31
+ json,
32
+ value
33
+ };
34
+ return cache.current.value;
35
+ };
36
+ return useSyncExternalStore(subscribe, () => {
37
+ const posthog = getLoadedPosthog();
38
+ return stable(posthog?.featureFlags.hasLoadedFlags ? read(posthog) : bootstrapped);
39
+ }, () => stable(bootstrapped));
40
+ }
41
+ /** A flag's value: `true`/`false`, a multivariate flag's variant, or `undefined` until loaded. */
42
+ function useFeatureFlagVariantKey(flag) {
43
+ const bootstrapped = use(Bootstrap)?.featureFlags?.[flag];
44
+ return useFlags((posthog) => posthog.getFeatureFlag(flag), bootstrapped);
45
+ }
46
+ function useFeatureFlagEnabled(flag, defaultValue) {
47
+ const value = use(Bootstrap)?.featureFlags?.[flag];
48
+ return useFlags((posthog) => posthog.isFeatureEnabled(flag), value === void 0 ? void 0 : !!value) ?? defaultValue;
49
+ }
50
+ /** A flag's payload, read without recording an exposure. */
51
+ function useFeatureFlagPayload(flag) {
52
+ const bootstrapped = use(Bootstrap)?.featureFlagPayloads?.[flag];
53
+ return useFlags((posthog) => posthog.getFeatureFlagResult(flag, { send_event: false })?.payload, bootstrapped);
54
+ }
55
+ /** A flag's value, variant and payload together; `undefined` while it is unknown. */
56
+ function useFeatureFlagResult(flag) {
57
+ const bootstrap = use(Bootstrap);
58
+ const value = bootstrap?.featureFlags?.[flag];
59
+ return useFlags((posthog) => posthog.getFeatureFlagResult(flag), value === void 0 ? void 0 : {
60
+ key: flag,
61
+ enabled: typeof value === "string" ? true : value,
62
+ variant: typeof value === "string" ? value : void 0,
63
+ payload: bootstrap?.featureFlagPayloads?.[flag]
64
+ });
65
+ }
66
+ /**
67
+ * The keys of the flags: only those that are on while bootstrapped, every flag the library has
68
+ * once loaded — as `posthog-js/react`'s does.
69
+ */
70
+ function useActiveFeatureFlags() {
71
+ const flags = use(Bootstrap)?.featureFlags ?? {};
72
+ return useFlags((posthog) => posthog.featureFlags.getFlags(), Object.keys(flags).filter((key) => flags[key]));
73
+ }
74
+ /**
75
+ * `window.posthog`, as `posthog-js/react`'s `usePostHog`: the snippet's stub until the library
76
+ * loads — which queues the calls returning nothing (`capture`, `identify`, …) — then the library,
77
+ * re-rendering when it replaces the stub; `undefined` on the server. Use the value of the latest
78
+ * render rather than one kept from before (e.g. in a ref): calls on a stub kept past the load are
79
+ * lost. A method that returns a value returns `undefined` on the stub; read flags with the hooks.
80
+ *
81
+ * The re-render comes from the flags loading, as the library answers the stub's queued
82
+ * `onFeatureFlags`: with feature flags disabled it stays on the stub until something else
83
+ * re-renders.
84
+ */
85
+ function usePostHog() {
86
+ return useSyncExternalStore(subscribe, getPosthog, () => void 0);
87
+ }
88
+ export { PosthogProvider, useActiveFeatureFlags, useFeatureFlagEnabled, useFeatureFlagPayload, useFeatureFlagResult, useFeatureFlagVariantKey, usePostHog };
89
+
90
+ //# sourceMappingURL=posthog.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"posthog.mjs","names":[],"sources":["../../src/react/posthog.ts"],"sourcesContent":["import type { BootstrapConfig, FeatureFlagResult, JsonType, PostHog } from 'posthog-js';\nimport {\n type ReactNode,\n createContext,\n createElement,\n use,\n useRef,\n useSyncExternalStore,\n} from 'react';\nimport { getLoadedPosthog, getPosthog } from '../third-parties/posthog';\n\nconst noop = () => {};\n\nconst Bootstrap = createContext<BootstrapConfig | undefined>(undefined);\n\n/**\n * The counterpart of `posthog-js/react`'s `PostHogProvider`, for the snippet-loaded library. It\n * does not initialize PostHog — `posthogAnalytics` does — only carries what the hooks need from\n * the server: the request's server-evaluated flags, the same object as the snippet's\n * `config.bootstrap`, for the flag hooks to render with on the server, through hydration and until\n * the library has loaded its flags — an experiment's variant renders at once, with no flicker and\n * no hydration mismatch. Wrap the app in it, e.g. in the root route.\n */\nexport function PosthogProvider({\n bootstrap,\n children,\n}: {\n bootstrap: BootstrapConfig | undefined;\n children: ReactNode;\n}) {\n return createElement(Bootstrap.Provider, { value: bootstrap }, children);\n}\n\n/** Subscribes to flag (re)loads; on the stub the subscription is queued and has no unsubscribe. */\nfunction subscribe(onChange: () => void): () => void {\n const unsubscribe: (() => void) | undefined = getPosthog()?.onFeatureFlags(onChange);\n return unsubscribe ?? noop;\n}\n\n/**\n * What `read` returns once the library has loaded its flags, and `bootstrapped` until then and on\n * the server, re-read when flags reload. The value is kept while its JSON is unchanged, as\n * `useSyncExternalStore` needs: PostHog builds a new result or payload object on every read.\n */\nfunction useFlags<T>(read: (posthog: PostHog) => T, bootstrapped: T): T {\n const cache = useRef<{ json: string | undefined; value: T }>(undefined);\n const stable = (value: T) => {\n // Typed wider: `JSON.stringify(undefined)` is `undefined`, whatever its type says.\n const json: string | undefined = JSON.stringify(value);\n if (!cache.current || cache.current.json !== json) cache.current = { json, value };\n return cache.current.value;\n };\n return useSyncExternalStore(\n subscribe,\n () => {\n const posthog = getLoadedPosthog();\n // As `posthog-js/react`: the bootstrap until the flags request has answered, not only until\n // the library has loaded, so no flag is read (and no exposure recorded) before then.\n return stable(posthog?.featureFlags.hasLoadedFlags ? read(posthog) : bootstrapped);\n },\n () => stable(bootstrapped)\n );\n}\n\n/*\n * The hooks of `posthog-js/react`, with its names and signatures, for the snippet-loaded library.\n *\n * Under a `<PosthogProvider>` each is the server's value until the library has loaded its\n * flags, on the server too. Without one it is `undefined` on the server and through hydration, so\n * the default renders first and the variant once flags arrive; to wait for them instead, call\n * `use(browser())` and `use(posthogFlagsReady())` above it, under a `<Suspense>`.\n *\n * Reading a flag records the exposure (`$feature_flag_called`) once the flags have loaded, as\n * PostHog's do — except the payload's — not while only a bootstrapped value is shown.\n */\n\n/** A flag's value: `true`/`false`, a multivariate flag's variant, or `undefined` until loaded. */\nexport function useFeatureFlagVariantKey(flag: string): string | boolean | undefined {\n const bootstrapped = use(Bootstrap)?.featureFlags?.[flag];\n return useFlags((posthog) => posthog.getFeatureFlag(flag), bootstrapped);\n}\n\n/** Whether a flag is on (a variant counts as on); `defaultValue` while it is unknown. */\nexport function useFeatureFlagEnabled(flag: string): boolean | undefined;\nexport function useFeatureFlagEnabled(flag: string, defaultValue: boolean): boolean;\nexport function useFeatureFlagEnabled(flag: string, defaultValue?: boolean) {\n const value = use(Bootstrap)?.featureFlags?.[flag];\n const bootstrapped = value === undefined ? undefined : !!value;\n return useFlags((posthog) => posthog.isFeatureEnabled(flag), bootstrapped) ?? defaultValue;\n}\n\n/** A flag's payload, read without recording an exposure. */\nexport function useFeatureFlagPayload(flag: string): JsonType {\n const bootstrapped = use(Bootstrap)?.featureFlagPayloads?.[flag];\n return useFlags(\n (posthog) => posthog.getFeatureFlagResult(flag, { send_event: false })?.payload,\n bootstrapped\n );\n}\n\n/** A flag's value, variant and payload together; `undefined` while it is unknown. */\nexport function useFeatureFlagResult(flag: string): FeatureFlagResult | undefined {\n const bootstrap = use(Bootstrap);\n const value = bootstrap?.featureFlags?.[flag];\n const bootstrapped: FeatureFlagResult | undefined =\n value === undefined\n ? undefined\n : {\n key: flag,\n enabled: typeof value === 'string' ? true : value,\n variant: typeof value === 'string' ? value : undefined,\n payload: bootstrap?.featureFlagPayloads?.[flag],\n };\n return useFlags((posthog) => posthog.getFeatureFlagResult(flag), bootstrapped);\n}\n\n/**\n * The keys of the flags: only those that are on while bootstrapped, every flag the library has\n * once loaded — as `posthog-js/react`'s does.\n */\nexport function useActiveFeatureFlags(): string[] {\n const flags = use(Bootstrap)?.featureFlags ?? {};\n const bootstrapped = Object.keys(flags).filter((key) => flags[key]);\n return useFlags((posthog) => posthog.featureFlags.getFlags(), bootstrapped);\n}\n\n/**\n * `window.posthog`, as `posthog-js/react`'s `usePostHog`: the snippet's stub until the library\n * loads — which queues the calls returning nothing (`capture`, `identify`, …) — then the library,\n * re-rendering when it replaces the stub; `undefined` on the server. Use the value of the latest\n * render rather than one kept from before (e.g. in a ref): calls on a stub kept past the load are\n * lost. A method that returns a value returns `undefined` on the stub; read flags with the hooks.\n *\n * The re-render comes from the flags loading, as the library answers the stub's queued\n * `onFeatureFlags`: with feature flags disabled it stays on the stub until something else\n * re-renders.\n */\nexport function usePostHog(): PostHog | undefined {\n return useSyncExternalStore(subscribe, getPosthog, () => undefined);\n}\n"],"mappings":";;;AAWA,MAAM,aAAa,CAAC;AAEpB,MAAM,YAAY,cAA2C,KAAA,CAAS;;;;;;;;;AAUtE,SAAgB,gBAAgB,EAC9B,WACA,YAIC;CACD,OAAO,cAAc,UAAU,UAAU,EAAE,OAAO,UAAU,GAAG,QAAQ;AACzE;;AAGA,SAAS,UAAU,UAAkC;CAEnD,OAD8C,WAAW,CAAC,EAAE,eAAe,QAAQ,KAC7D;AACxB;;;;;;AAOA,SAAS,SAAY,MAA+B,cAAoB;CACtE,MAAM,QAAQ,OAA+C,KAAA,CAAS;CACtE,MAAM,UAAU,UAAa;EAE3B,MAAM,OAA2B,KAAK,UAAU,KAAK;EACrD,IAAI,CAAC,MAAM,WAAW,MAAM,QAAQ,SAAS,MAAM,MAAM,UAAU;GAAE;GAAM;EAAM;EACjF,OAAO,MAAM,QAAQ;CACvB;CAC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B,WAAW,kBAAkB,KAAA,CAAS;AACpE"}
@@ -29,14 +29,14 @@ let flagsReady;
29
29
  /**
30
30
  * Resolves once PostHog has loaded its feature flags — or after `timeoutMs` (3 s by default),
31
31
  * since an ad blocker that stops the library would otherwise hold it forever; read the flags
32
- * after it with `useFeatureFlag` / `getLoadedPosthog`, which are `undefined` in that case. One
33
- * promise per page, so React's `use()` can suspend on it:
32
+ * after it with `useFeatureFlagVariantKey` / `getLoadedPosthog`, which are `undefined` in that
33
+ * case. One promise per page, so React's `use()` can suspend on it:
34
34
  *
35
35
  * ```tsx
36
36
  * function Checkout() {
37
37
  * use(browser()); // react-dom: the server renders the <Suspense> fallback instead
38
38
  * use(posthogFlagsReady());
39
- * return useFeatureFlag('new-checkout') === 'test' ? <NewCheckout /> : <OldCheckout />;
39
+ * return useFeatureFlagVariantKey('new-checkout') === 'test' ? <NewCheckout /> : <OldCheckout />;
40
40
  * }
41
41
  * ```
42
42
  *
@@ -1 +1 @@
1
- {"version":3,"file":"posthog.cjs","names":["getFirst"],"sources":["../../src/third-parties/posthog.ts"],"sourcesContent":["import type { PostHog, PostHogConfig } from 'posthog-js';\nimport type { UpdateVisitorDTO } from '../schema/index';\nimport type { EventName, TrackName, TrackProperties } from '../track/types';\nimport { getFirst } from '../utils/field';\nimport type { Integration } from './integration';\n\nexport type { PostHog, PostHogConfig } from 'posthog-js';\n\n/**\n * `window.posthog`, for calls that return nothing (`capture`, `identify`, `onFeatureFlags`, …):\n * the snippet's stub until the library loads, which queues them and replays them in order once it\n * has. A method that returns a value returns `undefined` on the stub — use `getLoadedPosthog` for\n * those. `undefined` on the server and before the snippet has run.\n *\n * Read off `window` rather than declared on it, so a host that also has `posthog-js`'s own types\n * does not get two conflicting declarations. Types only: install `posthog-js` (a dev dependency\n * is enough) for them; it is never bundled.\n */\nexport function getPosthog(): PostHog | undefined {\n if (typeof document === 'undefined') return undefined;\n return (window as { posthog?: PostHog }).posthog;\n}\n\n/**\n * The PostHog instance once the library has loaded, for the methods that return a value\n * (`getFeatureFlag`, `isFeatureEnabled`, `get_distinct_id`, …); `undefined` while only the stub is\n * there. To act when flags arrive, subscribe with `getPosthog()?.onFeatureFlags` instead, which\n * the stub queues.\n */\nexport function getLoadedPosthog(): PostHog | undefined {\n const posthog = getPosthog();\n return posthog?.__loaded ? posthog : undefined;\n}\n\nlet flagsReady: Promise<void> | undefined;\n\n/**\n * Resolves once PostHog has loaded its feature flags — or after `timeoutMs` (3 s by default),\n * since an ad blocker that stops the library would otherwise hold it forever; read the flags\n * after it with `useFeatureFlag` / `getLoadedPosthog`, which are `undefined` in that case. One\n * promise per page, so React's `use()` can suspend on it:\n *\n * ```tsx\n * function Checkout() {\n * use(browser()); // react-dom: the server renders the <Suspense> fallback instead\n * use(posthogFlagsReady());\n * return useFeatureFlag('new-checkout') === 'test' ? <NewCheckout /> : <OldCheckout />;\n * }\n * ```\n *\n * Waiting shows the fallback until the flags are in, instead of the default then the variant;\n * with server-evaluated flags in `config.bootstrap` it resolves as soon as the library loads.\n * Browser only: it never resolves on the server.\n */\nexport function posthogFlagsReady(timeoutMs = 3000): Promise<void> {\n if (typeof document === 'undefined') return new Promise(() => {});\n flagsReady ??= new Promise<void>((resolve) => {\n setTimeout(resolve, timeoutMs);\n const posthog = getPosthog();\n if (!posthog) return;\n // Queued on the stub; once loaded, called as soon as flags are (or already were) in.\n posthog.onFeatureFlags(() => resolve());\n });\n return flagsReady;\n}\n\nconst metrics = ['CLS', 'FCP', 'FID', 'INP', 'LCP', 'TTFB'];\n\nexport function sendPosthogEvent<T extends EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>\n) {\n // `document`, not `window`: React Native defines `window` as an alias of `global`, so a\n // window check would pass there and then throw on `window.location`, which it has no such\n // alias for.\n if (typeof document === 'undefined') return;\n const posthog = getPosthog();\n if (!posthog) {\n console.warn('posthog has not been initialized');\n return false;\n }\n if (metrics.includes(name)) return;\n if (window.location.host.includes('127.0.0.1')) return;\n if (window.location.host.includes('localhost')) return;\n\n posthog.capture(name, properties);\n}\n\n/**\n * Identifies the visitor to PostHog as the signed-in user, by the user's id — the server's\n * `distinct_id` for the visitor once someone has signed in on it. Only a user: identifying an\n * anonymous visitor by its own id would make PostHog treat it as an identified person, and\n * PostHog does not merge one identified person into another when the user later signs in, so the\n * pre-sign-in events would stay split off.\n *\n * Without a user it is sign-out (`reset()`): PostHog's identity is reset, so the next person on\n * this page starts anonymous instead of merging into the one who left.\n */\nexport function setPosthogUser({ user_id, user_data }: Omit<UpdateVisitorDTO, 'tags'>) {\n const posthog = getPosthog();\n if (!posthog) {\n console.warn('posthog has not been initialized');\n return;\n }\n if (!user_id) {\n posthog.reset();\n return;\n }\n posthog.identify(user_id, { email: getFirst(user_data?.email) });\n}\n\n/**\n * PostHog: every event, for behavior analysis. Loaded with PostHog's HTML snippet, which defines\n * a stub `window.posthog` and fetches the library (`array.js`) asynchronously from PostHog's\n * assets host, so it stays out of the app's bundle; calls made before it loads are queued.\n *\n * `config` is serialized into the snippet's `posthog.init` call, so only its JSON survives:\n * `api_host`, `defaults`, `bootstrap` (server-evaluated flags, so an experiment renders its variant\n * without a flicker), and the other plain options — functions such as `loaded` are dropped.\n */\nexport function posthogAnalytics(options: {\n token: `phc_${string}`;\n config: Partial<PostHogConfig> & { api_host: string };\n}): Integration {\n // Where the snippet loads `array.js` from, by its own rule; a relative `api_host` (a reverse\n // proxy on the site's origin) needs no preconnect.\n const assets = options.config.api_host.replace('.i.posthog.com', '-assets.i.posthog.com');\n // `<` escaped: `config` is arbitrary JSON (a `bootstrap` can carry user data), and a `</script>`\n // inside it would end this inline script early. `\\u003c` parses back to the same value.\n const config = JSON.stringify(options.config).replace(/</g, '\\\\u003c');\n return {\n type: 'analytics',\n track: sendPosthogEvent,\n setUser: setPosthogUser,\n preconnect: URL.canParse(assets) ? [new URL(assets).origin] : [],\n script: {\n id: 'posthog',\n // The stub must exist before hydration, whose effects already track (`page_view`) and\n // identify; it is a few lines, and `array.js` still loads async. PostHog's own Next example\n // does the same.\n strategy: 'beforeInteractive',\n inline: `\n !function(t,e){var o,n,p,r;e.__SV||(window.posthog=e,e._i=[],e.init=function(i,s,a){function g(t,e){var o=e.split(\".\");2==o.length&&(t=t[o[0]],e=o[1]),t[e]=function(){t.push([e].concat(Array.prototype.slice.call(arguments,0)))}}(p=t.createElement(\"script\")).type=\"text/javascript\",p.crossOrigin=\"anonymous\",p.async=!0,p.src=s.api_host.replace(\".i.posthog.com\",\"-assets.i.posthog.com\")+\"/static/array.js\",(r=t.getElementsByTagName(\"script\")[0]).parentNode.insertBefore(p,r);var u=e;for(void 0!==a?u=e[a]=[]:a=\"posthog\",u.people=u.people||[],Object.defineProperty(u,\"toString\",{configurable:!0,enumerable:!0,writable:!0,value:function(t){var e=\"posthog\";return\"posthog\"!==a&&(e+=\".\"+a),t||(e+=\" (stub)\"),e}}),Object.defineProperty(u.people,\"toString\",{configurable:!0,enumerable:!0,writable:!0,value:function(){return u.toString(1)+\".people (stub)\"}}),o=\"init capture register register_once register_for_session unregister unregister_for_session getFeatureFlag getFeatureFlagResult isFeatureEnabled reloadFeatureFlags updateEarlyAccessFeatureEnrollment getEarlyAccessFeatures on onFeatureFlags onSessionId getSurveys getActiveMatchingSurveys renderSurvey canRenderSurvey getNextSurveyStep identify setPersonProperties group resetGroups setPersonPropertiesForFlags resetPersonPropertiesForFlags setGroupPropertiesForFlags resetGroupPropertiesForFlags reset get_distinct_id getGroups get_session_id get_session_replay_url alias set_config startSessionRecording stopSessionRecording sessionRecordingStarted captureException loadToolbar get_property getSessionProperty createPersonProfile opt_in_capturing opt_out_capturing has_opted_in_capturing has_opted_out_capturing clear_opt_in_out_capturing debug\".split(\" \"),n=0;n<o.length;n++)g(u,o[n]);e._i.push([i,s,a])},e.__SV=1)}(document,window.posthog||[]);\n posthog.init(${JSON.stringify(options.token)}, ${config});\n `,\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;AAkBA,SAAgB,aAAkC;CAChD,IAAI,OAAO,aAAa,aA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U,QAAQ,MAAM,CAAC,CAAC,QAAQ,MAAM,SAAS;CACrE,OAAO;EACL,MAAM;EACN,OAAO;EACP,SAAS;EACT,YAAY,IAAI,SAAS,MAAM,IAAI,CAAC,IAAI,IAAI,MAAM,CAAC,CAAC,MAAM,IAAI,CAAC;EAC/D,QAAQ;GACN,IAAI;GAIJ,UAAU;GACV,QAAQ;;uBAES,KAAK,UAAU,QAAQ,KAAK,EAAE,IAAI,OAAO;;EAE5D;CACF;AACF"}
1
+ {"version":3,"file":"posthog.cjs","names":["getFirst"],"sources":["../../src/third-parties/posthog.ts"],"sourcesContent":["import type { PostHog, PostHogConfig } from 'posthog-js';\nimport type { UpdateVisitorDTO } from '../schema/index';\nimport type { EventName, TrackName, TrackProperties } from '../track/types';\nimport { getFirst } from '../utils/field';\nimport type { Integration } from './integration';\n\nexport type { PostHog, PostHogConfig } from 'posthog-js';\n\n/**\n * `window.posthog`, for calls that return nothing (`capture`, `identify`, `onFeatureFlags`, …):\n * the snippet's stub until the library loads, which queues them and replays them in order once it\n * has. A method that returns a value returns `undefined` on the stub — use `getLoadedPosthog` for\n * those. `undefined` on the server and before the snippet has run.\n *\n * Read off `window` rather than declared on it, so a host that also has `posthog-js`'s own types\n * does not get two conflicting declarations. Types only: install `posthog-js` (a dev dependency\n * is enough) for them; it is never bundled.\n */\nexport function getPosthog(): PostHog | undefined {\n if (typeof document === 'undefined') return undefined;\n return (window as { posthog?: PostHog }).posthog;\n}\n\n/**\n * The PostHog instance once the library has loaded, for the methods that return a value\n * (`getFeatureFlag`, `isFeatureEnabled`, `get_distinct_id`, …); `undefined` while only the stub is\n * there. To act when flags arrive, subscribe with `getPosthog()?.onFeatureFlags` instead, which\n * the stub queues.\n */\nexport function getLoadedPosthog(): PostHog | undefined {\n const posthog = getPosthog();\n return posthog?.__loaded ? posthog : undefined;\n}\n\nlet flagsReady: Promise<void> | undefined;\n\n/**\n * Resolves once PostHog has loaded its feature flags — or after `timeoutMs` (3 s by default),\n * since an ad blocker that stops the library would otherwise hold it forever; read the flags\n * after it with `useFeatureFlagVariantKey` / `getLoadedPosthog`, which are `undefined` in that\n * case. One promise per page, so React's `use()` can suspend on it:\n *\n * ```tsx\n * function Checkout() {\n * use(browser()); // react-dom: the server renders the <Suspense> fallback instead\n * use(posthogFlagsReady());\n * return useFeatureFlagVariantKey('new-checkout') === 'test' ? <NewCheckout /> : <OldCheckout />;\n * }\n * ```\n *\n * Waiting shows the fallback until the flags are in, instead of the default then the variant;\n * with server-evaluated flags in `config.bootstrap` it resolves as soon as the library loads.\n * Browser only: it never resolves on the server.\n */\nexport function posthogFlagsReady(timeoutMs = 3000): Promise<void> {\n if (typeof document === 'undefined') return new Promise(() => {});\n flagsReady ??= new Promise<void>((resolve) => {\n setTimeout(resolve, timeoutMs);\n const posthog = getPosthog();\n if (!posthog) return;\n // Queued on the stub; once loaded, called as soon as flags are (or already were) in.\n posthog.onFeatureFlags(() => resolve());\n });\n return flagsReady;\n}\n\nconst metrics = ['CLS', 'FCP', 'FID', 'INP', 'LCP', 'TTFB'];\n\nexport function sendPosthogEvent<T extends EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>\n) {\n // `document`, not `window`: React Native defines `window` as an alias of `global`, so a\n // window check would pass there and then throw on `window.location`, which it has no such\n // alias for.\n if (typeof document === 'undefined') return;\n const posthog = getPosthog();\n if (!posthog) {\n console.warn('posthog has not been initialized');\n return false;\n }\n if (metrics.includes(name)) return;\n if (window.location.host.includes('127.0.0.1')) return;\n if (window.location.host.includes('localhost')) return;\n\n posthog.capture(name, properties);\n}\n\n/**\n * Identifies the visitor to PostHog as the signed-in user, by the user's id — the server's\n * `distinct_id` for the visitor once someone has signed in on it. Only a user: identifying an\n * anonymous visitor by its own id would make PostHog treat it as an identified person, and\n * PostHog does not merge one identified person into another when the user later signs in, so the\n * pre-sign-in events would stay split off.\n *\n * Without a user it is sign-out (`reset()`): PostHog's identity is reset, so the next person on\n * this page starts anonymous instead of merging into the one who left.\n */\nexport function setPosthogUser({ user_id, user_data }: Omit<UpdateVisitorDTO, 'tags'>) {\n const posthog = getPosthog();\n if (!posthog) {\n console.warn('posthog has not been initialized');\n return;\n }\n if (!user_id) {\n posthog.reset();\n return;\n }\n posthog.identify(user_id, { email: getFirst(user_data?.email) });\n}\n\n/**\n * PostHog: every event, for behavior analysis. Loaded with PostHog's HTML snippet, which defines\n * a stub `window.posthog` and fetches the library (`array.js`) asynchronously from PostHog's\n * assets host, so it stays out of the app's bundle; calls made before it loads are queued.\n *\n * `config` is serialized into the snippet's `posthog.init` call, so only its JSON survives:\n * `api_host`, `defaults`, `bootstrap` (server-evaluated flags, so an experiment renders its variant\n * without a flicker), and the other plain options — functions such as `loaded` are dropped.\n */\nexport function posthogAnalytics(options: {\n token: `phc_${string}`;\n config: Partial<PostHogConfig> & { api_host: string };\n}): Integration {\n // Where the snippet loads `array.js` from, by its own rule; a relative `api_host` (a reverse\n // proxy on the site's origin) needs no preconnect.\n const assets = options.config.api_host.replace('.i.posthog.com', '-assets.i.posthog.com');\n // `<` escaped: `config` is arbitrary JSON (a `bootstrap` can carry user data), and a `</script>`\n // inside it would end this inline script early. `\\u003c` parses back to the same value.\n const config = JSON.stringify(options.config).replace(/</g, '\\\\u003c');\n return {\n type: 'analytics',\n track: sendPosthogEvent,\n setUser: setPosthogUser,\n preconnect: URL.canParse(assets) ? [new URL(assets).origin] : [],\n script: {\n id: 'posthog',\n // The stub must exist before hydration, whose effects already track (`page_view`) and\n // identify; it is a few lines, and `array.js` still loads async. PostHog's own Next example\n // does the same.\n strategy: 'beforeInteractive',\n inline: `\n !function(t,e){var o,n,p,r;e.__SV||(window.posthog=e,e._i=[],e.init=function(i,s,a){function g(t,e){var o=e.split(\".\");2==o.length&&(t=t[o[0]],e=o[1]),t[e]=function(){t.push([e].concat(Array.prototype.slice.call(arguments,0)))}}(p=t.createElement(\"script\")).type=\"text/javascript\",p.crossOrigin=\"anonymous\",p.async=!0,p.src=s.api_host.replace(\".i.posthog.com\",\"-assets.i.posthog.com\")+\"/static/array.js\",(r=t.getElementsByTagName(\"script\")[0]).parentNode.insertBefore(p,r);var u=e;for(void 0!==a?u=e[a]=[]:a=\"posthog\",u.people=u.people||[],Object.defineProperty(u,\"toString\",{configurable:!0,enumerable:!0,writable:!0,value:function(t){var e=\"posthog\";return\"posthog\"!==a&&(e+=\".\"+a),t||(e+=\" (stub)\"),e}}),Object.defineProperty(u.people,\"toString\",{configurable:!0,enumerable:!0,writable:!0,value:function(){return u.toString(1)+\".people (stub)\"}}),o=\"init capture register register_once register_for_session unregister unregister_for_session getFeatureFlag getFeatureFlagResult isFeatureEnabled reloadFeatureFlags updateEarlyAccessFeatureEnrollment getEarlyAccessFeatures on onFeatureFlags onSessionId getSurveys getActiveMatchingSurveys renderSurvey canRenderSurvey getNextSurveyStep identify setPersonProperties group resetGroups setPersonPropertiesForFlags resetPersonPropertiesForFlags setGroupPropertiesForFlags resetGroupPropertiesForFlags reset get_distinct_id getGroups get_session_id get_session_replay_url alias set_config startSessionRecording stopSessionRecording sessionRecordingStarted captureException loadToolbar get_property getSessionProperty createPersonProfile opt_in_capturing opt_out_capturing has_opted_in_capturing has_opted_out_capturing clear_opt_in_out_capturing debug\".split(\" \"),n=0;n<o.length;n++)g(u,o[n]);e._i.push([i,s,a])},e.__SV=1)}(document,window.posthog||[]);\n posthog.init(${JSON.stringify(options.token)}, ${config});\n `,\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;AAkBA,SAAgB,aAAkC;CAChD,IAAI,OAAO,aAAa,aAAa,OAAO,KAAA;CAC5C,OAAQ,OAAiC;AAC3C;;;;;;;AAQA,SAAgB,mBAAwC;CACtD,MAAM,UAAU,WAAW;CAC3B,OAAO,SAAS,WAAW,UAAU,KAAA;AACvC;AAEA,IAAI;;;;;;;;;;;;;;;;;;;AAoBJ,SAAgB,kBAAkB,YAAY,KAAqB;CACjE,IAAI,OAAO,aAAa,aAAa,OAAO,IAAI,cAAc,CAAC,CAAC;CAChE,eAAe,IAAI,S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ACF;AACF"}
@@ -23,14 +23,14 @@ export declare function getLoadedPosthog(): PostHog$1 | undefined;
23
23
  /**
24
24
  * Resolves once PostHog has loaded its feature flags — or after `timeoutMs` (3 s by default),
25
25
  * since an ad blocker that stops the library would otherwise hold it forever; read the flags
26
- * after it with `useFeatureFlag` / `getLoadedPosthog`, which are `undefined` in that case. One
27
- * promise per page, so React's `use()` can suspend on it:
26
+ * after it with `useFeatureFlagVariantKey` / `getLoadedPosthog`, which are `undefined` in that
27
+ * case. One promise per page, so React's `use()` can suspend on it:
28
28
  *
29
29
  * ```tsx
30
30
  * function Checkout() {
31
31
  * use(browser()); // react-dom: the server renders the <Suspense> fallback instead
32
32
  * use(posthogFlagsReady());
33
- * return useFeatureFlag('new-checkout') === 'test' ? <NewCheckout /> : <OldCheckout />;
33
+ * return useFeatureFlagVariantKey('new-checkout') === 'test' ? <NewCheckout /> : <OldCheckout />;
34
34
  * }
35
35
  * ```
36
36
  *
@@ -23,14 +23,14 @@ export declare function getLoadedPosthog(): PostHog$1 | undefined;
23
23
  /**
24
24
  * Resolves once PostHog has loaded its feature flags — or after `timeoutMs` (3 s by default),
25
25
  * since an ad blocker that stops the library would otherwise hold it forever; read the flags
26
- * after it with `useFeatureFlag` / `getLoadedPosthog`, which are `undefined` in that case. One
27
- * promise per page, so React's `use()` can suspend on it:
26
+ * after it with `useFeatureFlagVariantKey` / `getLoadedPosthog`, which are `undefined` in that
27
+ * case. One promise per page, so React's `use()` can suspend on it:
28
28
  *
29
29
  * ```tsx
30
30
  * function Checkout() {
31
31
  * use(browser()); // react-dom: the server renders the <Suspense> fallback instead
32
32
  * use(posthogFlagsReady());
33
- * return useFeatureFlag('new-checkout') === 'test' ? <NewCheckout /> : <OldCheckout />;
33
+ * return useFeatureFlagVariantKey('new-checkout') === 'test' ? <NewCheckout /> : <OldCheckout />;
34
34
  * }
35
35
  * ```
36
36
  *
@@ -28,14 +28,14 @@ let flagsReady;
28
28
  /**
29
29
  * Resolves once PostHog has loaded its feature flags — or after `timeoutMs` (3 s by default),
30
30
  * since an ad blocker that stops the library would otherwise hold it forever; read the flags
31
- * after it with `useFeatureFlag` / `getLoadedPosthog`, which are `undefined` in that case. One
32
- * promise per page, so React's `use()` can suspend on it:
31
+ * after it with `useFeatureFlagVariantKey` / `getLoadedPosthog`, which are `undefined` in that
32
+ * case. One promise per page, so React's `use()` can suspend on it:
33
33
  *
34
34
  * ```tsx
35
35
  * function Checkout() {
36
36
  * use(browser()); // react-dom: the server renders the <Suspense> fallback instead
37
37
  * use(posthogFlagsReady());
38
- * return useFeatureFlag('new-checkout') === 'test' ? <NewCheckout /> : <OldCheckout />;
38
+ * return useFeatureFlagVariantKey('new-checkout') === 'test' ? <NewCheckout /> : <OldCheckout />;
39
39
  * }
40
40
  * ```
41
41
  *
@@ -1 +1 @@
1
- {"version":3,"file":"posthog.mjs","names":[],"sources":["../../src/third-parties/posthog.ts"],"sourcesContent":["import type { PostHog, PostHogConfig } from 'posthog-js';\nimport type { UpdateVisitorDTO } from '../schema/index';\nimport type { EventName, TrackName, TrackProperties } from '../track/types';\nimport { getFirst } from '../utils/field';\nimport type { Integration } from './integration';\n\nexport type { PostHog, PostHogConfig } from 'posthog-js';\n\n/**\n * `window.posthog`, for calls that return nothing (`capture`, `identify`, `onFeatureFlags`, …):\n * the snippet's stub until the library loads, which queues them and replays them in order once it\n * has. A method that returns a value returns `undefined` on the stub — use `getLoadedPosthog` for\n * those. `undefined` on the server and before the snippet has run.\n *\n * Read off `window` rather than declared on it, so a host that also has `posthog-js`'s own types\n * does not get two conflicting declarations. Types only: install `posthog-js` (a dev dependency\n * is enough) for them; it is never bundled.\n */\nexport function getPosthog(): PostHog | undefined {\n if (typeof document === 'undefined') return undefined;\n return (window as { posthog?: PostHog }).posthog;\n}\n\n/**\n * The PostHog instance once the library has loaded, for the methods that return a value\n * (`getFeatureFlag`, `isFeatureEnabled`, `get_distinct_id`, …); `undefined` while only the stub is\n * there. To act when flags arrive, subscribe with `getPosthog()?.onFeatureFlags` instead, which\n * the stub queues.\n */\nexport function getLoadedPosthog(): PostHog | undefined {\n const posthog = getPosthog();\n return posthog?.__loaded ? posthog : undefined;\n}\n\nlet flagsReady: Promise<void> | undefined;\n\n/**\n * Resolves once PostHog has loaded its feature flags — or after `timeoutMs` (3 s by default),\n * since an ad blocker that stops the library would otherwise hold it forever; read the flags\n * after it with `useFeatureFlag` / `getLoadedPosthog`, which are `undefined` in that case. One\n * promise per page, so React's `use()` can suspend on it:\n *\n * ```tsx\n * function Checkout() {\n * use(browser()); // react-dom: the server renders the <Suspense> fallback instead\n * use(posthogFlagsReady());\n * return useFeatureFlag('new-checkout') === 'test' ? <NewCheckout /> : <OldCheckout />;\n * }\n * ```\n *\n * Waiting shows the fallback until the flags are in, instead of the default then the variant;\n * with server-evaluated flags in `config.bootstrap` it resolves as soon as the library loads.\n * Browser only: it never resolves on the server.\n */\nexport function posthogFlagsReady(timeoutMs = 3000): Promise<void> {\n if (typeof document === 'undefined') return new Promise(() => {});\n flagsReady ??= new Promise<void>((resolve) => {\n setTimeout(resolve, timeoutMs);\n const posthog = getPosthog();\n if (!posthog) return;\n // Queued on the stub; once loaded, called as soon as flags are (or already were) in.\n posthog.onFeatureFlags(() => resolve());\n });\n return flagsReady;\n}\n\nconst metrics = ['CLS', 'FCP', 'FID', 'INP', 'LCP', 'TTFB'];\n\nexport function sendPosthogEvent<T extends EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>\n) {\n // `document`, not `window`: React Native defines `window` as an alias of `global`, so a\n // window check would pass there and then throw on `window.location`, which it has no such\n // alias for.\n if (typeof document === 'undefined') return;\n const posthog = getPosthog();\n if (!posthog) {\n console.warn('posthog has not been initialized');\n return false;\n }\n if (metrics.includes(name)) return;\n if (window.location.host.includes('127.0.0.1')) return;\n if (window.location.host.includes('localhost')) return;\n\n posthog.capture(name, properties);\n}\n\n/**\n * Identifies the visitor to PostHog as the signed-in user, by the user's id — the server's\n * `distinct_id` for the visitor once someone has signed in on it. Only a user: identifying an\n * anonymous visitor by its own id would make PostHog treat it as an identified person, and\n * PostHog does not merge one identified person into another when the user later signs in, so the\n * pre-sign-in events would stay split off.\n *\n * Without a user it is sign-out (`reset()`): PostHog's identity is reset, so the next person on\n * this page starts anonymous instead of merging into the one who left.\n */\nexport function setPosthogUser({ user_id, user_data }: Omit<UpdateVisitorDTO, 'tags'>) {\n const posthog = getPosthog();\n if (!posthog) {\n console.warn('posthog has not been initialized');\n return;\n }\n if (!user_id) {\n posthog.reset();\n return;\n }\n posthog.identify(user_id, { email: getFirst(user_data?.email) });\n}\n\n/**\n * PostHog: every event, for behavior analysis. Loaded with PostHog's HTML snippet, which defines\n * a stub `window.posthog` and fetches the library (`array.js`) asynchronously from PostHog's\n * assets host, so it stays out of the app's bundle; calls made before it loads are queued.\n *\n * `config` is serialized into the snippet's `posthog.init` call, so only its JSON survives:\n * `api_host`, `defaults`, `bootstrap` (server-evaluated flags, so an experiment renders its variant\n * without a flicker), and the other plain options — functions such as `loaded` are dropped.\n */\nexport function posthogAnalytics(options: {\n token: `phc_${string}`;\n config: Partial<PostHogConfig> & { api_host: string };\n}): Integration {\n // Where the snippet loads `array.js` from, by its own rule; a relative `api_host` (a reverse\n // proxy on the site's origin) needs no preconnect.\n const assets = options.config.api_host.replace('.i.posthog.com', '-assets.i.posthog.com');\n // `<` escaped: `config` is arbitrary JSON (a `bootstrap` can carry user data), and a `</script>`\n // inside it would end this inline script early. `\\u003c` parses back to the same value.\n const config = JSON.stringify(options.config).replace(/</g, '\\\\u003c');\n return {\n type: 'analytics',\n track: sendPosthogEvent,\n setUser: setPosthogUser,\n preconnect: URL.canParse(assets) ? [new URL(assets).origin] : [],\n script: {\n id: 'posthog',\n // The stub must exist before hydration, whose effects already track (`page_view`) and\n // identify; it is a few lines, and `array.js` still loads async. PostHog's own Next example\n // does the same.\n strategy: 'beforeInteractive',\n inline: `\n !function(t,e){var o,n,p,r;e.__SV||(window.posthog=e,e._i=[],e.init=function(i,s,a){function g(t,e){var o=e.split(\".\");2==o.length&&(t=t[o[0]],e=o[1]),t[e]=function(){t.push([e].concat(Array.prototype.slice.call(arguments,0)))}}(p=t.createElement(\"script\")).type=\"text/javascript\",p.crossOrigin=\"anonymous\",p.async=!0,p.src=s.api_host.replace(\".i.posthog.com\",\"-assets.i.posthog.com\")+\"/static/array.js\",(r=t.getElementsByTagName(\"script\")[0]).parentNode.insertBefore(p,r);var u=e;for(void 0!==a?u=e[a]=[]:a=\"posthog\",u.people=u.people||[],Object.defineProperty(u,\"toString\",{configurable:!0,enumerable:!0,writable:!0,value:function(t){var e=\"posthog\";return\"posthog\"!==a&&(e+=\".\"+a),t||(e+=\" (stub)\"),e}}),Object.defineProperty(u.people,\"toString\",{configurable:!0,enumerable:!0,writable:!0,value:function(){return u.toString(1)+\".people (stub)\"}}),o=\"init capture register register_once register_for_session unregister unregister_for_session getFeatureFlag getFeatureFlagResult isFeatureEnabled reloadFeatureFlags updateEarlyAccessFeatureEnrollment getEarlyAccessFeatures on onFeatureFlags onSessionId getSurveys getActiveMatchingSurveys renderSurvey canRenderSurvey getNextSurveyStep identify setPersonProperties group resetGroups setPersonPropertiesForFlags resetPersonPropertiesForFlags setGroupPropertiesForFlags resetGroupPropertiesForFlags reset get_distinct_id getGroups get_session_id get_session_replay_url alias set_config startSessionRecording stopSessionRecording sessionRecordingStarted captureException loadToolbar get_property getSessionProperty createPersonProfile opt_in_capturing opt_out_capturing has_opted_in_capturing has_opted_out_capturing clear_opt_in_out_capturing debug\".split(\" \"),n=0;n<o.length;n++)g(u,o[n]);e._i.push([i,s,a])},e.__SV=1)}(document,window.posthog||[]);\n posthog.init(${JSON.stringify(options.token)}, ${config});\n `,\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;AAkBA,SAAgB,aAAkC;CAChD,IAAI,OAAO,aAAa,aAAa,OAAO,KAAA;CAC5C,OAAQ,OAAiC;AAC3C;;;;;;;AAQA,SAAgB,mBAAwC;CACtD,MAAM,UAAU,WAAW;CAC3B,OAA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M,IAAI,CAAC,IAAI,IAAI,MAAM,CAAC,CAAC,MAAM,IAAI,CAAC;EAC/D,QAAQ;GACN,IAAI;GAIJ,UAAU;GACV,QAAQ;;uBAES,KAAK,UAAU,QAAQ,KAAK,EAAE,IAAI,OAAO;;EAE5D;CACF;AACF"}
1
+ {"version":3,"file":"posthog.mjs","names":[],"sources":["../../src/third-parties/posthog.ts"],"sourcesContent":["import type { PostHog, PostHogConfig } from 'posthog-js';\nimport type { UpdateVisitorDTO } from '../schema/index';\nimport type { EventName, TrackName, TrackProperties } from '../track/types';\nimport { getFirst } from '../utils/field';\nimport type { Integration } from './integration';\n\nexport type { PostHog, PostHogConfig } from 'posthog-js';\n\n/**\n * `window.posthog`, for calls that return nothing (`capture`, `identify`, `onFeatureFlags`, …):\n * the snippet's stub until the library loads, which queues them and replays them in order once it\n * has. A method that returns a value returns `undefined` on the stub — use `getLoadedPosthog` for\n * those. `undefined` on the server and before the snippet has run.\n *\n * Read off `window` rather than declared on it, so a host that also has `posthog-js`'s own types\n * does not get two conflicting declarations. Types only: install `posthog-js` (a dev dependency\n * is enough) for them; it is never bundled.\n */\nexport function getPosthog(): PostHog | undefined {\n if (typeof document === 'undefined') return undefined;\n return (window as { posthog?: PostHog }).posthog;\n}\n\n/**\n * The PostHog instance once the library has loaded, for the methods that return a value\n * (`getFeatureFlag`, `isFeatureEnabled`, `get_distinct_id`, …); `undefined` while only the stub is\n * there. To act when flags arrive, subscribe with `getPosthog()?.onFeatureFlags` instead, which\n * the stub queues.\n */\nexport function getLoadedPosthog(): PostHog | undefined {\n const posthog = getPosthog();\n return posthog?.__loaded ? posthog : undefined;\n}\n\nlet flagsReady: Promise<void> | undefined;\n\n/**\n * Resolves once PostHog has loaded its feature flags — or after `timeoutMs` (3 s by default),\n * since an ad blocker that stops the library would otherwise hold it forever; read the flags\n * after it with `useFeatureFlagVariantKey` / `getLoadedPosthog`, which are `undefined` in that\n * case. One promise per page, so React's `use()` can suspend on it:\n *\n * ```tsx\n * function Checkout() {\n * use(browser()); // react-dom: the server renders the <Suspense> fallback instead\n * use(posthogFlagsReady());\n * return useFeatureFlagVariantKey('new-checkout') === 'test' ? <NewCheckout /> : <OldCheckout />;\n * }\n * ```\n *\n * Waiting shows the fallback until the flags are in, instead of the default then the variant;\n * with server-evaluated flags in `config.bootstrap` it resolves as soon as the library loads.\n * Browser only: it never resolves on the server.\n */\nexport function posthogFlagsReady(timeoutMs = 3000): Promise<void> {\n if (typeof document === 'undefined') return new Promise(() => {});\n flagsReady ??= new Promise<void>((resolve) => {\n setTimeout(resolve, timeoutMs);\n const posthog = getPosthog();\n if (!posthog) return;\n // Queued on the stub; once loaded, called as soon as flags are (or already were) in.\n posthog.onFeatureFlags(() => resolve());\n });\n return flagsReady;\n}\n\nconst metrics = ['CLS', 'FCP', 'FID', 'INP', 'LCP', 'TTFB'];\n\nexport function sendPosthogEvent<T extends EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>\n) {\n // `document`, not `window`: React Native defines `window` as an alias of `global`, so a\n // window check would pass there and then throw on `window.location`, which it has no such\n // alias for.\n if (typeof document === 'undefined') return;\n const posthog = getPosthog();\n if (!posthog) {\n console.warn('posthog has not been initialized');\n return false;\n }\n if (metrics.includes(name)) return;\n if (window.location.host.includes('127.0.0.1')) return;\n if (window.location.host.includes('localhost')) return;\n\n posthog.capture(name, properties);\n}\n\n/**\n * Identifies the visitor to PostHog as the signed-in user, by the user's id — the server's\n * `distinct_id` for the visitor once someone has signed in on it. Only a user: identifying an\n * anonymous visitor by its own id would make PostHog treat it as an identified person, and\n * PostHog does not merge one identified person into another when the user later signs in, so the\n * pre-sign-in events would stay split off.\n *\n * Without a user it is sign-out (`reset()`): PostHog's identity is reset, so the next person on\n * this page starts anonymous instead of merging into the one who left.\n */\nexport function setPosthogUser({ user_id, user_data }: Omit<UpdateVisitorDTO, 'tags'>) {\n const posthog = getPosthog();\n if (!posthog) {\n console.warn('posthog has not been initialized');\n return;\n }\n if (!user_id) {\n posthog.reset();\n return;\n }\n posthog.identify(user_id, { email: getFirst(user_data?.email) });\n}\n\n/**\n * PostHog: every event, for behavior analysis. Loaded with PostHog's HTML snippet, which defines\n * a stub `window.posthog` and fetches the library (`array.js`) asynchronously from PostHog's\n * assets host, so it stays out of the app's bundle; calls made before it loads are queued.\n *\n * `config` is serialized into the snippet's `posthog.init` call, so only its JSON survives:\n * `api_host`, `defaults`, `bootstrap` (server-evaluated flags, so an experiment renders its variant\n * without a flicker), and the other plain options — functions such as `loaded` are dropped.\n */\nexport function posthogAnalytics(options: {\n token: `phc_${string}`;\n config: Partial<PostHogConfig> & { api_host: string };\n}): Integration {\n // Where the snippet loads `array.js` from, by its own rule; a relative `api_host` (a reverse\n // proxy on the site's origin) needs no preconnect.\n const assets = options.config.api_host.replace('.i.posthog.com', '-assets.i.posthog.com');\n // `<` escaped: `config` is arbitrary JSON (a `bootstrap` can carry user data), and a `</script>`\n // inside it would end this inline script early. `\\u003c` parses back to the same value.\n const config = JSON.stringify(options.config).replace(/</g, '\\\\u003c');\n return {\n type: 'analytics',\n track: sendPosthogEvent,\n setUser: setPosthogUser,\n preconnect: URL.canParse(assets) ? [new URL(assets).origin] : [],\n script: {\n id: 'posthog',\n // The stub must exist before hydration, whose effects already track (`page_view`) and\n // identify; it is a few lines, and `array.js` still loads async. PostHog's own Next example\n // does the same.\n strategy: 'beforeInteractive',\n inline: `\n !function(t,e){var o,n,p,r;e.__SV||(window.posthog=e,e._i=[],e.init=function(i,s,a){function g(t,e){var o=e.split(\".\");2==o.length&&(t=t[o[0]],e=o[1]),t[e]=function(){t.push([e].concat(Array.prototype.slice.call(arguments,0)))}}(p=t.createElement(\"script\")).type=\"text/javascript\",p.crossOrigin=\"anonymous\",p.async=!0,p.src=s.api_host.replace(\".i.posthog.com\",\"-assets.i.posthog.com\")+\"/static/array.js\",(r=t.getElementsByTagName(\"script\")[0]).parentNode.insertBefore(p,r);var u=e;for(void 0!==a?u=e[a]=[]:a=\"posthog\",u.people=u.people||[],Object.defineProperty(u,\"toString\",{configurable:!0,enumerable:!0,writable:!0,value:function(t){var e=\"posthog\";return\"posthog\"!==a&&(e+=\".\"+a),t||(e+=\" (stub)\"),e}}),Object.defineProperty(u.people,\"toString\",{configurable:!0,enumerable:!0,writable:!0,value:function(){return u.toString(1)+\".people (stub)\"}}),o=\"init capture register register_once register_for_session unregister unregister_for_session getFeatureFlag getFeatureFlagResult isFeatureEnabled reloadFeatureFlags updateEarlyAccessFeatureEnrollment getEarlyAccessFeatures on onFeatureFlags onSessionId getSurveys getActiveMatchingSurveys renderSurvey canRenderSurvey getNextSurveyStep identify setPersonProperties group resetGroups setPersonPropertiesForFlags resetPersonPropertiesForFlags setGroupPropertiesForFlags resetGroupPropertiesForFlags reset get_distinct_id getGroups get_session_id get_session_replay_url alias set_config startSessionRecording stopSessionRecording sessionRecordingStarted captureException loadToolbar get_property getSessionProperty createPersonProfile opt_in_capturing opt_out_capturing has_opted_in_capturing has_opted_out_capturing clear_opt_in_out_capturing debug\".split(\" \"),n=0;n<o.length;n++)g(u,o[n]);e._i.push([i,s,a])},e.__SV=1)}(document,window.posthog||[]);\n posthog.init(${JSON.stringify(options.token)}, ${config});\n `,\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;AAkBA,SAAgB,aAAkC;CAChD,IAAI,OAAO,aAAa,aAAa,OAAO,KAAA;CAC5C,OAAQ,OAAiC;AAC3C;;;;;;;AAQA,SAAgB,mBAAwC;CACtD,MAAM,UAAU,WAAW;CAC3B,OAAO,SAAS,WAAW,UAAU,KAAA;AACvC;AAEA,IAAI;;;;;;;;;;;;;;;;;;;AAoBJ,SAAgB,kBAAkB,YAAY,KAAqB;CACjE,IAAI,OAAO,aAAa,aAAa,OAAO,IAAI,cAAc,CAAC,CAAC;CAChE,eAAe,IAAI,SAAe,YAAY;EAC5C,WAAW,SAAS,SAAS;EAC7B,MAAM,UAAU,WAAW;EAC3B,IAAI,CAAC,SAAS;EAEd,QAAQ,qBAAqB,QAAQ,CAAC;CACx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6
6
  "type": "git",
@@ -1,23 +0,0 @@
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/use-feature-flag.ts
5
- const noop = () => {};
6
- /** Subscribes to flag (re)loads; on the stub the subscription is queued and has no unsubscribe. */
7
- function subscribe(onChange) {
8
- return require_third_parties_posthog.getPosthog()?.onFeatureFlags(onChange) ?? noop;
9
- }
10
- /**
11
- * A PostHog feature flag's value — `true`/`false`, a multivariate flag's variant, or `undefined`
12
- * until PostHog has loaded its flags — re-rendering when they reload (e.g. after `identify`).
13
- * `undefined` on the server and through hydration, so the server markup always matches.
14
- *
15
- * Renders the default first and the variant once flags arrive. To wait for them instead, call
16
- * `use(browser())` and `use(posthogFlagsReady())` above it, under a `<Suspense>`.
17
- */
18
- function useFeatureFlag(key) {
19
- return (0, react.useSyncExternalStore)(subscribe, () => require_third_parties_posthog.getLoadedPosthog()?.getFeatureFlag(key), () => void 0);
20
- }
21
- exports.useFeatureFlag = useFeatureFlag;
22
-
23
- //# sourceMappingURL=use-feature-flag.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"use-feature-flag.cjs","names":["getPosthog","useSyncExternalStore","getLoadedPosthog"],"sources":["../../src/react/use-feature-flag.ts"],"sourcesContent":["import { useSyncExternalStore } from 'react';\nimport { getLoadedPosthog, getPosthog } from '../third-parties/posthog';\n\nconst noop = () => {};\n\n/** Subscribes to flag (re)loads; on the stub the subscription is queued and has no unsubscribe. */\nfunction subscribe(onChange: () => void): () => void {\n const unsubscribe: (() => void) | undefined = getPosthog()?.onFeatureFlags(onChange);\n return unsubscribe ?? noop;\n}\n\n/**\n * A PostHog feature flag's value — `true`/`false`, a multivariate flag's variant, or `undefined`\n * until PostHog has loaded its flags — re-rendering when they reload (e.g. after `identify`).\n * `undefined` on the server and through hydration, so the server markup always matches.\n *\n * Renders the default first and the variant once flags arrive. To wait for them instead, call\n * `use(browser())` and `use(posthogFlagsReady())` above it, under a `<Suspense>`.\n */\nexport function useFeatureFlag(key: string): string | boolean | undefined {\n return useSyncExternalStore(\n subscribe,\n () => getLoadedPosthog()?.getFeatureFlag(key),\n () => undefined\n );\n}\n"],"mappings":";;;;AAGA,MAAM,aAAa,CAAC;;AAGpB,SAAS,UAAU,UAAkC;CAEnD,OAD8CA,8BAAAA,WAAW,CAAC,EAAE,eAAe,QAAQ,KAC7D;AACxB;;;;;;;;;AAUA,SAAgB,eAAe,KAA2C;CACxE,QAAA,GAAOC,MAAAA,qBAAAA,CACL,iBACMC,8BAAAA,iBAAiB,CAAC,EAAE,eAAe,GAAG,SACtC,KAAA,CACR;AACF"}
@@ -1,10 +0,0 @@
1
- /**
2
- * A PostHog feature flag's value — `true`/`false`, a multivariate flag's variant, or `undefined`
3
- * until PostHog has loaded its flags — re-rendering when they reload (e.g. after `identify`).
4
- * `undefined` on the server and through hydration, so the server markup always matches.
5
- *
6
- * Renders the default first and the variant once flags arrive. To wait for them instead, call
7
- * `use(browser())` and `use(posthogFlagsReady())` above it, under a `<Suspense>`.
8
- */
9
- export declare function useFeatureFlag(key: string): string | boolean | undefined;
10
- //# sourceMappingURL=use-feature-flag.d.cts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"use-feature-flag.d.cts","names":[],"sources":["../../src/react/use-feature-flag.ts"],"mappings":";;;;;;;;wBAmBgB,eAAe"}
@@ -1,10 +0,0 @@
1
- /**
2
- * A PostHog feature flag's value — `true`/`false`, a multivariate flag's variant, or `undefined`
3
- * until PostHog has loaded its flags — re-rendering when they reload (e.g. after `identify`).
4
- * `undefined` on the server and through hydration, so the server markup always matches.
5
- *
6
- * Renders the default first and the variant once flags arrive. To wait for them instead, call
7
- * `use(browser())` and `use(posthogFlagsReady())` above it, under a `<Suspense>`.
8
- */
9
- export declare function useFeatureFlag(key: string): string | boolean | undefined;
10
- //# sourceMappingURL=use-feature-flag.d.mts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"use-feature-flag.d.mts","names":[],"sources":["../../src/react/use-feature-flag.ts"],"mappings":";;;;;;;;wBAmBgB,eAAe"}
@@ -1,22 +0,0 @@
1
- import { getLoadedPosthog, getPosthog } from "../third-parties/posthog.mjs";
2
- import { useSyncExternalStore } from "react";
3
- // src/react/use-feature-flag.ts
4
- const noop = () => {};
5
- /** Subscribes to flag (re)loads; on the stub the subscription is queued and has no unsubscribe. */
6
- function subscribe(onChange) {
7
- return getPosthog()?.onFeatureFlags(onChange) ?? noop;
8
- }
9
- /**
10
- * A PostHog feature flag's value — `true`/`false`, a multivariate flag's variant, or `undefined`
11
- * until PostHog has loaded its flags — re-rendering when they reload (e.g. after `identify`).
12
- * `undefined` on the server and through hydration, so the server markup always matches.
13
- *
14
- * Renders the default first and the variant once flags arrive. To wait for them instead, call
15
- * `use(browser())` and `use(posthogFlagsReady())` above it, under a `<Suspense>`.
16
- */
17
- function useFeatureFlag(key) {
18
- return useSyncExternalStore(subscribe, () => getLoadedPosthog()?.getFeatureFlag(key), () => void 0);
19
- }
20
- export { useFeatureFlag };
21
-
22
- //# sourceMappingURL=use-feature-flag.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"use-feature-flag.mjs","names":[],"sources":["../../src/react/use-feature-flag.ts"],"sourcesContent":["import { useSyncExternalStore } from 'react';\nimport { getLoadedPosthog, getPosthog } from '../third-parties/posthog';\n\nconst noop = () => {};\n\n/** Subscribes to flag (re)loads; on the stub the subscription is queued and has no unsubscribe. */\nfunction subscribe(onChange: () => void): () => void {\n const unsubscribe: (() => void) | undefined = getPosthog()?.onFeatureFlags(onChange);\n return unsubscribe ?? noop;\n}\n\n/**\n * A PostHog feature flag's value — `true`/`false`, a multivariate flag's variant, or `undefined`\n * until PostHog has loaded its flags — re-rendering when they reload (e.g. after `identify`).\n * `undefined` on the server and through hydration, so the server markup always matches.\n *\n * Renders the default first and the variant once flags arrive. To wait for them instead, call\n * `use(browser())` and `use(posthogFlagsReady())` above it, under a `<Suspense>`.\n */\nexport function useFeatureFlag(key: string): string | boolean | undefined {\n return useSyncExternalStore(\n subscribe,\n () => getLoadedPosthog()?.getFeatureFlag(key),\n () => undefined\n );\n}\n"],"mappings":";;;AAGA,MAAM,aAAa,CAAC;;AAGpB,SAAS,UAAU,UAAkC;CAEnD,OAD8C,WAAW,CAAC,EAAE,eAAe,QAAQ,KAC7D;AACxB;;;;;;;;;AAUA,SAAgB,eAAe,KAA2C;CACxE,OAAO,qBACL,iBACM,iBAAiB,CAAC,EAAE,eAAe,GAAG,SACtC,KAAA,CACR;AACF"}