@shware/analytics 16.2.2 → 16.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/README.md +13 -1
  2. package/dist/react/index.cjs +1 -1
  3. package/dist/react/index.cjs.map +1 -1
  4. package/dist/react/index.d.cts +2 -2
  5. package/dist/react/index.d.mts +2 -2
  6. package/dist/react/index.mjs +2 -2
  7. package/dist/react/index.mjs.map +1 -1
  8. package/dist/react/posthog-error-boundary.cjs +11 -10
  9. package/dist/react/posthog-error-boundary.cjs.map +1 -1
  10. package/dist/react/posthog-error-boundary.d.cts +7 -7
  11. package/dist/react/posthog-error-boundary.d.cts.map +1 -1
  12. package/dist/react/posthog-error-boundary.d.mts +7 -7
  13. package/dist/react/posthog-error-boundary.d.mts.map +1 -1
  14. package/dist/react/posthog-error-boundary.mjs +11 -10
  15. package/dist/react/posthog-error-boundary.mjs.map +1 -1
  16. package/dist/schema/index.cjs +9 -7
  17. package/dist/schema/index.cjs.map +1 -1
  18. package/dist/schema/index.d.cts.map +1 -1
  19. package/dist/schema/index.d.mts.map +1 -1
  20. package/dist/schema/index.mjs +9 -7
  21. package/dist/schema/index.mjs.map +1 -1
  22. package/dist/server/event-time.cjs +14 -0
  23. package/dist/server/event-time.cjs.map +1 -0
  24. package/dist/server/event-time.d.cts +8 -0
  25. package/dist/server/event-time.d.cts.map +1 -0
  26. package/dist/server/event-time.d.mts +8 -0
  27. package/dist/server/event-time.d.mts.map +1 -0
  28. package/dist/server/event-time.mjs +13 -0
  29. package/dist/server/event-time.mjs.map +1 -0
  30. package/dist/server/meta-capi.cjs +4 -3
  31. package/dist/server/meta-capi.cjs.map +1 -1
  32. package/dist/server/meta-capi.d.cts.map +1 -1
  33. package/dist/server/meta-capi.d.mts.map +1 -1
  34. package/dist/server/meta-capi.mjs +4 -3
  35. package/dist/server/meta-capi.mjs.map +1 -1
  36. package/dist/server/microsoft-conversions-api.cjs +2 -1
  37. package/dist/server/microsoft-conversions-api.cjs.map +1 -1
  38. package/dist/server/microsoft-conversions-api.d.cts.map +1 -1
  39. package/dist/server/microsoft-conversions-api.d.mts.map +1 -1
  40. package/dist/server/microsoft-conversions-api.mjs +2 -1
  41. package/dist/server/microsoft-conversions-api.mjs.map +1 -1
  42. package/dist/server/reddit-conversions-api.cjs +2 -1
  43. package/dist/server/reddit-conversions-api.cjs.map +1 -1
  44. package/dist/server/reddit-conversions-api.d.cts.map +1 -1
  45. package/dist/server/reddit-conversions-api.d.mts.map +1 -1
  46. package/dist/server/reddit-conversions-api.mjs +2 -1
  47. package/dist/server/reddit-conversions-api.mjs.map +1 -1
  48. package/dist/third-parties/index.cjs +1 -0
  49. package/dist/third-parties/index.d.cts +2 -2
  50. package/dist/third-parties/index.d.mts +2 -2
  51. package/dist/third-parties/index.mjs +2 -2
  52. package/dist/third-parties/posthog.cjs +62 -3
  53. package/dist/third-parties/posthog.cjs.map +1 -1
  54. package/dist/third-parties/posthog.d.cts +43 -1
  55. package/dist/third-parties/posthog.d.cts.map +1 -1
  56. package/dist/third-parties/posthog.d.mts +43 -1
  57. package/dist/third-parties/posthog.d.mts.map +1 -1
  58. package/dist/third-parties/posthog.mjs +62 -4
  59. package/dist/third-parties/posthog.mjs.map +1 -1
  60. package/dist/visitor/id.cjs +5 -2
  61. package/dist/visitor/id.cjs.map +1 -1
  62. package/dist/visitor/id.d.cts +4 -1
  63. package/dist/visitor/id.d.cts.map +1 -1
  64. package/dist/visitor/id.d.mts +4 -1
  65. package/dist/visitor/id.d.mts.map +1 -1
  66. package/dist/visitor/id.mjs +6 -3
  67. package/dist/visitor/id.mjs.map +1 -1
  68. package/package.json +1 -1
@@ -1,7 +1,7 @@
1
1
  import { EventName, TrackName, TrackProperties } from "../track/types.cjs";
2
2
  import { UpdateVisitorDTO } from "../schema/index.cjs";
3
3
  import { Integration } from "./integration.cjs";
4
- import { PostHog, PostHog as PostHog$1, PostHogConfig, PostHogConfig as PostHogConfig$1 } from "@posthog/types";
4
+ import { CaptureResult, ExceptionAutoCaptureConfig, PostHog, PostHog as PostHog$1, PostHogConfig, PostHogConfig as PostHogConfig$1, Properties } from "@posthog/types";
5
5
  /**
6
6
  * `window.posthog`, for calls that return nothing (`capture`, `identify`, `onFeatureFlags`, …):
7
7
  * the snippet's stub until the library loads, which queues them and replays them in order once it
@@ -51,6 +51,39 @@ export declare function sendPosthogEvent<T extends EventName>(name: TrackName<T>
51
51
  * this page starts anonymous instead of merging into the one who left.
52
52
  */
53
53
  export declare function setPosthogUser({ user_id, user_data }: Omit<UpdateVisitorDTO, 'tags'>): void;
54
+ /**
55
+ * Sends an error to PostHog's error tracking (`captureException`), as `sendPosthogEvent` does an
56
+ * event: queued on the snippet's stub until the library loads, so it can be called from anywhere
57
+ * at any time — an http client's error hook, a `catch` that recovers but should still be known.
58
+ * Returns the `$exception` event, `undefined` while only the stub is there (or without PostHog).
59
+ *
60
+ * Never throws: reporting an error must not become a second one where it is called. The
61
+ * `errorTracking` filter of `posthogAnalytics` applies, as to every exception.
62
+ */
63
+ export declare function capturePosthogException(error: unknown, properties?: Properties): CaptureResult | undefined;
64
+ /** A substring of what it is matched against, or a regular expression tested on it. */
65
+ export type ErrorPattern = string | RegExp;
66
+ export interface PosthogErrorTrackingOptions {
67
+ /**
68
+ * The library's exception autocapture: window errors and unhandled rejections, on by default.
69
+ * The same as `config.capture_exceptions`, which wins when both are set.
70
+ */
71
+ autocapture?: boolean | ExceptionAutoCaptureConfig;
72
+ /**
73
+ * Exceptions not sent, as Sentry's `ignoreErrors`: matched against `Type: message` and the
74
+ * message alone of each error in the chain (`$exception_list`), e.g. `'UET is not defined'` for an
75
+ * ad blocker stubbing a tag. Errors thrown by browser extensions need no entry: PostHog drops them
76
+ * itself (`error_tracking.captureExtensionExceptions`).
77
+ */
78
+ ignoreErrors?: readonly ErrorPattern[];
79
+ /**
80
+ * Exceptions not sent by where they were thrown, as Sentry's `denyUrls`: matched against the
81
+ * file of the error's innermost frame, e.g. `'/gsi/client'` for Google One Tap's own minified
82
+ * errors, whose messages change with every build. An error of yours that only passed through
83
+ * such a script (a callback it called) is still sent.
84
+ */
85
+ denyUrls?: readonly ErrorPattern[];
86
+ }
54
87
  /**
55
88
  * PostHog: every event, for behavior analysis. Loaded with PostHog's HTML snippet, which defines
56
89
  * a stub `window.posthog` and fetches the library (`array.js`) asynchronously from PostHog's
@@ -65,6 +98,15 @@ export declare function posthogAnalytics(options: {
65
98
  config: Partial<PostHogConfig$1> & {
66
99
  api_host: string;
67
100
  };
101
+ /**
102
+ * PostHog's error tracking. `true` or options turn on exception autocapture and filter what is
103
+ * sent (`ignoreErrors`, `denyUrls`); `false` sends no exception at all, autocaptured or
104
+ * reported (`capturePosthogException`, `PosthogErrorBoundary`, `setupPosthogReactErrorHandler`) — for
105
+ * local development, which would otherwise fill the production project's issues. Left out, the
106
+ * library's own `config` decides, as before. Each exception carries the session id, so its issue
107
+ * links to the session's replay.
108
+ */
109
+ errorTracking?: boolean | PosthogErrorTrackingOptions;
68
110
  }): Integration;
69
111
  export type { PostHog, PostHogConfig };
70
112
  //# sourceMappingURL=posthog.d.cts.map
@@ -1 +1 @@
1
- {"version":3,"file":"posthog.d.cts","names":["PostHog","PostHogConfig"],"sources":["../../src/third-parties/posthog.ts"],"mappings":";;;;;;;;;;;;;;wBAkBgB,cAAcA;;;;;;;wBAWd,oBAAoBA;;;;;;;;;;;;;;;;;;;wBAyBpB,kBAAkB,qBAAmB;wBAcrC,iBAAiB,UAAU,WACzC,MAAM,UAAU,IAChB,aAAa,gBAAgB;;;;;;;;;;;wBA4Bf,iBAAiB,SAAS,aAAa,KAAK;;;;;;;;;;wBAsB5C,iBAAiB;EAC/B;EACA,QAAQ,QAAQC;IAAmB;;IACjC"}
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,7 +1,7 @@
1
1
  import { EventName, TrackName, TrackProperties } from "../track/types.mjs";
2
2
  import { UpdateVisitorDTO } from "../schema/index.mjs";
3
3
  import { Integration } from "./integration.mjs";
4
- import { PostHog, PostHog as PostHog$1, PostHogConfig, PostHogConfig as PostHogConfig$1 } from "@posthog/types";
4
+ import { CaptureResult, ExceptionAutoCaptureConfig, PostHog, PostHog as PostHog$1, PostHogConfig, PostHogConfig as PostHogConfig$1, Properties } from "@posthog/types";
5
5
  /**
6
6
  * `window.posthog`, for calls that return nothing (`capture`, `identify`, `onFeatureFlags`, …):
7
7
  * the snippet's stub until the library loads, which queues them and replays them in order once it
@@ -51,6 +51,39 @@ export declare function sendPosthogEvent<T extends EventName>(name: TrackName<T>
51
51
  * this page starts anonymous instead of merging into the one who left.
52
52
  */
53
53
  export declare function setPosthogUser({ user_id, user_data }: Omit<UpdateVisitorDTO, 'tags'>): void;
54
+ /**
55
+ * Sends an error to PostHog's error tracking (`captureException`), as `sendPosthogEvent` does an
56
+ * event: queued on the snippet's stub until the library loads, so it can be called from anywhere
57
+ * at any time — an http client's error hook, a `catch` that recovers but should still be known.
58
+ * Returns the `$exception` event, `undefined` while only the stub is there (or without PostHog).
59
+ *
60
+ * Never throws: reporting an error must not become a second one where it is called. The
61
+ * `errorTracking` filter of `posthogAnalytics` applies, as to every exception.
62
+ */
63
+ export declare function capturePosthogException(error: unknown, properties?: Properties): CaptureResult | undefined;
64
+ /** A substring of what it is matched against, or a regular expression tested on it. */
65
+ export type ErrorPattern = string | RegExp;
66
+ export interface PosthogErrorTrackingOptions {
67
+ /**
68
+ * The library's exception autocapture: window errors and unhandled rejections, on by default.
69
+ * The same as `config.capture_exceptions`, which wins when both are set.
70
+ */
71
+ autocapture?: boolean | ExceptionAutoCaptureConfig;
72
+ /**
73
+ * Exceptions not sent, as Sentry's `ignoreErrors`: matched against `Type: message` and the
74
+ * message alone of each error in the chain (`$exception_list`), e.g. `'UET is not defined'` for an
75
+ * ad blocker stubbing a tag. Errors thrown by browser extensions need no entry: PostHog drops them
76
+ * itself (`error_tracking.captureExtensionExceptions`).
77
+ */
78
+ ignoreErrors?: readonly ErrorPattern[];
79
+ /**
80
+ * Exceptions not sent by where they were thrown, as Sentry's `denyUrls`: matched against the
81
+ * file of the error's innermost frame, e.g. `'/gsi/client'` for Google One Tap's own minified
82
+ * errors, whose messages change with every build. An error of yours that only passed through
83
+ * such a script (a callback it called) is still sent.
84
+ */
85
+ denyUrls?: readonly ErrorPattern[];
86
+ }
54
87
  /**
55
88
  * PostHog: every event, for behavior analysis. Loaded with PostHog's HTML snippet, which defines
56
89
  * a stub `window.posthog` and fetches the library (`array.js`) asynchronously from PostHog's
@@ -65,6 +98,15 @@ export declare function posthogAnalytics(options: {
65
98
  config: Partial<PostHogConfig$1> & {
66
99
  api_host: string;
67
100
  };
101
+ /**
102
+ * PostHog's error tracking. `true` or options turn on exception autocapture and filter what is
103
+ * sent (`ignoreErrors`, `denyUrls`); `false` sends no exception at all, autocaptured or
104
+ * reported (`capturePosthogException`, `PosthogErrorBoundary`, `setupPosthogReactErrorHandler`) — for
105
+ * local development, which would otherwise fill the production project's issues. Left out, the
106
+ * library's own `config` decides, as before. Each exception carries the session id, so its issue
107
+ * links to the session's replay.
108
+ */
109
+ errorTracking?: boolean | PosthogErrorTrackingOptions;
68
110
  }): Integration;
69
111
  export type { PostHog, PostHogConfig };
70
112
  //# sourceMappingURL=posthog.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"posthog.d.mts","names":["PostHog","PostHogConfig"],"sources":["../../src/third-parties/posthog.ts"],"mappings":";;;;;;;;;;;;;;wBAkBgB,cAAcA;;;;;;;wBAWd,oBAAoBA;;;;;;;;;;;;;;;;;;;wBAyBpB,kBAAkB,qBAAmB;wBAcrC,iBAAiB,UAAU,WACzC,MAAM,UAAU,IAChB,aAAa,gBAAgB;;;;;;;;;;;wBA4Bf,iBAAiB,SAAS,aAAa,KAAK;;;;;;;;;;wBAsB5C,iBAAiB;EAC/B;EACA,QAAQ,QAAQC;IAAmB;;IACjC"}
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"}
@@ -96,6 +96,48 @@ function setPosthogUser({ user_id, user_data }) {
96
96
  posthog.identify(user_id, { email: getFirst(user_data?.email) });
97
97
  }
98
98
  /**
99
+ * Sends an error to PostHog's error tracking (`captureException`), as `sendPosthogEvent` does an
100
+ * event: queued on the snippet's stub until the library loads, so it can be called from anywhere
101
+ * at any time — an http client's error hook, a `catch` that recovers but should still be known.
102
+ * Returns the `$exception` event, `undefined` while only the stub is there (or without PostHog).
103
+ *
104
+ * Never throws: reporting an error must not become a second one where it is called. The
105
+ * `errorTracking` filter of `posthogAnalytics` applies, as to every exception.
106
+ */
107
+ function capturePosthogException(error, properties) {
108
+ try {
109
+ return getPosthog()?.captureException(error, properties);
110
+ } catch (e) {
111
+ console.error("capturePosthogException: the error was not reported", e);
112
+ return;
113
+ }
114
+ }
115
+ function serializePatterns(patterns = []) {
116
+ return patterns.map((p) => typeof p === "string" ? p : {
117
+ source: p.source,
118
+ flags: p.flags.replace(/[gy]/g, "")
119
+ });
120
+ }
121
+ /**
122
+ * The snippet's `before_send`, as source: `config` goes to `posthog.init` as JSON, which drops
123
+ * functions, so the filter is written into the inline script instead — in place from the first
124
+ * event, with no window before the app's bundle could install it. ES5, as the rest of the snippet.
125
+ * Called with the rules (`off`, `errors`, `urls`); returns the `before_send` function.
126
+ */
127
+ const EXCEPTION_FILTER = `function(r){
128
+ 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}
129
+ 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}
130
+ var errors=compile(r.errors),urls=compile(r.urls);
131
+ return function(e){
132
+ if(!e||e.event!=="$exception")return e;
133
+ if(r.off)return null;
134
+ var l=(e.properties&&e.properties.$exception_list)||[];
135
+ 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}
136
+ var f=l[0]&&l[0].stacktrace&&l[0].stacktrace.frames,u=f&&f.length?f[f.length-1].filename:"";
137
+ return any(urls,u)?null:e;
138
+ };
139
+ }`;
140
+ /**
99
141
  * PostHog: every event, for behavior analysis. Loaded with PostHog's HTML snippet, which defines
100
142
  * a stub `window.posthog` and fetches the library (`array.js`) asynchronously from PostHog's
101
143
  * assets host, so it stays out of the app's bundle; calls made before it loads are queued.
@@ -106,7 +148,23 @@ function setPosthogUser({ user_id, user_data }) {
106
148
  */
107
149
  function posthogAnalytics(options) {
108
150
  const assets = options.config.api_host.replace(".i.posthog.com", "-assets.i.posthog.com");
109
- const config = JSON.stringify(options.config).replace(/</g, "\\u003c");
151
+ const json = (value) => JSON.stringify(value).replace(/</g, "\\u003c");
152
+ const token = JSON.stringify(options.token);
153
+ const { errorTracking } = options;
154
+ let init = `posthog.init(${token}, ${json(options.config)});`;
155
+ if (errorTracking !== void 0) {
156
+ const tracking = typeof errorTracking === "object" ? errorTracking : {};
157
+ const config = {
158
+ ...options.config,
159
+ capture_exceptions: options.config.capture_exceptions ?? (errorTracking && (tracking.autocapture ?? true))
160
+ };
161
+ const rules = {
162
+ off: !errorTracking,
163
+ errors: serializePatterns(tracking.ignoreErrors),
164
+ urls: serializePatterns(tracking.denyUrls)
165
+ };
166
+ init = `!function(){var c=${json(config)};c.before_send=(${EXCEPTION_FILTER})(${json(rules)});posthog.init(${token}, c)}();`;
167
+ }
110
168
  return {
111
169
  type: "analytics",
112
170
  track: sendPosthogEvent,
@@ -116,12 +174,12 @@ function posthogAnalytics(options) {
116
174
  id: "posthog-snippet",
117
175
  strategy: "beforeInteractive",
118
176
  inline: `
119
- !function(t,e){var o,n,p,r;e.__SV||(window.posthog=e,e._i=[],e.init=function(i,s,a){function g(t,e){var o=e.split(".");2==o.length&&(t=t[o[0]],e=o[1]),t[e]=function(){t.push([e].concat(Array.prototype.slice.call(arguments,0)))}}(p=t.createElement("script")).type="text/javascript",p.crossOrigin="anonymous",p.async=!0,p.src=s.api_host.replace(".i.posthog.com","-assets.i.posthog.com")+"/static/array.js",(r=t.getElementsByTagName("script")[0]).parentNode.insertBefore(p,r);var u=e;for(void 0!==a?u=e[a]=[]:a="posthog",u.people=u.people||[],Object.defineProperty(u,"toString",{configurable:!0,enumerable:!0,writable:!0,value:function(t){var e="posthog";return"posthog"!==a&&(e+="."+a),t||(e+=" (stub)"),e}}),Object.defineProperty(u.people,"toString",{configurable:!0,enumerable:!0,writable:!0,value:function(){return u.toString(1)+".people (stub)"}}),o="init capture register register_once register_for_session unregister unregister_for_session getFeatureFlag getFeatureFlagResult isFeatureEnabled reloadFeatureFlags updateEarlyAccessFeatureEnrollment getEarlyAccessFeatures on onFeatureFlags onSessionId getSurveys getActiveMatchingSurveys renderSurvey canRenderSurvey getNextSurveyStep identify setPersonProperties group resetGroups setPersonPropertiesForFlags resetPersonPropertiesForFlags setGroupPropertiesForFlags resetGroupPropertiesForFlags reset get_distinct_id getGroups get_session_id get_session_replay_url alias set_config startSessionRecording stopSessionRecording sessionRecordingStarted captureException loadToolbar get_property getSessionProperty createPersonProfile opt_in_capturing opt_out_capturing has_opted_in_capturing has_opted_out_capturing clear_opt_in_out_capturing debug".split(" "),n=0;n<o.length;n++)g(u,o[n]);e._i.push([i,s,a])},e.__SV=1)}(document,window.posthog||[]);
120
- posthog.init(${JSON.stringify(options.token)}, ${config});
177
+ !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||[]);
178
+ ${init}
121
179
  `
122
180
  }
123
181
  };
124
182
  }
125
- export { getLoadedPosthog, getPosthog, posthogAnalytics, posthogFlagsReady, sendPosthogEvent, setPosthogUser };
183
+ export { capturePosthogException, getLoadedPosthog, getPosthog, posthogAnalytics, posthogFlagsReady, sendPosthogEvent, setPosthogUser };
126
184
 
127
185
  //# sourceMappingURL=posthog.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"posthog.mjs","names":[],"sources":["../../src/third-parties/posthog.ts"],"sourcesContent":["import type { PostHog, PostHogConfig } from '@posthog/types';\nimport type { UpdateVisitorDTO } from '../schema/index';\nimport type { EventName, TrackName, TrackProperties } from '../track/types';\nimport { getFirst } from '../utils/field';\nimport type { Integration } from './integration';\n\nexport type { PostHog, PostHogConfig } from '@posthog/types';\n\n/**\n * `window.posthog`, for calls that return nothing (`capture`, `identify`, `onFeatureFlags`, …):\n * the snippet's stub until the library loads, which queues them and replays them in order once it\n * has. A method that returns a value returns `undefined` on the stub — use `getLoadedPosthog` for\n * those. `undefined` on the server and before the snippet has run.\n *\n * Read off `window` rather than declared on it, so a host that also has `posthog-js`'s own types\n * does not get two conflicting declarations. The types come from `@posthog/types`, PostHog's\n * types-only package for the snippet, so the host installs nothing for them.\n */\nexport function getPosthog(): PostHog | undefined {\n if (typeof document === 'undefined') return undefined;\n return (window as { posthog?: PostHog }).posthog;\n}\n\n/**\n * The PostHog instance once the library has loaded, for the methods that return a value\n * (`getFeatureFlag`, `isFeatureEnabled`, `get_distinct_id`, …); `undefined` while only the stub is\n * there. To act when flags arrive, subscribe with `getPosthog()?.onFeatureFlags` instead, which\n * the stub queues.\n */\nexport function getLoadedPosthog(): PostHog | undefined {\n const posthog = getPosthog();\n return posthog?.__loaded ? posthog : undefined;\n}\n\nlet flagsReady: Promise<void> | undefined;\n\n/**\n * Resolves once PostHog has loaded its feature flags — or after `timeoutMs` (3 s by default),\n * since an ad blocker that stops the library would otherwise hold it forever; read the flags\n * after it with `useFeatureFlagVariantKey` / `getLoadedPosthog`, which are `undefined` in that\n * case. One promise per page, so React's `use()` can suspend on it:\n *\n * ```tsx\n * function Checkout() {\n * use(browser()); // react-dom: the server renders the <Suspense> fallback instead\n * use(posthogFlagsReady());\n * return useFeatureFlagVariantKey('new-checkout') === 'test' ? <NewCheckout /> : <OldCheckout />;\n * }\n * ```\n *\n * Waiting shows the fallback until the flags are in, instead of the default then the variant;\n * with server-evaluated flags in `config.bootstrap` it resolves as soon as the library loads.\n * Browser only: it never resolves on the server.\n */\nexport function posthogFlagsReady(timeoutMs = 3000): Promise<void> {\n if (typeof document === 'undefined') return new Promise(() => {});\n flagsReady ??= new Promise<void>((resolve) => {\n setTimeout(resolve, timeoutMs);\n const posthog = getPosthog();\n if (!posthog) return;\n // Queued on the stub; once loaded, called as soon as flags are (or already were) in.\n posthog.onFeatureFlags(() => resolve());\n });\n return flagsReady;\n}\n\nconst metrics = ['CLS', 'FCP', 'FID', 'INP', 'LCP', 'TTFB'];\n\nexport function sendPosthogEvent<T extends EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>\n) {\n // `document`, not `window`: React Native defines `window` as an alias of `global`, so a\n // window check would pass there and then throw on `window.location`, which it has no such\n // alias for.\n if (typeof document === 'undefined') return;\n const posthog = getPosthog();\n if (!posthog) {\n console.warn('posthog has not been initialized');\n return false;\n }\n if (metrics.includes(name)) return;\n if (window.location.host.includes('127.0.0.1')) return;\n if (window.location.host.includes('localhost')) return;\n\n posthog.capture(name, properties);\n}\n\n/**\n * Identifies the visitor to PostHog as the signed-in user, by the user's id — the server's\n * `distinct_id` for the visitor once someone has signed in on it. Only a user: identifying an\n * anonymous visitor by its own id would make PostHog treat it as an identified person, and\n * PostHog does not merge one identified person into another when the user later signs in, so the\n * pre-sign-in events would stay split off.\n *\n * Without a user it is sign-out (`reset()`): PostHog's identity is reset, so the next person on\n * this page starts anonymous instead of merging into the one who left.\n */\nexport function setPosthogUser({ user_id, user_data }: Omit<UpdateVisitorDTO, 'tags'>) {\n const posthog = getPosthog();\n if (!posthog) {\n console.warn('posthog has not been initialized');\n return;\n }\n if (!user_id) {\n posthog.reset();\n return;\n }\n posthog.identify(user_id, { email: getFirst(user_data?.email) });\n}\n\n/**\n * PostHog: every event, for behavior analysis. Loaded with PostHog's HTML snippet, which defines\n * a stub `window.posthog` and fetches the library (`array.js`) asynchronously from PostHog's\n * assets host, so it stays out of the app's bundle; calls made before it loads are queued.\n *\n * `config` is serialized into the snippet's `posthog.init` call, so only its JSON survives:\n * `api_host`, `defaults`, `bootstrap` (server-evaluated flags, so an experiment renders its variant\n * without a flicker), and the other plain options — functions such as `loaded` are dropped.\n */\nexport function posthogAnalytics(options: {\n token: `phc_${string}`;\n config: Partial<PostHogConfig> & { api_host: string };\n}): Integration {\n // Where the snippet loads `array.js` from, by its own rule; a relative `api_host` (a reverse\n // proxy on the site's origin) needs no preconnect.\n const assets = options.config.api_host.replace('.i.posthog.com', '-assets.i.posthog.com');\n // `<` escaped: `config` is arbitrary JSON (a `bootstrap` can carry user data), and a `</script>`\n // inside it would end this inline script early. `\\u003c` parses back to the same value.\n const config = JSON.stringify(options.config).replace(/</g, '\\\\u003c');\n return {\n type: 'analytics',\n track: sendPosthogEvent,\n setUser: setPosthogUser,\n preconnect: URL.canParse(assets) ? [new URL(assets).origin] : [],\n script: {\n id: 'posthog-snippet',\n // The stub must exist before hydration, whose effects already track (`page_view`) and\n // identify; it is a few lines, and `array.js` still loads async. PostHog's own Next example\n // does the same.\n strategy: 'beforeInteractive',\n inline: `\n !function(t,e){var o,n,p,r;e.__SV||(window.posthog=e,e._i=[],e.init=function(i,s,a){function g(t,e){var o=e.split(\".\");2==o.length&&(t=t[o[0]],e=o[1]),t[e]=function(){t.push([e].concat(Array.prototype.slice.call(arguments,0)))}}(p=t.createElement(\"script\")).type=\"text/javascript\",p.crossOrigin=\"anonymous\",p.async=!0,p.src=s.api_host.replace(\".i.posthog.com\",\"-assets.i.posthog.com\")+\"/static/array.js\",(r=t.getElementsByTagName(\"script\")[0]).parentNode.insertBefore(p,r);var u=e;for(void 0!==a?u=e[a]=[]:a=\"posthog\",u.people=u.people||[],Object.defineProperty(u,\"toString\",{configurable:!0,enumerable:!0,writable:!0,value:function(t){var e=\"posthog\";return\"posthog\"!==a&&(e+=\".\"+a),t||(e+=\" (stub)\"),e}}),Object.defineProperty(u.people,\"toString\",{configurable:!0,enumerable:!0,writable:!0,value:function(){return u.toString(1)+\".people (stub)\"}}),o=\"init capture register register_once register_for_session unregister unregister_for_session getFeatureFlag getFeatureFlagResult isFeatureEnabled reloadFeatureFlags updateEarlyAccessFeatureEnrollment getEarlyAccessFeatures on onFeatureFlags onSessionId getSurveys getActiveMatchingSurveys renderSurvey canRenderSurvey getNextSurveyStep identify setPersonProperties group resetGroups setPersonPropertiesForFlags resetPersonPropertiesForFlags setGroupPropertiesForFlags resetGroupPropertiesForFlags reset get_distinct_id getGroups get_session_id get_session_replay_url alias set_config startSessionRecording stopSessionRecording sessionRecordingStarted captureException loadToolbar get_property getSessionProperty createPersonProfile opt_in_capturing opt_out_capturing has_opted_in_capturing has_opted_out_capturing clear_opt_in_out_capturing debug\".split(\" \"),n=0;n<o.length;n++)g(u,o[n]);e._i.push([i,s,a])},e.__SV=1)}(document,window.posthog||[]);\n posthog.init(${JSON.stringify(options.token)}, ${config});\n `,\n },\n };\n}\n"],"mappings":";;;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Q,kBAAkB,uBAAuB;CAGxF,MAAM,SAAS,KAAK,UAAU,QAAQ,MAAM,CAAC,CAAC,QAAQ,MAAM,SAAS;CACrE,OAAO;EACL,MAAM;EACN,OAAO;EACP,SAAS;EACT,YAAY,IAAI,SAAS,MAAM,IAAI,CAAC,IAAI,IAAI,MAAM,CAAC,CAAC,MAAM,IAAI,CAAC;EAC/D,QAAQ;GACN,IAAI;GAIJ,UAAU;GACV,QAAQ;;uBAES,KAAK,UAAU,QAAQ,KAAK,EAAE,IAAI,OAAO;;EAE5D;CACF;AACF"}
1
+ {"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":";;;;;;;;;;;;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-7,14 +7,17 @@ let uuid = require("uuid");
7
7
  * This visitor's id: generated here on the first visit (uuidv7) and kept in `config.storage`, so
8
8
  * it exists the moment the page loads. The first events, and the beacon of a visit left within a
9
9
  * second, go out without waiting for a round trip; the server creates the visitor from its first
10
- * events. An id a server issued to an older client is kept as it is: the visitor continues.
10
+ * events. A uuidv7 a server issued to an older client is kept as it is: the visitor continues.
11
+ * Anything else stored there is replaced, because the server rejects every batch carrying it:
12
+ * clients before 11.0 kept the int64 id older servers issued, and healed it by recreating the
13
+ * visitor when the server refused it; without that round trip the id would never change.
11
14
  *
12
15
  * Needs a server that creates visitors from events (see the README, "Visitors"); one that still
13
16
  * only creates them on `POST /visitors` rejects the events of a new visitor.
14
17
  */
15
18
  function visitorId() {
16
19
  const stored = require_setup_index.config.storage.getItem(require_constants_storage.keys.visitor_id);
17
- if (stored && stored !== "undefined") return stored;
20
+ if (stored && (0, uuid.validate)(stored) && (0, uuid.version)(stored) === 7) return stored;
18
21
  return newVisitorId();
19
22
  }
20
23
  /** Starts a new visitor on this device — `reset()` — and returns its id. */
@@ -1 +1 @@
1
- {"version":3,"file":"id.cjs","names":["config","keys","uuidv7"],"sources":["../../src/visitor/id.ts"],"sourcesContent":["import { v7 as uuidv7 } from 'uuid';\nimport { keys } from '../constants/storage';\nimport { config } from '../setup/index';\n\n/**\n * This visitor's id: generated here on the first visit (uuidv7) and kept in `config.storage`, so\n * it exists the moment the page loads. The first events, and the beacon of a visit left within a\n * second, go out without waiting for a round trip; the server creates the visitor from its first\n * events. An id a server issued to an older client is kept as it is: the visitor continues.\n *\n * Needs a server that creates visitors from events (see the README, \"Visitors\"); one that still\n * only creates them on `POST /visitors` rejects the events of a new visitor.\n */\nexport function visitorId(): string {\n const stored = config.storage.getItem(keys.visitor_id);\n // An old client stored the string 'undefined' as the id (it wrote an unset id): not an id, so it\n // is replaced below with a new one, which also clears the bad value from storage for good.\n if (stored && stored !== 'undefined') return stored;\n return newVisitorId();\n}\n\n/** Starts a new visitor on this device — `reset()` — and returns its id. */\nexport function newVisitorId(): string {\n const id = uuidv7();\n config.storage.setItem(keys.visitor_id, id);\n return id;\n}\n"],"mappings":";;;;;;;;;;;;;;AAaA,SAAgB,YAAoB;CAClC,MAAM,SAASA,oBAAAA,OAAO,QAAQ,QAAQC,0BAAAA,KAAK,UAAU;CAGrD,IAAI,UAAU,WAAW,aAAa,OAAO;CAC7C,OAAO,aAAa;AACtB;;AAGA,SAAgB,eAAuB;CACrC,MAAM,MAAA,GAAKC,KAAAA,GAAAA,CAAO;CAClB,oBAAA,OAAO,QAAQ,QAAQD,0BAAAA,KAAK,YAAY,EAAE;CAC1C,OAAO;AACT"}
1
+ {"version":3,"file":"id.cjs","names":["config","keys","validate","version","uuidv7"],"sources":["../../src/visitor/id.ts"],"sourcesContent":["import { v7 as uuidv7, validate, version } from 'uuid';\nimport { keys } from '../constants/storage';\nimport { config } from '../setup/index';\n\n/**\n * This visitor's id: generated here on the first visit (uuidv7) and kept in `config.storage`, so\n * it exists the moment the page loads. The first events, and the beacon of a visit left within a\n * second, go out without waiting for a round trip; the server creates the visitor from its first\n * events. A uuidv7 a server issued to an older client is kept as it is: the visitor continues.\n * Anything else stored there is replaced, because the server rejects every batch carrying it:\n * clients before 11.0 kept the int64 id older servers issued, and healed it by recreating the\n * visitor when the server refused it; without that round trip the id would never change.\n *\n * Needs a server that creates visitors from events (see the README, \"Visitors\"); one that still\n * only creates them on `POST /visitors` rejects the events of a new visitor.\n */\nexport function visitorId(): string {\n const stored = config.storage.getItem(keys.visitor_id);\n // Also covers the string 'undefined' an old client stored for an unset id. Replacing it below\n // writes the new id back, which clears the bad value from storage for good.\n if (stored && validate(stored) && version(stored) === 7) return stored;\n return newVisitorId();\n}\n\n/** Starts a new visitor on this device — `reset()` — and returns its id. */\nexport function newVisitorId(): string {\n const id = uuidv7();\n config.storage.setItem(keys.visitor_id, id);\n return id;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAgBA,SAAgB,YAAoB;CAClC,MAAM,SAASA,oBAAAA,OAAO,QAAQ,QAAQC,0BAAAA,KAAK,UAAU;CAGrD,IAAI,WAAA,GAAUC,KAAAA,SAAAA,CAAS,MAAM,MAAA,GAAKC,KAAAA,QAAAA,CAAQ,MAAM,MAAM,GAAG,OAAO;CAChE,OAAO,aAAa;AACtB;;AAGA,SAAgB,eAAuB;CACrC,MAAM,MAAA,GAAKC,KAAAA,GAAAA,CAAO;CAClB,oBAAA,OAAO,QAAQ,QAAQH,0BAAAA,KAAK,YAAY,EAAE;CAC1C,OAAO;AACT"}
@@ -2,7 +2,10 @@
2
2
  * This visitor's id: generated here on the first visit (uuidv7) and kept in `config.storage`, so
3
3
  * it exists the moment the page loads. The first events, and the beacon of a visit left within a
4
4
  * second, go out without waiting for a round trip; the server creates the visitor from its first
5
- * events. An id a server issued to an older client is kept as it is: the visitor continues.
5
+ * events. A uuidv7 a server issued to an older client is kept as it is: the visitor continues.
6
+ * Anything else stored there is replaced, because the server rejects every batch carrying it:
7
+ * clients before 11.0 kept the int64 id older servers issued, and healed it by recreating the
8
+ * visitor when the server refused it; without that round trip the id would never change.
6
9
  *
7
10
  * Needs a server that creates visitors from events (see the README, "Visitors"); one that still
8
11
  * only creates them on `POST /visitors` rejects the events of a new visitor.
@@ -1 +1 @@
1
- {"version":3,"file":"id.d.cts","names":[],"sources":["../../src/visitor/id.ts"],"mappings":";;;;;;;;;wBAagB;;wBASA"}
1
+ {"version":3,"file":"id.d.cts","names":[],"sources":["../../src/visitor/id.ts"],"mappings":";;;;;;;;;;;;wBAgBgB;;wBASA"}
@@ -2,7 +2,10 @@
2
2
  * This visitor's id: generated here on the first visit (uuidv7) and kept in `config.storage`, so
3
3
  * it exists the moment the page loads. The first events, and the beacon of a visit left within a
4
4
  * second, go out without waiting for a round trip; the server creates the visitor from its first
5
- * events. An id a server issued to an older client is kept as it is: the visitor continues.
5
+ * events. A uuidv7 a server issued to an older client is kept as it is: the visitor continues.
6
+ * Anything else stored there is replaced, because the server rejects every batch carrying it:
7
+ * clients before 11.0 kept the int64 id older servers issued, and healed it by recreating the
8
+ * visitor when the server refused it; without that round trip the id would never change.
6
9
  *
7
10
  * Needs a server that creates visitors from events (see the README, "Visitors"); one that still
8
11
  * only creates them on `POST /visitors` rejects the events of a new visitor.
@@ -1 +1 @@
1
- {"version":3,"file":"id.d.mts","names":[],"sources":["../../src/visitor/id.ts"],"mappings":";;;;;;;;;wBAagB;;wBASA"}
1
+ {"version":3,"file":"id.d.mts","names":[],"sources":["../../src/visitor/id.ts"],"mappings":";;;;;;;;;;;;wBAgBgB;;wBASA"}
@@ -1,19 +1,22 @@
1
1
  import { config } from "../setup/index.mjs";
2
2
  import { keys } from "../constants/storage.mjs";
3
- import { v7 } from "uuid";
3
+ import { v7, validate, version } from "uuid";
4
4
  // src/visitor/id.ts
5
5
  /**
6
6
  * This visitor's id: generated here on the first visit (uuidv7) and kept in `config.storage`, so
7
7
  * it exists the moment the page loads. The first events, and the beacon of a visit left within a
8
8
  * second, go out without waiting for a round trip; the server creates the visitor from its first
9
- * events. An id a server issued to an older client is kept as it is: the visitor continues.
9
+ * events. A uuidv7 a server issued to an older client is kept as it is: the visitor continues.
10
+ * Anything else stored there is replaced, because the server rejects every batch carrying it:
11
+ * clients before 11.0 kept the int64 id older servers issued, and healed it by recreating the
12
+ * visitor when the server refused it; without that round trip the id would never change.
10
13
  *
11
14
  * Needs a server that creates visitors from events (see the README, "Visitors"); one that still
12
15
  * only creates them on `POST /visitors` rejects the events of a new visitor.
13
16
  */
14
17
  function visitorId() {
15
18
  const stored = config.storage.getItem(keys.visitor_id);
16
- if (stored && stored !== "undefined") return stored;
19
+ if (stored && validate(stored) && version(stored) === 7) return stored;
17
20
  return newVisitorId();
18
21
  }
19
22
  /** Starts a new visitor on this device — `reset()` — and returns its id. */
@@ -1 +1 @@
1
- {"version":3,"file":"id.mjs","names":["uuidv7"],"sources":["../../src/visitor/id.ts"],"sourcesContent":["import { v7 as uuidv7 } from 'uuid';\nimport { keys } from '../constants/storage';\nimport { config } from '../setup/index';\n\n/**\n * This visitor's id: generated here on the first visit (uuidv7) and kept in `config.storage`, so\n * it exists the moment the page loads. The first events, and the beacon of a visit left within a\n * second, go out without waiting for a round trip; the server creates the visitor from its first\n * events. An id a server issued to an older client is kept as it is: the visitor continues.\n *\n * Needs a server that creates visitors from events (see the README, \"Visitors\"); one that still\n * only creates them on `POST /visitors` rejects the events of a new visitor.\n */\nexport function visitorId(): string {\n const stored = config.storage.getItem(keys.visitor_id);\n // An old client stored the string 'undefined' as the id (it wrote an unset id): not an id, so it\n // is replaced below with a new one, which also clears the bad value from storage for good.\n if (stored && stored !== 'undefined') return stored;\n return newVisitorId();\n}\n\n/** Starts a new visitor on this device — `reset()` — and returns its id. */\nexport function newVisitorId(): string {\n const id = uuidv7();\n config.storage.setItem(keys.visitor_id, id);\n return id;\n}\n"],"mappings":";;;;;;;;;;;;;AAaA,SAAgB,YAAoB;CAClC,MAAM,SAAS,OAAO,QAAQ,QAAQ,KAAK,UAAU;CAGrD,IAAI,UAAU,WAAW,aAAa,OAAO;CAC7C,OAAO,aAAa;AACtB;;AAGA,SAAgB,eAAuB;CACrC,MAAM,KAAKA,GAAO;CAClB,OAAO,QAAQ,QAAQ,KAAK,YAAY,EAAE;CAC1C,OAAO;AACT"}
1
+ {"version":3,"file":"id.mjs","names":["uuidv7"],"sources":["../../src/visitor/id.ts"],"sourcesContent":["import { v7 as uuidv7, validate, version } from 'uuid';\nimport { keys } from '../constants/storage';\nimport { config } from '../setup/index';\n\n/**\n * This visitor's id: generated here on the first visit (uuidv7) and kept in `config.storage`, so\n * it exists the moment the page loads. The first events, and the beacon of a visit left within a\n * second, go out without waiting for a round trip; the server creates the visitor from its first\n * events. A uuidv7 a server issued to an older client is kept as it is: the visitor continues.\n * Anything else stored there is replaced, because the server rejects every batch carrying it:\n * clients before 11.0 kept the int64 id older servers issued, and healed it by recreating the\n * visitor when the server refused it; without that round trip the id would never change.\n *\n * Needs a server that creates visitors from events (see the README, \"Visitors\"); one that still\n * only creates them on `POST /visitors` rejects the events of a new visitor.\n */\nexport function visitorId(): string {\n const stored = config.storage.getItem(keys.visitor_id);\n // Also covers the string 'undefined' an old client stored for an unset id. Replacing it below\n // writes the new id back, which clears the bad value from storage for good.\n if (stored && validate(stored) && version(stored) === 7) return stored;\n return newVisitorId();\n}\n\n/** Starts a new visitor on this device — `reset()` — and returns its id. */\nexport function newVisitorId(): string {\n const id = uuidv7();\n config.storage.setItem(keys.visitor_id, id);\n return id;\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAgBA,SAAgB,YAAoB;CAClC,MAAM,SAAS,OAAO,QAAQ,QAAQ,KAAK,UAAU;CAGrD,IAAI,UAAU,SAAS,MAAM,KAAK,QAAQ,MAAM,MAAM,GAAG,OAAO;CAChE,OAAO,aAAa;AACtB;;AAGA,SAAgB,eAAuB;CACrC,MAAM,KAAKA,GAAO;CAClB,OAAO,QAAQ,QAAQ,KAAK,YAAY,EAAE;CAC1C,OAAO;AACT"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@shware/analytics",
3
- "version": "16.2.2",
3
+ "version": "16.3.0",
4
4
  "private": false,
5
5
  "repository": {
6
6
  "type": "git",