posthog-node 6.0.5 → 6.1.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 (43) hide show
  1. package/dist/client.d.ts +28 -3
  2. package/dist/client.d.ts.map +1 -1
  3. package/dist/client.js +23 -1
  4. package/dist/client.mjs +23 -1
  5. package/dist/exports.d.ts +3 -0
  6. package/dist/exports.d.ts.map +1 -1
  7. package/dist/exports.js +73 -51
  8. package/dist/exports.mjs +2 -0
  9. package/dist/extensions/feature-flags/feature-flags.d.ts +2 -0
  10. package/dist/extensions/feature-flags/feature-flags.d.ts.map +1 -1
  11. package/dist/extensions/feature-flags/feature-flags.js +8 -0
  12. package/dist/extensions/feature-flags/feature-flags.mjs +8 -0
  13. package/dist/extensions/react-router.d.ts +59 -0
  14. package/dist/extensions/react-router.d.ts.map +1 -0
  15. package/dist/extensions/react-router.js +78 -0
  16. package/dist/extensions/react-router.mjs +40 -0
  17. package/dist/extensions/request-exception.d.ts +22 -0
  18. package/dist/extensions/request-exception.d.ts.map +1 -0
  19. package/dist/extensions/request-exception.js +134 -0
  20. package/dist/extensions/request-exception.mjs +86 -0
  21. package/dist/extensions/tracing-headers.d.ts +13 -5
  22. package/dist/extensions/tracing-headers.d.ts.map +1 -1
  23. package/dist/extensions/tracing-headers.js +36 -12
  24. package/dist/extensions/tracing-headers.mjs +34 -13
  25. package/dist/remote-config-errors.d.ts +20 -0
  26. package/dist/remote-config-errors.d.ts.map +1 -0
  27. package/dist/remote-config-errors.js +44 -0
  28. package/dist/remote-config-errors.mjs +6 -0
  29. package/dist/types.d.ts +8 -2
  30. package/dist/types.d.ts.map +1 -1
  31. package/dist/version.d.ts +1 -1
  32. package/dist/version.js +1 -1
  33. package/dist/version.mjs +1 -1
  34. package/package.json +4 -3
  35. package/src/client.ts +65 -4
  36. package/src/exports.ts +3 -0
  37. package/src/extensions/feature-flags/feature-flags.ts +29 -0
  38. package/src/extensions/react-router.ts +137 -0
  39. package/src/extensions/request-exception.ts +153 -0
  40. package/src/extensions/tracing-headers.ts +61 -16
  41. package/src/remote-config-errors.ts +19 -0
  42. package/src/types.ts +8 -2
  43. package/src/version.ts +1 -1
@@ -0,0 +1,78 @@
1
+ "use strict";
2
+ var __webpack_require__ = {};
3
+ (()=>{
4
+ __webpack_require__.d = (exports1, getters, values)=>{
5
+ var define = (defs, kind)=>{
6
+ for(var key in defs)if (__webpack_require__.o(defs, key) && !__webpack_require__.o(exports1, key)) Object.defineProperty(exports1, key, {
7
+ enumerable: true,
8
+ [kind]: defs[key]
9
+ });
10
+ };
11
+ define(getters, "get");
12
+ define(values, "value");
13
+ };
14
+ })();
15
+ (()=>{
16
+ __webpack_require__.o = (obj, prop)=>Object.prototype.hasOwnProperty.call(obj, prop);
17
+ })();
18
+ (()=>{
19
+ __webpack_require__.r = (exports1)=>{
20
+ if ("u" > typeof Symbol && Symbol.toStringTag) Object.defineProperty(exports1, Symbol.toStringTag, {
21
+ value: 'Module'
22
+ });
23
+ Object.defineProperty(exports1, '__esModule', {
24
+ value: true
25
+ });
26
+ };
27
+ })();
28
+ var __webpack_exports__ = {};
29
+ __webpack_require__.r(__webpack_exports__);
30
+ __webpack_require__.d(__webpack_exports__, {
31
+ createReactRouterErrorHandler: ()=>createReactRouterErrorHandler
32
+ });
33
+ const external_request_exception_js_namespaceObject = require("./request-exception.js");
34
+ function isRouteErrorResponse(error) {
35
+ if (null === error || 'object' != typeof error) return false;
36
+ const candidate = error;
37
+ return 'number' == typeof candidate.status && 'string' == typeof candidate.statusText && 'boolean' == typeof candidate.internal && 'data' in candidate;
38
+ }
39
+ function getApplicationError(error) {
40
+ return isRouteErrorResponse(error) && !error.internal && void 0 !== error.error ? error.error : error;
41
+ }
42
+ function isExpected(error, request) {
43
+ return request.signal.aborted || isRouteErrorResponse(error);
44
+ }
45
+ function getPageUrl(request) {
46
+ try {
47
+ const { origin, pathname: path } = new URL(request.url);
48
+ const pagePath = path.endsWith('/_root.data') ? path.slice(0, -11) || '/' : path.endsWith('/_.data') ? path.slice(0, -6) : path.replace(/\.data$/, '');
49
+ return pagePath === path ? void 0 : `${origin}${pagePath}`;
50
+ } catch {
51
+ return;
52
+ }
53
+ }
54
+ function logLikeReactRouter(error, { request }) {
55
+ if (request.signal.aborted) return;
56
+ console.error(isRouteErrorResponse(error) && error.error ? error.error : error);
57
+ }
58
+ function createReactRouterErrorHandler(posthog, options = {}) {
59
+ return (error, args)=>{
60
+ let captured = Promise.resolve();
61
+ try {
62
+ const applicationError = getApplicationError(error);
63
+ if (!isExpected(applicationError, args.request) && options.shouldCapture?.(applicationError, args) !== false) captured = (0, external_request_exception_js_namespaceObject.captureRequestException)(posthog, applicationError, args.request, {
64
+ url: getPageUrl(args.request),
65
+ source: 'react_router.handle_error'
66
+ });
67
+ } catch {}
68
+ (options.handleError ?? logLikeReactRouter)(error, args);
69
+ return captured;
70
+ };
71
+ }
72
+ exports.createReactRouterErrorHandler = __webpack_exports__.createReactRouterErrorHandler;
73
+ for(var __rspack_i in __webpack_exports__)if (-1 === [
74
+ "createReactRouterErrorHandler"
75
+ ].indexOf(__rspack_i)) exports[__rspack_i] = __webpack_exports__[__rspack_i];
76
+ Object.defineProperty(exports, '__esModule', {
77
+ value: true
78
+ });
@@ -0,0 +1,40 @@
1
+ import { captureRequestException } from "./request-exception.mjs";
2
+ function isRouteErrorResponse(error) {
3
+ if (null === error || 'object' != typeof error) return false;
4
+ const candidate = error;
5
+ return 'number' == typeof candidate.status && 'string' == typeof candidate.statusText && 'boolean' == typeof candidate.internal && 'data' in candidate;
6
+ }
7
+ function getApplicationError(error) {
8
+ return isRouteErrorResponse(error) && !error.internal && void 0 !== error.error ? error.error : error;
9
+ }
10
+ function isExpected(error, request) {
11
+ return request.signal.aborted || isRouteErrorResponse(error);
12
+ }
13
+ function getPageUrl(request) {
14
+ try {
15
+ const { origin, pathname: path } = new URL(request.url);
16
+ const pagePath = path.endsWith('/_root.data') ? path.slice(0, -11) || '/' : path.endsWith('/_.data') ? path.slice(0, -6) : path.replace(/\.data$/, '');
17
+ return pagePath === path ? void 0 : `${origin}${pagePath}`;
18
+ } catch {
19
+ return;
20
+ }
21
+ }
22
+ function logLikeReactRouter(error, { request }) {
23
+ if (request.signal.aborted) return;
24
+ console.error(isRouteErrorResponse(error) && error.error ? error.error : error);
25
+ }
26
+ function createReactRouterErrorHandler(posthog, options = {}) {
27
+ return (error, args)=>{
28
+ let captured = Promise.resolve();
29
+ try {
30
+ const applicationError = getApplicationError(error);
31
+ if (!isExpected(applicationError, args.request) && options.shouldCapture?.(applicationError, args) !== false) captured = captureRequestException(posthog, applicationError, args.request, {
32
+ url: getPageUrl(args.request),
33
+ source: 'react_router.handle_error'
34
+ });
35
+ } catch {}
36
+ (options.handleError ?? logLikeReactRouter)(error, args);
37
+ return captured;
38
+ };
39
+ }
40
+ export { createReactRouterErrorHandler };
@@ -0,0 +1,22 @@
1
+ import type { PostHogBackendClient } from '../client';
2
+ export interface CaptureRequestExceptionOptions {
3
+ /** `$exception_source`, as lowercase `<technology>.<hook>`, for example `react_router.handle_error`. */
4
+ source: string;
5
+ /** The page URL to report instead of `request.url`, for an internal request (a data endpoint, for example). */
6
+ url?: string;
7
+ }
8
+ /**
9
+ * Captures an exception a framework caught while handling a fetch API `Request`, with the request's person, session
10
+ * and request properties, marked unhandled with the `middleware` mechanism. The query string is never sent.
11
+ *
12
+ * Identity, first match wins per field: the active context, the `x-posthog-*` tracing headers, then the posthog-js
13
+ * cookie (with the client's `readPostHogCookie`), where an anonymous visitor's id keeps the event personless. When the
14
+ * visitor's consent cookie opts out, the event is personless and keeps no session, device, user agent or IP, even from
15
+ * the active context or registered properties.
16
+ *
17
+ * An error object is captured once per request and project, however many hooks pass it here. When the client has a
18
+ * `waitUntil` option, the capture is handed to it, so a serverless runtime stays alive until it is queued and flushed.
19
+ * The returned promise resolves once the event is queued.
20
+ */
21
+ export declare function captureRequestException(posthog: PostHogBackendClient, error: unknown, request: Request, options: CaptureRequestExceptionOptions): Promise<void>;
22
+ //# sourceMappingURL=request-exception.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"request-exception.d.ts","sourceRoot":"","sources":["../../src/extensions/request-exception.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,WAAW,CAAA;AAWrD,MAAM,WAAW,8BAA8B;IAC7C,wGAAwG;IACxG,MAAM,EAAE,MAAM,CAAA;IACd,+GAA+G;IAC/G,GAAG,CAAC,EAAE,MAAM,CAAA;CACb;AA8CD;;;;;;;;;;;;GAYG;AACH,wBAAgB,uBAAuB,CACrC,OAAO,EAAE,oBAAoB,EAC7B,KAAK,EAAE,OAAO,EACd,OAAO,EAAE,OAAO,EAChB,OAAO,EAAE,8BAA8B,GACtC,OAAO,CAAC,IAAI,CAAC,CAuEf"}
@@ -0,0 +1,134 @@
1
+ "use strict";
2
+ var __webpack_require__ = {};
3
+ (()=>{
4
+ __webpack_require__.n = (module)=>{
5
+ var getter = module && module.__esModule ? ()=>module['default'] : ()=>module;
6
+ __webpack_require__.d(getter, {
7
+ a: getter
8
+ });
9
+ return getter;
10
+ };
11
+ })();
12
+ (()=>{
13
+ __webpack_require__.d = (exports1, getters, values)=>{
14
+ var define = (defs, kind)=>{
15
+ for(var key in defs)if (__webpack_require__.o(defs, key) && !__webpack_require__.o(exports1, key)) Object.defineProperty(exports1, key, {
16
+ enumerable: true,
17
+ [kind]: defs[key]
18
+ });
19
+ };
20
+ define(getters, "get");
21
+ define(values, "value");
22
+ };
23
+ })();
24
+ (()=>{
25
+ __webpack_require__.o = (obj, prop)=>Object.prototype.hasOwnProperty.call(obj, prop);
26
+ })();
27
+ (()=>{
28
+ __webpack_require__.r = (exports1)=>{
29
+ if ("u" > typeof Symbol && Symbol.toStringTag) Object.defineProperty(exports1, Symbol.toStringTag, {
30
+ value: 'Module'
31
+ });
32
+ Object.defineProperty(exports1, '__esModule', {
33
+ value: true
34
+ });
35
+ };
36
+ })();
37
+ var __webpack_exports__ = {};
38
+ __webpack_require__.r(__webpack_exports__);
39
+ __webpack_require__.d(__webpack_exports__, {
40
+ captureRequestException: ()=>captureRequestException
41
+ });
42
+ const index_js_namespaceObject = require("./error-tracking/index.js");
43
+ var index_js_default = /*#__PURE__*/ __webpack_require__.n(index_js_namespaceObject);
44
+ const external_tracing_headers_js_namespaceObject = require("./tracing-headers.js");
45
+ const external_url_utils_js_namespaceObject = require("./url-utils.js");
46
+ const capturedByRequest = new WeakMap();
47
+ function claimRequestCapture(posthog, error, request) {
48
+ if (index_js_default().isPreviouslyCapturedError(error)) return false;
49
+ if (('object' != typeof error || null === error) && 'function' != typeof error) return true;
50
+ const byProject = capturedByRequest.get(request) ?? new Map();
51
+ capturedByRequest.set(request, byProject);
52
+ const project = `${posthog.apiKey}@${posthog.host}`;
53
+ const captured = byProject.get(project) ?? new WeakSet();
54
+ byProject.set(project, captured);
55
+ if (captured.has(error)) return false;
56
+ captured.add(error);
57
+ return true;
58
+ }
59
+ const VISITOR_PROPERTIES = [
60
+ '$session_id',
61
+ '$window_id',
62
+ '$device_id',
63
+ '$user_agent',
64
+ '$raw_user_agent',
65
+ '$ip'
66
+ ];
67
+ function withoutVisitor(context) {
68
+ if (!context) return;
69
+ const { distinctId: _distinctId, sessionId: _sessionId, ...rest } = context;
70
+ return rest;
71
+ }
72
+ function parseUrl(value) {
73
+ try {
74
+ return new URL(value);
75
+ } catch {
76
+ return;
77
+ }
78
+ }
79
+ function captureRequestException(posthog, error, request, options) {
80
+ try {
81
+ if (!claimRequestCapture(posthog, error, request)) return Promise.resolve();
82
+ const cookieOptions = (0, external_tracing_headers_js_namespaceObject.getPostHogCookieReadOptions)(posthog);
83
+ const optedOut = (0, external_tracing_headers_js_namespaceObject.isPostHogCookieOptedOut)(request.headers.get('cookie') ?? void 0, posthog.apiKey, cookieOptions?.optOutCapturingByDefault === true);
84
+ const context = optedOut ? withoutVisitor(posthog.getContext()) : posthog.getContext();
85
+ const properties = {};
86
+ let distinctId;
87
+ let personless = optedOut;
88
+ if (!optedOut) {
89
+ const ids = (0, external_tracing_headers_js_namespaceObject.readPostHogTracingHeaders)(posthog.options, Object.fromEntries(request.headers), cookieOptions, true);
90
+ distinctId = context?.distinctId ?? ids.distinctId;
91
+ personless = distinctId === ids.distinctId && true === ids.anonymous;
92
+ (0, external_tracing_headers_js_namespaceObject.addProperty)(properties, '$session_id', context?.sessionId ?? ids.sessionId);
93
+ (0, external_tracing_headers_js_namespaceObject.addProperty)(properties, '$user_agent', request.headers.get('user-agent') ?? void 0);
94
+ }
95
+ const url = parseUrl(options.url ?? request.url);
96
+ (0, external_tracing_headers_js_namespaceObject.addProperty)(properties, '$current_url', url ? `${url.origin}${url.pathname}` : void 0);
97
+ (0, external_tracing_headers_js_namespaceObject.addProperty)(properties, '$request_method', request.method);
98
+ (0, external_tracing_headers_js_namespaceObject.addProperty)(properties, '$request_path', url ? (0, external_url_utils_js_namespaceObject.normalizeRequestPath)(url.pathname, true === posthog.options.disableCaptureUrlHashes) : void 0);
99
+ const hint = {
100
+ mechanism: {
101
+ type: 'middleware',
102
+ handled: false
103
+ },
104
+ syntheticException: new Error('PostHog syntheticException')
105
+ };
106
+ const queued = posthog._captureIntegrationException(error, ()=>index_js_default().buildEventMessage(posthog.getErrorPropertiesBuilder(), error, hint, distinctId, properties, void 0, context).then((msg)=>({
107
+ ...msg,
108
+ properties: {
109
+ ...msg.properties,
110
+ $exception_source: options.source
111
+ },
112
+ ...personless ? {
113
+ options: {
114
+ ...msg.options,
115
+ process_person_profile: false
116
+ }
117
+ } : {}
118
+ })), optedOut ? VISITOR_PROPERTIES : void 0);
119
+ const waitUntil = posthog.options.waitUntil;
120
+ if (waitUntil) try {
121
+ waitUntil(queued);
122
+ } catch {}
123
+ return queued;
124
+ } catch {
125
+ return Promise.resolve();
126
+ }
127
+ }
128
+ exports.captureRequestException = __webpack_exports__.captureRequestException;
129
+ for(var __rspack_i in __webpack_exports__)if (-1 === [
130
+ "captureRequestException"
131
+ ].indexOf(__rspack_i)) exports[__rspack_i] = __webpack_exports__[__rspack_i];
132
+ Object.defineProperty(exports, '__esModule', {
133
+ value: true
134
+ });
@@ -0,0 +1,86 @@
1
+ import error_tracking from "./error-tracking/index.mjs";
2
+ import { addProperty, getPostHogCookieReadOptions, isPostHogCookieOptedOut, readPostHogTracingHeaders } from "./tracing-headers.mjs";
3
+ import { normalizeRequestPath } from "./url-utils.mjs";
4
+ const capturedByRequest = new WeakMap();
5
+ function claimRequestCapture(posthog, error, request) {
6
+ if (error_tracking.isPreviouslyCapturedError(error)) return false;
7
+ if (('object' != typeof error || null === error) && 'function' != typeof error) return true;
8
+ const byProject = capturedByRequest.get(request) ?? new Map();
9
+ capturedByRequest.set(request, byProject);
10
+ const project = `${posthog.apiKey}@${posthog.host}`;
11
+ const captured = byProject.get(project) ?? new WeakSet();
12
+ byProject.set(project, captured);
13
+ if (captured.has(error)) return false;
14
+ captured.add(error);
15
+ return true;
16
+ }
17
+ const VISITOR_PROPERTIES = [
18
+ '$session_id',
19
+ '$window_id',
20
+ '$device_id',
21
+ '$user_agent',
22
+ '$raw_user_agent',
23
+ '$ip'
24
+ ];
25
+ function withoutVisitor(context) {
26
+ if (!context) return;
27
+ const { distinctId: _distinctId, sessionId: _sessionId, ...rest } = context;
28
+ return rest;
29
+ }
30
+ function parseUrl(value) {
31
+ try {
32
+ return new URL(value);
33
+ } catch {
34
+ return;
35
+ }
36
+ }
37
+ function captureRequestException(posthog, error, request, options) {
38
+ try {
39
+ if (!claimRequestCapture(posthog, error, request)) return Promise.resolve();
40
+ const cookieOptions = getPostHogCookieReadOptions(posthog);
41
+ const optedOut = isPostHogCookieOptedOut(request.headers.get('cookie') ?? void 0, posthog.apiKey, cookieOptions?.optOutCapturingByDefault === true);
42
+ const context = optedOut ? withoutVisitor(posthog.getContext()) : posthog.getContext();
43
+ const properties = {};
44
+ let distinctId;
45
+ let personless = optedOut;
46
+ if (!optedOut) {
47
+ const ids = readPostHogTracingHeaders(posthog.options, Object.fromEntries(request.headers), cookieOptions, true);
48
+ distinctId = context?.distinctId ?? ids.distinctId;
49
+ personless = distinctId === ids.distinctId && true === ids.anonymous;
50
+ addProperty(properties, '$session_id', context?.sessionId ?? ids.sessionId);
51
+ addProperty(properties, '$user_agent', request.headers.get('user-agent') ?? void 0);
52
+ }
53
+ const url = parseUrl(options.url ?? request.url);
54
+ addProperty(properties, '$current_url', url ? `${url.origin}${url.pathname}` : void 0);
55
+ addProperty(properties, '$request_method', request.method);
56
+ addProperty(properties, '$request_path', url ? normalizeRequestPath(url.pathname, true === posthog.options.disableCaptureUrlHashes) : void 0);
57
+ const hint = {
58
+ mechanism: {
59
+ type: 'middleware',
60
+ handled: false
61
+ },
62
+ syntheticException: new Error('PostHog syntheticException')
63
+ };
64
+ const queued = posthog._captureIntegrationException(error, ()=>error_tracking.buildEventMessage(posthog.getErrorPropertiesBuilder(), error, hint, distinctId, properties, void 0, context).then((msg)=>({
65
+ ...msg,
66
+ properties: {
67
+ ...msg.properties,
68
+ $exception_source: options.source
69
+ },
70
+ ...personless ? {
71
+ options: {
72
+ ...msg.options,
73
+ process_person_profile: false
74
+ }
75
+ } : {}
76
+ })), optedOut ? VISITOR_PROPERTIES : void 0);
77
+ const waitUntil = posthog.options.waitUntil;
78
+ if (waitUntil) try {
79
+ waitUntil(queued);
80
+ } catch {}
81
+ return queued;
82
+ } catch {
83
+ return Promise.resolve();
84
+ }
85
+ }
86
+ export { captureRequestException };
@@ -24,6 +24,8 @@ export declare function getPostHogCookieReadOptions(posthog: {
24
24
  export interface PostHogTracingHeaderValues {
25
25
  sessionId?: string;
26
26
  distinctId?: string;
27
+ /** The distinct ID is from the cookie and belongs to a visitor posthog-js has not identified. */
28
+ anonymous?: true;
27
29
  }
28
30
  export declare function addProperty(properties: Record<string, any>, key: string, value: unknown): void;
29
31
  export declare function getFirstHeaderValue(value: HeaderValue): string | undefined;
@@ -32,21 +34,27 @@ export declare function sanitizeTracingHeaderValue(value: HeaderValue): string |
32
34
  * Reads the live session ID, and the distinct ID of an identified user, from the cookie that posthog-js writes with its
33
35
  * default persistence. The browser sends it on every same-site request, so backend events link to the browser session
34
36
  * without `tracing_headers`. A session past the posthog-js idle timeout or length cap is not returned, because the
35
- * browser starts a new session on its next activity. An anonymous distinct ID is not returned, so backend events for
36
- * anonymous visitors stay personless. Nothing is returned when the visitor's consent cookie opts out.
37
+ * browser starts a new session on its next activity. An anonymous distinct ID is returned only with
38
+ * `includeAnonymousDistinctId` (marked `anonymous`), so backend events for anonymous visitors otherwise stay
39
+ * personless. Nothing is returned when the visitor's consent cookie opts out.
37
40
  */
38
- export declare function getPostHogCookieValues(cookieHeader: HeaderValue, apiKey: string, now?: number, sessionIdleTimeoutMs?: number, optOutCapturingByDefault?: boolean): PostHogTracingHeaderValues;
41
+ export declare function getPostHogCookieValues(cookieHeader: HeaderValue, apiKey: string, now?: number, sessionIdleTimeoutMs?: number, optOutCapturingByDefault?: boolean, includeAnonymousDistinctId?: boolean): PostHogTracingHeaderValues;
42
+ /**
43
+ * Whether the visitor's posthog-js consent cookie opts out of capture, or, with `optOutCapturingByDefault`, does not
44
+ * opt in. posthog-js keeps consent in localStorage by default, which the server cannot read.
45
+ */
46
+ export declare function isPostHogCookieOptedOut(cookieHeader: HeaderValue, apiKey: string, optOutCapturingByDefault?: boolean): boolean;
39
47
  /**
40
48
  * The request's tracing ids, with the posthog-js cookie fallback when `cookie` is set. When the client's
41
49
  * `captureTracingHeaders` is `false`, the tracing headers count as absent, so only the cookie can supply ids.
42
50
  */
43
51
  export declare function readPostHogTracingHeaders(options: {
44
52
  captureTracingHeaders?: boolean;
45
- }, headers?: IncomingHttpHeaders, cookie?: PostHogCookieReadOptions | null): PostHogTracingHeaderValues;
53
+ }, headers?: IncomingHttpHeaders, cookie?: PostHogCookieReadOptions | null, includeAnonymousDistinctId?: boolean): PostHogTracingHeaderValues;
46
54
  /**
47
55
  * Reads the PostHog tracing headers. With cookie read options, a request with neither header falls back to the posthog-js
48
56
  * cookie. A request with either header uses headers only, so one request never mixes two identities.
49
57
  */
50
- export declare function getPostHogTracingHeaderValues(headers?: IncomingHttpHeaders, cookie?: PostHogCookieReadOptions | null): PostHogTracingHeaderValues;
58
+ export declare function getPostHogTracingHeaderValues(headers?: IncomingHttpHeaders, cookie?: PostHogCookieReadOptions | null, includeAnonymousDistinctId?: boolean): PostHogTracingHeaderValues;
51
59
  export {};
52
60
  //# sourceMappingURL=tracing-headers.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"tracing-headers.d.ts","sourceRoot":"","sources":["../../src/extensions/tracing-headers.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,WAAW,CAAA;AAapD,KAAK,WAAW,GAAG,mBAAmB,CAAC,MAAM,CAAC,CAAA;AAE9C,eAAO,MAAM,uBAAuB;aAClC,SAAS,EAAE,sBAAsB;aACjC,UAAU,EAAE,uBAAuB;CAC3B,CAAA;AAEV,MAAM,WAAW,wBAAwB;IACvC,MAAM,EAAE,MAAM,CAAA;IACd,yBAAyB,CAAC,EAAE,MAAM,CAAA;IAClC,wBAAwB,CAAC,EAAE,OAAO,CAAA;CACnC;AAED;;GAEG;AACH,wBAAgB,2BAA2B,CAAC,OAAO,EAAE;IACnD,MAAM,EAAE,MAAM,CAAA;IACd,OAAO,EAAE;QAAE,iBAAiB,CAAC,EAAE,OAAO,GAAG;YAAE,yBAAyB,CAAC,EAAE,MAAM,CAAC;YAAC,wBAAwB,CAAC,EAAE,OAAO,CAAA;SAAE,CAAA;KAAE,CAAA;CACtH,GAAG,wBAAwB,GAAG,IAAI,CAalC;AAED,MAAM,WAAW,0BAA0B;IACzC,SAAS,CAAC,EAAE,MAAM,CAAA;IAClB,UAAU,CAAC,EAAE,MAAM,CAAA;CACpB;AAED,wBAAgB,WAAW,CAAC,UAAU,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,EAAE,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,GAAG,IAAI,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C,OAAO,CAAC,EAAE,mBAAmB,EAC7B,MAAM,CAAC,EAAE,wBAAwB,GAAG,IAAI,EACxC,0BAA0B,GAAE,OAAe,GAC1C,0BAA0B,CAiB5B"}
@@ -34,6 +34,7 @@ __webpack_require__.d(__webpack_exports__, {
34
34
  getPostHogCookieReadOptions: ()=>getPostHogCookieReadOptions,
35
35
  getPostHogCookieValues: ()=>getPostHogCookieValues,
36
36
  getPostHogTracingHeaderValues: ()=>getPostHogTracingHeaderValues,
37
+ isPostHogCookieOptedOut: ()=>isPostHogCookieOptedOut,
37
38
  readPostHogTracingHeaders: ()=>readPostHogTracingHeaders,
38
39
  sanitizeTracingHeaderValue: ()=>sanitizeTracingHeaderValue
39
40
  });
@@ -82,16 +83,16 @@ function sanitizeTracingHeaderValue(value) {
82
83
  function isRecent(timestamp, now, maxAgeMs) {
83
84
  return 'number' == typeof timestamp && Number.isFinite(timestamp) && Math.abs(now - timestamp) <= maxAgeMs;
84
85
  }
85
- function getPostHogCookieValues(cookieHeader, apiKey, now = Date.now(), sessionIdleTimeoutMs = COOKIE_SESSION_IDLE_TIMEOUT_MS, optOutCapturingByDefault = false) {
86
+ function getPostHogCookieValues(cookieHeader, apiKey, now = Date.now(), sessionIdleTimeoutMs = COOKIE_SESSION_IDLE_TIMEOUT_MS, optOutCapturingByDefault = false, includeAnonymousDistinctId = false) {
86
87
  try {
87
88
  if ('string' != typeof cookieHeader) return {};
88
- const cookies = (0, core_namespaceObject.cookieStoreFromHeader)(cookieHeader.split(';').reverse().join(';'));
89
+ const cookies = readCookieStore(cookieHeader);
89
90
  const raw = cookies.get((0, core_namespaceObject.getPostHogCookieName)(apiKey))?.value;
90
- const consent = cookies.get((0, core_namespaceObject.getConsentCookieName)(apiKey))?.value ?? '';
91
- if (!raw || (0, core_namespaceObject.isNoLike)(consent) || optOutCapturingByDefault && !(0, core_namespaceObject.isYesLike)(consent)) return {};
91
+ if (!raw || isOptedOutByCookie(cookies, apiKey, optOutCapturingByDefault)) return {};
92
92
  const data = JSON.parse(raw);
93
93
  if (!data || 'object' != typeof data) return {};
94
- const distinctId = 'identified' === data.$user_state ? sanitizeTracingHeaderValue(data.distinct_id) : void 0;
94
+ const identified = 'identified' === data.$user_state;
95
+ const distinctId = identified || includeAnonymousDistinctId ? sanitizeTracingHeaderValue(data.distinct_id) : void 0;
95
96
  let sessionId;
96
97
  const session = data.$sesid;
97
98
  if (Array.isArray(session) && (2 === session.length || 3 === session.length)) {
@@ -104,29 +105,47 @@ function getPostHogCookieValues(cookieHeader, apiKey, now = Date.now(), sessionI
104
105
  } : {},
105
106
  ...void 0 !== distinctId ? {
106
107
  distinctId
108
+ } : {},
109
+ ...void 0 !== distinctId && !identified ? {
110
+ anonymous: true
107
111
  } : {}
108
112
  };
109
113
  } catch {
110
114
  return {};
111
115
  }
112
116
  }
117
+ function readCookieStore(cookieHeader) {
118
+ return (0, core_namespaceObject.cookieStoreFromHeader)(cookieHeader.split(';').reverse().join(';'));
119
+ }
120
+ function isOptedOutByCookie(cookies, apiKey, optOutCapturingByDefault) {
121
+ const consent = cookies.get((0, core_namespaceObject.getConsentCookieName)(apiKey))?.value ?? '';
122
+ return (0, core_namespaceObject.isNoLike)(consent) || optOutCapturingByDefault && !(0, core_namespaceObject.isYesLike)(consent);
123
+ }
124
+ function isPostHogCookieOptedOut(cookieHeader, apiKey, optOutCapturingByDefault = false) {
125
+ try {
126
+ const header = 'string' == typeof cookieHeader ? cookieHeader : '';
127
+ return isOptedOutByCookie(readCookieStore(header), apiKey, optOutCapturingByDefault);
128
+ } catch {
129
+ return false;
130
+ }
131
+ }
113
132
  function getSessionIdleTimeoutMs(cookie) {
114
133
  const seconds = cookie.sessionIdleTimeoutSeconds;
115
134
  if ('number' != typeof seconds || !Number.isFinite(seconds) || 0 === seconds) return COOKIE_SESSION_IDLE_TIMEOUT_MS;
116
135
  return 1000 * Math.min(Math.max(seconds, MIN_SESSION_IDLE_TIMEOUT_SECONDS), MAX_SESSION_IDLE_TIMEOUT_SECONDS);
117
136
  }
118
- function readCookieValues(headers, cookie) {
119
- return getPostHogCookieValues(headers.cookie, cookie.apiKey, Date.now(), getSessionIdleTimeoutMs(cookie), true === cookie.optOutCapturingByDefault);
137
+ function readCookieValues(headers, cookie, includeAnonymousDistinctId) {
138
+ return getPostHogCookieValues(headers.cookie, cookie.apiKey, Date.now(), getSessionIdleTimeoutMs(cookie), true === cookie.optOutCapturingByDefault, includeAnonymousDistinctId);
120
139
  }
121
- function readPostHogTracingHeaders(options, headers, cookie) {
122
- if (false !== options.captureTracingHeaders) return getPostHogTracingHeaderValues(headers, cookie);
123
- return headers && cookie ? readCookieValues(headers, cookie) : {};
140
+ function readPostHogTracingHeaders(options, headers, cookie, includeAnonymousDistinctId = false) {
141
+ if (false !== options.captureTracingHeaders) return getPostHogTracingHeaderValues(headers, cookie, includeAnonymousDistinctId);
142
+ return headers && cookie ? readCookieValues(headers, cookie, includeAnonymousDistinctId) : {};
124
143
  }
125
- function getPostHogTracingHeaderValues(headers, cookie) {
144
+ function getPostHogTracingHeaderValues(headers, cookie, includeAnonymousDistinctId = false) {
126
145
  if (!headers) return {};
127
146
  const headerSessionId = sanitizeTracingHeaderValue(headers[POSTHOG_TRACING_HEADERS.sessionId]);
128
147
  const headerDistinctId = sanitizeTracingHeaderValue(headers[POSTHOG_TRACING_HEADERS.distinctId]);
129
- const { sessionId, distinctId } = void 0 === headerSessionId && void 0 === headerDistinctId && cookie ? readCookieValues(headers, cookie) : {
148
+ const { sessionId, distinctId, anonymous } = void 0 === headerSessionId && void 0 === headerDistinctId && cookie ? readCookieValues(headers, cookie, includeAnonymousDistinctId) : {
130
149
  sessionId: headerSessionId,
131
150
  distinctId: headerDistinctId
132
151
  };
@@ -136,6 +155,9 @@ function getPostHogTracingHeaderValues(headers, cookie) {
136
155
  } : {},
137
156
  ...void 0 !== distinctId ? {
138
157
  distinctId
158
+ } : {},
159
+ ...anonymous ? {
160
+ anonymous
139
161
  } : {}
140
162
  };
141
163
  }
@@ -145,6 +167,7 @@ exports.getFirstHeaderValue = __webpack_exports__.getFirstHeaderValue;
145
167
  exports.getPostHogCookieReadOptions = __webpack_exports__.getPostHogCookieReadOptions;
146
168
  exports.getPostHogCookieValues = __webpack_exports__.getPostHogCookieValues;
147
169
  exports.getPostHogTracingHeaderValues = __webpack_exports__.getPostHogTracingHeaderValues;
170
+ exports.isPostHogCookieOptedOut = __webpack_exports__.isPostHogCookieOptedOut;
148
171
  exports.readPostHogTracingHeaders = __webpack_exports__.readPostHogTracingHeaders;
149
172
  exports.sanitizeTracingHeaderValue = __webpack_exports__.sanitizeTracingHeaderValue;
150
173
  for(var __rspack_i in __webpack_exports__)if (-1 === [
@@ -154,6 +177,7 @@ for(var __rspack_i in __webpack_exports__)if (-1 === [
154
177
  "getPostHogCookieReadOptions",
155
178
  "getPostHogCookieValues",
156
179
  "getPostHogTracingHeaderValues",
180
+ "isPostHogCookieOptedOut",
157
181
  "readPostHogTracingHeaders",
158
182
  "sanitizeTracingHeaderValue"
159
183
  ].indexOf(__rspack_i)) exports[__rspack_i] = __webpack_exports__[__rspack_i];
@@ -43,16 +43,16 @@ function sanitizeTracingHeaderValue(value) {
43
43
  function isRecent(timestamp, now, maxAgeMs) {
44
44
  return 'number' == typeof timestamp && Number.isFinite(timestamp) && Math.abs(now - timestamp) <= maxAgeMs;
45
45
  }
46
- function getPostHogCookieValues(cookieHeader, apiKey, now = Date.now(), sessionIdleTimeoutMs = COOKIE_SESSION_IDLE_TIMEOUT_MS, optOutCapturingByDefault = false) {
46
+ function getPostHogCookieValues(cookieHeader, apiKey, now = Date.now(), sessionIdleTimeoutMs = COOKIE_SESSION_IDLE_TIMEOUT_MS, optOutCapturingByDefault = false, includeAnonymousDistinctId = false) {
47
47
  try {
48
48
  if ('string' != typeof cookieHeader) return {};
49
- const cookies = cookieStoreFromHeader(cookieHeader.split(';').reverse().join(';'));
49
+ const cookies = readCookieStore(cookieHeader);
50
50
  const raw = cookies.get(getPostHogCookieName(apiKey))?.value;
51
- const consent = cookies.get(getConsentCookieName(apiKey))?.value ?? '';
52
- if (!raw || isNoLike(consent) || optOutCapturingByDefault && !isYesLike(consent)) return {};
51
+ if (!raw || isOptedOutByCookie(cookies, apiKey, optOutCapturingByDefault)) return {};
53
52
  const data = JSON.parse(raw);
54
53
  if (!data || 'object' != typeof data) return {};
55
- const distinctId = 'identified' === data.$user_state ? sanitizeTracingHeaderValue(data.distinct_id) : void 0;
54
+ const identified = 'identified' === data.$user_state;
55
+ const distinctId = identified || includeAnonymousDistinctId ? sanitizeTracingHeaderValue(data.distinct_id) : void 0;
56
56
  let sessionId;
57
57
  const session = data.$sesid;
58
58
  if (Array.isArray(session) && (2 === session.length || 3 === session.length)) {
@@ -65,29 +65,47 @@ function getPostHogCookieValues(cookieHeader, apiKey, now = Date.now(), sessionI
65
65
  } : {},
66
66
  ...void 0 !== distinctId ? {
67
67
  distinctId
68
+ } : {},
69
+ ...void 0 !== distinctId && !identified ? {
70
+ anonymous: true
68
71
  } : {}
69
72
  };
70
73
  } catch {
71
74
  return {};
72
75
  }
73
76
  }
77
+ function readCookieStore(cookieHeader) {
78
+ return cookieStoreFromHeader(cookieHeader.split(';').reverse().join(';'));
79
+ }
80
+ function isOptedOutByCookie(cookies, apiKey, optOutCapturingByDefault) {
81
+ const consent = cookies.get(getConsentCookieName(apiKey))?.value ?? '';
82
+ return isNoLike(consent) || optOutCapturingByDefault && !isYesLike(consent);
83
+ }
84
+ function isPostHogCookieOptedOut(cookieHeader, apiKey, optOutCapturingByDefault = false) {
85
+ try {
86
+ const header = 'string' == typeof cookieHeader ? cookieHeader : '';
87
+ return isOptedOutByCookie(readCookieStore(header), apiKey, optOutCapturingByDefault);
88
+ } catch {
89
+ return false;
90
+ }
91
+ }
74
92
  function getSessionIdleTimeoutMs(cookie) {
75
93
  const seconds = cookie.sessionIdleTimeoutSeconds;
76
94
  if ('number' != typeof seconds || !Number.isFinite(seconds) || 0 === seconds) return COOKIE_SESSION_IDLE_TIMEOUT_MS;
77
95
  return 1000 * Math.min(Math.max(seconds, MIN_SESSION_IDLE_TIMEOUT_SECONDS), MAX_SESSION_IDLE_TIMEOUT_SECONDS);
78
96
  }
79
- function readCookieValues(headers, cookie) {
80
- return getPostHogCookieValues(headers.cookie, cookie.apiKey, Date.now(), getSessionIdleTimeoutMs(cookie), true === cookie.optOutCapturingByDefault);
97
+ function readCookieValues(headers, cookie, includeAnonymousDistinctId) {
98
+ return getPostHogCookieValues(headers.cookie, cookie.apiKey, Date.now(), getSessionIdleTimeoutMs(cookie), true === cookie.optOutCapturingByDefault, includeAnonymousDistinctId);
81
99
  }
82
- function readPostHogTracingHeaders(options, headers, cookie) {
83
- if (false !== options.captureTracingHeaders) return getPostHogTracingHeaderValues(headers, cookie);
84
- return headers && cookie ? readCookieValues(headers, cookie) : {};
100
+ function readPostHogTracingHeaders(options, headers, cookie, includeAnonymousDistinctId = false) {
101
+ if (false !== options.captureTracingHeaders) return getPostHogTracingHeaderValues(headers, cookie, includeAnonymousDistinctId);
102
+ return headers && cookie ? readCookieValues(headers, cookie, includeAnonymousDistinctId) : {};
85
103
  }
86
- function getPostHogTracingHeaderValues(headers, cookie) {
104
+ function getPostHogTracingHeaderValues(headers, cookie, includeAnonymousDistinctId = false) {
87
105
  if (!headers) return {};
88
106
  const headerSessionId = sanitizeTracingHeaderValue(headers[POSTHOG_TRACING_HEADERS.sessionId]);
89
107
  const headerDistinctId = sanitizeTracingHeaderValue(headers[POSTHOG_TRACING_HEADERS.distinctId]);
90
- const { sessionId, distinctId } = void 0 === headerSessionId && void 0 === headerDistinctId && cookie ? readCookieValues(headers, cookie) : {
108
+ const { sessionId, distinctId, anonymous } = void 0 === headerSessionId && void 0 === headerDistinctId && cookie ? readCookieValues(headers, cookie, includeAnonymousDistinctId) : {
91
109
  sessionId: headerSessionId,
92
110
  distinctId: headerDistinctId
93
111
  };
@@ -97,7 +115,10 @@ function getPostHogTracingHeaderValues(headers, cookie) {
97
115
  } : {},
98
116
  ...void 0 !== distinctId ? {
99
117
  distinctId
118
+ } : {},
119
+ ...anonymous ? {
120
+ anonymous
100
121
  } : {}
101
122
  };
102
123
  }
103
- export { POSTHOG_TRACING_HEADERS, addProperty, getFirstHeaderValue, getPostHogCookieReadOptions, getPostHogCookieValues, getPostHogTracingHeaderValues, readPostHogTracingHeaders, sanitizeTracingHeaderValue };
124
+ export { POSTHOG_TRACING_HEADERS, addProperty, getFirstHeaderValue, getPostHogCookieReadOptions, getPostHogCookieValues, getPostHogTracingHeaderValues, isPostHogCookieOptedOut, readPostHogTracingHeaders, sanitizeTracingHeaderValue };
@@ -0,0 +1,20 @@
1
+ /**
2
+ * PostHog answered a `getRemoteConfigPayload` request with a status outside 200 to 299.
3
+ *
4
+ * Emitted on the client's `error` event; the call itself resolves to `undefined`.
5
+ * Branch on `statusCode`, for example `404` when the flag does not exist or is not a remote
6
+ * config flag, versus `429` or `5xx` when the request should be tried again later.
7
+ */
8
+ export declare class RemoteConfigPayloadError extends Error {
9
+ /** The key of the flag whose payload was requested. */
10
+ readonly flagKey: string;
11
+ /** The HTTP status PostHog answered with. */
12
+ readonly statusCode: number;
13
+ name: string;
14
+ constructor(
15
+ /** The key of the flag whose payload was requested. */
16
+ flagKey: string,
17
+ /** The HTTP status PostHog answered with. */
18
+ statusCode: number);
19
+ }
20
+ //# sourceMappingURL=remote-config-errors.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"remote-config-errors.d.ts","sourceRoot":"","sources":["../src/remote-config-errors.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,qBAAa,wBAAyB,SAAQ,KAAK;IAI/C,uDAAuD;IACvD,QAAQ,CAAC,OAAO,EAAE,MAAM;IACxB,6CAA6C;IAC7C,QAAQ,CAAC,UAAU,EAAE,MAAM;IAN7B,IAAI,SAA6B;IAEjC;IACE,uDAAuD;IAC9C,OAAO,EAAE,MAAM;IACxB,6CAA6C;IACpC,UAAU,EAAE,MAAM,EAG5B;CACF"}