@shware/analytics 16.3.0 → 16.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -139,6 +139,18 @@ const EXCEPTION_FILTER = `function(r){
139
139
  };
140
140
  }`;
141
141
  /**
142
+ * The origin to preconnect to, or none for a relative URL (a reverse proxy on the site's own
143
+ * origin). `new URL` in a try rather than `URL.canParse`, which Safari before 17 and Chrome before
144
+ * 120 lack: this runs while the app sets up its analytics, where a throw takes the page down.
145
+ */
146
+ function originOf(url) {
147
+ try {
148
+ return [new URL(url).origin];
149
+ } catch {
150
+ return [];
151
+ }
152
+ }
153
+ /**
142
154
  * PostHog: every event, for behavior analysis. Loaded with PostHog's HTML snippet, which defines
143
155
  * a stub `window.posthog` and fetches the library (`array.js`) asynchronously from PostHog's
144
156
  * assets host, so it stays out of the app's bundle; calls made before it loads are queued.
@@ -170,7 +182,7 @@ function posthogAnalytics(options) {
170
182
  type: "analytics",
171
183
  track: sendPosthogEvent,
172
184
  setUser: setPosthogUser,
173
- preconnect: URL.canParse(assets) ? [new URL(assets).origin] : [],
185
+ preconnect: originOf(assets),
174
186
  script: {
175
187
  id: "posthog-snippet",
176
188
  strategy: "beforeInteractive",
@@ -1 +1 @@
1
- {"version":3,"file":"posthog.cjs","names":["getFirst"],"sources":["../../src/third-parties/posthog.ts"],"sourcesContent":["import type {\n CaptureResult,\n ExceptionAutoCaptureConfig,\n PostHog,\n PostHogConfig,\n Properties,\n} 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 * Sends an error to PostHog's error tracking (`captureException`), as `sendPosthogEvent` does an\n * event: queued on the snippet's stub until the library loads, so it can be called from anywhere\n * at any time — an http client's error hook, a `catch` that recovers but should still be known.\n * Returns the `$exception` event, `undefined` while only the stub is there (or without PostHog).\n *\n * Never throws: reporting an error must not become a second one where it is called. The\n * `errorTracking` filter of `posthogAnalytics` applies, as to every exception.\n */\nexport function capturePosthogException(\n error: unknown,\n properties?: Properties\n): CaptureResult | undefined {\n try {\n return getPosthog()?.captureException(error, properties);\n } catch (e: unknown) {\n console.error('capturePosthogException: the error was not reported', e);\n return undefined;\n }\n}\n\n/** A substring of what it is matched against, or a regular expression tested on it. */\nexport type ErrorPattern = string | RegExp;\n\nexport interface PosthogErrorTrackingOptions {\n /**\n * The library's exception autocapture: window errors and unhandled rejections, on by default.\n * The same as `config.capture_exceptions`, which wins when both are set.\n */\n autocapture?: boolean | ExceptionAutoCaptureConfig;\n /**\n * Exceptions not sent, as Sentry's `ignoreErrors`: matched against `Type: message` and the\n * message alone of each error in the chain (`$exception_list`), e.g. `'UET is not defined'` for an\n * ad blocker stubbing a tag. Errors thrown by browser extensions need no entry: PostHog drops them\n * itself (`error_tracking.captureExtensionExceptions`).\n */\n ignoreErrors?: readonly ErrorPattern[];\n /**\n * Exceptions not sent by where they were thrown, as Sentry's `denyUrls`: matched against the\n * file of the error's innermost frame, e.g. `'/gsi/client'` for Google One Tap's own minified\n * errors, whose messages change with every build. An error of yours that only passed through\n * such a script (a callback it called) is still sent.\n */\n denyUrls?: readonly ErrorPattern[];\n}\n\n/**\n * A pattern as JSON: a regular expression by its source and flags, rebuilt in the snippet. `g`\n * and `y` are dropped: they make `test` resume from the last match, so one rule would match the\n * same message only every other time.\n */\ntype SerializedPattern = string | { source: string; flags: string };\n\nfunction serializePatterns(patterns: readonly ErrorPattern[] = []): SerializedPattern[] {\n return patterns.map((p) =>\n typeof p === 'string' ? p : { source: p.source, flags: p.flags.replace(/[gy]/g, '') }\n );\n}\n\n/**\n * The snippet's `before_send`, as source: `config` goes to `posthog.init` as JSON, which drops\n * functions, so the filter is written into the inline script instead — in place from the first\n * event, with no window before the app's bundle could install it. ES5, as the rest of the snippet.\n * Called with the rules (`off`, `errors`, `urls`); returns the `before_send` function.\n */\nconst EXCEPTION_FILTER = `function(r){\n function compile(ps){var o=[];for(var i=0;i<ps.length;i++){var p=ps[i];o.push(typeof p===\"string\"?p:new RegExp(p.source,p.flags))}return o}\n function any(ps,t){if(!t)return false;for(var i=0;i<ps.length;i++){var p=ps[i];if(typeof p===\"string\"?t.indexOf(p)!==-1:p.test(t))return true}return false}\n var errors=compile(r.errors),urls=compile(r.urls);\n return function(e){\n if(!e||e.event!==\"$exception\")return e;\n if(r.off)return null;\n var l=(e.properties&&e.properties.$exception_list)||[];\n for(var i=0;i<l.length;i++){var x=l[i]||{},v=x.value||\"\";if(any(errors,x.type?x.type+\": \"+v:v)||any(errors,v))return null}\n var f=l[0]&&l[0].stacktrace&&l[0].stacktrace.frames,u=f&&f.length?f[f.length-1].filename:\"\";\n return any(urls,u)?null:e;\n };\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 /**\n * PostHog's error tracking. `true` or options turn on exception autocapture and filter what is\n * sent (`ignoreErrors`, `denyUrls`); `false` sends no exception at all, autocaptured or\n * reported (`capturePosthogException`, `PosthogErrorBoundary`, `setupPosthogReactErrorHandler`) — for\n * local development, which would otherwise fill the production project's issues. Left out, the\n * library's own `config` decides, as before. Each exception carries the session id, so its issue\n * links to the session's replay.\n */\n errorTracking?: boolean | PosthogErrorTrackingOptions;\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, a pattern any\n // text), and a `</script>` inside it would end this inline script early. `\\u003c` parses back\n // to the same value.\n const json = (value: unknown) => JSON.stringify(value).replace(/</g, '\\\\u003c');\n const token = JSON.stringify(options.token);\n const { errorTracking } = options;\n let init = `posthog.init(${token}, ${json(options.config)});`;\n if (errorTracking !== undefined) {\n const tracking = typeof errorTracking === 'object' ? errorTracking : {};\n const config = {\n ...options.config,\n capture_exceptions:\n options.config.capture_exceptions ?? (errorTracking && (tracking.autocapture ?? true)),\n };\n const rules = {\n off: !errorTracking,\n errors: serializePatterns(tracking.ignoreErrors),\n urls: serializePatterns(tracking.denyUrls),\n };\n // In a function, so `c` does not become a global of this classic script.\n init = `!function(){var c=${json(config)};c.before_send=(${EXCEPTION_FILTER})(${json(rules)});posthog.init(${token}, c)}();`;\n }\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. The snippet is PostHog's current one, verbatim\n // (posthog.com/docs/error-tracking/installation/web): it leaves an already loaded library in\n // place, inserts `array.js` once, and retries it on the next `init` if it failed to load.\n strategy: 'beforeInteractive',\n inline: `\n !function(t,e){var o,n,p,r;e.__SV||(window.posthog && window.posthog.__loaded)||(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||((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\",p.onerror=function(){p=null},(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 ${init}\n `,\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;AAwBA,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;CACh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SAAS,eAAe;EACpF;EACA,MAAM,QAAQ;GACZ,KAAK,CAAC;GACN,QAAQ,kBAAkB,SAAS,YAAY;GAC/C,MAAM,kBAAkB,SAAS,QAAQ;EAC3C;EAEA,OAAO,qBAAqB,KAAK,MAAM,EAAE,kBAAkB,iBAAiB,IAAI,KAAK,KAAK,EAAE,iBAAiB,MAAM;CACrH;CACA,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;GAMJ,UAAU;GACV,QAAQ;;UAEJ,KAAK;;EAEX;CACF;AACF"}
1
+ {"version":3,"file":"posthog.cjs","names":["getFirst"],"sources":["../../src/third-parties/posthog.ts"],"sourcesContent":["import type {\n CaptureResult,\n ExceptionAutoCaptureConfig,\n PostHog,\n PostHogConfig,\n Properties,\n} 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 * Sends an error to PostHog's error tracking (`captureException`), as `sendPosthogEvent` does an\n * event: queued on the snippet's stub until the library loads, so it can be called from anywhere\n * at any time — an http client's error hook, a `catch` that recovers but should still be known.\n * Returns the `$exception` event, `undefined` while only the stub is there (or without PostHog).\n *\n * Never throws: reporting an error must not become a second one where it is called. The\n * `errorTracking` filter of `posthogAnalytics` applies, as to every exception.\n */\nexport function capturePosthogException(\n error: unknown,\n properties?: Properties\n): CaptureResult | undefined {\n try {\n return getPosthog()?.captureException(error, properties);\n } catch (e: unknown) {\n console.error('capturePosthogException: the error was not reported', e);\n return undefined;\n }\n}\n\n/** A substring of what it is matched against, or a regular expression tested on it. */\nexport type ErrorPattern = string | RegExp;\n\nexport interface PosthogErrorTrackingOptions {\n /**\n * The library's exception autocapture: window errors and unhandled rejections, on by default.\n * The same as `config.capture_exceptions`, which wins when both are set.\n */\n autocapture?: boolean | ExceptionAutoCaptureConfig;\n /**\n * Exceptions not sent, as Sentry's `ignoreErrors`: matched against `Type: message` and the\n * message alone of each error in the chain (`$exception_list`), e.g. `'UET is not defined'` for an\n * ad blocker stubbing a tag. Errors thrown by browser extensions need no entry: PostHog drops them\n * itself (`error_tracking.captureExtensionExceptions`).\n */\n ignoreErrors?: readonly ErrorPattern[];\n /**\n * Exceptions not sent by where they were thrown, as Sentry's `denyUrls`: matched against the\n * file of the error's innermost frame, e.g. `'/gsi/client'` for Google One Tap's own minified\n * errors, whose messages change with every build. An error of yours that only passed through\n * such a script (a callback it called) is still sent.\n */\n denyUrls?: readonly ErrorPattern[];\n}\n\n/**\n * A pattern as JSON: a regular expression by its source and flags, rebuilt in the snippet. `g`\n * and `y` are dropped: they make `test` resume from the last match, so one rule would match the\n * same message only every other time.\n */\ntype SerializedPattern = string | { source: string; flags: string };\n\nfunction serializePatterns(patterns: readonly ErrorPattern[] = []): SerializedPattern[] {\n return patterns.map((p) =>\n typeof p === 'string' ? p : { source: p.source, flags: p.flags.replace(/[gy]/g, '') }\n );\n}\n\n/**\n * The snippet's `before_send`, as source: `config` goes to `posthog.init` as JSON, which drops\n * functions, so the filter is written into the inline script instead — in place from the first\n * event, with no window before the app's bundle could install it. ES5, as the rest of the snippet.\n * Called with the rules (`off`, `errors`, `urls`); returns the `before_send` function.\n */\nconst EXCEPTION_FILTER = `function(r){\n function compile(ps){var o=[];for(var i=0;i<ps.length;i++){var p=ps[i];o.push(typeof p===\"string\"?p:new RegExp(p.source,p.flags))}return o}\n function any(ps,t){if(!t)return false;for(var i=0;i<ps.length;i++){var p=ps[i];if(typeof p===\"string\"?t.indexOf(p)!==-1:p.test(t))return true}return false}\n var errors=compile(r.errors),urls=compile(r.urls);\n return function(e){\n if(!e||e.event!==\"$exception\")return e;\n if(r.off)return null;\n var l=(e.properties&&e.properties.$exception_list)||[];\n for(var i=0;i<l.length;i++){var x=l[i]||{},v=x.value||\"\";if(any(errors,x.type?x.type+\": \"+v:v)||any(errors,v))return null}\n var f=l[0]&&l[0].stacktrace&&l[0].stacktrace.frames,u=f&&f.length?f[f.length-1].filename:\"\";\n return any(urls,u)?null:e;\n };\n}`;\n\n/**\n * The origin to preconnect to, or none for a relative URL (a reverse proxy on the site's own\n * origin). `new URL` in a try rather than `URL.canParse`, which Safari before 17 and Chrome before\n * 120 lack: this runs while the app sets up its analytics, where a throw takes the page down.\n */\nfunction originOf(url: string): string[] {\n try {\n return [new URL(url).origin];\n } catch {\n return [];\n }\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 /**\n * PostHog's error tracking. `true` or options turn on exception autocapture and filter what is\n * sent (`ignoreErrors`, `denyUrls`); `false` sends no exception at all, autocaptured or\n * reported (`capturePosthogException`, `PosthogErrorBoundary`, `setupPosthogReactErrorHandler`) — for\n * local development, which would otherwise fill the production project's issues. Left out, the\n * library's own `config` decides, as before. Each exception carries the session id, so its issue\n * links to the session's replay.\n */\n errorTracking?: boolean | PosthogErrorTrackingOptions;\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, a pattern any\n // text), and a `</script>` inside it would end this inline script early. `\\u003c` parses back\n // to the same value.\n const json = (value: unknown) => JSON.stringify(value).replace(/</g, '\\\\u003c');\n const token = JSON.stringify(options.token);\n const { errorTracking } = options;\n let init = `posthog.init(${token}, ${json(options.config)});`;\n if (errorTracking !== undefined) {\n const tracking = typeof errorTracking === 'object' ? errorTracking : {};\n const config = {\n ...options.config,\n capture_exceptions:\n options.config.capture_exceptions ?? (errorTracking && (tracking.autocapture ?? true)),\n };\n const rules = {\n off: !errorTracking,\n errors: serializePatterns(tracking.ignoreErrors),\n urls: serializePatterns(tracking.denyUrls),\n };\n // In a function, so `c` does not become a global of this classic script.\n init = `!function(){var c=${json(config)};c.before_send=(${EXCEPTION_FILTER})(${json(rules)});posthog.init(${token}, c)}();`;\n }\n return {\n type: 'analytics',\n track: sendPosthogEvent,\n setUser: setPosthogUser,\n preconnect: originOf(assets),\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. The snippet is PostHog's current one, verbatim\n // (posthog.com/docs/error-tracking/installation/web): it leaves an already loaded library in\n // place, inserts `array.js` once, and retries it on the next `init` if it failed to load.\n strategy: 'beforeInteractive',\n inline: `\n !function(t,e){var o,n,p,r;e.__SV||(window.posthog && window.posthog.__loaded)||(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||((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\",p.onerror=function(){p=null},(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 ${init}\n `,\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;AAwBA,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;C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MAAM,QAAQ;GACZ,KAAK,CAAC;GACN,QAAQ,kBAAkB,SAAS,YAAY;GAC/C,MAAM,kBAAkB,SAAS,QAAQ;EAC3C;EAEA,OAAO,qBAAqB,KAAK,MAAM,EAAE,kBAAkB,iBAAiB,IAAI,KAAK,KAAK,EAAE,iBAAiB,MAAM;CACrH;CACA,OAAO;EACL,MAAM;EACN,OAAO;EACP,SAAS;EACT,YAAY,SAAS,MAAM;EAC3B,QAAQ;GACN,IAAI;GAMJ,UAAU;GACV,QAAQ;;UAEJ,KAAK;;EAEX;CACF;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"posthog.d.cts","names":["PostHog","PostHogConfig"],"sources":["../../src/third-parties/posthog.ts"],"mappings":";;;;;;;;;;;;;;wBAwBgB,cAAcA;;;;;;;wBAWd,oBAAoBA;;;;;;;;;;;;;;;;;;;wBAyBpB,kBAAkB,qBAAmB;wBAcrC,iBAAiB,UAAU,WACzC,MAAM,UAAU,IAChB,aAAa,gBAAgB;;;;;;;;;;;wBA4Bf,iBAAiB,SAAS,aAAa,KAAK;;;;;;;;;;wBAsB5C,wBACd,gBACA,aAAa,aACZ;;YAUS,wBAAwB;iBAEnB;;;;;EAKf,wBAAwB;;;;;;;EAOxB,wBAAwB;;;;;;;EAOxB,oBAAoB;;;;;;;;;;;wBA6CN,iBAAiB;EAC/B;EACA,QAAQ,QAAQC;IAAmB;;;;;;;;;;EASnC,0BAA0B;IACxB"}
1
+ {"version":3,"file":"posthog.d.cts","names":["PostHog","PostHogConfig"],"sources":["../../src/third-parties/posthog.ts"],"mappings":";;;;;;;;;;;;;;wBAwBgB,cAAcA;;;;;;;wBAWd,oBAAoBA;;;;;;;;;;;;;;;;;;;wBAyBpB,kBAAkB,qBAAmB;wBAcrC,iBAAiB,UAAU,WACzC,MAAM,UAAU,IAChB,aAAa,gBAAgB;;;;;;;;;;;wBA4Bf,iBAAiB,SAAS,aAAa,KAAK;;;;;;;;;;wBAsB5C,wBACd,gBACA,aAAa,aACZ;;YAUS,wBAAwB;iBAEnB;;;;;EAKf,wBAAwB;;;;;;;EAOxB,wBAAwB;;;;;;;EAOxB,oBAAoB;;;;;;;;;;;wBA0DN,iBAAiB;EAC/B;EACA,QAAQ,QAAQC;IAAmB;;;;;;;;;;EASnC,0BAA0B;IACxB"}
@@ -1 +1 @@
1
- {"version":3,"file":"posthog.d.mts","names":["PostHog","PostHogConfig"],"sources":["../../src/third-parties/posthog.ts"],"mappings":";;;;;;;;;;;;;;wBAwBgB,cAAcA;;;;;;;wBAWd,oBAAoBA;;;;;;;;;;;;;;;;;;;wBAyBpB,kBAAkB,qBAAmB;wBAcrC,iBAAiB,UAAU,WACzC,MAAM,UAAU,IAChB,aAAa,gBAAgB;;;;;;;;;;;wBA4Bf,iBAAiB,SAAS,aAAa,KAAK;;;;;;;;;;wBAsB5C,wBACd,gBACA,aAAa,aACZ;;YAUS,wBAAwB;iBAEnB;;;;;EAKf,wBAAwB;;;;;;;EAOxB,wBAAwB;;;;;;;EAOxB,oBAAoB;;;;;;;;;;;wBA6CN,iBAAiB;EAC/B;EACA,QAAQ,QAAQC;IAAmB;;;;;;;;;;EASnC,0BAA0B;IACxB"}
1
+ {"version":3,"file":"posthog.d.mts","names":["PostHog","PostHogConfig"],"sources":["../../src/third-parties/posthog.ts"],"mappings":";;;;;;;;;;;;;;wBAwBgB,cAAcA;;;;;;;wBAWd,oBAAoBA;;;;;;;;;;;;;;;;;;;wBAyBpB,kBAAkB,qBAAmB;wBAcrC,iBAAiB,UAAU,WACzC,MAAM,UAAU,IAChB,aAAa,gBAAgB;;;;;;;;;;;wBA4Bf,iBAAiB,SAAS,aAAa,KAAK;;;;;;;;;;wBAsB5C,wBACd,gBACA,aAAa,aACZ;;YAUS,wBAAwB;iBAEnB;;;;;EAKf,wBAAwB;;;;;;;EAOxB,wBAAwB;;;;;;;EAOxB,oBAAoB;;;;;;;;;;;wBA0DN,iBAAiB;EAC/B;EACA,QAAQ,QAAQC;IAAmB;;;;;;;;;;EASnC,0BAA0B;IACxB"}
@@ -138,6 +138,18 @@ const EXCEPTION_FILTER = `function(r){
138
138
  };
139
139
  }`;
140
140
  /**
141
+ * The origin to preconnect to, or none for a relative URL (a reverse proxy on the site's own
142
+ * origin). `new URL` in a try rather than `URL.canParse`, which Safari before 17 and Chrome before
143
+ * 120 lack: this runs while the app sets up its analytics, where a throw takes the page down.
144
+ */
145
+ function originOf(url) {
146
+ try {
147
+ return [new URL(url).origin];
148
+ } catch {
149
+ return [];
150
+ }
151
+ }
152
+ /**
141
153
  * PostHog: every event, for behavior analysis. Loaded with PostHog's HTML snippet, which defines
142
154
  * a stub `window.posthog` and fetches the library (`array.js`) asynchronously from PostHog's
143
155
  * assets host, so it stays out of the app's bundle; calls made before it loads are queued.
@@ -169,7 +181,7 @@ function posthogAnalytics(options) {
169
181
  type: "analytics",
170
182
  track: sendPosthogEvent,
171
183
  setUser: setPosthogUser,
172
- preconnect: URL.canParse(assets) ? [new URL(assets).origin] : [],
184
+ preconnect: originOf(assets),
173
185
  script: {
174
186
  id: "posthog-snippet",
175
187
  strategy: "beforeInteractive",
@@ -1 +1 @@
1
- {"version":3,"file":"posthog.mjs","names":[],"sources":["../../src/third-parties/posthog.ts"],"sourcesContent":["import type {\n CaptureResult,\n ExceptionAutoCaptureConfig,\n PostHog,\n PostHogConfig,\n Properties,\n} 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 * Sends an error to PostHog's error tracking (`captureException`), as `sendPosthogEvent` does an\n * event: queued on the snippet's stub until the library loads, so it can be called from anywhere\n * at any time — an http client's error hook, a `catch` that recovers but should still be known.\n * Returns the `$exception` event, `undefined` while only the stub is there (or without PostHog).\n *\n * Never throws: reporting an error must not become a second one where it is called. The\n * `errorTracking` filter of `posthogAnalytics` applies, as to every exception.\n */\nexport function capturePosthogException(\n error: unknown,\n properties?: Properties\n): CaptureResult | undefined {\n try {\n return getPosthog()?.captureException(error, properties);\n } catch (e: unknown) {\n console.error('capturePosthogException: the error was not reported', e);\n return undefined;\n }\n}\n\n/** A substring of what it is matched against, or a regular expression tested on it. */\nexport type ErrorPattern = string | RegExp;\n\nexport interface PosthogErrorTrackingOptions {\n /**\n * The library's exception autocapture: window errors and unhandled rejections, on by default.\n * The same as `config.capture_exceptions`, which wins when both are set.\n */\n autocapture?: boolean | ExceptionAutoCaptureConfig;\n /**\n * Exceptions not sent, as Sentry's `ignoreErrors`: matched against `Type: message` and the\n * message alone of each error in the chain (`$exception_list`), e.g. `'UET is not defined'` for an\n * ad blocker stubbing a tag. Errors thrown by browser extensions need no entry: PostHog drops them\n * itself (`error_tracking.captureExtensionExceptions`).\n */\n ignoreErrors?: readonly ErrorPattern[];\n /**\n * Exceptions not sent by where they were thrown, as Sentry's `denyUrls`: matched against the\n * file of the error's innermost frame, e.g. `'/gsi/client'` for Google One Tap's own minified\n * errors, whose messages change with every build. An error of yours that only passed through\n * such a script (a callback it called) is still sent.\n */\n denyUrls?: readonly ErrorPattern[];\n}\n\n/**\n * A pattern as JSON: a regular expression by its source and flags, rebuilt in the snippet. `g`\n * and `y` are dropped: they make `test` resume from the last match, so one rule would match the\n * same message only every other time.\n */\ntype SerializedPattern = string | { source: string; flags: string };\n\nfunction serializePatterns(patterns: readonly ErrorPattern[] = []): SerializedPattern[] {\n return patterns.map((p) =>\n typeof p === 'string' ? p : { source: p.source, flags: p.flags.replace(/[gy]/g, '') }\n );\n}\n\n/**\n * The snippet's `before_send`, as source: `config` goes to `posthog.init` as JSON, which drops\n * functions, so the filter is written into the inline script instead — in place from the first\n * event, with no window before the app's bundle could install it. ES5, as the rest of the snippet.\n * Called with the rules (`off`, `errors`, `urls`); returns the `before_send` function.\n */\nconst EXCEPTION_FILTER = `function(r){\n function compile(ps){var o=[];for(var i=0;i<ps.length;i++){var p=ps[i];o.push(typeof p===\"string\"?p:new RegExp(p.source,p.flags))}return o}\n function any(ps,t){if(!t)return false;for(var i=0;i<ps.length;i++){var p=ps[i];if(typeof p===\"string\"?t.indexOf(p)!==-1:p.test(t))return true}return false}\n var errors=compile(r.errors),urls=compile(r.urls);\n return function(e){\n if(!e||e.event!==\"$exception\")return e;\n if(r.off)return null;\n var l=(e.properties&&e.properties.$exception_list)||[];\n for(var i=0;i<l.length;i++){var x=l[i]||{},v=x.value||\"\";if(any(errors,x.type?x.type+\": \"+v:v)||any(errors,v))return null}\n var f=l[0]&&l[0].stacktrace&&l[0].stacktrace.frames,u=f&&f.length?f[f.length-1].filename:\"\";\n return any(urls,u)?null:e;\n };\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 /**\n * PostHog's error tracking. `true` or options turn on exception autocapture and filter what is\n * sent (`ignoreErrors`, `denyUrls`); `false` sends no exception at all, autocaptured or\n * reported (`capturePosthogException`, `PosthogErrorBoundary`, `setupPosthogReactErrorHandler`) — for\n * local development, which would otherwise fill the production project's issues. Left out, the\n * library's own `config` decides, as before. Each exception carries the session id, so its issue\n * links to the session's replay.\n */\n errorTracking?: boolean | PosthogErrorTrackingOptions;\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, a pattern any\n // text), and a `</script>` inside it would end this inline script early. `\\u003c` parses back\n // to the same value.\n const json = (value: unknown) => JSON.stringify(value).replace(/</g, '\\\\u003c');\n const token = JSON.stringify(options.token);\n const { errorTracking } = options;\n let init = `posthog.init(${token}, ${json(options.config)});`;\n if (errorTracking !== undefined) {\n const tracking = typeof errorTracking === 'object' ? errorTracking : {};\n const config = {\n ...options.config,\n capture_exceptions:\n options.config.capture_exceptions ?? (errorTracking && (tracking.autocapture ?? true)),\n };\n const rules = {\n off: !errorTracking,\n errors: serializePatterns(tracking.ignoreErrors),\n urls: serializePatterns(tracking.denyUrls),\n };\n // In a function, so `c` does not become a global of this classic script.\n init = `!function(){var c=${json(config)};c.before_send=(${EXCEPTION_FILTER})(${json(rules)});posthog.init(${token}, c)}();`;\n }\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. The snippet is PostHog's current one, verbatim\n // (posthog.com/docs/error-tracking/installation/web): it leaves an already loaded library in\n // place, inserts `array.js` once, and retries it on the next `init` if it failed to load.\n strategy: 'beforeInteractive',\n inline: `\n !function(t,e){var o,n,p,r;e.__SV||(window.posthog && window.posthog.__loaded)||(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||((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\",p.onerror=function(){p=null},(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 ${init}\n `,\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;AAwBA,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;;;;;;;;;;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kB,SAAS,QAAQ;EAC3C;EAEA,OAAO,qBAAqB,KAAK,MAAM,EAAE,kBAAkB,iBAAiB,IAAI,KAAK,KAAK,EAAE,iBAAiB,MAAM;CACrH;CACA,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;GAMJ,UAAU;GACV,QAAQ;;UAEJ,KAAK;;EAEX;CACF;AACF"}
1
+ {"version":3,"file":"posthog.mjs","names":[],"sources":["../../src/third-parties/posthog.ts"],"sourcesContent":["import type {\n CaptureResult,\n ExceptionAutoCaptureConfig,\n PostHog,\n PostHogConfig,\n Properties,\n} 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 * Sends an error to PostHog's error tracking (`captureException`), as `sendPosthogEvent` does an\n * event: queued on the snippet's stub until the library loads, so it can be called from anywhere\n * at any time — an http client's error hook, a `catch` that recovers but should still be known.\n * Returns the `$exception` event, `undefined` while only the stub is there (or without PostHog).\n *\n * Never throws: reporting an error must not become a second one where it is called. The\n * `errorTracking` filter of `posthogAnalytics` applies, as to every exception.\n */\nexport function capturePosthogException(\n error: unknown,\n properties?: Properties\n): CaptureResult | undefined {\n try {\n return getPosthog()?.captureException(error, properties);\n } catch (e: unknown) {\n console.error('capturePosthogException: the error was not reported', e);\n return undefined;\n }\n}\n\n/** A substring of what it is matched against, or a regular expression tested on it. */\nexport type ErrorPattern = string | RegExp;\n\nexport interface PosthogErrorTrackingOptions {\n /**\n * The library's exception autocapture: window errors and unhandled rejections, on by default.\n * The same as `config.capture_exceptions`, which wins when both are set.\n */\n autocapture?: boolean | ExceptionAutoCaptureConfig;\n /**\n * Exceptions not sent, as Sentry's `ignoreErrors`: matched against `Type: message` and the\n * message alone of each error in the chain (`$exception_list`), e.g. `'UET is not defined'` for an\n * ad blocker stubbing a tag. Errors thrown by browser extensions need no entry: PostHog drops them\n * itself (`error_tracking.captureExtensionExceptions`).\n */\n ignoreErrors?: readonly ErrorPattern[];\n /**\n * Exceptions not sent by where they were thrown, as Sentry's `denyUrls`: matched against the\n * file of the error's innermost frame, e.g. `'/gsi/client'` for Google One Tap's own minified\n * errors, whose messages change with every build. An error of yours that only passed through\n * such a script (a callback it called) is still sent.\n */\n denyUrls?: readonly ErrorPattern[];\n}\n\n/**\n * A pattern as JSON: a regular expression by its source and flags, rebuilt in the snippet. `g`\n * and `y` are dropped: they make `test` resume from the last match, so one rule would match the\n * same message only every other time.\n */\ntype SerializedPattern = string | { source: string; flags: string };\n\nfunction serializePatterns(patterns: readonly ErrorPattern[] = []): SerializedPattern[] {\n return patterns.map((p) =>\n typeof p === 'string' ? p : { source: p.source, flags: p.flags.replace(/[gy]/g, '') }\n );\n}\n\n/**\n * The snippet's `before_send`, as source: `config` goes to `posthog.init` as JSON, which drops\n * functions, so the filter is written into the inline script instead — in place from the first\n * event, with no window before the app's bundle could install it. ES5, as the rest of the snippet.\n * Called with the rules (`off`, `errors`, `urls`); returns the `before_send` function.\n */\nconst EXCEPTION_FILTER = `function(r){\n function compile(ps){var o=[];for(var i=0;i<ps.length;i++){var p=ps[i];o.push(typeof p===\"string\"?p:new RegExp(p.source,p.flags))}return o}\n function any(ps,t){if(!t)return false;for(var i=0;i<ps.length;i++){var p=ps[i];if(typeof p===\"string\"?t.indexOf(p)!==-1:p.test(t))return true}return false}\n var errors=compile(r.errors),urls=compile(r.urls);\n return function(e){\n if(!e||e.event!==\"$exception\")return e;\n if(r.off)return null;\n var l=(e.properties&&e.properties.$exception_list)||[];\n for(var i=0;i<l.length;i++){var x=l[i]||{},v=x.value||\"\";if(any(errors,x.type?x.type+\": \"+v:v)||any(errors,v))return null}\n var f=l[0]&&l[0].stacktrace&&l[0].stacktrace.frames,u=f&&f.length?f[f.length-1].filename:\"\";\n return any(urls,u)?null:e;\n };\n}`;\n\n/**\n * The origin to preconnect to, or none for a relative URL (a reverse proxy on the site's own\n * origin). `new URL` in a try rather than `URL.canParse`, which Safari before 17 and Chrome before\n * 120 lack: this runs while the app sets up its analytics, where a throw takes the page down.\n */\nfunction originOf(url: string): string[] {\n try {\n return [new URL(url).origin];\n } catch {\n return [];\n }\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 /**\n * PostHog's error tracking. `true` or options turn on exception autocapture and filter what is\n * sent (`ignoreErrors`, `denyUrls`); `false` sends no exception at all, autocaptured or\n * reported (`capturePosthogException`, `PosthogErrorBoundary`, `setupPosthogReactErrorHandler`) — for\n * local development, which would otherwise fill the production project's issues. Left out, the\n * library's own `config` decides, as before. Each exception carries the session id, so its issue\n * links to the session's replay.\n */\n errorTracking?: boolean | PosthogErrorTrackingOptions;\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, a pattern any\n // text), and a `</script>` inside it would end this inline script early. `\\u003c` parses back\n // to the same value.\n const json = (value: unknown) => JSON.stringify(value).replace(/</g, '\\\\u003c');\n const token = JSON.stringify(options.token);\n const { errorTracking } = options;\n let init = `posthog.init(${token}, ${json(options.config)});`;\n if (errorTracking !== undefined) {\n const tracking = typeof errorTracking === 'object' ? errorTracking : {};\n const config = {\n ...options.config,\n capture_exceptions:\n options.config.capture_exceptions ?? (errorTracking && (tracking.autocapture ?? true)),\n };\n const rules = {\n off: !errorTracking,\n errors: serializePatterns(tracking.ignoreErrors),\n urls: serializePatterns(tracking.denyUrls),\n };\n // In a function, so `c` does not become a global of this classic script.\n init = `!function(){var c=${json(config)};c.before_send=(${EXCEPTION_FILTER})(${json(rules)});posthog.init(${token}, c)}();`;\n }\n return {\n type: 'analytics',\n track: sendPosthogEvent,\n setUser: setPosthogUser,\n preconnect: originOf(assets),\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. The snippet is PostHog's current one, verbatim\n // (posthog.com/docs/error-tracking/installation/web): it leaves an already loaded library in\n // place, inserts `array.js` once, and retries it on the next `init` if it failed to load.\n strategy: 'beforeInteractive',\n inline: `\n !function(t,e){var o,n,p,r;e.__SV||(window.posthog && window.posthog.__loaded)||(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||((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\",p.onerror=function(){p=null},(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 ${init}\n `,\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;AAwBA,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;C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