posthog-node 4.4.0 → 4.5.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 (36) hide show
  1. package/CHANGELOG.md +11 -0
  2. package/index.ts +1 -0
  3. package/lib/index.cjs.js +911 -7
  4. package/lib/index.cjs.js.map +1 -1
  5. package/lib/index.d.ts +44 -3
  6. package/lib/index.esm.js +911 -7
  7. package/lib/index.esm.js.map +1 -1
  8. package/lib/posthog-core/src/index.d.ts +6 -0
  9. package/lib/posthog-core/src/types.d.ts +1 -0
  10. package/lib/posthog-core/src/utils.d.ts +2 -0
  11. package/lib/posthog-node/index.d.ts +1 -0
  12. package/lib/posthog-node/src/error-tracking.d.ts +12 -0
  13. package/lib/posthog-node/src/extensions/error-tracking/autocapture.d.ts +3 -0
  14. package/lib/posthog-node/src/extensions/error-tracking/context-lines.d.ts +4 -0
  15. package/lib/posthog-node/src/extensions/error-tracking/error-conversion.d.ts +5 -0
  16. package/lib/posthog-node/src/extensions/error-tracking/reduceable-cache.d.ts +12 -0
  17. package/lib/posthog-node/src/extensions/error-tracking/stack-trace.d.ts +15 -0
  18. package/lib/posthog-node/src/extensions/error-tracking/type-checking.d.ts +7 -0
  19. package/lib/posthog-node/src/extensions/error-tracking/types.d.ts +57 -0
  20. package/lib/posthog-node/src/extensions/express.d.ts +17 -0
  21. package/lib/posthog-node/src/extensions/sentry-integration.d.ts +1 -2
  22. package/lib/posthog-node/src/fetch.d.ts +1 -2
  23. package/lib/posthog-node/src/posthog-node.d.ts +5 -0
  24. package/package.json +1 -1
  25. package/src/error-tracking.ts +66 -0
  26. package/src/extensions/error-tracking/autocapture.ts +62 -0
  27. package/src/extensions/error-tracking/context-lines.ts +389 -0
  28. package/src/extensions/error-tracking/error-conversion.ts +250 -0
  29. package/src/extensions/error-tracking/reduceable-cache.ts +36 -0
  30. package/src/extensions/error-tracking/stack-trace.ts +269 -0
  31. package/src/extensions/error-tracking/type-checking.ts +37 -0
  32. package/src/extensions/error-tracking/types.ts +62 -0
  33. package/src/extensions/express.ts +37 -0
  34. package/src/extensions/sentry-integration.ts +1 -3
  35. package/src/fetch.ts +3 -7
  36. package/src/posthog-node.ts +10 -0
package/lib/index.esm.js CHANGED
@@ -1,6 +1,9 @@
1
1
  import { createHash } from 'node:crypto';
2
+ import { createReadStream } from 'node:fs';
3
+ import { createInterface } from 'node:readline';
4
+ import { posix, dirname, sep } from 'node:path';
2
5
 
3
- var version = "4.4.0";
6
+ var version = "4.5.0";
4
7
 
5
8
  var PostHogPersistedProperty;
6
9
  (function (PostHogPersistedProperty) {
@@ -65,6 +68,9 @@ function safeSetTimeout(fn, timeout) {
65
68
  // We unref if available to prevent Node.js hanging on exit
66
69
  t?.unref && t?.unref();
67
70
  return t;
71
+ }
72
+ function getFetch() {
73
+ return typeof fetch !== 'undefined' ? fetch : typeof global.fetch !== 'undefined' ? global.fetch : undefined;
68
74
  }
69
75
 
70
76
  // Copyright (c) 2013 Pieroxy <pieroxy@pieroxy.net>
@@ -1427,10 +1433,7 @@ class PostHogMemoryStorage {
1427
1433
  * This is currently solved by using the global fetch if available instead.
1428
1434
  * See https://github.com/PostHog/posthog-js-lite/issues/127 for more info
1429
1435
  */
1430
- let _fetch =
1431
- // eslint-disable-next-line @typescript-eslint/prefer-ts-expect-error
1432
- // @ts-ignore
1433
- typeof fetch !== 'undefined' ? fetch : typeof global.fetch !== 'undefined' ? global.fetch : undefined;
1436
+ let _fetch = getFetch();
1434
1437
  if (!_fetch) {
1435
1438
  // eslint-disable-next-line @typescript-eslint/no-var-requires
1436
1439
  const axios = require('axios');
@@ -2036,6 +2039,884 @@ function relativeDateParseForFeatureFlagMatching(value) {
2036
2039
  }
2037
2040
  }
2038
2041
 
2042
+ function makeUncaughtExceptionHandler(captureFn, onFatalFn) {
2043
+ let calledFatalError = false;
2044
+ return Object.assign(error => {
2045
+ // Attaching a listener to `uncaughtException` will prevent the node process from exiting. We generally do not
2046
+ // want to alter this behaviour so we check for other listeners that users may have attached themselves and adjust
2047
+ // exit behaviour of the SDK accordingly:
2048
+ // - If other listeners are attached, do not exit.
2049
+ // - If the only listener attached is ours, exit.
2050
+ const userProvidedListenersCount = global.process.listeners('uncaughtException').filter(listener => {
2051
+ // There are 2 listeners we ignore:
2052
+ return (
2053
+ // as soon as we're using domains this listener is attached by node itself
2054
+ listener.name !== 'domainUncaughtExceptionClear' &&
2055
+ // the handler we register in this integration
2056
+ listener._posthogErrorHandler !== true
2057
+ );
2058
+ }).length;
2059
+ const processWouldExit = userProvidedListenersCount === 0;
2060
+ captureFn(error, {
2061
+ mechanism: {
2062
+ type: 'onuncaughtexception',
2063
+ handled: false
2064
+ }
2065
+ });
2066
+ if (!calledFatalError && processWouldExit) {
2067
+ calledFatalError = true;
2068
+ onFatalFn();
2069
+ }
2070
+ }, {
2071
+ _posthogErrorHandler: true
2072
+ });
2073
+ }
2074
+ function addUncaughtExceptionListener(captureFn, onFatalFn) {
2075
+ global.process.on('uncaughtException', makeUncaughtExceptionHandler(captureFn, onFatalFn));
2076
+ }
2077
+ function addUnhandledRejectionListener(captureFn) {
2078
+ global.process.on('unhandledRejection', reason => {
2079
+ captureFn(reason, {
2080
+ mechanism: {
2081
+ type: 'onunhandledrejection',
2082
+ handled: false
2083
+ }
2084
+ });
2085
+ });
2086
+ }
2087
+
2088
+ function isEvent(candidate) {
2089
+ return typeof Event !== 'undefined' && isInstanceOf(candidate, Event);
2090
+ }
2091
+ function isPlainObject(candidate) {
2092
+ return isBuiltin(candidate, 'Object');
2093
+ }
2094
+ function isError(candidate) {
2095
+ switch (Object.prototype.toString.call(candidate)) {
2096
+ case '[object Error]':
2097
+ case '[object Exception]':
2098
+ case '[object DOMException]':
2099
+ case '[object WebAssembly.Exception]':
2100
+ return true;
2101
+ default:
2102
+ return isInstanceOf(candidate, Error);
2103
+ }
2104
+ }
2105
+ function isInstanceOf(candidate, base) {
2106
+ try {
2107
+ return candidate instanceof base;
2108
+ } catch {
2109
+ return false;
2110
+ }
2111
+ }
2112
+ function isErrorEvent(event) {
2113
+ return isBuiltin(event, 'ErrorEvent');
2114
+ }
2115
+ function isBuiltin(candidate, className) {
2116
+ return Object.prototype.toString.call(candidate) === `[object ${className}]`;
2117
+ }
2118
+
2119
+ /** A simple Least Recently Used map */
2120
+ class ReduceableCache {
2121
+ constructor(_maxSize) {
2122
+ this._maxSize = _maxSize;
2123
+ this._cache = new Map();
2124
+ }
2125
+ /** Get an entry or undefined if it was not in the cache. Re-inserts to update the recently used order */
2126
+ get(key) {
2127
+ const value = this._cache.get(key);
2128
+ if (value === undefined) {
2129
+ return undefined;
2130
+ }
2131
+ // Remove and re-insert to update the order
2132
+ this._cache.delete(key);
2133
+ this._cache.set(key, value);
2134
+ return value;
2135
+ }
2136
+ /** Insert an entry and evict an older entry if we've reached maxSize */
2137
+ set(key, value) {
2138
+ this._cache.set(key, value);
2139
+ }
2140
+ /** Remove an entry and return the entry if it was in the cache */
2141
+ reduce() {
2142
+ while (this._cache.size >= this._maxSize) {
2143
+ const value = this._cache.keys().next().value;
2144
+ if (value) {
2145
+ // keys() returns an iterator in insertion order so keys().next() gives us the oldest key
2146
+ this._cache.delete(value);
2147
+ }
2148
+ }
2149
+ }
2150
+ }
2151
+
2152
+ const LRU_FILE_CONTENTS_CACHE = new ReduceableCache(25);
2153
+ const LRU_FILE_CONTENTS_FS_READ_FAILED = new ReduceableCache(20);
2154
+ const DEFAULT_LINES_OF_CONTEXT = 7;
2155
+ // Determines the upper bound of lineno/colno that we will attempt to read. Large colno values are likely to be
2156
+ // minified code while large lineno values are likely to be bundled code.
2157
+ // Exported for testing purposes.
2158
+ const MAX_CONTEXTLINES_COLNO = 1000;
2159
+ const MAX_CONTEXTLINES_LINENO = 10000;
2160
+ async function addSourceContext(frames) {
2161
+ // keep a lookup map of which files we've already enqueued to read,
2162
+ // so we don't enqueue the same file multiple times which would cause multiple i/o reads
2163
+ const filesToLines = {};
2164
+ // Maps preserve insertion order, so we iterate in reverse, starting at the
2165
+ // outermost frame and closer to where the exception has occurred (poor mans priority)
2166
+ for (let i = frames.length - 1; i >= 0; i--) {
2167
+ const frame = frames[i];
2168
+ const filename = frame?.filename;
2169
+ if (!frame || typeof filename !== 'string' || typeof frame.lineno !== 'number' || shouldSkipContextLinesForFile(filename) || shouldSkipContextLinesForFrame(frame)) {
2170
+ continue;
2171
+ }
2172
+ const filesToLinesOutput = filesToLines[filename];
2173
+ if (!filesToLinesOutput) {
2174
+ filesToLines[filename] = [];
2175
+ }
2176
+ filesToLines[filename].push(frame.lineno);
2177
+ }
2178
+ const files = Object.keys(filesToLines);
2179
+ if (files.length == 0) {
2180
+ return frames;
2181
+ }
2182
+ const readlinePromises = [];
2183
+ for (const file of files) {
2184
+ // If we failed to read this before, dont try reading it again.
2185
+ if (LRU_FILE_CONTENTS_FS_READ_FAILED.get(file)) {
2186
+ continue;
2187
+ }
2188
+ const filesToLineRanges = filesToLines[file];
2189
+ if (!filesToLineRanges) {
2190
+ continue;
2191
+ }
2192
+ // Sort ranges so that they are sorted by line increasing order and match how the file is read.
2193
+ filesToLineRanges.sort((a, b) => a - b);
2194
+ // Check if the contents are already in the cache and if we can avoid reading the file again.
2195
+ const ranges = makeLineReaderRanges(filesToLineRanges);
2196
+ if (ranges.every(r => rangeExistsInContentCache(file, r))) {
2197
+ continue;
2198
+ }
2199
+ const cache = emplace(LRU_FILE_CONTENTS_CACHE, file, {});
2200
+ readlinePromises.push(getContextLinesFromFile(file, ranges, cache));
2201
+ }
2202
+ // The promise rejections are caught in order to prevent them from short circuiting Promise.all
2203
+ await Promise.all(readlinePromises).catch(() => {});
2204
+ // Perform the same loop as above, but this time we can assume all files are in the cache
2205
+ // and attempt to add source context to frames.
2206
+ if (frames && frames.length > 0) {
2207
+ addSourceContextToFrames(frames, LRU_FILE_CONTENTS_CACHE);
2208
+ }
2209
+ // Once we're finished processing an exception reduce the files held in the cache
2210
+ // so that we don't indefinetly increase the size of this map
2211
+ LRU_FILE_CONTENTS_CACHE.reduce();
2212
+ return frames;
2213
+ }
2214
+ /**
2215
+ * Extracts lines from a file and stores them in a cache.
2216
+ */
2217
+ function getContextLinesFromFile(path, ranges, output) {
2218
+ return new Promise(resolve => {
2219
+ // It is important *not* to have any async code between createInterface and the 'line' event listener
2220
+ // as it will cause the 'line' event to
2221
+ // be emitted before the listener is attached.
2222
+ const stream = createReadStream(path);
2223
+ const lineReaded = createInterface({
2224
+ input: stream
2225
+ });
2226
+ // We need to explicitly destroy the stream to prevent memory leaks,
2227
+ // removing the listeners on the readline interface is not enough.
2228
+ // See: https://github.com/nodejs/node/issues/9002 and https://github.com/getsentry/sentry-javascript/issues/14892
2229
+ function destroyStreamAndResolve() {
2230
+ stream.destroy();
2231
+ resolve();
2232
+ }
2233
+ // Init at zero and increment at the start of the loop because lines are 1 indexed.
2234
+ let lineNumber = 0;
2235
+ let currentRangeIndex = 0;
2236
+ const range = ranges[currentRangeIndex];
2237
+ if (range === undefined) {
2238
+ // We should never reach this point, but if we do, we should resolve the promise to prevent it from hanging.
2239
+ destroyStreamAndResolve();
2240
+ return;
2241
+ }
2242
+ let rangeStart = range[0];
2243
+ let rangeEnd = range[1];
2244
+ // We use this inside Promise.all, so we need to resolve the promise even if there is an error
2245
+ // to prevent Promise.all from short circuiting the rest.
2246
+ function onStreamError() {
2247
+ // Mark file path as failed to read and prevent multiple read attempts.
2248
+ LRU_FILE_CONTENTS_FS_READ_FAILED.set(path, 1);
2249
+ lineReaded.close();
2250
+ lineReaded.removeAllListeners();
2251
+ destroyStreamAndResolve();
2252
+ }
2253
+ // We need to handle the error event to prevent the process from crashing in < Node 16
2254
+ // https://github.com/nodejs/node/pull/31603
2255
+ stream.on('error', onStreamError);
2256
+ lineReaded.on('error', onStreamError);
2257
+ lineReaded.on('close', destroyStreamAndResolve);
2258
+ lineReaded.on('line', line => {
2259
+ lineNumber++;
2260
+ if (lineNumber < rangeStart) {
2261
+ return;
2262
+ }
2263
+ // !Warning: This mutates the cache by storing the snipped line into the cache.
2264
+ output[lineNumber] = snipLine(line, 0);
2265
+ if (lineNumber >= rangeEnd) {
2266
+ if (currentRangeIndex === ranges.length - 1) {
2267
+ // We need to close the file stream and remove listeners, else the reader will continue to run our listener;
2268
+ lineReaded.close();
2269
+ lineReaded.removeAllListeners();
2270
+ return;
2271
+ }
2272
+ currentRangeIndex++;
2273
+ const range = ranges[currentRangeIndex];
2274
+ if (range === undefined) {
2275
+ // This should never happen as it means we have a bug in the context.
2276
+ lineReaded.close();
2277
+ lineReaded.removeAllListeners();
2278
+ return;
2279
+ }
2280
+ rangeStart = range[0];
2281
+ rangeEnd = range[1];
2282
+ }
2283
+ });
2284
+ });
2285
+ }
2286
+ /** Adds context lines to frames */
2287
+ function addSourceContextToFrames(frames, cache) {
2288
+ for (const frame of frames) {
2289
+ // Only add context if we have a filename and it hasn't already been added
2290
+ if (frame.filename && frame.context_line === undefined && typeof frame.lineno === 'number') {
2291
+ const contents = cache.get(frame.filename);
2292
+ if (contents === undefined) {
2293
+ continue;
2294
+ }
2295
+ addContextToFrame(frame.lineno, frame, contents);
2296
+ }
2297
+ }
2298
+ }
2299
+ /**
2300
+ * Resolves context lines before and after the given line number and appends them to the frame;
2301
+ */
2302
+ function addContextToFrame(lineno, frame, contents) {
2303
+ // When there is no line number in the frame, attaching context is nonsensical and will even break grouping.
2304
+ // We already check for lineno before calling this, but since StackFrame lineno is optional, we check it again.
2305
+ if (frame.lineno === undefined || contents === undefined) {
2306
+ return;
2307
+ }
2308
+ frame.pre_context = [];
2309
+ for (let i = makeRangeStart(lineno); i < lineno; i++) {
2310
+ // We always expect the start context as line numbers cannot be negative. If we dont find a line, then
2311
+ // something went wrong somewhere. Clear the context and return without adding any linecontext.
2312
+ const line = contents[i];
2313
+ if (line === undefined) {
2314
+ clearLineContext(frame);
2315
+ return;
2316
+ }
2317
+ frame.pre_context.push(line);
2318
+ }
2319
+ // We should always have the context line. If we dont, something went wrong, so we clear the context and return
2320
+ // without adding any linecontext.
2321
+ if (contents[lineno] === undefined) {
2322
+ clearLineContext(frame);
2323
+ return;
2324
+ }
2325
+ frame.context_line = contents[lineno];
2326
+ const end = makeRangeEnd(lineno);
2327
+ frame.post_context = [];
2328
+ for (let i = lineno + 1; i <= end; i++) {
2329
+ // Since we dont track when the file ends, we cant clear the context if we dont find a line as it could
2330
+ // just be that we reached the end of the file.
2331
+ const line = contents[i];
2332
+ if (line === undefined) {
2333
+ break;
2334
+ }
2335
+ frame.post_context.push(line);
2336
+ }
2337
+ }
2338
+ /**
2339
+ * Clears the context lines from a frame, used to reset a frame to its original state
2340
+ * if we fail to resolve all context lines for it.
2341
+ */
2342
+ function clearLineContext(frame) {
2343
+ delete frame.pre_context;
2344
+ delete frame.context_line;
2345
+ delete frame.post_context;
2346
+ }
2347
+ /**
2348
+ * Determines if context lines should be skipped for a file.
2349
+ * - .min.(mjs|cjs|js) files are and not useful since they dont point to the original source
2350
+ * - node: prefixed modules are part of the runtime and cannot be resolved to a file
2351
+ * - data: skip json, wasm and inline js https://nodejs.org/api/esm.html#data-imports
2352
+ */
2353
+ function shouldSkipContextLinesForFile(path) {
2354
+ // Test the most common prefix and extension first. These are the ones we
2355
+ // are most likely to see in user applications and are the ones we can break out of first.
2356
+ return path.startsWith('node:') || path.endsWith('.min.js') || path.endsWith('.min.cjs') || path.endsWith('.min.mjs') || path.startsWith('data:');
2357
+ }
2358
+ /**
2359
+ * Determines if we should skip contextlines based off the max lineno and colno values.
2360
+ */
2361
+ function shouldSkipContextLinesForFrame(frame) {
2362
+ if (frame.lineno !== undefined && frame.lineno > MAX_CONTEXTLINES_LINENO) {
2363
+ return true;
2364
+ }
2365
+ if (frame.colno !== undefined && frame.colno > MAX_CONTEXTLINES_COLNO) {
2366
+ return true;
2367
+ }
2368
+ return false;
2369
+ }
2370
+ /**
2371
+ * Checks if we have all the contents that we need in the cache.
2372
+ */
2373
+ function rangeExistsInContentCache(file, range) {
2374
+ const contents = LRU_FILE_CONTENTS_CACHE.get(file);
2375
+ if (contents === undefined) {
2376
+ return false;
2377
+ }
2378
+ for (let i = range[0]; i <= range[1]; i++) {
2379
+ if (contents[i] === undefined) {
2380
+ return false;
2381
+ }
2382
+ }
2383
+ return true;
2384
+ }
2385
+ /**
2386
+ * Creates contiguous ranges of lines to read from a file. In the case where context lines overlap,
2387
+ * the ranges are merged to create a single range.
2388
+ */
2389
+ function makeLineReaderRanges(lines) {
2390
+ if (!lines.length) {
2391
+ return [];
2392
+ }
2393
+ let i = 0;
2394
+ const line = lines[0];
2395
+ if (typeof line !== 'number') {
2396
+ return [];
2397
+ }
2398
+ let current = makeContextRange(line);
2399
+ const out = [];
2400
+ while (true) {
2401
+ if (i === lines.length - 1) {
2402
+ out.push(current);
2403
+ break;
2404
+ }
2405
+ // If the next line falls into the current range, extend the current range to lineno + linecontext.
2406
+ const next = lines[i + 1];
2407
+ if (typeof next !== 'number') {
2408
+ break;
2409
+ }
2410
+ if (next <= current[1]) {
2411
+ current[1] = next + DEFAULT_LINES_OF_CONTEXT;
2412
+ } else {
2413
+ out.push(current);
2414
+ current = makeContextRange(next);
2415
+ }
2416
+ i++;
2417
+ }
2418
+ return out;
2419
+ }
2420
+ // Determine start and end indices for context range (inclusive);
2421
+ function makeContextRange(line) {
2422
+ return [makeRangeStart(line), makeRangeEnd(line)];
2423
+ }
2424
+ // Compute inclusive end context range
2425
+ function makeRangeStart(line) {
2426
+ return Math.max(1, line - DEFAULT_LINES_OF_CONTEXT);
2427
+ }
2428
+ // Compute inclusive start context range
2429
+ function makeRangeEnd(line) {
2430
+ return line + DEFAULT_LINES_OF_CONTEXT;
2431
+ }
2432
+ /**
2433
+ * Get or init map value
2434
+ */
2435
+ function emplace(map, key, contents) {
2436
+ const value = map.get(key);
2437
+ if (value === undefined) {
2438
+ map.set(key, contents);
2439
+ return contents;
2440
+ }
2441
+ return value;
2442
+ }
2443
+ function snipLine(line, colno) {
2444
+ let newLine = line;
2445
+ const lineLength = newLine.length;
2446
+ if (lineLength <= 150) {
2447
+ return newLine;
2448
+ }
2449
+ if (colno > lineLength) {
2450
+ colno = lineLength;
2451
+ }
2452
+ let start = Math.max(colno - 60, 0);
2453
+ if (start < 5) {
2454
+ start = 0;
2455
+ }
2456
+ let end = Math.min(start + 140, lineLength);
2457
+ if (end > lineLength - 5) {
2458
+ end = lineLength;
2459
+ }
2460
+ if (end === lineLength) {
2461
+ start = Math.max(end - 140, 0);
2462
+ }
2463
+ newLine = newLine.slice(start, end);
2464
+ if (start > 0) {
2465
+ newLine = `...${newLine}`;
2466
+ }
2467
+ if (end < lineLength) {
2468
+ newLine += '...';
2469
+ }
2470
+ return newLine;
2471
+ }
2472
+
2473
+ /**
2474
+ * based on the very wonderful MIT licensed Sentry SDK
2475
+ */
2476
+ async function propertiesFromUnknownInput(stackParser, input, hint) {
2477
+ const providedMechanism = hint && hint.mechanism;
2478
+ const mechanism = providedMechanism || {
2479
+ handled: true,
2480
+ type: 'generic'
2481
+ };
2482
+ const error = getError(mechanism, input, hint);
2483
+ const exception = await exceptionFromError(stackParser, error);
2484
+ exception.value = exception.value || '';
2485
+ exception.type = exception.type || 'Error';
2486
+ exception.mechanism = mechanism;
2487
+ const properties = {
2488
+ $exception_list: [exception]
2489
+ };
2490
+ return properties;
2491
+ }
2492
+ function getError(mechanism, exception, hint) {
2493
+ if (isError(exception)) {
2494
+ return exception;
2495
+ }
2496
+ mechanism.synthetic = true;
2497
+ if (isPlainObject(exception)) {
2498
+ const errorFromProp = getErrorPropertyFromObject(exception);
2499
+ if (errorFromProp) {
2500
+ return errorFromProp;
2501
+ }
2502
+ const message = getMessageForObject(exception);
2503
+ const ex = hint?.syntheticException || new Error(message);
2504
+ ex.message = message;
2505
+ return ex;
2506
+ }
2507
+ // This handles when someone does: `throw "something awesome";`
2508
+ // We use synthesized Error here so we can extract a (rough) stack trace.
2509
+ const ex = hint?.syntheticException || new Error(exception);
2510
+ ex.message = `${exception}`;
2511
+ return ex;
2512
+ }
2513
+ /** If a plain object has a property that is an `Error`, return this error. */
2514
+ function getErrorPropertyFromObject(obj) {
2515
+ for (const prop in obj) {
2516
+ if (Object.prototype.hasOwnProperty.call(obj, prop)) {
2517
+ const value = obj[prop];
2518
+ if (value instanceof Error) {
2519
+ return value;
2520
+ }
2521
+ }
2522
+ }
2523
+ return undefined;
2524
+ }
2525
+ function getMessageForObject(exception) {
2526
+ if ('name' in exception && typeof exception.name === 'string') {
2527
+ let message = `'${exception.name}' captured as exception`;
2528
+ if ('message' in exception && typeof exception.message === 'string') {
2529
+ message += ` with message '${exception.message}'`;
2530
+ }
2531
+ return message;
2532
+ } else if ('message' in exception && typeof exception.message === 'string') {
2533
+ return exception.message;
2534
+ }
2535
+ const keys = extractExceptionKeysForMessage(exception);
2536
+ // Some ErrorEvent instances do not have an `error` property, which is why they are not handled before
2537
+ // We still want to try to get a decent message for these cases
2538
+ if (isErrorEvent(exception)) {
2539
+ return `Event \`ErrorEvent\` captured as exception with message \`${exception.message}\``;
2540
+ }
2541
+ const className = getObjectClassName(exception);
2542
+ return `${className && className !== 'Object' ? `'${className}'` : 'Object'} captured as exception with keys: ${keys}`;
2543
+ }
2544
+ function getObjectClassName(obj) {
2545
+ try {
2546
+ const prototype = Object.getPrototypeOf(obj);
2547
+ return prototype ? prototype.constructor.name : undefined;
2548
+ } catch (e) {
2549
+ // ignore errors here
2550
+ }
2551
+ }
2552
+ /**
2553
+ * Given any captured exception, extract its keys and create a sorted
2554
+ * and truncated list that will be used inside the event message.
2555
+ * eg. `Non-error exception captured with keys: foo, bar, baz`
2556
+ */
2557
+ function extractExceptionKeysForMessage(exception, maxLength = 40) {
2558
+ const keys = Object.keys(convertToPlainObject(exception));
2559
+ keys.sort();
2560
+ const firstKey = keys[0];
2561
+ if (!firstKey) {
2562
+ return '[object has no keys]';
2563
+ }
2564
+ if (firstKey.length >= maxLength) {
2565
+ return truncate(firstKey, maxLength);
2566
+ }
2567
+ for (let includedKeys = keys.length; includedKeys > 0; includedKeys--) {
2568
+ const serialized = keys.slice(0, includedKeys).join(', ');
2569
+ if (serialized.length > maxLength) {
2570
+ continue;
2571
+ }
2572
+ if (includedKeys === keys.length) {
2573
+ return serialized;
2574
+ }
2575
+ return truncate(serialized, maxLength);
2576
+ }
2577
+ return '';
2578
+ }
2579
+ function truncate(str, max = 0) {
2580
+ if (typeof str !== 'string' || max === 0) {
2581
+ return str;
2582
+ }
2583
+ return str.length <= max ? str : `${str.slice(0, max)}...`;
2584
+ }
2585
+ /**
2586
+ * Transforms any `Error` or `Event` into a plain object with all of their enumerable properties, and some of their
2587
+ * non-enumerable properties attached.
2588
+ *
2589
+ * @param value Initial source that we have to transform in order for it to be usable by the serializer
2590
+ * @returns An Event or Error turned into an object - or the value argument itself, when value is neither an Event nor
2591
+ * an Error.
2592
+ */
2593
+ function convertToPlainObject(value) {
2594
+ if (isError(value)) {
2595
+ return {
2596
+ message: value.message,
2597
+ name: value.name,
2598
+ stack: value.stack,
2599
+ ...getOwnProperties(value)
2600
+ };
2601
+ } else if (isEvent(value)) {
2602
+ const newObj = {
2603
+ type: value.type,
2604
+ target: serializeEventTarget(value.target),
2605
+ currentTarget: serializeEventTarget(value.currentTarget),
2606
+ ...getOwnProperties(value)
2607
+ };
2608
+ // TODO: figure out why this fails typing (I think CustomEvent is only supported in Node 19 onwards)
2609
+ // if (typeof CustomEvent !== 'undefined' && isInstanceOf(value, CustomEvent)) {
2610
+ // newObj.detail = (value as unknown as CustomEvent).detail
2611
+ // }
2612
+ return newObj;
2613
+ } else {
2614
+ return value;
2615
+ }
2616
+ }
2617
+ /** Filters out all but an object's own properties */
2618
+ function getOwnProperties(obj) {
2619
+ if (typeof obj === 'object' && obj !== null) {
2620
+ const extractedProps = {};
2621
+ for (const property in obj) {
2622
+ if (Object.prototype.hasOwnProperty.call(obj, property)) {
2623
+ extractedProps[property] = obj[property];
2624
+ }
2625
+ }
2626
+ return extractedProps;
2627
+ } else {
2628
+ return {};
2629
+ }
2630
+ }
2631
+ /** Creates a string representation of the target of an `Event` object */
2632
+ function serializeEventTarget(target) {
2633
+ try {
2634
+ return Object.prototype.toString.call(target);
2635
+ } catch (_oO) {
2636
+ return '<unknown>';
2637
+ }
2638
+ }
2639
+ /**
2640
+ * Extracts stack frames from the error and builds an Exception
2641
+ */
2642
+ async function exceptionFromError(stackParser, error) {
2643
+ const exception = {
2644
+ type: error.name || error.constructor.name,
2645
+ value: error.message
2646
+ };
2647
+ const frames = await addSourceContext(parseStackFrames(stackParser, error));
2648
+ if (frames.length) {
2649
+ exception.stacktrace = {
2650
+ frames,
2651
+ type: 'raw'
2652
+ };
2653
+ }
2654
+ return exception;
2655
+ }
2656
+ /**
2657
+ * Extracts stack frames from the error.stack string
2658
+ */
2659
+ function parseStackFrames(stackParser, error) {
2660
+ return stackParser(error.stack || '', 1);
2661
+ }
2662
+
2663
+ // copied and adapted from https://github.com/getsentry/sentry-javascript/blob/41fef4b10f3a644179b77985f00f8696c908539f/packages/browser/src/stack-parsers.ts
2664
+ // This was originally forked from https://github.com/csnover/TraceKit, and was largely
2665
+ // re-written as part of raven - js.
2666
+ //
2667
+ // This code was later copied to the JavaScript mono - repo and further modified and
2668
+ // refactored over the years.
2669
+ // Copyright (c) 2013 Onur Can Cakmak onur.cakmak@gmail.com and all TraceKit contributors.
2670
+ //
2671
+ // Permission is hereby granted, free of charge, to any person obtaining a copy of this
2672
+ // software and associated documentation files(the 'Software'), to deal in the Software
2673
+ // without restriction, including without limitation the rights to use, copy, modify,
2674
+ // merge, publish, distribute, sublicense, and / or sell copies of the Software, and to
2675
+ // permit persons to whom the Software is furnished to do so, subject to the following
2676
+ // conditions:
2677
+ //
2678
+ // The above copyright notice and this permission notice shall be included in all copies
2679
+ // or substantial portions of the Software.
2680
+ //
2681
+ // THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
2682
+ // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
2683
+ // PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
2684
+ // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
2685
+ // CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
2686
+ // OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
2687
+ const WEBPACK_ERROR_REGEXP = /\(error: (.*)\)/;
2688
+ const STACKTRACE_FRAME_LIMIT = 50;
2689
+ const UNKNOWN_FUNCTION = '?';
2690
+ /** Node Stack line parser */
2691
+ function node(getModule) {
2692
+ const FILENAME_MATCH = /^\s*[-]{4,}$/;
2693
+ const FULL_MATCH = /at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/;
2694
+ return line => {
2695
+ const lineMatch = line.match(FULL_MATCH);
2696
+ if (lineMatch) {
2697
+ let object;
2698
+ let method;
2699
+ let functionName;
2700
+ let typeName;
2701
+ let methodName;
2702
+ if (lineMatch[1]) {
2703
+ functionName = lineMatch[1];
2704
+ let methodStart = functionName.lastIndexOf('.');
2705
+ if (functionName[methodStart - 1] === '.') {
2706
+ methodStart--;
2707
+ }
2708
+ if (methodStart > 0) {
2709
+ object = functionName.slice(0, methodStart);
2710
+ method = functionName.slice(methodStart + 1);
2711
+ const objectEnd = object.indexOf('.Module');
2712
+ if (objectEnd > 0) {
2713
+ functionName = functionName.slice(objectEnd + 1);
2714
+ object = object.slice(0, objectEnd);
2715
+ }
2716
+ }
2717
+ typeName = undefined;
2718
+ }
2719
+ if (method) {
2720
+ typeName = object;
2721
+ methodName = method;
2722
+ }
2723
+ if (method === '<anonymous>') {
2724
+ methodName = undefined;
2725
+ functionName = undefined;
2726
+ }
2727
+ if (functionName === undefined) {
2728
+ methodName = methodName || UNKNOWN_FUNCTION;
2729
+ functionName = typeName ? `${typeName}.${methodName}` : methodName;
2730
+ }
2731
+ let filename = lineMatch[2]?.startsWith('file://') ? lineMatch[2].slice(7) : lineMatch[2];
2732
+ const isNative = lineMatch[5] === 'native';
2733
+ // If it's a Windows path, trim the leading slash so that `/C:/foo` becomes `C:/foo`
2734
+ if (filename?.match(/\/[A-Z]:/)) {
2735
+ filename = filename.slice(1);
2736
+ }
2737
+ if (!filename && lineMatch[5] && !isNative) {
2738
+ filename = lineMatch[5];
2739
+ }
2740
+ return {
2741
+ filename: filename ? decodeURI(filename) : undefined,
2742
+ module: getModule ? getModule(filename) : undefined,
2743
+ function: functionName,
2744
+ lineno: _parseIntOrUndefined(lineMatch[3]),
2745
+ colno: _parseIntOrUndefined(lineMatch[4]),
2746
+ in_app: filenameIsInApp(filename || '', isNative),
2747
+ platform: 'node:javascript'
2748
+ };
2749
+ }
2750
+ if (line.match(FILENAME_MATCH)) {
2751
+ return {
2752
+ filename: line,
2753
+ platform: 'node:javascript'
2754
+ };
2755
+ }
2756
+ return undefined;
2757
+ };
2758
+ }
2759
+ /**
2760
+ * Does this filename look like it's part of the app code?
2761
+ */
2762
+ function filenameIsInApp(filename, isNative = false) {
2763
+ const isInternal = isNative || filename &&
2764
+ // It's not internal if it's an absolute linux path
2765
+ !filename.startsWith('/') &&
2766
+ // It's not internal if it's an absolute windows path
2767
+ !filename.match(/^[A-Z]:/) &&
2768
+ // It's not internal if the path is starting with a dot
2769
+ !filename.startsWith('.') &&
2770
+ // It's not internal if the frame has a protocol. In node, this is usually the case if the file got pre-processed with a bundler like webpack
2771
+ !filename.match(/^[a-zA-Z]([a-zA-Z0-9.\-+])*:\/\//); // Schema from: https://stackoverflow.com/a/3641782
2772
+ // in_app is all that's not an internal Node function or a module within node_modules
2773
+ // note that isNative appears to return true even for node core libraries
2774
+ // see https://github.com/getsentry/raven-node/issues/176
2775
+ return !isInternal && filename !== undefined && !filename.includes('node_modules/');
2776
+ }
2777
+ function _parseIntOrUndefined(input) {
2778
+ return parseInt(input || '', 10) || undefined;
2779
+ }
2780
+ function nodeStackLineParser(getModule) {
2781
+ return [90, node(getModule)];
2782
+ }
2783
+ const defaultStackParser = createStackParser(nodeStackLineParser(createGetModuleFromFilename()));
2784
+ /** Creates a function that gets the module name from a filename */
2785
+ function createGetModuleFromFilename(basePath = process.argv[1] ? dirname(process.argv[1]) : process.cwd(), isWindows = sep === '\\') {
2786
+ const normalizedBase = isWindows ? normalizeWindowsPath(basePath) : basePath;
2787
+ return filename => {
2788
+ if (!filename) {
2789
+ return;
2790
+ }
2791
+ const normalizedFilename = isWindows ? normalizeWindowsPath(filename) : filename;
2792
+ // eslint-disable-next-line prefer-const
2793
+ let {
2794
+ dir,
2795
+ base: file,
2796
+ ext
2797
+ } = posix.parse(normalizedFilename);
2798
+ if (ext === '.js' || ext === '.mjs' || ext === '.cjs') {
2799
+ file = file.slice(0, ext.length * -1);
2800
+ }
2801
+ // The file name might be URI-encoded which we want to decode to
2802
+ // the original file name.
2803
+ const decodedFile = decodeURIComponent(file);
2804
+ if (!dir) {
2805
+ // No dirname whatsoever
2806
+ dir = '.';
2807
+ }
2808
+ const n = dir.lastIndexOf('/node_modules');
2809
+ if (n > -1) {
2810
+ return `${dir.slice(n + 14).replace(/\//g, '.')}:${decodedFile}`;
2811
+ }
2812
+ // Let's see if it's a part of the main module
2813
+ // To be a part of main module, it has to share the same base
2814
+ if (dir.startsWith(normalizedBase)) {
2815
+ const moduleName = dir.slice(normalizedBase.length + 1).replace(/\//g, '.');
2816
+ return moduleName ? `${moduleName}:${decodedFile}` : decodedFile;
2817
+ }
2818
+ return decodedFile;
2819
+ };
2820
+ }
2821
+ /** normalizes Windows paths */
2822
+ function normalizeWindowsPath(path) {
2823
+ return path.replace(/^[A-Z]:/, '') // remove Windows-style prefix
2824
+ .replace(/\\/g, '/'); // replace all `\` instances with `/`
2825
+ }
2826
+ function createStackParser(...parsers) {
2827
+ const sortedParsers = parsers.sort((a, b) => a[0] - b[0]).map(p => p[1]);
2828
+ return (stack, skipFirstLines = 0) => {
2829
+ const frames = [];
2830
+ const lines = stack.split('\n');
2831
+ for (let i = skipFirstLines; i < lines.length; i++) {
2832
+ const line = lines[i];
2833
+ // Ignore lines over 1kb as they are unlikely to be stack frames.
2834
+ if (line.length > 1024) {
2835
+ continue;
2836
+ }
2837
+ // https://github.com/getsentry/sentry-javascript/issues/5459
2838
+ // Remove webpack (error: *) wrappers
2839
+ const cleanedLine = WEBPACK_ERROR_REGEXP.test(line) ? line.replace(WEBPACK_ERROR_REGEXP, '$1') : line;
2840
+ // https://github.com/getsentry/sentry-javascript/issues/7813
2841
+ // Skip Error: lines
2842
+ if (cleanedLine.match(/\S*Error: /)) {
2843
+ continue;
2844
+ }
2845
+ for (const parser of sortedParsers) {
2846
+ const frame = parser(cleanedLine);
2847
+ if (frame) {
2848
+ frames.push(frame);
2849
+ break;
2850
+ }
2851
+ }
2852
+ if (frames.length >= STACKTRACE_FRAME_LIMIT) {
2853
+ break;
2854
+ }
2855
+ }
2856
+ return reverseAndStripFrames(frames);
2857
+ };
2858
+ }
2859
+ function reverseAndStripFrames(stack) {
2860
+ if (!stack.length) {
2861
+ return [];
2862
+ }
2863
+ const localStack = Array.from(stack);
2864
+ localStack.reverse();
2865
+ return localStack.slice(0, STACKTRACE_FRAME_LIMIT).map(frame => ({
2866
+ ...frame,
2867
+ filename: frame.filename || getLastStackFrame(localStack).filename,
2868
+ function: frame.function || UNKNOWN_FUNCTION
2869
+ }));
2870
+ }
2871
+ function getLastStackFrame(arr) {
2872
+ return arr[arr.length - 1] || {};
2873
+ }
2874
+
2875
+ const SHUTDOWN_TIMEOUT = 2000;
2876
+ class ErrorTracking {
2877
+ static async captureException(client, error, distinctId, hint, additionalProperties) {
2878
+ const properties = {
2879
+ ...additionalProperties
2880
+ };
2881
+ if (!distinctId) {
2882
+ properties.$process_person_profile = false;
2883
+ }
2884
+ const exceptionProperties = await propertiesFromUnknownInput(defaultStackParser, error, hint);
2885
+ client.capture({
2886
+ event: '$exception',
2887
+ distinctId: distinctId || uuidv7(),
2888
+ properties: {
2889
+ ...exceptionProperties,
2890
+ ...properties
2891
+ }
2892
+ });
2893
+ }
2894
+ constructor(client, options) {
2895
+ this.client = client;
2896
+ this._exceptionAutocaptureEnabled = options.enableExceptionAutocapture || false;
2897
+ this.startAutocaptureIfEnabled();
2898
+ }
2899
+ startAutocaptureIfEnabled() {
2900
+ if (this.isEnabled()) {
2901
+ addUncaughtExceptionListener(this.onException.bind(this), this.onFatalError.bind(this));
2902
+ addUnhandledRejectionListener(this.onException.bind(this));
2903
+ }
2904
+ }
2905
+ onException(exception, hint) {
2906
+ // Given stateless nature of Node SDK we capture exceptions using personless processing
2907
+ // when no user can be determined e.g. in the case of exception autocapture
2908
+ ErrorTracking.captureException(this.client, exception, uuidv7(), hint, {
2909
+ $process_person_profile: false
2910
+ });
2911
+ }
2912
+ async onFatalError() {
2913
+ await this.client.shutdown(SHUTDOWN_TIMEOUT);
2914
+ }
2915
+ isEnabled() {
2916
+ return !this.client.isDisabled && this._exceptionAutocaptureEnabled;
2917
+ }
2918
+ }
2919
+
2039
2920
  const THIRTY_SECONDS = 30 * 1000;
2040
2921
  const MAX_CACHE_SIZE = 50 * 1000;
2041
2922
  // The actual exported Nodejs API.
@@ -2058,6 +2939,7 @@ class PostHog extends PostHogCoreStateless {
2058
2939
  customHeaders: this.getCustomHeaders()
2059
2940
  });
2060
2941
  }
2942
+ this.errorTracking = new ErrorTracking(this, options);
2061
2943
  this.distinctIdHasSentFlagCalls = {};
2062
2944
  this.maxCacheSize = options.maxCacheSize || MAX_CACHE_SIZE;
2063
2945
  }
@@ -2361,6 +3243,12 @@ class PostHog extends PostHogCoreStateless {
2361
3243
  allGroupProperties
2362
3244
  };
2363
3245
  }
3246
+ captureException(error, distinctId, additionalProperties) {
3247
+ const syntheticException = new Error('PostHog syntheticException');
3248
+ ErrorTracking.captureException(this, error, distinctId, {
3249
+ syntheticException
3250
+ }, additionalProperties);
3251
+ }
2364
3252
  }
2365
3253
 
2366
3254
  /**
@@ -2386,7 +3274,6 @@ class PostHog extends PostHogCoreStateless {
2386
3274
  * @param {string} [prefix] Optional: Url of a self-hosted sentry instance (default: https://sentry.io/organizations/)
2387
3275
  * @param {SeverityLevel[] | '*'} [severityAllowList] Optional: send events matching the provided levels. Use '*' to send all events (default: ['error'])
2388
3276
  */
2389
- const severityLevels = ['fatal', 'error', 'warning', 'log', 'info', 'debug'];
2390
3277
  const NAME = 'posthog-node';
2391
3278
  function createEventProcessor(_posthog, {
2392
3279
  organization,
@@ -2471,5 +3358,22 @@ class PostHogSentryIntegration {
2471
3358
  }
2472
3359
  PostHogSentryIntegration.POSTHOG_ID_TAG = 'posthog_distinct_id';
2473
3360
 
2474
- export { PostHog, PostHogSentryIntegration, createEventProcessor, sentryIntegration, severityLevels };
3361
+ function setupExpressErrorHandler(_posthog, app) {
3362
+ app.use((error, _, __, next) => {
3363
+ const hint = {
3364
+ mechanism: {
3365
+ type: 'middleware',
3366
+ handled: false
3367
+ }
3368
+ };
3369
+ // Given stateless nature of Node SDK we capture exceptions using personless processing
3370
+ // when no user can be determined e.g. in the case of exception autocapture
3371
+ ErrorTracking.captureException(_posthog, error, uuidv7(), hint, {
3372
+ $process_person_profile: false
3373
+ });
3374
+ next(error);
3375
+ });
3376
+ }
3377
+
3378
+ export { PostHog, PostHogSentryIntegration, createEventProcessor, sentryIntegration, setupExpressErrorHandler };
2475
3379
  //# sourceMappingURL=index.esm.js.map