@easy-cookie/posthog 0.1.3 → 0.1.5

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/dist/index.cjs CHANGED
@@ -30,6 +30,41 @@ function connectPostHog(posthog, api, options = {}) {
30
30
  const category = options.category ?? "measurement";
31
31
  const granted = () => options.service ? api.isServiceGranted(options.service) : api.isGranted(category);
32
32
  let last = null;
33
+ const ph = posthog;
34
+ let remoteConfig;
35
+ let restoreRemoteConfig;
36
+ if (options.sessionReplay && typeof ph._onRemoteConfig === "function") {
37
+ const hadOwn = Object.prototype.hasOwnProperty.call(ph, "_onRemoteConfig");
38
+ const previous = ph._onRemoteConfig;
39
+ const bound = previous.bind(ph);
40
+ ph._onRemoteConfig = (config) => {
41
+ remoteConfig = config;
42
+ bound(config);
43
+ };
44
+ restoreRemoteConfig = () => {
45
+ if (hadOwn) ph._onRemoteConfig = previous;
46
+ else delete ph._onRemoteConfig;
47
+ };
48
+ }
49
+ const fetchRemoteConfig = async () => {
50
+ try {
51
+ const token = ph.config?.token;
52
+ const url = token && ph.requestRouter?.endpointFor?.("assets", `/array/${token}/config`);
53
+ if (!url) return void 0;
54
+ const res = await fetch(url);
55
+ return res.ok ? await res.json() : void 0;
56
+ } catch {
57
+ return void 0;
58
+ }
59
+ };
60
+ const restartReplay = async () => {
61
+ try {
62
+ const config = remoteConfig ?? await fetchRemoteConfig();
63
+ if (config && "sessionRecording" in config) ph.sessionRecording?.onRemoteConfig?.(config);
64
+ posthog.startSessionRecording?.();
65
+ } catch {
66
+ }
67
+ };
33
68
  const status = () => {
34
69
  const explicit = posthog.get_explicit_consent_status?.();
35
70
  if (explicit === "granted") return "in";
@@ -54,8 +89,12 @@ function connectPostHog(posthog, api, options = {}) {
54
89
  }
55
90
  if (granted()) {
56
91
  if (last !== "in") {
92
+ const fromCookieless = status() === "out";
57
93
  if (status() !== "in") posthog.opt_in_capturing({ captureEventName: false });
58
- if (options.sessionReplay) posthog.startSessionRecording?.();
94
+ if (options.sessionReplay) {
95
+ if (fromCookieless) void restartReplay();
96
+ else posthog.startSessionRecording?.();
97
+ }
59
98
  last = "in";
60
99
  }
61
100
  const id = options.identify?.();
@@ -69,7 +108,10 @@ function connectPostHog(posthog, api, options = {}) {
69
108
  const events = ["ready", "replay", "consent", "change"];
70
109
  const unsubs = events.map((ev) => api.on(ev, apply));
71
110
  apply();
72
- return () => unsubs.forEach((u) => u());
111
+ return () => {
112
+ unsubs.forEach((u) => u());
113
+ restoreRemoteConfig?.();
114
+ };
73
115
  }
74
116
  var NON_ESSENTIAL_EVENTS = [
75
117
  "$autocapture",
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts"],"sourcesContent":["import type { EasyCookieApi, EasyCookieEvent } from '@easy-cookie/core/shared';\n\n/**\n * The few posthog-js methods the adapter uses. Typed loosely on purpose, so\n * `posthog-js` stays an optional peer dependency and any compatible client works.\n */\nexport interface PostHogLike {\n opt_in_capturing(options?: { captureEventName?: string | null | false; [key: string]: unknown }): void;\n opt_out_capturing(): void;\n has_opted_in_capturing?(): boolean;\n has_opted_out_capturing?(): boolean;\n clear_opt_in_out_capturing?(): void;\n /** posthog-js ≥ 1.2xx: 'granted' | 'denied' | 'pending' (reliable with cookieless_mode). */\n get_explicit_consent_status?(): string;\n startSessionRecording?(...args: unknown[]): void;\n stopSessionRecording?(): void;\n identify?(distinctId?: string, ...rest: unknown[]): void;\n get_distinct_id?(): string;\n}\n\n/** Minimal shape of a PostHog event passed to `before_send`. */\nexport interface PostHogEventLike {\n event: string;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- matches posthog-js `Properties`\n properties?: Record<string, any>;\n}\n\nexport interface ConnectPostHogOptions {\n /** Category that allows PostHog cookies/profiles. Default `measurement`. */\n category?: string;\n /** Service id: when set, the service's own consent decides instead of the category. */\n service?: string;\n /**\n * Return the logged-in user id (or undefined). Called after opt-in, so the\n * identified person profile is created only with consent.\n */\n identify?: () => string | undefined | null;\n /**\n * Before the visitor's first choice:\n * - `'pending'` (default): capture nothing. A stale opt-in left in storage by an\n * earlier setup is cleared, so nothing is captured with cookies.\n * - `'cookieless'`: count visits without cookies (same as after a rejection).\n * Only if your privacy policy covers cookieless measurement without consent.\n */\n beforeChoice?: 'pending' | 'cookieless';\n /** Start session recording on opt-in and stop it on opt-out. Default false. */\n sessionReplay?: boolean;\n}\n\n/**\n * Keep PostHog's capture state in sync with the visitor's consent, without reloads.\n *\n * PostHog must be initialised by the host with `cookieless_mode: 'on_reject'`\n * (see {@link posthogInitOptions}): before a choice it captures nothing (or counts\n * cookieless with `beforeChoice: 'cookieless'`), after a\n * rejection it keeps counting anonymously with no cookies or storage, and after\n * an acceptance it switches to normal cookie-based capture.\n *\n * On `replay`, `consent` and `change` the adapter calls `opt_in_capturing()` or\n * `opt_out_capturing()`. Returns an unsubscribe function.\n */\nexport function connectPostHog(posthog: PostHogLike, api: EasyCookieApi, options: ConnectPostHogOptions = {}): () => void {\n const category = options.category ?? 'measurement';\n const granted = () => (options.service ? api.isServiceGranted(options.service) : api.isGranted(category));\n let last: 'in' | 'out' | null = null;\n\n // With cookieless_mode, has_opted_out_capturing() is already true while consent\n // is pending, so prefer the explicit consent status when the client has it.\n const status = (): 'in' | 'out' | 'pending' => {\n const explicit = posthog.get_explicit_consent_status?.();\n if (explicit === 'granted') return 'in';\n if (explicit === 'denied') return 'out';\n if (explicit === 'pending') return 'pending';\n if (posthog.has_opted_in_capturing?.()) return 'in';\n if (posthog.has_opted_out_capturing?.()) return 'out';\n return 'pending';\n };\n\n const apply = () => {\n // Until run() has read the stored choice, \"no choice\" is not known yet:\n // acting now could opt out (and reset) a returning visitor who accepted.\n if (!api.getConfig()) return;\n if (!api.get()) {\n if (options.beforeChoice === 'cookieless') {\n if (last !== 'out') {\n // Also when already out: on a full page load posthog-js sends the first\n // cookieless $pageview only from opt_out_capturing() (no reset when not opted in).\n if (status() !== 'out' || last === null) posthog.opt_out_capturing();\n last = 'out';\n }\n } else if (status() === 'in') {\n // Pending: an opt-in stored by a previous banner must not keep capturing.\n posthog.clear_opt_in_out_capturing?.();\n }\n return;\n }\n if (granted()) {\n if (last !== 'in') {\n // No `$opt_in` event: the consent itself is recorded by easy-cookie.\n if (status() !== 'in') posthog.opt_in_capturing({ captureEventName: false });\n if (options.sessionReplay) posthog.startSessionRecording?.();\n last = 'in';\n }\n const id = options.identify?.();\n if (id && posthog.identify && posthog.get_distinct_id?.() !== id) posthog.identify(id);\n } else if (last !== 'out') {\n if (options.sessionReplay) posthog.stopSessionRecording?.();\n if (status() !== 'out' || last === null) posthog.opt_out_capturing();\n last = 'out';\n }\n };\n\n const events: EasyCookieEvent[] = ['ready', 'replay', 'consent', 'change'];\n const unsubs = events.map((ev) => api.on(ev, apply));\n // The stored choice may have been replayed before we subscribed.\n apply();\n return () => unsubs.forEach((u) => u());\n}\n\n/** Events dropped by {@link consentBeforeSend} while consent is missing. */\nexport const NON_ESSENTIAL_EVENTS: readonly string[] = [\n '$autocapture',\n '$rageclick',\n '$dead_click',\n '$exception',\n '$web_vitals',\n '$$heatmap',\n '$heatmap',\n];\n\nexport interface ConsentBeforeSendOptions {\n /** Category checked by the default `isGranted`. Default `measurement`. */\n category?: string;\n /**\n * Consent check. Defaults to the runtime when `api` is given, otherwise to the\n * state published by the head script (`window.__easyCookieHead.granted`).\n */\n isGranted?: () => boolean;\n api?: Pick<EasyCookieApi, 'isGranted'> | null;\n /** Event names to drop without consent. Default {@link NON_ESSENTIAL_EVENTS}. */\n drop?: readonly string[];\n}\n\nfunction headGranted(category: string): boolean {\n const head = (globalThis as { __easyCookieHead?: { granted?: string[]; valid?: boolean } }).__easyCookieHead;\n return !!head?.valid && !!head.granted?.includes(category);\n}\n\n/**\n * `before_send` filter: without consent, drop autocapture, exceptions, web vitals\n * and heatmap events, so cookieless mode only sends the essentials (pageviews,\n * explicit captures). Pass it as `before_send` or use {@link posthogInitOptions}.\n */\nexport function consentBeforeSend(options: ConsentBeforeSendOptions = {}) {\n const category = options.category ?? 'measurement';\n const drop = new Set(options.drop ?? NON_ESSENTIAL_EVENTS);\n const isGranted =\n options.isGranted ?? (() => (options.api ? options.api.isGranted(category) : headGranted(category)));\n return <T extends PostHogEventLike | null>(event: T): T | null => {\n if (!event) return event;\n if (drop.has(event.event) && !isGranted()) return null;\n return event;\n };\n}\n\nexport interface PostHogInitOptions {\n cookieless_mode: 'on_reject';\n persistence: 'localStorage+cookie';\n person_profiles: 'identified_only';\n before_send: ReturnType<typeof consentBeforeSend>;\n [key: string]: unknown;\n}\n\n/**\n * Recommended `posthog.init()` options for easy-cookie:\n * - `cookieless_mode: 'on_reject'` (requires \"Cookieless server hash mode\" enabled\n * in the PostHog project settings);\n * - `persistence: 'localStorage+cookie'` (only used after opt-in);\n * - `person_profiles: 'identified_only'`;\n * - a consent-aware `before_send` filter.\n *\n * Spread your own options after it: `posthog.init(key, { ...posthogInitOptions(), api_host })`.\n */\nexport function posthogInitOptions(options: ConsentBeforeSendOptions = {}): PostHogInitOptions {\n return {\n cookieless_mode: 'on_reject',\n persistence: 'localStorage+cookie',\n person_profiles: 'identified_only',\n before_send: consentBeforeSend(options),\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA6DO,SAAS,eAAe,SAAsB,KAAoB,UAAiC,CAAC,GAAe;AACxH,QAAM,WAAW,QAAQ,YAAY;AACrC,QAAM,UAAU,MAAO,QAAQ,UAAU,IAAI,iBAAiB,QAAQ,OAAO,IAAI,IAAI,UAAU,QAAQ;AACvG,MAAI,OAA4B;AAIhC,QAAM,SAAS,MAAgC;AAC7C,UAAM,WAAW,QAAQ,8BAA8B;AACvD,QAAI,aAAa,UAAW,QAAO;AACnC,QAAI,aAAa,SAAU,QAAO;AAClC,QAAI,aAAa,UAAW,QAAO;AACnC,QAAI,QAAQ,yBAAyB,EAAG,QAAO;AAC/C,QAAI,QAAQ,0BAA0B,EAAG,QAAO;AAChD,WA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AAOO,SAAS,kBAAkB,UAAoC,CAAC,GAAG;AACxE,QAAM,WAAW,QAAQ,YAAY;AACrC,QAAM,OAAO,IAAI,IAAI,QAAQ,QAAQ,oBAAoB;AACzD,QAAM,YACJ,QAAQ,cAAc,MAAO,QAAQ,MAAM,QAAQ,IAAI,UAAU,QAAQ,IAAI,YAAY,QAAQ;AACnG,SAAO,CAAoC,UAAuB;AAChE,QAAI,CAAC,MAAO,QAAO;AACnB,QAAI,KAAK,IAAI,MAAM,KAAK,KAAK,CAAC,UAAU,EAAG,QAAO;AAClD,WAAO;AAAA,EACT;AACF;AAoBO,SAAS,mBAAmB,UAAoC,CAAC,GAAuB;AAC7F,SAAO;AAAA,IACL,iBAAiB;AAAA,IACjB,aAAa;AAAA,IACb,iBAAiB;AAAA,IACjB,aAAa,kBAAkB,OAAO;AAAA,EACxC;AACF;","names":[]}
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["import type { EasyCookieApi, EasyCookieEvent } from '@easy-cookie/core/shared';\n\n/**\n * The few posthog-js methods the adapter uses. Typed loosely on purpose, so\n * `posthog-js` stays an optional peer dependency and any compatible client works.\n */\nexport interface PostHogLike {\n opt_in_capturing(options?: { captureEventName?: string | null | false; [key: string]: unknown }): void;\n opt_out_capturing(): void;\n has_opted_in_capturing?(): boolean;\n has_opted_out_capturing?(): boolean;\n clear_opt_in_out_capturing?(): void;\n /** posthog-js ≥ 1.2xx: 'granted' | 'denied' | 'pending' (reliable with cookieless_mode). */\n get_explicit_consent_status?(): string;\n startSessionRecording?(...args: unknown[]): void;\n stopSessionRecording?(): void;\n identify?(distinctId?: string, ...rest: unknown[]): void;\n get_distinct_id?(): string;\n}\n\n/**\n * posthog-js internals used only to restart session replay after a cookieless →\n * opt-in switch. Kept out of {@link PostHogLike} so posthog-js' own (stricter)\n * signatures never conflict with ours; accessed through a guarded cast.\n */\ninterface PostHogInternals {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n _onRemoteConfig?: (config: any) => void;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n sessionRecording?: { onRemoteConfig?(config: any): void } | null;\n config?: { token?: string };\n requestRouter?: { endpointFor?(target: string, path: string): string };\n}\n\n/** Minimal shape of a PostHog event passed to `before_send`. */\nexport interface PostHogEventLike {\n event: string;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- matches posthog-js `Properties`\n properties?: Record<string, any>;\n}\n\nexport interface ConnectPostHogOptions {\n /** Category that allows PostHog cookies/profiles. Default `measurement`. */\n category?: string;\n /** Service id: when set, the service's own consent decides instead of the category. */\n service?: string;\n /**\n * Return the logged-in user id (or undefined). Called after opt-in, so the\n * identified person profile is created only with consent.\n */\n identify?: () => string | undefined | null;\n /**\n * Before the visitor's first choice:\n * - `'pending'` (default): capture nothing. A stale opt-in left in storage by an\n * earlier setup is cleared, so nothing is captured with cookies.\n * - `'cookieless'`: count visits without cookies (same as after a rejection).\n * Only if your privacy policy covers cookieless measurement without consent.\n */\n beforeChoice?: 'pending' | 'cookieless';\n /** Start session recording on opt-in and stop it on opt-out. Default false. */\n sessionReplay?: boolean;\n}\n\n/**\n * Keep PostHog's capture state in sync with the visitor's consent, without reloads.\n *\n * PostHog must be initialised by the host with `cookieless_mode: 'on_reject'`\n * (see {@link posthogInitOptions}): before a choice it captures nothing (or counts\n * cookieless with `beforeChoice: 'cookieless'`), after a\n * rejection it keeps counting anonymously with no cookies or storage, and after\n * an acceptance it switches to normal cookie-based capture.\n *\n * On `replay`, `consent` and `change` the adapter calls `opt_in_capturing()` or\n * `opt_out_capturing()`. Returns an unsubscribe function.\n */\nexport function connectPostHog(posthog: PostHogLike, api: EasyCookieApi, options: ConnectPostHogOptions = {}): () => void {\n const category = options.category ?? 'measurement';\n const granted = () => (options.service ? api.isServiceGranted(options.service) : api.isGranted(category));\n let last: 'in' | 'out' | null = null;\n\n // Session replay after a cookieless → opt-in switch. posthog-js resets the instance\n // and creates a new recorder that waits for the remote config, which it only\n // fetches once per page load (and which the cookieless instance never stored).\n // Keep the config posthog-js receives, or fetch it again, and hand it to the new\n // recorder. Every call is guarded: with a different posthog-js the replay simply\n // starts on the next page load, as before.\n const ph = posthog as PostHogLike & PostHogInternals;\n let remoteConfig: Record<string, unknown> | undefined;\n let restoreRemoteConfig: (() => void) | undefined;\n if (options.sessionReplay && typeof ph._onRemoteConfig === 'function') {\n const hadOwn = Object.prototype.hasOwnProperty.call(ph, '_onRemoteConfig');\n const previous = ph._onRemoteConfig;\n const bound = previous.bind(ph);\n ph._onRemoteConfig = (config: Record<string, unknown>) => {\n remoteConfig = config;\n bound(config);\n };\n // Undo on disconnect, so reconnecting never stacks wrappers.\n restoreRemoteConfig = () => {\n if (hadOwn) ph._onRemoteConfig = previous;\n else delete ph._onRemoteConfig;\n };\n }\n const fetchRemoteConfig = async (): Promise<Record<string, unknown> | undefined> => {\n try {\n const token = ph.config?.token;\n const url = token && ph.requestRouter?.endpointFor?.('assets', `/array/${token}/config`);\n if (!url) return undefined;\n const res = await fetch(url);\n return res.ok ? ((await res.json()) as Record<string, unknown>) : undefined;\n } catch {\n return undefined;\n }\n };\n const restartReplay = async () => {\n try {\n const config = remoteConfig ?? (await fetchRemoteConfig());\n if (config && 'sessionRecording' in config) ph.sessionRecording?.onRemoteConfig?.(config);\n posthog.startSessionRecording?.();\n } catch {\n /* replay starts on the next page load */\n }\n };\n\n // With cookieless_mode, has_opted_out_capturing() is already true while consent\n // is pending, so prefer the explicit consent status when the client has it.\n const status = (): 'in' | 'out' | 'pending' => {\n const explicit = posthog.get_explicit_consent_status?.();\n if (explicit === 'granted') return 'in';\n if (explicit === 'denied') return 'out';\n if (explicit === 'pending') return 'pending';\n if (posthog.has_opted_in_capturing?.()) return 'in';\n if (posthog.has_opted_out_capturing?.()) return 'out';\n return 'pending';\n };\n\n const apply = () => {\n // Until run() has read the stored choice, \"no choice\" is not known yet:\n // acting now could opt out (and reset) a returning visitor who accepted.\n if (!api.getConfig()) return;\n if (!api.get()) {\n if (options.beforeChoice === 'cookieless') {\n if (last !== 'out') {\n // Also when already out: on a full page load posthog-js sends the first\n // cookieless $pageview only from opt_out_capturing() (no reset when not opted in).\n if (status() !== 'out' || last === null) posthog.opt_out_capturing();\n last = 'out';\n }\n } else if (status() === 'in') {\n // Pending: an opt-in stored by a previous banner must not keep capturing.\n posthog.clear_opt_in_out_capturing?.();\n }\n return;\n }\n if (granted()) {\n if (last !== 'in') {\n // No `$opt_in` event: the consent itself is recorded by easy-cookie.\n const fromCookieless = status() === 'out';\n if (status() !== 'in') posthog.opt_in_capturing({ captureEventName: false });\n if (options.sessionReplay) {\n if (fromCookieless) void restartReplay();\n else posthog.startSessionRecording?.();\n }\n last = 'in';\n }\n const id = options.identify?.();\n if (id && posthog.identify && posthog.get_distinct_id?.() !== id) posthog.identify(id);\n } else if (last !== 'out') {\n if (options.sessionReplay) posthog.stopSessionRecording?.();\n if (status() !== 'out' || last === null) posthog.opt_out_capturing();\n last = 'out';\n }\n };\n\n const events: EasyCookieEvent[] = ['ready', 'replay', 'consent', 'change'];\n const unsubs = events.map((ev) => api.on(ev, apply));\n // The stored choice may have been replayed before we subscribed.\n apply();\n return () => {\n unsubs.forEach((u) => u());\n restoreRemoteConfig?.();\n };\n}\n\n/** Events dropped by {@link consentBeforeSend} while consent is missing. */\nexport const NON_ESSENTIAL_EVENTS: readonly string[] = [\n '$autocapture',\n '$rageclick',\n '$dead_click',\n '$exception',\n '$web_vitals',\n '$$heatmap',\n '$heatmap',\n];\n\nexport interface ConsentBeforeSendOptions {\n /** Category checked by the default `isGranted`. Default `measurement`. */\n category?: string;\n /**\n * Consent check. Defaults to the runtime when `api` is given, otherwise to the\n * state published by the head script (`window.__easyCookieHead.granted`).\n */\n isGranted?: () => boolean;\n api?: Pick<EasyCookieApi, 'isGranted'> | null;\n /** Event names to drop without consent. Default {@link NON_ESSENTIAL_EVENTS}. */\n drop?: readonly string[];\n}\n\nfunction headGranted(category: string): boolean {\n const head = (globalThis as { __easyCookieHead?: { granted?: string[]; valid?: boolean } }).__easyCookieHead;\n return !!head?.valid && !!head.granted?.includes(category);\n}\n\n/**\n * `before_send` filter: without consent, drop autocapture, exceptions, web vitals\n * and heatmap events, so cookieless mode only sends the essentials (pageviews,\n * explicit captures). Pass it as `before_send` or use {@link posthogInitOptions}.\n */\nexport function consentBeforeSend(options: ConsentBeforeSendOptions = {}) {\n const category = options.category ?? 'measurement';\n const drop = new Set(options.drop ?? NON_ESSENTIAL_EVENTS);\n const isGranted =\n options.isGranted ?? (() => (options.api ? options.api.isGranted(category) : headGranted(category)));\n return <T extends PostHogEventLike | null>(event: T): T | null => {\n if (!event) return event;\n if (drop.has(event.event) && !isGranted()) return null;\n return event;\n };\n}\n\nexport interface PostHogInitOptions {\n cookieless_mode: 'on_reject';\n persistence: 'localStorage+cookie';\n person_profiles: 'identified_only';\n before_send: ReturnType<typeof consentBeforeSend>;\n [key: string]: unknown;\n}\n\n/**\n * Recommended `posthog.init()` options for easy-cookie:\n * - `cookieless_mode: 'on_reject'` (requires \"Cookieless server hash mode\" enabled\n * in the PostHog project settings);\n * - `persistence: 'localStorage+cookie'` (only used after opt-in);\n * - `person_profiles: 'identified_only'`;\n * - a consent-aware `before_send` filter.\n *\n * Spread your own options after it: `posthog.init(key, { ...posthogInitOptions(), api_host })`.\n */\nexport function posthogInitOptions(options: ConsentBeforeSendOptions = {}): PostHogInitOptions {\n return {\n cookieless_mode: 'on_reject',\n persistence: 'localStorage+cookie',\n person_profiles: 'identified_only',\n before_send: consentBeforeSend(options),\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA2EO,SAAS,eAAe,SAAsB,KAAoB,UAAiC,CAAC,GAAe;AACxH,QAAM,WAAW,QAAQ,YAAY;AACrC,QAAM,UAAU,MAAO,QAAQ,UAAU,IAAI,iBAAiB,QAAQ,OAAO,IAAI,IAAI,UAAU,QAAQ;AACvG,MAAI,OAA4B;AAQhC,QAAM,KAAK;AACX,MA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O,SAAS,kBAAkB,UAAoC,CAAC,GAAG;AACxE,QAAM,WAAW,QAAQ,YAAY;AACrC,QAAM,OAAO,IAAI,IAAI,QAAQ,QAAQ,oBAAoB;AACzD,QAAM,YACJ,QAAQ,cAAc,MAAO,QAAQ,MAAM,QAAQ,IAAI,UAAU,QAAQ,IAAI,YAAY,QAAQ;AACnG,SAAO,CAAoC,UAAuB;AAChE,QAAI,CAAC,MAAO,QAAO;AACnB,QAAI,KAAK,IAAI,MAAM,KAAK,KAAK,CAAC,UAAU,EAAG,QAAO;AAClD,WAAO;AAAA,EACT;AACF;AAoBO,SAAS,mBAAmB,UAAoC,CAAC,GAAuB;AAC7F,SAAO;AAAA,IACL,iBAAiB;AAAA,IACjB,aAAa;AAAA,IACb,iBAAiB;AAAA,IACjB,aAAa,kBAAkB,OAAO;AAAA,EACxC;AACF;","names":[]}
package/dist/index.js CHANGED
@@ -3,6 +3,41 @@ function connectPostHog(posthog, api, options = {}) {
3
3
  const category = options.category ?? "measurement";
4
4
  const granted = () => options.service ? api.isServiceGranted(options.service) : api.isGranted(category);
5
5
  let last = null;
6
+ const ph = posthog;
7
+ let remoteConfig;
8
+ let restoreRemoteConfig;
9
+ if (options.sessionReplay && typeof ph._onRemoteConfig === "function") {
10
+ const hadOwn = Object.prototype.hasOwnProperty.call(ph, "_onRemoteConfig");
11
+ const previous = ph._onRemoteConfig;
12
+ const bound = previous.bind(ph);
13
+ ph._onRemoteConfig = (config) => {
14
+ remoteConfig = config;
15
+ bound(config);
16
+ };
17
+ restoreRemoteConfig = () => {
18
+ if (hadOwn) ph._onRemoteConfig = previous;
19
+ else delete ph._onRemoteConfig;
20
+ };
21
+ }
22
+ const fetchRemoteConfig = async () => {
23
+ try {
24
+ const token = ph.config?.token;
25
+ const url = token && ph.requestRouter?.endpointFor?.("assets", `/array/${token}/config`);
26
+ if (!url) return void 0;
27
+ const res = await fetch(url);
28
+ return res.ok ? await res.json() : void 0;
29
+ } catch {
30
+ return void 0;
31
+ }
32
+ };
33
+ const restartReplay = async () => {
34
+ try {
35
+ const config = remoteConfig ?? await fetchRemoteConfig();
36
+ if (config && "sessionRecording" in config) ph.sessionRecording?.onRemoteConfig?.(config);
37
+ posthog.startSessionRecording?.();
38
+ } catch {
39
+ }
40
+ };
6
41
  const status = () => {
7
42
  const explicit = posthog.get_explicit_consent_status?.();
8
43
  if (explicit === "granted") return "in";
@@ -27,8 +62,12 @@ function connectPostHog(posthog, api, options = {}) {
27
62
  }
28
63
  if (granted()) {
29
64
  if (last !== "in") {
65
+ const fromCookieless = status() === "out";
30
66
  if (status() !== "in") posthog.opt_in_capturing({ captureEventName: false });
31
- if (options.sessionReplay) posthog.startSessionRecording?.();
67
+ if (options.sessionReplay) {
68
+ if (fromCookieless) void restartReplay();
69
+ else posthog.startSessionRecording?.();
70
+ }
32
71
  last = "in";
33
72
  }
34
73
  const id = options.identify?.();
@@ -42,7 +81,10 @@ function connectPostHog(posthog, api, options = {}) {
42
81
  const events = ["ready", "replay", "consent", "change"];
43
82
  const unsubs = events.map((ev) => api.on(ev, apply));
44
83
  apply();
45
- return () => unsubs.forEach((u) => u());
84
+ return () => {
85
+ unsubs.forEach((u) => u());
86
+ restoreRemoteConfig?.();
87
+ };
46
88
  }
47
89
  var NON_ESSENTIAL_EVENTS = [
48
90
  "$autocapture",
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts"],"sourcesContent":["import type { EasyCookieApi, EasyCookieEvent } from '@easy-cookie/core/shared';\n\n/**\n * The few posthog-js methods the adapter uses. Typed loosely on purpose, so\n * `posthog-js` stays an optional peer dependency and any compatible client works.\n */\nexport interface PostHogLike {\n opt_in_capturing(options?: { captureEventName?: string | null | false; [key: string]: unknown }): void;\n opt_out_capturing(): void;\n has_opted_in_capturing?(): boolean;\n has_opted_out_capturing?(): boolean;\n clear_opt_in_out_capturing?(): void;\n /** posthog-js ≥ 1.2xx: 'granted' | 'denied' | 'pending' (reliable with cookieless_mode). */\n get_explicit_consent_status?(): string;\n startSessionRecording?(...args: unknown[]): void;\n stopSessionRecording?(): void;\n identify?(distinctId?: string, ...rest: unknown[]): void;\n get_distinct_id?(): string;\n}\n\n/** Minimal shape of a PostHog event passed to `before_send`. */\nexport interface PostHogEventLike {\n event: string;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- matches posthog-js `Properties`\n properties?: Record<string, any>;\n}\n\nexport interface ConnectPostHogOptions {\n /** Category that allows PostHog cookies/profiles. Default `measurement`. */\n category?: string;\n /** Service id: when set, the service's own consent decides instead of the category. */\n service?: string;\n /**\n * Return the logged-in user id (or undefined). Called after opt-in, so the\n * identified person profile is created only with consent.\n */\n identify?: () => string | undefined | null;\n /**\n * Before the visitor's first choice:\n * - `'pending'` (default): capture nothing. A stale opt-in left in storage by an\n * earlier setup is cleared, so nothing is captured with cookies.\n * - `'cookieless'`: count visits without cookies (same as after a rejection).\n * Only if your privacy policy covers cookieless measurement without consent.\n */\n beforeChoice?: 'pending' | 'cookieless';\n /** Start session recording on opt-in and stop it on opt-out. Default false. */\n sessionReplay?: boolean;\n}\n\n/**\n * Keep PostHog's capture state in sync with the visitor's consent, without reloads.\n *\n * PostHog must be initialised by the host with `cookieless_mode: 'on_reject'`\n * (see {@link posthogInitOptions}): before a choice it captures nothing (or counts\n * cookieless with `beforeChoice: 'cookieless'`), after a\n * rejection it keeps counting anonymously with no cookies or storage, and after\n * an acceptance it switches to normal cookie-based capture.\n *\n * On `replay`, `consent` and `change` the adapter calls `opt_in_capturing()` or\n * `opt_out_capturing()`. Returns an unsubscribe function.\n */\nexport function connectPostHog(posthog: PostHogLike, api: EasyCookieApi, options: ConnectPostHogOptions = {}): () => void {\n const category = options.category ?? 'measurement';\n const granted = () => (options.service ? api.isServiceGranted(options.service) : api.isGranted(category));\n let last: 'in' | 'out' | null = null;\n\n // With cookieless_mode, has_opted_out_capturing() is already true while consent\n // is pending, so prefer the explicit consent status when the client has it.\n const status = (): 'in' | 'out' | 'pending' => {\n const explicit = posthog.get_explicit_consent_status?.();\n if (explicit === 'granted') return 'in';\n if (explicit === 'denied') return 'out';\n if (explicit === 'pending') return 'pending';\n if (posthog.has_opted_in_capturing?.()) return 'in';\n if (posthog.has_opted_out_capturing?.()) return 'out';\n return 'pending';\n };\n\n const apply = () => {\n // Until run() has read the stored choice, \"no choice\" is not known yet:\n // acting now could opt out (and reset) a returning visitor who accepted.\n if (!api.getConfig()) return;\n if (!api.get()) {\n if (options.beforeChoice === 'cookieless') {\n if (last !== 'out') {\n // Also when already out: on a full page load posthog-js sends the first\n // cookieless $pageview only from opt_out_capturing() (no reset when not opted in).\n if (status() !== 'out' || last === null) posthog.opt_out_capturing();\n last = 'out';\n }\n } else if (status() === 'in') {\n // Pending: an opt-in stored by a previous banner must not keep capturing.\n posthog.clear_opt_in_out_capturing?.();\n }\n return;\n }\n if (granted()) {\n if (last !== 'in') {\n // No `$opt_in` event: the consent itself is recorded by easy-cookie.\n if (status() !== 'in') posthog.opt_in_capturing({ captureEventName: false });\n if (options.sessionReplay) posthog.startSessionRecording?.();\n last = 'in';\n }\n const id = options.identify?.();\n if (id && posthog.identify && posthog.get_distinct_id?.() !== id) posthog.identify(id);\n } else if (last !== 'out') {\n if (options.sessionReplay) posthog.stopSessionRecording?.();\n if (status() !== 'out' || last === null) posthog.opt_out_capturing();\n last = 'out';\n }\n };\n\n const events: EasyCookieEvent[] = ['ready', 'replay', 'consent', 'change'];\n const unsubs = events.map((ev) => api.on(ev, apply));\n // The stored choice may have been replayed before we subscribed.\n apply();\n return () => unsubs.forEach((u) => u());\n}\n\n/** Events dropped by {@link consentBeforeSend} while consent is missing. */\nexport const NON_ESSENTIAL_EVENTS: readonly string[] = [\n '$autocapture',\n '$rageclick',\n '$dead_click',\n '$exception',\n '$web_vitals',\n '$$heatmap',\n '$heatmap',\n];\n\nexport interface ConsentBeforeSendOptions {\n /** Category checked by the default `isGranted`. Default `measurement`. */\n category?: string;\n /**\n * Consent check. Defaults to the runtime when `api` is given, otherwise to the\n * state published by the head script (`window.__easyCookieHead.granted`).\n */\n isGranted?: () => boolean;\n api?: Pick<EasyCookieApi, 'isGranted'> | null;\n /** Event names to drop without consent. Default {@link NON_ESSENTIAL_EVENTS}. */\n drop?: readonly string[];\n}\n\nfunction headGranted(category: string): boolean {\n const head = (globalThis as { __easyCookieHead?: { granted?: string[]; valid?: boolean } }).__easyCookieHead;\n return !!head?.valid && !!head.granted?.includes(category);\n}\n\n/**\n * `before_send` filter: without consent, drop autocapture, exceptions, web vitals\n * and heatmap events, so cookieless mode only sends the essentials (pageviews,\n * explicit captures). Pass it as `before_send` or use {@link posthogInitOptions}.\n */\nexport function consentBeforeSend(options: ConsentBeforeSendOptions = {}) {\n const category = options.category ?? 'measurement';\n const drop = new Set(options.drop ?? NON_ESSENTIAL_EVENTS);\n const isGranted =\n options.isGranted ?? (() => (options.api ? options.api.isGranted(category) : headGranted(category)));\n return <T extends PostHogEventLike | null>(event: T): T | null => {\n if (!event) return event;\n if (drop.has(event.event) && !isGranted()) return null;\n return event;\n };\n}\n\nexport interface PostHogInitOptions {\n cookieless_mode: 'on_reject';\n persistence: 'localStorage+cookie';\n person_profiles: 'identified_only';\n before_send: ReturnType<typeof consentBeforeSend>;\n [key: string]: unknown;\n}\n\n/**\n * Recommended `posthog.init()` options for easy-cookie:\n * - `cookieless_mode: 'on_reject'` (requires \"Cookieless server hash mode\" enabled\n * in the PostHog project settings);\n * - `persistence: 'localStorage+cookie'` (only used after opt-in);\n * - `person_profiles: 'identified_only'`;\n * - a consent-aware `before_send` filter.\n *\n * Spread your own options after it: `posthog.init(key, { ...posthogInitOptions(), api_host })`.\n */\nexport function posthogInitOptions(options: ConsentBeforeSendOptions = {}): PostHogInitOptions {\n return {\n cookieless_mode: 'on_reject',\n persistence: 'localStorage+cookie',\n person_profiles: 'identified_only',\n before_send: consentBeforeSend(options),\n };\n}\n"],"mappings":";AA6DO,SAAS,eAAe,SAAsB,KAAoB,UAAiC,CAAC,GAAe;AACxH,QAAM,W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AS,OAAO,IAAI,CAAC,OAAO,IAAI,GAAG,IAAI,KAAK,CAAC;AAEnD,QAAM;AACN,SAAO,MAAM,OAAO,QAAQ,CAAC,MAAM,EAAE,CAAC;AACxC;AAGO,IAAM,uBAA0C;AAAA,EACrD;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAeA,SAAS,YAAY,UAA2B;AAC9C,QAAM,OAAQ,WAA8E;AAC5F,SAAO,CAAC,CAAC,MAAM,SAAS,CAAC,CAAC,KAAK,SAAS,SAAS,QAAQ;AAC3D;AAOO,SAAS,kBAAkB,UAAoC,CAAC,GAAG;AACxE,QAAM,WAAW,QAAQ,YAAY;AACrC,QAAM,OAAO,IAAI,IAAI,QAAQ,QAAQ,oBAAoB;AACzD,QAAM,YACJ,QAAQ,cAAc,MAAO,QAAQ,MAAM,QAAQ,IAAI,UAAU,QAAQ,IAAI,YAAY,QAAQ;AACnG,SAAO,CAAoC,UAAuB;AAChE,QAAI,CAAC,MAAO,QAAO;AACnB,QAAI,KAAK,IAAI,MAAM,KAAK,KAAK,CAAC,UAAU,EAAG,QAAO;AAClD,WAAO;AAAA,EACT;AACF;AAoBO,SAAS,mBAAmB,UAAoC,CAAC,GAAuB;AAC7F,SAAO;AAAA,IACL,iBAAiB;AAAA,IACjB,aAAa;AAAA,IACb,iBAAiB;AAAA,IACjB,aAAa,kBAAkB,OAAO;AAAA,EACxC;AACF;","names":[]}
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["import type { EasyCookieApi, EasyCookieEvent } from '@easy-cookie/core/shared';\n\n/**\n * The few posthog-js methods the adapter uses. Typed loosely on purpose, so\n * `posthog-js` stays an optional peer dependency and any compatible client works.\n */\nexport interface PostHogLike {\n opt_in_capturing(options?: { captureEventName?: string | null | false; [key: string]: unknown }): void;\n opt_out_capturing(): void;\n has_opted_in_capturing?(): boolean;\n has_opted_out_capturing?(): boolean;\n clear_opt_in_out_capturing?(): void;\n /** posthog-js ≥ 1.2xx: 'granted' | 'denied' | 'pending' (reliable with cookieless_mode). */\n get_explicit_consent_status?(): string;\n startSessionRecording?(...args: unknown[]): void;\n stopSessionRecording?(): void;\n identify?(distinctId?: string, ...rest: unknown[]): void;\n get_distinct_id?(): string;\n}\n\n/**\n * posthog-js internals used only to restart session replay after a cookieless →\n * opt-in switch. Kept out of {@link PostHogLike} so posthog-js' own (stricter)\n * signatures never conflict with ours; accessed through a guarded cast.\n */\ninterface PostHogInternals {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n _onRemoteConfig?: (config: any) => void;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n sessionRecording?: { onRemoteConfig?(config: any): void } | null;\n config?: { token?: string };\n requestRouter?: { endpointFor?(target: string, path: string): string };\n}\n\n/** Minimal shape of a PostHog event passed to `before_send`. */\nexport interface PostHogEventLike {\n event: string;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- matches posthog-js `Properties`\n properties?: Record<string, any>;\n}\n\nexport interface ConnectPostHogOptions {\n /** Category that allows PostHog cookies/profiles. Default `measurement`. */\n category?: string;\n /** Service id: when set, the service's own consent decides instead of the category. */\n service?: string;\n /**\n * Return the logged-in user id (or undefined). Called after opt-in, so the\n * identified person profile is created only with consent.\n */\n identify?: () => string | undefined | null;\n /**\n * Before the visitor's first choice:\n * - `'pending'` (default): capture nothing. A stale opt-in left in storage by an\n * earlier setup is cleared, so nothing is captured with cookies.\n * - `'cookieless'`: count visits without cookies (same as after a rejection).\n * Only if your privacy policy covers cookieless measurement without consent.\n */\n beforeChoice?: 'pending' | 'cookieless';\n /** Start session recording on opt-in and stop it on opt-out. Default false. */\n sessionReplay?: boolean;\n}\n\n/**\n * Keep PostHog's capture state in sync with the visitor's consent, without reloads.\n *\n * PostHog must be initialised by the host with `cookieless_mode: 'on_reject'`\n * (see {@link posthogInitOptions}): before a choice it captures nothing (or counts\n * cookieless with `beforeChoice: 'cookieless'`), after a\n * rejection it keeps counting anonymously with no cookies or storage, and after\n * an acceptance it switches to normal cookie-based capture.\n *\n * On `replay`, `consent` and `change` the adapter calls `opt_in_capturing()` or\n * `opt_out_capturing()`. Returns an unsubscribe function.\n */\nexport function connectPostHog(posthog: PostHogLike, api: EasyCookieApi, options: ConnectPostHogOptions = {}): () => void {\n const category = options.category ?? 'measurement';\n const granted = () => (options.service ? api.isServiceGranted(options.service) : api.isGranted(category));\n let last: 'in' | 'out' | null = null;\n\n // Session replay after a cookieless → opt-in switch. posthog-js resets the instance\n // and creates a new recorder that waits for the remote config, which it only\n // fetches once per page load (and which the cookieless instance never stored).\n // Keep the config posthog-js receives, or fetch it again, and hand it to the new\n // recorder. Every call is guarded: with a different posthog-js the replay simply\n // starts on the next page load, as before.\n const ph = posthog as PostHogLike & PostHogInternals;\n let remoteConfig: Record<string, unknown> | undefined;\n let restoreRemoteConfig: (() => void) | undefined;\n if (options.sessionReplay && typeof ph._onRemoteConfig === 'function') {\n const hadOwn = Object.prototype.hasOwnProperty.call(ph, '_onRemoteConfig');\n const previous = ph._onRemoteConfig;\n const bound = previous.bind(ph);\n ph._onRemoteConfig = (config: Record<string, unknown>) => {\n remoteConfig = config;\n bound(config);\n };\n // Undo on disconnect, so reconnecting never stacks wrappers.\n restoreRemoteConfig = () => {\n if (hadOwn) ph._onRemoteConfig = previous;\n else delete ph._onRemoteConfig;\n };\n }\n const fetchRemoteConfig = async (): Promise<Record<string, unknown> | undefined> => {\n try {\n const token = ph.config?.token;\n const url = token && ph.requestRouter?.endpointFor?.('assets', `/array/${token}/config`);\n if (!url) return undefined;\n const res = await fetch(url);\n return res.ok ? ((await res.json()) as Record<string, unknown>) : undefined;\n } catch {\n return undefined;\n }\n };\n const restartReplay = async () => {\n try {\n const config = remoteConfig ?? (await fetchRemoteConfig());\n if (config && 'sessionRecording' in config) ph.sessionRecording?.onRemoteConfig?.(config);\n posthog.startSessionRecording?.();\n } catch {\n /* replay starts on the next page load */\n }\n };\n\n // With cookieless_mode, has_opted_out_capturing() is already true while consent\n // is pending, so prefer the explicit consent status when the client has it.\n const status = (): 'in' | 'out' | 'pending' => {\n const explicit = posthog.get_explicit_consent_status?.();\n if (explicit === 'granted') return 'in';\n if (explicit === 'denied') return 'out';\n if (explicit === 'pending') return 'pending';\n if (posthog.has_opted_in_capturing?.()) return 'in';\n if (posthog.has_opted_out_capturing?.()) return 'out';\n return 'pending';\n };\n\n const apply = () => {\n // Until run() has read the stored choice, \"no choice\" is not known yet:\n // acting now could opt out (and reset) a returning visitor who accepted.\n if (!api.getConfig()) return;\n if (!api.get()) {\n if (options.beforeChoice === 'cookieless') {\n if (last !== 'out') {\n // Also when already out: on a full page load posthog-js sends the first\n // cookieless $pageview only from opt_out_capturing() (no reset when not opted in).\n if (status() !== 'out' || last === null) posthog.opt_out_capturing();\n last = 'out';\n }\n } else if (status() === 'in') {\n // Pending: an opt-in stored by a previous banner must not keep capturing.\n posthog.clear_opt_in_out_capturing?.();\n }\n return;\n }\n if (granted()) {\n if (last !== 'in') {\n // No `$opt_in` event: the consent itself is recorded by easy-cookie.\n const fromCookieless = status() === 'out';\n if (status() !== 'in') posthog.opt_in_capturing({ captureEventName: false });\n if (options.sessionReplay) {\n if (fromCookieless) void restartReplay();\n else posthog.startSessionRecording?.();\n }\n last = 'in';\n }\n const id = options.identify?.();\n if (id && posthog.identify && posthog.get_distinct_id?.() !== id) posthog.identify(id);\n } else if (last !== 'out') {\n if (options.sessionReplay) posthog.stopSessionRecording?.();\n if (status() !== 'out' || last === null) posthog.opt_out_capturing();\n last = 'out';\n }\n };\n\n const events: EasyCookieEvent[] = ['ready', 'replay', 'consent', 'change'];\n const unsubs = events.map((ev) => api.on(ev, apply));\n // The stored choice may have been replayed before we subscribed.\n apply();\n return () => {\n unsubs.forEach((u) => u());\n restoreRemoteConfig?.();\n };\n}\n\n/** Events dropped by {@link consentBeforeSend} while consent is missing. */\nexport const NON_ESSENTIAL_EVENTS: readonly string[] = [\n '$autocapture',\n '$rageclick',\n '$dead_click',\n '$exception',\n '$web_vitals',\n '$$heatmap',\n '$heatmap',\n];\n\nexport interface ConsentBeforeSendOptions {\n /** Category checked by the default `isGranted`. Default `measurement`. */\n category?: string;\n /**\n * Consent check. Defaults to the runtime when `api` is given, otherwise to the\n * state published by the head script (`window.__easyCookieHead.granted`).\n */\n isGranted?: () => boolean;\n api?: Pick<EasyCookieApi, 'isGranted'> | null;\n /** Event names to drop without consent. Default {@link NON_ESSENTIAL_EVENTS}. */\n drop?: readonly string[];\n}\n\nfunction headGranted(category: string): boolean {\n const head = (globalThis as { __easyCookieHead?: { granted?: string[]; valid?: boolean } }).__easyCookieHead;\n return !!head?.valid && !!head.granted?.includes(category);\n}\n\n/**\n * `before_send` filter: without consent, drop autocapture, exceptions, web vitals\n * and heatmap events, so cookieless mode only sends the essentials (pageviews,\n * explicit captures). Pass it as `before_send` or use {@link posthogInitOptions}.\n */\nexport function consentBeforeSend(options: ConsentBeforeSendOptions = {}) {\n const category = options.category ?? 'measurement';\n const drop = new Set(options.drop ?? NON_ESSENTIAL_EVENTS);\n const isGranted =\n options.isGranted ?? (() => (options.api ? options.api.isGranted(category) : headGranted(category)));\n return <T extends PostHogEventLike | null>(event: T): T | null => {\n if (!event) return event;\n if (drop.has(event.event) && !isGranted()) return null;\n return event;\n };\n}\n\nexport interface PostHogInitOptions {\n cookieless_mode: 'on_reject';\n persistence: 'localStorage+cookie';\n person_profiles: 'identified_only';\n before_send: ReturnType<typeof consentBeforeSend>;\n [key: string]: unknown;\n}\n\n/**\n * Recommended `posthog.init()` options for easy-cookie:\n * - `cookieless_mode: 'on_reject'` (requires \"Cookieless server hash mode\" enabled\n * in the PostHog project settings);\n * - `persistence: 'localStorage+cookie'` (only used after opt-in);\n * - `person_profiles: 'identified_only'`;\n * - a consent-aware `before_send` filter.\n *\n * Spread your own options after it: `posthog.init(key, { ...posthogInitOptions(), api_host })`.\n */\nexport function posthogInitOptions(options: ConsentBeforeSendOptions = {}): PostHogInitOptions {\n return {\n cookieless_mode: 'on_reject',\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,CAAC,MAAM,EAAE,CAAC;AACzB,0BAAsB;AAAA,EACxB;AACF;AAGO,IAAM,uBAA0C;AAAA,EACrD;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAeA,SAAS,YAAY,UAA2B;AAC9C,QAAM,OAAQ,WAA8E;AAC5F,SAAO,CAAC,CAAC,MAAM,SAAS,CAAC,CAAC,KAAK,SAAS,SAAS,QAAQ;AAC3D;AAOO,SAAS,kBAAkB,UAAoC,CAAC,GAAG;AACxE,QAAM,WAAW,QAAQ,YAAY;AACrC,QAAM,OAAO,IAAI,IAAI,QAAQ,QAAQ,oBAAoB;AACzD,QAAM,YACJ,QAAQ,cAAc,MAAO,QAAQ,MAAM,QAAQ,IAAI,UAAU,QAAQ,IAAI,YAAY,QAAQ;AACnG,SAAO,CAAoC,UAAuB;AAChE,QAAI,CAAC,MAAO,QAAO;AACnB,QAAI,KAAK,IAAI,MAAM,KAAK,KAAK,CAAC,UAAU,EAAG,QAAO;AAClD,WAAO;AAAA,EACT;AACF;AAoBO,SAAS,mBAAmB,UAAoC,CAAC,GAAuB;AAC7F,SAAO;AAAA,IACL,iBAAiB;AAAA,IACjB,aAAa;AAAA,IACb,iBAAiB;AAAA,IACjB,aAAa,kBAAkB,OAAO;AAAA,EACxC;AACF;","names":[]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@easy-cookie/posthog",
3
- "version": "0.1.3",
3
+ "version": "0.1.5",
4
4
  "description": "PostHog adapter for easy-cookie: cookieless on_reject mode and opt-in/out synced with consent.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -28,7 +28,7 @@
28
28
  "dist"
29
29
  ],
30
30
  "dependencies": {
31
- "@easy-cookie/core": "^0.1.3"
31
+ "@easy-cookie/core": "^0.1.5"
32
32
  },
33
33
  "peerDependencies": {
34
34
  "posthog-js": ">=1.200.0"