@shware/analytics 16.2.0 → 16.2.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/react/posthog-error-boundary.cjs.map +1 -1
- package/dist/react/posthog-error-boundary.d.cts +1 -1
- package/dist/react/posthog-error-boundary.d.mts +1 -1
- package/dist/react/posthog-error-boundary.mjs.map +1 -1
- package/dist/react/posthog.cjs.map +1 -1
- package/dist/react/posthog.d.cts +1 -1
- package/dist/react/posthog.d.cts.map +1 -1
- package/dist/react/posthog.d.mts +1 -1
- package/dist/react/posthog.d.mts.map +1 -1
- package/dist/react/posthog.mjs.map +1 -1
- package/dist/third-parties/google-analytics.cjs +1 -1
- package/dist/third-parties/google-analytics.cjs.map +1 -1
- package/dist/third-parties/google-analytics.mjs +1 -1
- package/dist/third-parties/google-analytics.mjs.map +1 -1
- package/dist/third-parties/integration.cjs.map +1 -1
- package/dist/third-parties/integration.d.cts +5 -1
- package/dist/third-parties/integration.d.cts.map +1 -1
- package/dist/third-parties/integration.d.mts +5 -1
- package/dist/third-parties/integration.d.mts.map +1 -1
- package/dist/third-parties/integration.mjs.map +1 -1
- package/dist/third-parties/posthog.cjs +3 -3
- package/dist/third-parties/posthog.cjs.map +1 -1
- package/dist/third-parties/posthog.d.cts +3 -3
- package/dist/third-parties/posthog.d.mts +3 -3
- package/dist/third-parties/posthog.mjs +3 -3
- package/dist/third-parties/posthog.mjs.map +1 -1
- package/package.json +2 -5
package/README.md
CHANGED
|
@@ -130,7 +130,7 @@ With server-evaluated flags, skip the wait: pass them in `config.bootstrap` and
|
|
|
130
130
|
|
|
131
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
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
|
|
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/types`, PostHog's types-only package for the snippet, a dependency of this one: the host does not install `posthog-js` 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`).
|
|
134
134
|
|
|
135
135
|
`getHeaders` is also accepted, for a backend that wants extra headers on the analytics requests.
|
|
136
136
|
|
|
@@ -1 +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
|
|
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/types';\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"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { Component, ErrorInfo, FunctionComponent, ReactNode } from "react";
|
|
2
|
-
import { CaptureResult, Properties } from "posthog
|
|
2
|
+
import { CaptureResult, Properties } from "@posthog/types";
|
|
3
3
|
export interface PosthogErrorBoundaryFallbackProps {
|
|
4
4
|
error: unknown;
|
|
5
5
|
/** The `$exception` event sent; `undefined` while only the stub is there, which queues it. */
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { Component, ErrorInfo, FunctionComponent, ReactNode } from "react";
|
|
2
|
-
import { CaptureResult, Properties } from "posthog
|
|
2
|
+
import { CaptureResult, Properties } from "@posthog/types";
|
|
3
3
|
export interface PosthogErrorBoundaryFallbackProps {
|
|
4
4
|
error: unknown;
|
|
5
5
|
/** The `$exception` event sent; `undefined` while only the stub is there, which queues it. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"posthog-error-boundary.mjs","names":[],"sources":["../../src/react/posthog-error-boundary.tsx"],"sourcesContent":["import type { CaptureResult, Properties } from 'posthog
|
|
1
|
+
{"version":3,"file":"posthog-error-boundary.mjs","names":[],"sources":["../../src/react/posthog-error-boundary.tsx"],"sourcesContent":["import type { CaptureResult, Properties } from '@posthog/types';\nimport {\n Component,\n type ErrorInfo,\n type FunctionComponent,\n type ReactNode,\n isValidElement,\n} from 'react';\nimport { getPosthog } from '../third-parties/posthog';\n\nexport interface PosthogErrorBoundaryFallbackProps {\n error: unknown;\n /** The `$exception` event sent; `undefined` while only the stub is there, which queues it. */\n exceptionEvent: CaptureResult | undefined;\n componentStack: string;\n resetError: () => void;\n}\n\nexport interface PosthogErrorBoundaryProps {\n children?: ReactNode | (() => ReactNode);\n fallback?: ReactNode | FunctionComponent<PosthogErrorBoundaryFallbackProps>;\n additionalProperties?: Properties | ((error: unknown, errorInfo: ErrorInfo) => Properties);\n}\n\ninterface State {\n error: unknown;\n componentStack: string | null;\n exceptionEvent: CaptureResult | undefined;\n}\n\nconst INITIAL_STATE: State = { error: null, componentStack: null, exceptionEvent: undefined };\n\n/**\n * The error as PostHog's own boundary reports it: the React component stack added as a cause, so\n * the issue shows which components it was thrown in.\n */\nfunction withComponentStack(error: unknown, componentStack: string | null | undefined): unknown {\n if (!componentStack) return error;\n const isError = error instanceof Error;\n const stackError = new Error(\n isError ? error.message : `Primitive value captured as exception: ${String(error)}`\n );\n stackError.name = `React ErrorBoundary ${isError ? error.name : 'Error'}`;\n stackError.stack = componentStack;\n if (!isError) return stackError;\n // At the end of the error's cause chain, keeping a last cause that is not an error under it.\n const seen = new WeakSet<Error>();\n let current = error;\n while (!seen.has(current)) {\n seen.add(current);\n if (!(current.cause instanceof Error)) {\n if (current.cause !== undefined) stackError.cause = current.cause;\n current.cause = stackError;\n break;\n }\n current = current.cause;\n }\n return error;\n}\n\n/**\n * `posthog-js/react`'s `PostHogErrorBoundary`, with its props, for the snippet-loaded library: a\n * render error in `children` is sent to PostHog's error tracking (`captureException`, as an\n * `$exception` event tied to the session's replay) and `fallback` renders instead — a\n * component gets the error and `resetError`. An error thrown before the library has loaded is\n * queued on the stub and sent once it has.\n *\n * The boundary itself never throws: a failure to report (no PostHog, an ad blocker that stopped the\n * library, a throwing `additionalProperties`) is logged and the fallback still renders. It\n * catches render errors only, as any error boundary; errors outside React's render (event\n * handlers, unhandled rejections) are the library's exception autocapture's, enabled in the\n * snippet's `config` (`capture_exceptions`).\n */\nexport class PosthogErrorBoundary extends Component<PosthogErrorBoundaryProps, State> {\n override state = INITIAL_STATE;\n\n override componentDidCatch(error: unknown, errorInfo: ErrorInfo) {\n const componentStack = errorInfo.componentStack ?? '';\n let exceptionEvent: CaptureResult | undefined;\n // Reporting must never fail the boundary: an error thrown here would go to the boundary\n // above it, if any — `additionalProperties` throwing, or an error that cannot take a cause.\n try {\n const { additionalProperties } = this.props;\n const properties =\n typeof additionalProperties === 'function'\n ? additionalProperties(error, errorInfo)\n : additionalProperties;\n exceptionEvent = getPosthog()?.captureException(\n withComponentStack(error, componentStack),\n properties\n );\n } catch (e: unknown) {\n console.error('PosthogErrorBoundary: the error was not reported', e);\n }\n this.setState({ error, componentStack, exceptionEvent });\n }\n\n resetError = () => {\n this.setState(INITIAL_STATE);\n };\n\n override render() {\n const { children, fallback } = this.props;\n const { error, componentStack, exceptionEvent } = this.state;\n if (componentStack === null) return typeof children === 'function' ? children() : children;\n\n const element =\n typeof fallback === 'function'\n ? fallback({ error, componentStack, exceptionEvent, resetError: this.resetError })\n : fallback;\n if (isValidElement(element)) return element;\n console.warn('PosthogErrorBoundary: fallback is not a React element; rendering nothing');\n return null;\n }\n}\n\n/**\n * `posthog-js/react`'s `setupReactErrorHandler`, for the snippet-loaded library, so without its\n * `client`: a handler for React 19's root options, which report what no `PosthogErrorBoundary`\n * sees — `onUncaughtError` (no boundary caught it), `onCaughtError` (a framework's boundary did,\n * e.g. TanStack Router's `errorComponent`) and `onRecoverableError` (a hydration mismatch React\n * recovered from). The error goes to PostHog with its component stack; `callback` gets the event\n * (`undefined` while only the stub is there), as React's own logging does not run once a handler\n * is set.\n *\n * ```tsx\n * hydrateRoot(document, <StartClient />, {\n * onUncaughtError: setupReactErrorHandler(),\n * onCaughtError: setupReactErrorHandler(),\n * onRecoverableError: setupReactErrorHandler(),\n * });\n * ```\n *\n * Never throws, as `PosthogErrorBoundary`: a failure to report is logged.\n */\nexport function setupReactErrorHandler(\n callback?: (event: CaptureResult | undefined, error: unknown, errorInfo: ErrorInfo) => void\n): (error: unknown, errorInfo: ErrorInfo) => void {\n return (error, errorInfo) => {\n let event: CaptureResult | undefined;\n try {\n event = getPosthog()?.captureException(withComponentStack(error, errorInfo.componentStack));\n } catch (e: unknown) {\n console.error('setupReactErrorHandler: the error was not reported', e);\n }\n callback?.(event, error, errorInfo);\n };\n}\n"],"mappings":";;;AA8BA,MAAM,gBAAuB;CAAE,OAAO;CAAM,gBAAgB;CAAM,gBAAgB,KAAA;AAAU;;;;;AAM5F,SAAS,mBAAmB,OAAgB,gBAAoD;CAC9F,IAAI,CAAC,gBAAgB,OAAO;CAC5B,MAAM,UAAU,iBAAiB;CACjC,MAAM,aAAa,IAAI,MACrB,UAAU,MAAM,UAAU,0CAA0C,OAAO,KAAK,GAClF;CACA,WAAW,OAAO,uBAAuB,UAAU,MAAM,OAAO;CAChE,WAAW,QAAQ;CACnB,IAAI,CAAC,SAAS,OAAO;CAErB,MAAM,uBAAO,IAAI,QAAe;CAChC,IAAI,UAAU;CACd,OAAO,CAAC,KAAK,IAAI,OAAO,GAAG;EACzB,KAAK,IAAI,OAAO;EAChB,IAAI,EAAE,QAAQ,iBAAiB,QAAQ;GACrC,IAAI,QAAQ,UAAU,KAAA,GAAW,WAAW,QAAQ,QAAQ;GAC5D,QAAQ,QAAQ;GAChB;EACF;EACA,UAAU,QAAQ;CACpB;CACA,OAAO;AACT;;;;;;;;;;;;;;AAeA,IAAa,uBAAb,cAA0C,UAA4C;;;EACnE,KAAA,QAAA;EAuBE,KAAA,mBAAA;GACjB,KAAK,SAAS,aAAa;EAC7B;;CAvBA,kBAA2B,OAAgB,WAAsB;EAC/D,MAAM,iBAAiB,UAAU,kBAAkB;EACnD,IAAI;EAGJ,IAAI;GACF,MAAM,EAAE,yBAAyB,KAAK;GACtC,MAAM,aACJ,OAAO,yBAAyB,aAC5B,qBAAqB,OAAO,SAAS,IACrC;GACN,iBAAiB,WAAW,CAAC,EAAE,iBAC7B,mBAAmB,OAAO,cAAc,GACxC,UACF;EACF,SAAS,GAAY;GACnB,QAAQ,MAAM,oDAAoD,CAAC;EACrE;EACA,KAAK,SAAS;GAAE;GAAO;GAAgB;EAAe,CAAC;CACzD;CAMA,SAAkB;EAChB,MAAM,EAAE,UAAU,aAAa,KAAK;EACpC,MAAM,EAAE,OAAO,gBAAgB,mBAAmB,KAAK;EACvD,IAAI,mBAAmB,MAAM,OAAO,OAAO,aAAa,aAAa,SAAS,IAAI;EAElF,MAAM,UACJ,OAAO,aAAa,aAChB,SAAS;GAAE;GAAO;GAAgB;GAAgB,YAAY,KAAK;EAAW,CAAC,IAC/E;EACN,IAAI,eAAe,OAAO,GAAG,OAAO;EACpC,QAAQ,KAAK,0EAA0E;EACvF,OAAO;CACT;AACF;;;;;;;;;;;;;;;;;;;;AAqBA,SAAgB,uBACd,UACgD;CAChD,QAAQ,OAAO,cAAc;EAC3B,IAAI;EACJ,IAAI;GACF,QAAQ,WAAW,CAAC,EAAE,iBAAiB,mBAAmB,OAAO,UAAU,cAAc,CAAC;EAC5F,SAAS,GAAY;GACnB,QAAQ,MAAM,sDAAsD,CAAC;EACvE;EACA,WAAW,OAAO,OAAO,SAAS;CACpC;AACF"}
|
|
@@ -1 +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
|
|
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/types';\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 * The loaded library's flag state, which `posthog-js/react` reads too: on the instance, but left\n * out of `@posthog/types`, whose `featureFlags` declares only the override methods.\n */\ntype LoadedPostHog = PostHog & {\n featureFlags: { hasLoadedFlags: boolean; getFlags(): string[] };\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: LoadedPostHog) => 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() as LoadedPostHog | undefined;\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;;;;;;AAeA,SAAS,SAAY,MAAqC,cAAoB;CAC5E,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,yBAAyB,MAA4C;CACnF,MAAM,gBAAA,GAAeC,MAAAA,IAAAA,CAAI,SAAS,CAAC,EAAE,eAAe;CACpD,OAAO,UAAU,YAAY,QAAQ,eAAe,IAAI,GAAG,YAAY;AACzE;AAKA,SAAgB,sBAAsB,MAAc,cAAwB;CAC1E,MAAM,SAAA,GAAQA,MAAAA,IAAAA,CAAI,SAAS,CAAC,EAAE,eAAe;CAE7C,OAAO,UAAU,YAAY,QAAQ,iBAAiB,IAAI,GADrC,UAAU,KAAA,IAAY,KAAA,IAAY,CAAC,CAAC,KACgB,KAAK;AAChF;;AAGA,SAAgB,sBAAsB,MAAwB;CAC5D,MAAM,gBAAA,GAAeA,MAAAA,IAAAA,CAAI,SAAS,CAAC,EAAE,sBAAsB;CAC3D,OAAO,UACJ,YAAY,QAAQ,qBAAqB,MAAM,EAAE,YAAY,MAAM,CAAC,CAAC,EAAE,SACxE,YACF;AACF;;AAGA,SAAgB,qBAAqB,MAA6C;CAChF,MAAM,aAAA,GAAYA,MAAAA,IAAAA,CAAI,SAAS;CAC/B,MAAM,QAAQ,WAAW,eAAe;CAUxC,OAAO,UAAU,YAAY,QAAQ,qBAAqB,IAAI,GAR5D,UAAU,KAAA,IACN,KAAA,IACA;EACE,KAAK;EACL,SAAS,OAAO,UAAU,WAAW,OAAO;EAC5C,SAAS,OAAO,UAAU,WAAW,QAAQ,KAAA;EAC7C,SAAS,WAAW,sBAAsB;CAC5C,CACuE;AAC/E;;;;;AAMA,SAAgB,wBAAkC;CAChD,MAAM,SAAA,GAAQA,MAAAA,IAAAA,CAAI,SAAS,CAAC,EAAE,gBAAgB,CAAC;CAE/C,OAAO,UAAU,YAAY,QAAQ,aAAa,SAAS,GADtC,OAAO,KAAK,KAAK,CAAC,CAAC,QAAQ,QAAQ,MAAM,IACW,CAAC;AAC5E;;;;;;;;;;;;AAaA,SAAgB,aAAkC;CAChD,QAAA,GAAOF,MAAAA,qBAAAA,CAAqB,WAAWF,8BAAAA,kBAAkB,KAAA,CAAS;AACpE"}
|
package/dist/react/posthog.d.cts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { ReactNode } from "react";
|
|
2
|
-
import { BootstrapConfig, FeatureFlagResult, JsonType, PostHog } from "posthog
|
|
2
|
+
import { BootstrapConfig, FeatureFlagResult, JsonType, PostHog } from "@posthog/types";
|
|
3
3
|
/**
|
|
4
4
|
* The counterpart of `posthog-js/react`'s `PostHogProvider`, for the snippet-loaded library. It
|
|
5
5
|
* does not initialize PostHog — `posthogAnalytics` does — only carries what the hooks need from
|
|
@@ -1 +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;;
|
|
1
|
+
{"version":3,"file":"posthog.d.cts","names":[],"sources":["../../src/react/posthog.ts"],"mappings":";;;;;;;;;;wBAuBgB,kBACd,WACA;EAEA,WAAW;EACX,UAAU;oBACX,yCAAA,cAAA;;wBAwDe,yBAAyB;;wBAMzB,sBAAsB;wBACtB,sBAAsB,cAAc;;wBAQpC,sBAAsB,eAAe;;wBASrC,qBAAqB,eAAe;;;;;wBAmBpC;;;;;;;;;;;;wBAiBA,cAAc"}
|
package/dist/react/posthog.d.mts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { ReactNode } from "react";
|
|
2
|
-
import { BootstrapConfig, FeatureFlagResult, JsonType, PostHog } from "posthog
|
|
2
|
+
import { BootstrapConfig, FeatureFlagResult, JsonType, PostHog } from "@posthog/types";
|
|
3
3
|
/**
|
|
4
4
|
* The counterpart of `posthog-js/react`'s `PostHogProvider`, for the snippet-loaded library. It
|
|
5
5
|
* does not initialize PostHog — `posthogAnalytics` does — only carries what the hooks need from
|
|
@@ -1 +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;;
|
|
1
|
+
{"version":3,"file":"posthog.d.mts","names":[],"sources":["../../src/react/posthog.ts"],"mappings":";;;;;;;;;;wBAuBgB,kBACd,WACA;EAEA,WAAW;EACX,UAAU;oBACX,yCAAA,cAAA;;wBAwDe,yBAAyB;;wBAMzB,sBAAsB;wBACtB,sBAAsB,cAAc;;wBAQpC,sBAAsB,eAAe;;wBASrC,qBAAqB,eAAe;;;;;wBAmBpC;;;;;;;;;;;;wBAiBA,cAAc"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"posthog.mjs","names":[],"sources":["../../src/react/posthog.ts"],"sourcesContent":["import type { BootstrapConfig, FeatureFlagResult, JsonType, PostHog } from 'posthog
|
|
1
|
+
{"version":3,"file":"posthog.mjs","names":[],"sources":["../../src/react/posthog.ts"],"sourcesContent":["import type { BootstrapConfig, FeatureFlagResult, JsonType, PostHog } from '@posthog/types';\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 * The loaded library's flag state, which `posthog-js/react` reads too: on the instance, but left\n * out of `@posthog/types`, whose `featureFlags` declares only the override methods.\n */\ntype LoadedPostHog = PostHog & {\n featureFlags: { hasLoadedFlags: boolean; getFlags(): string[] };\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: LoadedPostHog) => 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() as LoadedPostHog | undefined;\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;;;;;;AAeA,SAAS,SAAY,MAAqC,cAAoB;CAC5E,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;CACA,OAAO,qBACL,iBACM;EACJ,MAAM,UAAU,iBAAiB;EAGjC,OAAO,OAAO,SAAS,aAAa,iBAAiB,KAAK,OAAO,IAAI,YAAY;CACnF,SACM,OAAO,YAAY,CAC3B;AACF;;AAeA,SAAgB,yBAAyB,MAA4C;CACnF,MAAM,eAAe,IAAI,SAAS,CAAC,EAAE,eAAe;CACpD,OAAO,UAAU,YAAY,QAAQ,eAAe,IAAI,GAAG,YAAY;AACzE;AAKA,SAAgB,sBAAsB,MAAc,cAAwB;CAC1E,MAAM,QAAQ,IAAI,SAAS,CAAC,EAAE,eAAe;CAE7C,OAAO,UAAU,YAAY,QAAQ,iBAAiB,IAAI,GADrC,UAAU,KAAA,IAAY,KAAA,IAAY,CAAC,CAAC,KACgB,KAAK;AAChF;;AAGA,SAAgB,sBAAsB,MAAwB;CAC5D,MAAM,eAAe,IAAI,SAAS,CAAC,EAAE,sBAAsB;CAC3D,OAAO,UACJ,YAAY,QAAQ,qBAAqB,MAAM,EAAE,YAAY,MAAM,CAAC,CAAC,EAAE,SACxE,YACF;AACF;;AAGA,SAAgB,qBAAqB,MAA6C;CAChF,MAAM,YAAY,IAAI,SAAS;CAC/B,MAAM,QAAQ,WAAW,eAAe;CAUxC,OAAO,UAAU,YAAY,QAAQ,qBAAqB,IAAI,GAR5D,UAAU,KAAA,IACN,KAAA,IACA;EACE,KAAK;EACL,SAAS,OAAO,UAAU,WAAW,OAAO;EAC5C,SAAS,OAAO,UAAU,WAAW,QAAQ,KAAA;EAC7C,SAAS,WAAW,sBAAsB;CAC5C,CACuE;AAC/E;;;;;AAMA,SAAgB,wBAAkC;CAChD,MAAM,QAAQ,IAAI,SAAS,CAAC,EAAE,gBAAgB,CAAC;CAE/C,OAAO,UAAU,YAAY,QAAQ,aAAa,SAAS,GADtC,OAAO,KAAK,KAAK,CAAC,CAAC,QAAQ,QAAQ,MAAM,IACW,CAAC;AAC5E;;;;;;;;;;;;AAaA,SAAgB,aAAkC;CAChD,OAAO,qBAAqB,WAAW,kBAAkB,KAAA,CAAS;AACpE"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"google-analytics.cjs","names":[],"sources":["../../src/third-parties/google-analytics.ts"],"sourcesContent":["import type { UpdateVisitorDTO } from '../schema/index';\nimport type { GaId, Gtag } from '../track/gtag';\nimport type { EventName, TrackName, TrackProperties } from '../track/types';\nimport type { Integration } from './integration';\n\ndeclare global {\n interface Window {\n /** Undefined until the Google tag (gtag.js) script has loaded. */\n gtag?: Gtag['gtag'];\n }\n}\n\nexport function sendGAEvent<T extends EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>\n) {\n if (typeof window === 'undefined' || !window.gtag) {\n console.warn('GA has not been initialized');\n return false;\n }\n window.gtag('event', name, properties);\n}\n\nexport function setGAUser({ user_id, user_data }: UpdateVisitorDTO) {\n if (typeof window === 'undefined' || !window.gtag) {\n console.warn('GA has not been initialized');\n return;\n }\n // No user is sign-out (`reset()`): GA keeps a set user_id for every later event on the page, so\n // it is cleared explicitly.\n window.gtag('set', 'user_id', user_id || null);\n if (user_data) window.gtag('set', 'user_data', user_data);\n}\n\n/**\n * Google Analytics 4 (gtag.js): every event, for behavior analysis. `src` serves gtag.js from\n * another path (a first-party proxy); `debug` turns on GA4's DebugView for this page.\n */\nexport function googleAnalytics(options: { id: GaId; src?: string; debug?: boolean }): Integration {\n const src = options.src ?? `https://www.googletagmanager.com/gtag/js?id=${options.id}`;\n return {\n type: 'analytics',\n track: sendGAEvent,\n setUser: setGAUser,\n script: {\n id: '
|
|
1
|
+
{"version":3,"file":"google-analytics.cjs","names":[],"sources":["../../src/third-parties/google-analytics.ts"],"sourcesContent":["import type { UpdateVisitorDTO } from '../schema/index';\nimport type { GaId, Gtag } from '../track/gtag';\nimport type { EventName, TrackName, TrackProperties } from '../track/types';\nimport type { Integration } from './integration';\n\ndeclare global {\n interface Window {\n /** Undefined until the Google tag (gtag.js) script has loaded. */\n gtag?: Gtag['gtag'];\n }\n}\n\nexport function sendGAEvent<T extends EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>\n) {\n if (typeof window === 'undefined' || !window.gtag) {\n console.warn('GA has not been initialized');\n return false;\n }\n window.gtag('event', name, properties);\n}\n\nexport function setGAUser({ user_id, user_data }: UpdateVisitorDTO) {\n if (typeof window === 'undefined' || !window.gtag) {\n console.warn('GA has not been initialized');\n return;\n }\n // No user is sign-out (`reset()`): GA keeps a set user_id for every later event on the page, so\n // it is cleared explicitly.\n window.gtag('set', 'user_id', user_id || null);\n if (user_data) window.gtag('set', 'user_data', user_data);\n}\n\n/**\n * Google Analytics 4 (gtag.js): every event, for behavior analysis. `src` serves gtag.js from\n * another path (a first-party proxy); `debug` turns on GA4's DebugView for this page.\n */\nexport function googleAnalytics(options: { id: GaId; src?: string; debug?: boolean }): Integration {\n const src = options.src ?? `https://www.googletagmanager.com/gtag/js?id=${options.id}`;\n return {\n type: 'analytics',\n track: sendGAEvent,\n setUser: setGAUser,\n script: {\n id: 'google-analytics',\n inline: `\n window.dataLayer = window.dataLayer || [];\n function gtag(){dataLayer.push(arguments);}\n gtag('js', new Date());\n gtag('config', ${JSON.stringify(options.id)}${options.debug ? ', { debug_mode: true }' : ''});\n (function (d, s, u) {\n var j = d.createElement(s);\n j.async = true;\n // A script added here does not inherit the nonce: hand it this one's, or a CSP that\n // allows scripts by nonce (without 'strict-dynamic') blocks gtag.js.\n j.nonce = d.currentScript && d.currentScript.nonce;\n j.src = u;\n var f = d.getElementsByTagName(s)[0];\n f.parentNode.insertBefore(j, f);\n })(document, 'script', ${JSON.stringify(src)});\n `,\n },\n };\n}\n"],"mappings":";;AAYA,SAAgB,YACd,MACA,YACA;CACA,IAAI,OAAO,WAAW,eAAe,CAAC,OAAO,MAAM;EACjD,QAAQ,KAAK,6BAA6B;EAC1C,OAAO;CACT;CACA,OAAO,KAAK,SAAS,MAAM,UAAU;AACvC;AAEA,SAAgB,UAAU,EAAE,SAAS,aAA+B;CAClE,IAAI,OAAO,WAAW,eAAe,CAAC,OAAO,MAAM;EACjD,QAAQ,KAAK,6BAA6B;EAC1C;CACF;CAGA,OAAO,KAAK,OAAO,WAAW,WAAW,IAAI;CAC7C,IAAI,WAAW,OAAO,KAAK,OAAO,aAAa,SAAS;AAC1D;;;;;AAMA,SAAgB,gBAAgB,SAAmE;CACjG,MAAM,MAAM,QAAQ,OAAO,+CAA+C,QAAQ;CAClF,OAAO;EACL,MAAM;EACN,OAAO;EACP,SAAS;EACT,QAAQ;GACN,IAAI;GACJ,QAAQ;;;;yBAIW,KAAK,UAAU,QAAQ,EAAE,IAAI,QAAQ,QAAQ,2BAA2B,GAAG;;;;;;;;;;iCAUnE,KAAK,UAAU,GAAG,EAAE;;EAEjD;CACF;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"google-analytics.mjs","names":[],"sources":["../../src/third-parties/google-analytics.ts"],"sourcesContent":["import type { UpdateVisitorDTO } from '../schema/index';\nimport type { GaId, Gtag } from '../track/gtag';\nimport type { EventName, TrackName, TrackProperties } from '../track/types';\nimport type { Integration } from './integration';\n\ndeclare global {\n interface Window {\n /** Undefined until the Google tag (gtag.js) script has loaded. */\n gtag?: Gtag['gtag'];\n }\n}\n\nexport function sendGAEvent<T extends EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>\n) {\n if (typeof window === 'undefined' || !window.gtag) {\n console.warn('GA has not been initialized');\n return false;\n }\n window.gtag('event', name, properties);\n}\n\nexport function setGAUser({ user_id, user_data }: UpdateVisitorDTO) {\n if (typeof window === 'undefined' || !window.gtag) {\n console.warn('GA has not been initialized');\n return;\n }\n // No user is sign-out (`reset()`): GA keeps a set user_id for every later event on the page, so\n // it is cleared explicitly.\n window.gtag('set', 'user_id', user_id || null);\n if (user_data) window.gtag('set', 'user_data', user_data);\n}\n\n/**\n * Google Analytics 4 (gtag.js): every event, for behavior analysis. `src` serves gtag.js from\n * another path (a first-party proxy); `debug` turns on GA4's DebugView for this page.\n */\nexport function googleAnalytics(options: { id: GaId; src?: string; debug?: boolean }): Integration {\n const src = options.src ?? `https://www.googletagmanager.com/gtag/js?id=${options.id}`;\n return {\n type: 'analytics',\n track: sendGAEvent,\n setUser: setGAUser,\n script: {\n id: '
|
|
1
|
+
{"version":3,"file":"google-analytics.mjs","names":[],"sources":["../../src/third-parties/google-analytics.ts"],"sourcesContent":["import type { UpdateVisitorDTO } from '../schema/index';\nimport type { GaId, Gtag } from '../track/gtag';\nimport type { EventName, TrackName, TrackProperties } from '../track/types';\nimport type { Integration } from './integration';\n\ndeclare global {\n interface Window {\n /** Undefined until the Google tag (gtag.js) script has loaded. */\n gtag?: Gtag['gtag'];\n }\n}\n\nexport function sendGAEvent<T extends EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>\n) {\n if (typeof window === 'undefined' || !window.gtag) {\n console.warn('GA has not been initialized');\n return false;\n }\n window.gtag('event', name, properties);\n}\n\nexport function setGAUser({ user_id, user_data }: UpdateVisitorDTO) {\n if (typeof window === 'undefined' || !window.gtag) {\n console.warn('GA has not been initialized');\n return;\n }\n // No user is sign-out (`reset()`): GA keeps a set user_id for every later event on the page, so\n // it is cleared explicitly.\n window.gtag('set', 'user_id', user_id || null);\n if (user_data) window.gtag('set', 'user_data', user_data);\n}\n\n/**\n * Google Analytics 4 (gtag.js): every event, for behavior analysis. `src` serves gtag.js from\n * another path (a first-party proxy); `debug` turns on GA4's DebugView for this page.\n */\nexport function googleAnalytics(options: { id: GaId; src?: string; debug?: boolean }): Integration {\n const src = options.src ?? `https://www.googletagmanager.com/gtag/js?id=${options.id}`;\n return {\n type: 'analytics',\n track: sendGAEvent,\n setUser: setGAUser,\n script: {\n id: 'google-analytics',\n inline: `\n window.dataLayer = window.dataLayer || [];\n function gtag(){dataLayer.push(arguments);}\n gtag('js', new Date());\n gtag('config', ${JSON.stringify(options.id)}${options.debug ? ', { debug_mode: true }' : ''});\n (function (d, s, u) {\n var j = d.createElement(s);\n j.async = true;\n // A script added here does not inherit the nonce: hand it this one's, or a CSP that\n // allows scripts by nonce (without 'strict-dynamic') blocks gtag.js.\n j.nonce = d.currentScript && d.currentScript.nonce;\n j.src = u;\n var f = d.getElementsByTagName(s)[0];\n f.parentNode.insertBefore(j, f);\n })(document, 'script', ${JSON.stringify(src)});\n `,\n },\n };\n}\n"],"mappings":";AAYA,SAAgB,YACd,MACA,YACA;CACA,IAAI,OAAO,WAAW,eAAe,CAAC,OAAO,MAAM;EACjD,QAAQ,KAAK,6BAA6B;EAC1C,OAAO;CACT;CACA,OAAO,KAAK,SAAS,MAAM,UAAU;AACvC;AAEA,SAAgB,UAAU,EAAE,SAAS,aAA+B;CAClE,IAAI,OAAO,WAAW,eAAe,CAAC,OAAO,MAAM;EACjD,QAAQ,KAAK,6BAA6B;EAC1C;CACF;CAGA,OAAO,KAAK,OAAO,WAAW,WAAW,IAAI;CAC7C,IAAI,WAAW,OAAO,KAAK,OAAO,aAAa,SAAS;AAC1D;;;;;AAMA,SAAgB,gBAAgB,SAAmE;CACjG,MAAM,MAAM,QAAQ,OAAO,+CAA+C,QAAQ;CAClF,OAAO;EACL,MAAM;EACN,OAAO;EACP,SAAS;EACT,QAAQ;GACN,IAAI;GACJ,QAAQ;;;;yBAIW,KAAK,UAAU,QAAQ,EAAE,IAAI,QAAQ,QAAQ,2BAA2B,GAAG;;;;;;;;;;iCAUnE,KAAK,UAAU,GAAG,EAAE;;EAEjD;CACF;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"integration.cjs","names":[],"sources":["../../src/third-parties/integration.ts"],"sourcesContent":["import type { EventName, ThirdPartyTracker, TrackName } from '../track/types';\nimport type { ThirdPartyUserSetter } from '../visitor/types';\n\n/**\n * The one script an integration puts on the page, rendered by `<Analytics integrations>`\n * (react, next) with the request's `nonce`: an inline snippet that loads the\n * vendor's own script from its host, as every vendor's official snippet does.\n */\nexport interface IntegrationScript {\n
|
|
1
|
+
{"version":3,"file":"integration.cjs","names":[],"sources":["../../src/third-parties/integration.ts"],"sourcesContent":["import type { EventName, ThirdPartyTracker, TrackName } from '../track/types';\nimport type { ThirdPartyUserSetter } from '../visitor/types';\n\n/**\n * The one script an integration puts on the page, rendered by `<Analytics integrations>`\n * (react, next) with the request's `nonce`: an inline snippet that loads the\n * vendor's own script from its host, as every vendor's official snippet does.\n */\nexport interface IntegrationScript {\n /**\n * The element id; also its React key, and how a test or a CSP report finds it. Never a global's\n * name: an element's id is readable as `window[id]` until a script defines it, so an id like\n * `posthog` hands the snippet's `window.posthog || []` the <script> element. Keep a hyphen in it.\n */\n readonly id: string;\n readonly inline: string;\n /** `next/script`'s loading strategy, `afterInteractive` by default; the other frameworks ignore it. */\n readonly strategy?: 'beforeInteractive' | 'afterInteractive' | 'lazyOnload';\n}\n\n/**\n * One third party, configured in one place: how events reach it, how it learns the signed-in\n * user, and the script it needs. Built by the factories in `@shware/analytics/third-parties`\n * (`googleAnalytics`, `metaAds`, …) and handed to both `setupAnalytics({ integrations })` and\n * `<Analytics integrations>`. A host can write its own for a platform the SDK does not cover.\n *\n * `type` says what the platform is for. An `analytics` integration (GA4, PostHog) receives every\n * event, for behavior analysis. An `ads` integration receives only what helps an ad platform\n * optimize and build audiences — the conversion events it maps to its own standard events, plus\n * the custom events it was explicitly given — and filters in its own `track`.\n */\nexport interface Integration {\n readonly type: 'analytics' | 'ads';\n readonly track: ThirdPartyTracker;\n readonly setUser?: ThirdPartyUserSetter;\n readonly script?: IntegrationScript;\n /**\n * Origins `<Analytics>` preconnects to (`react-dom`'s `preconnect`), so the connection is up\n * before the script asks for something there — e.g. where a snippet loads its library from.\n */\n readonly preconnect?: readonly string[];\n}\n\n/**\n * The GA4 recommended events that are conversions or close to one, for an ad platform with no\n * standard events of its own to map to (Microsoft UET), so it is not sent the whole product.\n */\nexport const CONVERSION_EVENTS = [\n 'sign_up',\n 'login',\n 'generate_lead',\n 'view_item',\n 'add_to_cart',\n 'add_to_wishlist',\n 'begin_checkout',\n 'add_payment_info',\n 'purchase',\n 'subscribe',\n 'trial_begin',\n 'search',\n 'schedule',\n 'submit_application',\n 'contact',\n] as const satisfies readonly EventName[];\n\nexport interface AdsOptions {\n /**\n * Custom events this platform receives besides the conversions it maps to its standard\n * events, e.g. one used as an optimization goal or for an audience. Everything else is not\n * sent to it. The names `track` accepts, so with strict event names a typo is a compile error.\n */\n customEvents?: readonly TrackName[];\n}\n\n/**\n * Which events an ad platform receives: what `isStandard` accepts — the events its mapper turns\n * into one of its standard events — and the custom events the host listed. Everything else in the\n * product (feature use, clicks, onboarding steps) is behavior analysis, which is GA4's and\n * PostHog's job, and only noise to an ad platform's optimization. The same rule picks what the\n * browser tag and the platform's conversions API send (`@shware/analytics/server`), so the two\n * report the same events.\n */\nexport function adEvents(\n isStandard: (name: string) => boolean,\n customEvents: readonly string[] = []\n): (name: string) => boolean {\n return (name) => isStandard(name) || customEvents.includes(name);\n}\n\n/** An ad tracker that sends only the events `accepts` lets through (`adEvents`). */\nexport function adsTracker(\n send: ThirdPartyTracker,\n accepts: (name: string) => boolean\n): ThirdPartyTracker {\n return (name, properties, eventId) => {\n if (!accepts(name)) return;\n return send(name, properties, eventId);\n };\n}\n"],"mappings":";;;;;;AA+CA,MAAa,oBAAoB;CAC/B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;;;;;;;;AAmBA,SAAgB,SACd,YACA,eAAkC,CAAC,GACR;CAC3B,QAAQ,SAAS,WAAW,IAAI,KAAK,aAAa,SAAS,IAAI;AACjE;;AAGA,SAAgB,WACd,MACA,SACmB;CACnB,QAAQ,MAAM,YAAY,YAAY;EACpC,IAAI,CAAC,QAAQ,IAAI,GAAG;EACpB,OAAO,KAAK,MAAM,YAAY,OAAO;CACvC;AACF"}
|
|
@@ -6,7 +6,11 @@ import { ThirdPartyUserSetter } from "../visitor/types.cjs";
|
|
|
6
6
|
* vendor's own script from its host, as every vendor's official snippet does.
|
|
7
7
|
*/
|
|
8
8
|
export interface IntegrationScript {
|
|
9
|
-
/**
|
|
9
|
+
/**
|
|
10
|
+
* The element id; also its React key, and how a test or a CSP report finds it. Never a global's
|
|
11
|
+
* name: an element's id is readable as `window[id]` until a script defines it, so an id like
|
|
12
|
+
* `posthog` hands the snippet's `window.posthog || []` the <script> element. Keep a hyphen in it.
|
|
13
|
+
*/
|
|
10
14
|
readonly id: string;
|
|
11
15
|
readonly inline: string;
|
|
12
16
|
/** `next/script`'s loading strategy, `afterInteractive` by default; the other frameworks ignore it. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"integration.d.cts","names":[],"sources":["../../src/third-parties/integration.ts"],"mappings":";;;;;;;iBAQiB
|
|
1
|
+
{"version":3,"file":"integration.d.cts","names":[],"sources":["../../src/third-parties/integration.ts"],"mappings":";;;;;;;iBAQiB;;;;;;WAMN;WACA;;WAEA;;;;;;;;;;;;;iBAcM;WACN;WACA,OAAO;WACP,UAAU;WACV,SAAS;;;;;WAKT;;;;;;qBAOE;iBAkBI;;;;;;EAMf,wBAAwB;;;;;;;;;;wBAWV,SACd,aAAa,0BACb,oCACE;;wBAKY,WACd,MAAM,mBACN,UAAU,2BACT"}
|
|
@@ -6,7 +6,11 @@ import { ThirdPartyUserSetter } from "../visitor/types.mjs";
|
|
|
6
6
|
* vendor's own script from its host, as every vendor's official snippet does.
|
|
7
7
|
*/
|
|
8
8
|
export interface IntegrationScript {
|
|
9
|
-
/**
|
|
9
|
+
/**
|
|
10
|
+
* The element id; also its React key, and how a test or a CSP report finds it. Never a global's
|
|
11
|
+
* name: an element's id is readable as `window[id]` until a script defines it, so an id like
|
|
12
|
+
* `posthog` hands the snippet's `window.posthog || []` the <script> element. Keep a hyphen in it.
|
|
13
|
+
*/
|
|
10
14
|
readonly id: string;
|
|
11
15
|
readonly inline: string;
|
|
12
16
|
/** `next/script`'s loading strategy, `afterInteractive` by default; the other frameworks ignore it. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"integration.d.mts","names":[],"sources":["../../src/third-parties/integration.ts"],"mappings":";;;;;;;iBAQiB
|
|
1
|
+
{"version":3,"file":"integration.d.mts","names":[],"sources":["../../src/third-parties/integration.ts"],"mappings":";;;;;;;iBAQiB;;;;;;WAMN;WACA;;WAEA;;;;;;;;;;;;;iBAcM;WACN;WACA,OAAO;WACP,UAAU;WACV,SAAS;;;;;WAKT;;;;;;qBAOE;iBAkBI;;;;;;EAMf,wBAAwB;;;;;;;;;;wBAWV,SACd,aAAa,0BACb,oCACE;;wBAKY,WACd,MAAM,mBACN,UAAU,2BACT"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"integration.mjs","names":[],"sources":["../../src/third-parties/integration.ts"],"sourcesContent":["import type { EventName, ThirdPartyTracker, TrackName } from '../track/types';\nimport type { ThirdPartyUserSetter } from '../visitor/types';\n\n/**\n * The one script an integration puts on the page, rendered by `<Analytics integrations>`\n * (react, next) with the request's `nonce`: an inline snippet that loads the\n * vendor's own script from its host, as every vendor's official snippet does.\n */\nexport interface IntegrationScript {\n
|
|
1
|
+
{"version":3,"file":"integration.mjs","names":[],"sources":["../../src/third-parties/integration.ts"],"sourcesContent":["import type { EventName, ThirdPartyTracker, TrackName } from '../track/types';\nimport type { ThirdPartyUserSetter } from '../visitor/types';\n\n/**\n * The one script an integration puts on the page, rendered by `<Analytics integrations>`\n * (react, next) with the request's `nonce`: an inline snippet that loads the\n * vendor's own script from its host, as every vendor's official snippet does.\n */\nexport interface IntegrationScript {\n /**\n * The element id; also its React key, and how a test or a CSP report finds it. Never a global's\n * name: an element's id is readable as `window[id]` until a script defines it, so an id like\n * `posthog` hands the snippet's `window.posthog || []` the <script> element. Keep a hyphen in it.\n */\n readonly id: string;\n readonly inline: string;\n /** `next/script`'s loading strategy, `afterInteractive` by default; the other frameworks ignore it. */\n readonly strategy?: 'beforeInteractive' | 'afterInteractive' | 'lazyOnload';\n}\n\n/**\n * One third party, configured in one place: how events reach it, how it learns the signed-in\n * user, and the script it needs. Built by the factories in `@shware/analytics/third-parties`\n * (`googleAnalytics`, `metaAds`, …) and handed to both `setupAnalytics({ integrations })` and\n * `<Analytics integrations>`. A host can write its own for a platform the SDK does not cover.\n *\n * `type` says what the platform is for. An `analytics` integration (GA4, PostHog) receives every\n * event, for behavior analysis. An `ads` integration receives only what helps an ad platform\n * optimize and build audiences — the conversion events it maps to its own standard events, plus\n * the custom events it was explicitly given — and filters in its own `track`.\n */\nexport interface Integration {\n readonly type: 'analytics' | 'ads';\n readonly track: ThirdPartyTracker;\n readonly setUser?: ThirdPartyUserSetter;\n readonly script?: IntegrationScript;\n /**\n * Origins `<Analytics>` preconnects to (`react-dom`'s `preconnect`), so the connection is up\n * before the script asks for something there — e.g. where a snippet loads its library from.\n */\n readonly preconnect?: readonly string[];\n}\n\n/**\n * The GA4 recommended events that are conversions or close to one, for an ad platform with no\n * standard events of its own to map to (Microsoft UET), so it is not sent the whole product.\n */\nexport const CONVERSION_EVENTS = [\n 'sign_up',\n 'login',\n 'generate_lead',\n 'view_item',\n 'add_to_cart',\n 'add_to_wishlist',\n 'begin_checkout',\n 'add_payment_info',\n 'purchase',\n 'subscribe',\n 'trial_begin',\n 'search',\n 'schedule',\n 'submit_application',\n 'contact',\n] as const satisfies readonly EventName[];\n\nexport interface AdsOptions {\n /**\n * Custom events this platform receives besides the conversions it maps to its standard\n * events, e.g. one used as an optimization goal or for an audience. Everything else is not\n * sent to it. The names `track` accepts, so with strict event names a typo is a compile error.\n */\n customEvents?: readonly TrackName[];\n}\n\n/**\n * Which events an ad platform receives: what `isStandard` accepts — the events its mapper turns\n * into one of its standard events — and the custom events the host listed. Everything else in the\n * product (feature use, clicks, onboarding steps) is behavior analysis, which is GA4's and\n * PostHog's job, and only noise to an ad platform's optimization. The same rule picks what the\n * browser tag and the platform's conversions API send (`@shware/analytics/server`), so the two\n * report the same events.\n */\nexport function adEvents(\n isStandard: (name: string) => boolean,\n customEvents: readonly string[] = []\n): (name: string) => boolean {\n return (name) => isStandard(name) || customEvents.includes(name);\n}\n\n/** An ad tracker that sends only the events `accepts` lets through (`adEvents`). */\nexport function adsTracker(\n send: ThirdPartyTracker,\n accepts: (name: string) => boolean\n): ThirdPartyTracker {\n return (name, properties, eventId) => {\n if (!accepts(name)) return;\n return send(name, properties, eventId);\n };\n}\n"],"mappings":";;;;;AA+CA,MAAa,oBAAoB;CAC/B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;;;;;;;;AAmBA,SAAgB,SACd,YACA,eAAkC,CAAC,GACR;CAC3B,QAAQ,SAAS,WAAW,IAAI,KAAK,aAAa,SAAS,IAAI;AACjE;;AAGA,SAAgB,WACd,MACA,SACmB;CACnB,QAAQ,MAAM,YAAY,YAAY;EACpC,IAAI,CAAC,QAAQ,IAAI,GAAG;EACpB,OAAO,KAAK,MAAM,YAAY,OAAO;CACvC;AACF"}
|
|
@@ -8,8 +8,8 @@ const require_utils_field = require("../utils/field.cjs");
|
|
|
8
8
|
* those. `undefined` on the server and before the snippet has run.
|
|
9
9
|
*
|
|
10
10
|
* Read off `window` rather than declared on it, so a host that also has `posthog-js`'s own types
|
|
11
|
-
* does not get two conflicting declarations.
|
|
12
|
-
*
|
|
11
|
+
* does not get two conflicting declarations. The types come from `@posthog/types`, PostHog's
|
|
12
|
+
* types-only package for the snippet, so the host installs nothing for them.
|
|
13
13
|
*/
|
|
14
14
|
function getPosthog() {
|
|
15
15
|
if (typeof document === "undefined") return void 0;
|
|
@@ -114,7 +114,7 @@ function posthogAnalytics(options) {
|
|
|
114
114
|
setUser: setPosthogUser,
|
|
115
115
|
preconnect: URL.canParse(assets) ? [new URL(assets).origin] : [],
|
|
116
116
|
script: {
|
|
117
|
-
id: "posthog",
|
|
117
|
+
id: "posthog-snippet",
|
|
118
118
|
strategy: "beforeInteractive",
|
|
119
119
|
inline: `
|
|
120
120
|
!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||[]);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"posthog.cjs","names":["getFirst"],"sources":["../../src/third-parties/posthog.ts"],"sourcesContent":["import type { PostHog, PostHogConfig } from 'posthog
|
|
1
|
+
{"version":3,"file":"posthog.cjs","names":["getFirst"],"sources":["../../src/third-parties/posthog.ts"],"sourcesContent":["import type { PostHog, PostHogConfig } from '@posthog/types';\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/types';\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. The types come from `@posthog/types`, PostHog's\n * types-only package for the snippet, so the host installs nothing for them.\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-snippet',\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;CACxC,CAAC;CACD,OAAO;AACT;AAEA,MAAM,UAAU;CAAC;CAAO;CAAO;CAAO;CAAO;CAAO;AAAM;AAE1D,SAAgB,iBACd,MACA,YACA;CAIA,IAAI,OAAO,aAAa,aAAa;CACrC,MAAM,UAAU,WAAW;CAC3B,IAAI,CAAC,SAAS;EACZ,QAAQ,KAAK,kCAAkC;EAC/C,OAAO;CACT;CACA,IAAI,QAAQ,SAAS,IAAI,GAAG;CAC5B,IAAI,OAAO,SAAS,KAAK,SAAS,WAAW,GAAG;CAChD,IAAI,OAAO,SAAS,KAAK,SAAS,WAAW,GAAG;CAEhD,QAAQ,QAAQ,MAAM,UAAU;AAClC;;;;;;;;;;;AAYA,SAAgB,eAAe,EAAE,SAAS,aAA6C;CACrF,MAAM,UAAU,WAAW;CAC3B,IAAI,CAAC,SAAS;EACZ,QAAQ,KAAK,kCAAkC;EAC/C;CACF;CACA,IAAI,CAAC,SAAS;EACZ,QAAQ,MAAM;EACd;CACF;CACA,QAAQ,SAAS,SAAS,EAAE,OAAOA,oBAAAA,SAAS,WAAW,KAAK,EAAE,CAAC;AACjE;;;;;;;;;;AAWA,SAAgB,iBAAiB,SAGjB;CAGd,MAAM,SAAS,QAAQ,OAAO,SAAS,QAAQ,kBAAkB,uBAAuB;CAGxF,MAAM,SAAS,KAAK,UAAU,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,7 +1,7 @@
|
|
|
1
1
|
import { EventName, TrackName, TrackProperties } from "../track/types.cjs";
|
|
2
2
|
import { UpdateVisitorDTO } from "../schema/index.cjs";
|
|
3
3
|
import { Integration } from "./integration.cjs";
|
|
4
|
-
import { PostHog, PostHog as PostHog$1, PostHogConfig, PostHogConfig as PostHogConfig$1 } from "posthog
|
|
4
|
+
import { PostHog, PostHog as PostHog$1, PostHogConfig, PostHogConfig as PostHogConfig$1 } from "@posthog/types";
|
|
5
5
|
/**
|
|
6
6
|
* `window.posthog`, for calls that return nothing (`capture`, `identify`, `onFeatureFlags`, …):
|
|
7
7
|
* the snippet's stub until the library loads, which queues them and replays them in order once it
|
|
@@ -9,8 +9,8 @@ import { PostHog, PostHog as PostHog$1, PostHogConfig, PostHogConfig as PostHogC
|
|
|
9
9
|
* those. `undefined` on the server and before the snippet has run.
|
|
10
10
|
*
|
|
11
11
|
* Read off `window` rather than declared on it, so a host that also has `posthog-js`'s own types
|
|
12
|
-
* does not get two conflicting declarations.
|
|
13
|
-
*
|
|
12
|
+
* does not get two conflicting declarations. The types come from `@posthog/types`, PostHog's
|
|
13
|
+
* types-only package for the snippet, so the host installs nothing for them.
|
|
14
14
|
*/
|
|
15
15
|
export declare function getPosthog(): PostHog$1 | undefined;
|
|
16
16
|
/**
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { EventName, TrackName, TrackProperties } from "../track/types.mjs";
|
|
2
2
|
import { UpdateVisitorDTO } from "../schema/index.mjs";
|
|
3
3
|
import { Integration } from "./integration.mjs";
|
|
4
|
-
import { PostHog, PostHog as PostHog$1, PostHogConfig, PostHogConfig as PostHogConfig$1 } from "posthog
|
|
4
|
+
import { PostHog, PostHog as PostHog$1, PostHogConfig, PostHogConfig as PostHogConfig$1 } from "@posthog/types";
|
|
5
5
|
/**
|
|
6
6
|
* `window.posthog`, for calls that return nothing (`capture`, `identify`, `onFeatureFlags`, …):
|
|
7
7
|
* the snippet's stub until the library loads, which queues them and replays them in order once it
|
|
@@ -9,8 +9,8 @@ import { PostHog, PostHog as PostHog$1, PostHogConfig, PostHogConfig as PostHogC
|
|
|
9
9
|
* those. `undefined` on the server and before the snippet has run.
|
|
10
10
|
*
|
|
11
11
|
* Read off `window` rather than declared on it, so a host that also has `posthog-js`'s own types
|
|
12
|
-
* does not get two conflicting declarations.
|
|
13
|
-
*
|
|
12
|
+
* does not get two conflicting declarations. The types come from `@posthog/types`, PostHog's
|
|
13
|
+
* types-only package for the snippet, so the host installs nothing for them.
|
|
14
14
|
*/
|
|
15
15
|
export declare function getPosthog(): PostHog$1 | undefined;
|
|
16
16
|
/**
|
|
@@ -7,8 +7,8 @@ import { getFirst } from "../utils/field.mjs";
|
|
|
7
7
|
* those. `undefined` on the server and before the snippet has run.
|
|
8
8
|
*
|
|
9
9
|
* Read off `window` rather than declared on it, so a host that also has `posthog-js`'s own types
|
|
10
|
-
* does not get two conflicting declarations.
|
|
11
|
-
*
|
|
10
|
+
* does not get two conflicting declarations. The types come from `@posthog/types`, PostHog's
|
|
11
|
+
* types-only package for the snippet, so the host installs nothing for them.
|
|
12
12
|
*/
|
|
13
13
|
function getPosthog() {
|
|
14
14
|
if (typeof document === "undefined") return void 0;
|
|
@@ -113,7 +113,7 @@ function posthogAnalytics(options) {
|
|
|
113
113
|
setUser: setPosthogUser,
|
|
114
114
|
preconnect: URL.canParse(assets) ? [new URL(assets).origin] : [],
|
|
115
115
|
script: {
|
|
116
|
-
id: "posthog",
|
|
116
|
+
id: "posthog-snippet",
|
|
117
117
|
strategy: "beforeInteractive",
|
|
118
118
|
inline: `
|
|
119
119
|
!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||[]);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"posthog.mjs","names":[],"sources":["../../src/third-parties/posthog.ts"],"sourcesContent":["import type { PostHog, PostHogConfig } from 'posthog
|
|
1
|
+
{"version":3,"file":"posthog.mjs","names":[],"sources":["../../src/third-parties/posthog.ts"],"sourcesContent":["import type { PostHog, PostHogConfig } from '@posthog/types';\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/types';\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. The types come from `@posthog/types`, PostHog's\n * types-only package for the snippet, so the host installs nothing for them.\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-snippet',\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;CACxC,CAAC;CACD,OAAO;AACT;AAEA,MAAM,UAAU;CAAC;CAAO;CAAO;CAAO;CAAO;CAAO;AAAM;AAE1D,SAAgB,iBACd,MACA,YACA;CAIA,IAAI,OAAO,aAAa,aAAa;CACrC,MAAM,UAAU,WAAW;CAC3B,IAAI,CAAC,SAAS;EACZ,QAAQ,KAAK,kCAAkC;EAC/C,OAAO;CACT;CACA,IAAI,QAAQ,SAAS,IAAI,GAAG;CAC5B,IAAI,OAAO,SAAS,KAAK,SAAS,WAAW,GAAG;CAChD,IAAI,OAAO,SAAS,KAAK,SAAS,WAAW,GAAG;CAEhD,QAAQ,QAAQ,MAAM,UAAU;AAClC;;;;;;;;;;;AAYA,SAAgB,eAAe,EAAE,SAAS,aAA6C;CACrF,MAAM,UAAU,WAAW;CAC3B,IAAI,CAAC,SAAS;EACZ,QAAQ,KAAK,kCAAkC;EAC/C;CACF;CACA,IAAI,CAAC,SAAS;EACZ,QAAQ,MAAM;EACd;CACF;CACA,QAAQ,SAAS,SAAS,EAAE,OAAO,SAAS,WAAW,KAAK,EAAE,CAAC;AACjE;;;;;;;;;;AAWA,SAAgB,iBAAiB,SAGjB;CAGd,MAAM,SAAS,QAAQ,OAAO,SAAS,QAAQ,kBAAkB,uBAAuB;CAGxF,MAAM,SAAS,KAAK,UAAU,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"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@shware/analytics",
|
|
3
|
-
"version": "16.2.
|
|
3
|
+
"version": "16.2.2",
|
|
4
4
|
"private": false,
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -136,6 +136,7 @@
|
|
|
136
136
|
"access": "public"
|
|
137
137
|
},
|
|
138
138
|
"dependencies": {
|
|
139
|
+
"@posthog/types": "^1.419.0",
|
|
139
140
|
"@shware/utils": "^2.0.2",
|
|
140
141
|
"capi-param-builder-nodejs": "~1.3.2",
|
|
141
142
|
"cookie": "^2.0.1",
|
|
@@ -170,7 +171,6 @@
|
|
|
170
171
|
"expo-sqlite": "^57.0.3 || ^58.0.0",
|
|
171
172
|
"expo-tracking-transparency": "^57.0.2 || ^58.0.0",
|
|
172
173
|
"next": "^16.4.3",
|
|
173
|
-
"posthog-js": "^1.438.21",
|
|
174
174
|
"react": "^19.3.1",
|
|
175
175
|
"react-dom": "^19.3.1",
|
|
176
176
|
"react-native": "^0.87.1 || ^0.88.0",
|
|
@@ -208,9 +208,6 @@
|
|
|
208
208
|
"next": {
|
|
209
209
|
"optional": true
|
|
210
210
|
},
|
|
211
|
-
"posthog-js": {
|
|
212
|
-
"optional": true
|
|
213
|
-
},
|
|
214
211
|
"react": {
|
|
215
212
|
"optional": true
|
|
216
213
|
},
|