@posthog/core 1.64.1 → 1.66.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.
@@ -8,6 +8,7 @@ export declare class PostHogLogs {
8
8
  private readonly _onReady;
9
9
  private readonly _waitForStoragePersist;
10
10
  private readonly _scopeName?;
11
+ private readonly _isConsentWithdrawn;
11
12
  private _maxBufferSize;
12
13
  private _maxQueueSize;
13
14
  private _flushIntervalMs;
@@ -16,6 +17,7 @@ export declare class PostHogLogs {
16
17
  private _flushPromise;
17
18
  private _evictedSinceAdvance;
18
19
  private _queueGeneration;
20
+ private _backgroundFlushPromise;
19
21
  private _retryAfter;
20
22
  private _consecutiveFlushFailures;
21
23
  private _flushJitter;
@@ -24,13 +26,15 @@ export declare class PostHogLogs {
24
26
  private _intervalWindowStart;
25
27
  private _intervalLogCount;
26
28
  private _droppedWarned;
27
- constructor(_instance: LogsHost, _config: ResolvedPostHogLogsConfig, _logger: Logger, _getContext: () => LogSdkContext, _onReady: (fn: () => void) => void, _waitForStoragePersist?: () => Promise<void>, _scopeName?: string | undefined);
29
+ constructor(_instance: LogsHost, _config: ResolvedPostHogLogsConfig, _logger: Logger, _getContext: () => LogSdkContext, _onReady: (fn: () => void) => void, _waitForStoragePersist?: () => Promise<void>, _scopeName?: string | undefined, _isConsentWithdrawn?: () => boolean);
28
30
  /**
29
31
  * Drops every queued record. A batch this instance has in flight is retired with
30
32
  * them, so it can neither re-send what was just purged nor advance past records
31
33
  * captured after this call.
32
34
  */
33
35
  clearQueue(): void;
36
+ /** True while the endpoint's `Retry-After` window is open, so a host's automatic flush can skip logs. */
37
+ get throttled(): boolean;
34
38
  /**
35
39
  * Clears the flush timer and rate-cap state. The host owns the record queue
36
40
  * and clears it separately (the browser empties its in-memory store).
@@ -88,6 +92,12 @@ export declare class PostHogLogs {
88
92
  */
89
93
  flush(): Promise<void>;
90
94
  private _flushInner;
95
+ /**
96
+ * Drops the queue once consent is withdrawn. Records carry the distinct id and
97
+ * session id, so whatever is still queued when the user opts out must not be
98
+ * exported, by a pending timer or by a drain already under way.
99
+ */
100
+ private _discardQueueIfConsentWithdrawn;
91
101
  private _persistQueueAdvance;
92
102
  private _buildResourceAttributes;
93
103
  private _enqueue;
@@ -118,6 +128,13 @@ export declare class PostHogLogs {
118
128
  * unhandled-rejection logs — the next regular flush cycle will retry.
119
129
  */
120
130
  flushWithTimeout(timeoutMs: number): Promise<void>;
131
+ /**
132
+ * `flush()` for a host that drives logs from its own flush cycle. Never rejects, and when
133
+ * records remain (a failed send, or captures that landed mid-flush) re-arms the timer with
134
+ * backoff, as the pipeline's own timer flush does. A bare `flush()` clears the timer and
135
+ * leaves nothing to retry the records once traffic stops.
136
+ */
137
+ flushInBackground(): Promise<void>;
121
138
  private _flushInBackground;
122
139
  }
123
140
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/logs/index.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,MAAM,EAA4B,MAAM,UAAU,CAAA;AAK3D,OAAO,KAAK,EAAoB,iBAAiB,EAAE,aAAa,EAAE,QAAQ,EAAE,yBAAyB,EAAE,MAAM,SAAS,CAAA;AAItH,qBAAa,WAAW;IAsCpB,OAAO,CAAC,QAAQ,CAAC,SAAS;IAC1B,OAAO,CAAC,QAAQ,CAAC,OAAO;IACxB,OAAO,CAAC,QAAQ,CAAC,OAAO;IACxB,OAAO,CAAC,QAAQ,CAAC,WAAW;IAC5B,OAAO,CAAC,QAAQ,CAAC,QAAQ;IAMzB,OAAO,CAAC,QAAQ,CAAC,sBAAsB;IAIvC,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAC;IAnD9B,OAAO,CAAC,cAAc,CAAQ;IAG9B,OAAO,CAAC,aAAa,CAAQ;IAC7B,OAAO,CAAC,gBAAgB,CAAQ;IAIhC,OAAO,CAAC,uBAAuB,CAAQ;IACvC,OAAO,CAAC,QAAQ,CAAC,W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,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAYhD;IAED;;;;;;;;;;;OAWG;IACG,gBAAgB,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAOvD;IAED;;;;;OAKG;IACH,iBAAiB,IAAI,OAAO,CAAC,IAAI,CAAC,CA6BjC;IAED,OAAO,CAAC,kBAAkB;CAG3B"}
@@ -37,7 +37,7 @@ const flush_timer_js_namespaceObject = require("../utils/flush-timer.js");
37
37
  const retry_after_js_namespaceObject = require("../utils/retry-after.js");
38
38
  const backoff_js_namespaceObject = require("../utils/backoff.js");
39
39
  class PostHogLogs {
40
- constructor(_instance, _config, _logger, _getContext, _onReady, _waitForStoragePersist = ()=>Promise.resolve(), _scopeName){
40
+ constructor(_instance, _config, _logger, _getContext, _onReady, _waitForStoragePersist = ()=>Promise.resolve(), _scopeName, _isConsentWithdrawn = ()=>false){
41
41
  this._instance = _instance;
42
42
  this._config = _config;
43
43
  this._logger = _logger;
@@ -45,10 +45,12 @@ class PostHogLogs {
45
45
  this._onReady = _onReady;
46
46
  this._waitForStoragePersist = _waitForStoragePersist;
47
47
  this._scopeName = _scopeName;
48
+ this._isConsentWithdrawn = _isConsentWithdrawn;
48
49
  this._flushTimer = new flush_timer_js_namespaceObject.FlushTimer(()=>this._flushInBackground());
49
50
  this._flushPromise = null;
50
51
  this._evictedSinceAdvance = 0;
51
52
  this._queueGeneration = 0;
53
+ this._backgroundFlushPromise = null;
52
54
  this._retryAfter = new retry_after_js_namespaceObject.RetryAfterWindow();
53
55
  this._consecutiveFlushFailures = 0;
54
56
  this._flushJitter = backoff_js_namespaceObject.NO_JITTER;
@@ -66,6 +68,9 @@ class PostHogLogs {
66
68
  this._queueGeneration++;
67
69
  this._instance.setPersistedProperty(external_types_js_namespaceObject.PostHogPersistedProperty.LogsQueue, []);
68
70
  }
71
+ get throttled() {
72
+ return this._retryAfter.isOpen();
73
+ }
69
74
  reset() {
70
75
  this._flushTimer.clear();
71
76
  this._intervalWindowStart = 0;
@@ -148,11 +153,13 @@ class PostHogLogs {
148
153
  }
149
154
  async _flushInner() {
150
155
  this._flushTimer.clear();
156
+ if (this._discardQueueIfConsentWithdrawn()) return;
151
157
  let queue = this._instance.getPersistedProperty(external_types_js_namespaceObject.PostHogPersistedProperty.LogsQueue) ?? [];
152
158
  if (0 === queue.length) return;
153
159
  const originalQueueLength = queue.length;
154
160
  let sentCount = 0;
155
161
  while(queue.length > 0 && sentCount < originalQueueLength){
162
+ if (this._discardQueueIfConsentWithdrawn()) return;
156
163
  const generation = this._queueGeneration;
157
164
  this._evictedSinceAdvance = 0;
158
165
  const batchSize = Math.min(queue.length, this._maxBatchRecordsPerPost);
@@ -177,6 +184,11 @@ class PostHogLogs {
177
184
  if ('fatal' === outcome.kind) throw outcome.error;
178
185
  }
179
186
  }
187
+ _discardQueueIfConsentWithdrawn() {
188
+ if (!this._isConsentWithdrawn()) return false;
189
+ if (this._hasQueuedRecords()) this.clearQueue();
190
+ return true;
191
+ }
180
192
  async _persistQueueAdvance(consumed) {
181
193
  const evicted = this._evictedSinceAdvance;
182
194
  const drop = Math.max(0, consumed - evicted);
@@ -223,8 +235,9 @@ class PostHogLogs {
223
235
  flushPromise.catch(()=>{});
224
236
  });
225
237
  }
226
- _flushInBackground() {
227
- this.flush().then(()=>{
238
+ flushInBackground() {
239
+ if (this._backgroundFlushPromise) return this._backgroundFlushPromise;
240
+ const promise = this.flush().then(()=>{
228
241
  this._consecutiveFlushFailures = 0;
229
242
  this._flushJitter = backoff_js_namespaceObject.NO_JITTER;
230
243
  }, (err)=>{
@@ -232,8 +245,14 @@ class PostHogLogs {
232
245
  this._flushJitter = (0, backoff_js_namespaceObject.drawJitter)();
233
246
  this._logger.error('PostHog logs flush failed:', err);
234
247
  }).finally(()=>{
248
+ if (this._backgroundFlushPromise === promise) this._backgroundFlushPromise = null;
235
249
  if (!this._instance.isDisabled && this._hasQueuedRecords()) this._flushTimer.armNoEarlierThan(this._nextFlushDelay());
236
250
  });
251
+ this._backgroundFlushPromise = promise;
252
+ return promise;
253
+ }
254
+ _flushInBackground() {
255
+ this.flushInBackground();
237
256
  }
238
257
  }
239
258
  exports.PostHogLogs = __webpack_exports__.PostHogLogs;
@@ -5,7 +5,7 @@ import { FlushTimer } from "../utils/flush-timer.mjs";
5
5
  import { RetryAfterWindow } from "../utils/retry-after.mjs";
6
6
  import { MAX_FLUSH_BACKOFF_MS, NO_JITTER, backoffDelayMs, drawJitter } from "../utils/backoff.mjs";
7
7
  class PostHogLogs {
8
- constructor(_instance, _config, _logger, _getContext, _onReady, _waitForStoragePersist = ()=>Promise.resolve(), _scopeName){
8
+ constructor(_instance, _config, _logger, _getContext, _onReady, _waitForStoragePersist = ()=>Promise.resolve(), _scopeName, _isConsentWithdrawn = ()=>false){
9
9
  this._instance = _instance;
10
10
  this._config = _config;
11
11
  this._logger = _logger;
@@ -13,10 +13,12 @@ class PostHogLogs {
13
13
  this._onReady = _onReady;
14
14
  this._waitForStoragePersist = _waitForStoragePersist;
15
15
  this._scopeName = _scopeName;
16
+ this._isConsentWithdrawn = _isConsentWithdrawn;
16
17
  this._flushTimer = new FlushTimer(()=>this._flushInBackground());
17
18
  this._flushPromise = null;
18
19
  this._evictedSinceAdvance = 0;
19
20
  this._queueGeneration = 0;
21
+ this._backgroundFlushPromise = null;
20
22
  this._retryAfter = new RetryAfterWindow();
21
23
  this._consecutiveFlushFailures = 0;
22
24
  this._flushJitter = NO_JITTER;
@@ -34,6 +36,9 @@ class PostHogLogs {
34
36
  this._queueGeneration++;
35
37
  this._instance.setPersistedProperty(PostHogPersistedProperty.LogsQueue, []);
36
38
  }
39
+ get throttled() {
40
+ return this._retryAfter.isOpen();
41
+ }
37
42
  reset() {
38
43
  this._flushTimer.clear();
39
44
  this._intervalWindowStart = 0;
@@ -116,11 +121,13 @@ class PostHogLogs {
116
121
  }
117
122
  async _flushInner() {
118
123
  this._flushTimer.clear();
124
+ if (this._discardQueueIfConsentWithdrawn()) return;
119
125
  let queue = this._instance.getPersistedProperty(PostHogPersistedProperty.LogsQueue) ?? [];
120
126
  if (0 === queue.length) return;
121
127
  const originalQueueLength = queue.length;
122
128
  let sentCount = 0;
123
129
  while(queue.length > 0 && sentCount < originalQueueLength){
130
+ if (this._discardQueueIfConsentWithdrawn()) return;
124
131
  const generation = this._queueGeneration;
125
132
  this._evictedSinceAdvance = 0;
126
133
  const batchSize = Math.min(queue.length, this._maxBatchRecordsPerPost);
@@ -145,6 +152,11 @@ class PostHogLogs {
145
152
  if ('fatal' === outcome.kind) throw outcome.error;
146
153
  }
147
154
  }
155
+ _discardQueueIfConsentWithdrawn() {
156
+ if (!this._isConsentWithdrawn()) return false;
157
+ if (this._hasQueuedRecords()) this.clearQueue();
158
+ return true;
159
+ }
148
160
  async _persistQueueAdvance(consumed) {
149
161
  const evicted = this._evictedSinceAdvance;
150
162
  const drop = Math.max(0, consumed - evicted);
@@ -191,8 +203,9 @@ class PostHogLogs {
191
203
  flushPromise.catch(()=>{});
192
204
  });
193
205
  }
194
- _flushInBackground() {
195
- this.flush().then(()=>{
206
+ flushInBackground() {
207
+ if (this._backgroundFlushPromise) return this._backgroundFlushPromise;
208
+ const promise = this.flush().then(()=>{
196
209
  this._consecutiveFlushFailures = 0;
197
210
  this._flushJitter = NO_JITTER;
198
211
  }, (err)=>{
@@ -200,8 +213,14 @@ class PostHogLogs {
200
213
  this._flushJitter = drawJitter();
201
214
  this._logger.error('PostHog logs flush failed:', err);
202
215
  }).finally(()=>{
216
+ if (this._backgroundFlushPromise === promise) this._backgroundFlushPromise = null;
203
217
  if (!this._instance.isDisabled && this._hasQueuedRecords()) this._flushTimer.armNoEarlierThan(this._nextFlushDelay());
204
218
  });
219
+ this._backgroundFlushPromise = promise;
220
+ return promise;
221
+ }
222
+ _flushInBackground() {
223
+ this.flushInBackground();
205
224
  }
206
225
  }
207
226
  export { PostHogLogs };
package/dist/privacy.d.ts CHANGED
@@ -2,6 +2,8 @@ export interface TextSanitizationOptions {
2
2
  maxStringLength: number;
3
3
  truncationSuffix: string;
4
4
  }
5
+ /** Whether a key names a credential, so its value is captured as `[redacted]` whatever it holds. */
6
+ export declare function shouldRedactKey(key: string): boolean;
5
7
  /**
6
8
  * Sanitizes agent-narrated free text (`$mcp_intent`, the `send_feedback`
7
9
  * fields): structured PII on top of the passes every captured string gets.
@@ -29,7 +31,10 @@ export declare function sanitizeCapturedValue(value: unknown, options: TextSanit
29
31
  /**
30
32
  * {@link sanitizeCapturedValue} with the intent-grade string pass
31
33
  * ({@link sanitizeFreeText}) on every string leaf, so nested agent-narrated
32
- * values get structured-PII redaction in the load-bearing order too.
34
+ * values get structured-PII redaction in the load-bearing order too. Keys and
35
+ * numbers are read as free text as well, since a value sent as JSON text carries
36
+ * them: a number that holds an identifier becomes `[redacted]`, so the text
37
+ * stays valid JSON.
33
38
  */
34
39
  export declare function sanitizeFreeTextValue(value: unknown, options: TextSanitizationOptions): unknown;
35
40
  //# sourceMappingURL=privacy.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"privacy.d.ts","sourceRoot":"","sources":["../src/privacy.ts"],"names":[],"mappings":"AAKA,MAAM,WAAW,uBAAuB;IACtC,eAAe,EAAE,MAAM,CAAA;IACvB,gBAAgB,EAAE,MAAM,CAAA;CACzB;AA2iBD;;;;;;;;;;;GAWG;AACH,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,uBAAuB,GAAG,MAAM,CAKxF;AA6DD;;;;;;;;GAQG;AACH,wBAAgB,SAAS,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAU/C;AAED,wBAAgB,qBAAqB,CAAC,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,uBAAuB,GAAG,OAAO,CAE/F;AAED;;;;GAIG;AACH,wBAAgB,qBAAqB,CAAC,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,uBAAuB,GAAG,OAAO,CAE/F"}
1
+ {"version":3,"file":"privacy.d.ts","sourceRoot":"","sources":["../src/privacy.ts"],"names":[],"mappings":"AAKA,MAAM,WAAW,uBAAuB;IACtC,eAAe,EAAE,MAAM,CAAA;IACvB,gBAAgB,EAAE,MAAM,CAAA;CACzB;AAsHD,oGAAoG;AACpG,wBAAgB,eAAe,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAEpD;AAgbD;;;;;;;;;;;GAWG;AACH,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,uBAAuB,GAAG,MAAM,CAKxF;AA6HD;;;;;;;;GAQG;AACH,wBAAgB,SAAS,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAU/C;AAED,wBAAgB,qBAAqB,CAAC,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,uBAAuB,GAAG,OAAO,CAK/F;AAED;;;;;;;GAOG;AACH,wBAAgB,qBAAqB,CAAC,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,uBAAuB,GAAG,OAAO,CAK/F"}
package/dist/privacy.js CHANGED
@@ -55,7 +55,7 @@ const EMAIL_PATTERN = /[A-Za-z0-9._%+-]{1,64}@[A-Za-z0-9.-]{1,255}\.[A-Za-z]{2,2
55
55
  const IPV4_PATTERN = /\b(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\b/g;
56
56
  const IPV6_PATTERN = /(^|[^\w:])((?:(?:[0-9A-Fa-f]{1,4}:){7}[0-9A-Fa-f]{1,4}|(?:[0-9A-Fa-f]{1,4}:){1,7}:|(?:[0-9A-Fa-f]{1,4}:){1,6}:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4}){0,5}|::(?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4}){0,6})))(?=$|[^\w:])/g;
57
57
  const US_SSN_PATTERN = /\b\d{3}[ .-]\d{2}[ .-]\d{4}\b/g;
58
- const CREDIT_CARD_CANDIDATE_PATTERN = /\b\d(?:[ ./-]?\d){12,}\b/g;
58
+ const CARD_SEPARATORS = ' ./-';
59
59
  const DIGIT_GROUP_PATTERN = /\d+/g;
60
60
  const PHONE_NANP_PATTERN = /(^|[^\w+])((?:\+?1[ ./-]?)?(?:\(\d{3}\)[ ./-]?|\d{3}[ ./-])\d{3}[ ./-]\d{4})(?![\w])/g;
61
61
  const PHONE_INTL_PATTERN = /(^|[^\w])(\+\d{1,3}(?:[ ./()-]{0,2}\d){7,13})(?![\w])/g;
@@ -295,6 +295,40 @@ function passesLuhn(digits) {
295
295
  }
296
296
  return sum % 10 === 0;
297
297
  }
298
+ function isDigitAt(text, index) {
299
+ const code = text.charCodeAt(index);
300
+ return code >= 48 && code <= 57;
301
+ }
302
+ function isWordAt(text, index) {
303
+ const code = text.charCodeAt(index);
304
+ return isDigitAt(text, index) || 95 === code || code >= 65 && code <= 90 || code >= 97 && code <= 122;
305
+ }
306
+ function digitsEnd(text, index) {
307
+ let end = index;
308
+ while(isDigitAt(text, end))end++;
309
+ return end;
310
+ }
311
+ function findCardCandidate(text, from) {
312
+ for(let start = from; start < text.length; start++){
313
+ if (!isDigitAt(text, start) || isWordAt(text, start - 1)) continue;
314
+ let digits = 0;
315
+ let end = -1;
316
+ let groupStart = start;
317
+ for(;;){
318
+ const groupEnd = digitsEnd(text, groupStart);
319
+ digits += groupEnd - groupStart;
320
+ if (digits >= 13 && !isWordAt(text, groupEnd)) end = groupEnd;
321
+ groupStart = groupEnd + 1;
322
+ if (!CARD_SEPARATORS.includes(text.charAt(groupEnd)) || !isDigitAt(text, groupStart)) break;
323
+ }
324
+ if (end >= 0) return [
325
+ start,
326
+ end
327
+ ];
328
+ start = groupStart - 1;
329
+ }
330
+ return null;
331
+ }
298
332
  function redactCardInMatch(match) {
299
333
  const groups = [];
300
334
  for(let m = DIGIT_GROUP_PATTERN.exec(match); null !== m; m = DIGIT_GROUP_PATTERN.exec(match))groups.push({
@@ -321,48 +355,73 @@ function redactCardInMatch(match) {
321
355
  }
322
356
  return output + match.slice(cursor);
323
357
  }
358
+ function redactCards(text) {
359
+ let output = '';
360
+ let cursor = 0;
361
+ for(let run = findCardCandidate(text, 0); null !== run; run = findCardCandidate(text, run[1])){
362
+ output += text.slice(cursor, run[0]) + redactCardInMatch(text.slice(run[0], run[1]));
363
+ cursor = run[1];
364
+ }
365
+ return output + text.slice(cursor);
366
+ }
324
367
  function redactPii(value) {
325
368
  let result = value.replace(UNICODE_SPACE_PATTERN, ' ');
326
369
  result = result.replace(EMAIL_PATTERN, REDACTED_VALUE);
327
370
  result = result.replace(IPV4_PATTERN, REDACTED_VALUE);
328
371
  result = result.replace(IPV6_PATTERN, `$1${REDACTED_VALUE}`);
329
- result = result.replace(CREDIT_CARD_CANDIDATE_PATTERN, redactCardInMatch);
372
+ result = redactCards(result);
330
373
  result = result.replace(US_SSN_PATTERN, REDACTED_VALUE);
331
374
  result = result.replace(PHONE_NANP_PATTERN, `$1${REDACTED_VALUE}`);
332
375
  result = result.replace(PHONE_INTL_PATTERN, `$1${REDACTED_VALUE}`);
333
376
  return result;
334
377
  }
335
378
  function sanitizeCapturedValue(value, options) {
336
- return sanitizeValueWith(value, (stringValue)=>sanitizeString(stringValue, options));
379
+ return sanitizeValueWith(value, {
380
+ text: (stringValue)=>sanitizeString(stringValue, options),
381
+ readsKeysAndNumbers: false
382
+ });
337
383
  }
338
384
  function sanitizeFreeTextValue(value, options) {
339
- return sanitizeValueWith(value, (stringValue)=>sanitizeFreeText(stringValue, options));
385
+ return sanitizeValueWith(value, {
386
+ text: (stringValue)=>sanitizeFreeText(stringValue, options),
387
+ readsKeysAndNumbers: true
388
+ });
340
389
  }
341
- function sanitizeValueWith(value, sanitizeStringFn) {
390
+ function sanitizeValueWith(value, sanitizer) {
342
391
  if (null == value) return value;
343
- if ('string' == typeof value) return sanitizeStringFn(value);
344
- if (Array.isArray(value)) return value.map((item)=>sanitizeValueWith(item, sanitizeStringFn));
392
+ if ('string' == typeof value) return sanitizer.text(value);
393
+ if ('number' == typeof value && sanitizer.readsKeysAndNumbers) {
394
+ const text = String(value);
395
+ return sanitizer.text(text) === text ? value : REDACTED_VALUE;
396
+ }
397
+ if (Array.isArray(value)) return value.map((item)=>sanitizeValueWith(item, sanitizer));
345
398
  if (value instanceof Date) return value;
346
399
  if ('object' != typeof value) return value;
347
400
  const result = {};
348
- for (const [key, nestedValue] of Object.entries(value))result[key] = shouldRedactKey(key) ? REDACTED_VALUE : sanitizeValueWith(nestedValue, sanitizeStringFn);
401
+ for (const [key, nestedValue] of Object.entries(value)){
402
+ const capturedKey = sanitizer.readsKeysAndNumbers ? sanitizer.text(key) : key;
403
+ result[capturedKey] = shouldRedactKey(key) ? REDACTED_VALUE : sanitizeValueWith(nestedValue, sanitizer);
404
+ }
349
405
  return result;
350
406
  }
351
407
  __webpack_require__.d(__webpack_exports__, {
352
408
  redactPii: ()=>redactPii,
353
409
  sanitizeCapturedValue: ()=>sanitizeCapturedValue,
354
410
  sanitizeFreeText: ()=>sanitizeFreeText,
355
- sanitizeFreeTextValue: ()=>sanitizeFreeTextValue
411
+ sanitizeFreeTextValue: ()=>sanitizeFreeTextValue,
412
+ shouldRedactKey: ()=>shouldRedactKey
356
413
  });
357
414
  exports.redactPii = __webpack_exports__.redactPii;
358
415
  exports.sanitizeCapturedValue = __webpack_exports__.sanitizeCapturedValue;
359
416
  exports.sanitizeFreeText = __webpack_exports__.sanitizeFreeText;
360
417
  exports.sanitizeFreeTextValue = __webpack_exports__.sanitizeFreeTextValue;
418
+ exports.shouldRedactKey = __webpack_exports__.shouldRedactKey;
361
419
  for(var __rspack_i in __webpack_exports__)if (-1 === [
362
420
  "redactPii",
363
421
  "sanitizeCapturedValue",
364
422
  "sanitizeFreeText",
365
- "sanitizeFreeTextValue"
423
+ "sanitizeFreeTextValue",
424
+ "shouldRedactKey"
366
425
  ].indexOf(__rspack_i)) exports[__rspack_i] = __webpack_exports__[__rspack_i];
367
426
  Object.defineProperty(exports, '__esModule', {
368
427
  value: true
package/dist/privacy.mjs CHANGED
@@ -26,7 +26,7 @@ const EMAIL_PATTERN = /[A-Za-z0-9._%+-]{1,64}@[A-Za-z0-9.-]{1,255}\.[A-Za-z]{2,2
26
26
  const IPV4_PATTERN = /\b(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\b/g;
27
27
  const IPV6_PATTERN = /(^|[^\w:])((?:(?:[0-9A-Fa-f]{1,4}:){7}[0-9A-Fa-f]{1,4}|(?:[0-9A-Fa-f]{1,4}:){1,7}:|(?:[0-9A-Fa-f]{1,4}:){1,6}:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4}){0,5}|::(?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4}){0,6})))(?=$|[^\w:])/g;
28
28
  const US_SSN_PATTERN = /\b\d{3}[ .-]\d{2}[ .-]\d{4}\b/g;
29
- const CREDIT_CARD_CANDIDATE_PATTERN = /\b\d(?:[ ./-]?\d){12,}\b/g;
29
+ const CARD_SEPARATORS = ' ./-';
30
30
  const DIGIT_GROUP_PATTERN = /\d+/g;
31
31
  const PHONE_NANP_PATTERN = /(^|[^\w+])((?:\+?1[ ./-]?)?(?:\(\d{3}\)[ ./-]?|\d{3}[ ./-])\d{3}[ ./-]\d{4})(?![\w])/g;
32
32
  const PHONE_INTL_PATTERN = /(^|[^\w])(\+\d{1,3}(?:[ ./()-]{0,2}\d){7,13})(?![\w])/g;
@@ -266,6 +266,40 @@ function passesLuhn(digits) {
266
266
  }
267
267
  return sum % 10 === 0;
268
268
  }
269
+ function isDigitAt(text, index) {
270
+ const code = text.charCodeAt(index);
271
+ return code >= 48 && code <= 57;
272
+ }
273
+ function isWordAt(text, index) {
274
+ const code = text.charCodeAt(index);
275
+ return isDigitAt(text, index) || 95 === code || code >= 65 && code <= 90 || code >= 97 && code <= 122;
276
+ }
277
+ function digitsEnd(text, index) {
278
+ let end = index;
279
+ while(isDigitAt(text, end))end++;
280
+ return end;
281
+ }
282
+ function findCardCandidate(text, from) {
283
+ for(let start = from; start < text.length; start++){
284
+ if (!isDigitAt(text, start) || isWordAt(text, start - 1)) continue;
285
+ let digits = 0;
286
+ let end = -1;
287
+ let groupStart = start;
288
+ for(;;){
289
+ const groupEnd = digitsEnd(text, groupStart);
290
+ digits += groupEnd - groupStart;
291
+ if (digits >= 13 && !isWordAt(text, groupEnd)) end = groupEnd;
292
+ groupStart = groupEnd + 1;
293
+ if (!CARD_SEPARATORS.includes(text.charAt(groupEnd)) || !isDigitAt(text, groupStart)) break;
294
+ }
295
+ if (end >= 0) return [
296
+ start,
297
+ end
298
+ ];
299
+ start = groupStart - 1;
300
+ }
301
+ return null;
302
+ }
269
303
  function redactCardInMatch(match) {
270
304
  const groups = [];
271
305
  for(let m = DIGIT_GROUP_PATTERN.exec(match); null !== m; m = DIGIT_GROUP_PATTERN.exec(match))groups.push({
@@ -292,31 +326,53 @@ function redactCardInMatch(match) {
292
326
  }
293
327
  return output + match.slice(cursor);
294
328
  }
329
+ function redactCards(text) {
330
+ let output = '';
331
+ let cursor = 0;
332
+ for(let run = findCardCandidate(text, 0); null !== run; run = findCardCandidate(text, run[1])){
333
+ output += text.slice(cursor, run[0]) + redactCardInMatch(text.slice(run[0], run[1]));
334
+ cursor = run[1];
335
+ }
336
+ return output + text.slice(cursor);
337
+ }
295
338
  function redactPii(value) {
296
339
  let result = value.replace(UNICODE_SPACE_PATTERN, ' ');
297
340
  result = result.replace(EMAIL_PATTERN, REDACTED_VALUE);
298
341
  result = result.replace(IPV4_PATTERN, REDACTED_VALUE);
299
342
  result = result.replace(IPV6_PATTERN, `$1${REDACTED_VALUE}`);
300
- result = result.replace(CREDIT_CARD_CANDIDATE_PATTERN, redactCardInMatch);
343
+ result = redactCards(result);
301
344
  result = result.replace(US_SSN_PATTERN, REDACTED_VALUE);
302
345
  result = result.replace(PHONE_NANP_PATTERN, `$1${REDACTED_VALUE}`);
303
346
  result = result.replace(PHONE_INTL_PATTERN, `$1${REDACTED_VALUE}`);
304
347
  return result;
305
348
  }
306
349
  function sanitizeCapturedValue(value, options) {
307
- return sanitizeValueWith(value, (stringValue)=>sanitizeString(stringValue, options));
350
+ return sanitizeValueWith(value, {
351
+ text: (stringValue)=>sanitizeString(stringValue, options),
352
+ readsKeysAndNumbers: false
353
+ });
308
354
  }
309
355
  function sanitizeFreeTextValue(value, options) {
310
- return sanitizeValueWith(value, (stringValue)=>sanitizeFreeText(stringValue, options));
356
+ return sanitizeValueWith(value, {
357
+ text: (stringValue)=>sanitizeFreeText(stringValue, options),
358
+ readsKeysAndNumbers: true
359
+ });
311
360
  }
312
- function sanitizeValueWith(value, sanitizeStringFn) {
361
+ function sanitizeValueWith(value, sanitizer) {
313
362
  if (null == value) return value;
314
- if ('string' == typeof value) return sanitizeStringFn(value);
315
- if (Array.isArray(value)) return value.map((item)=>sanitizeValueWith(item, sanitizeStringFn));
363
+ if ('string' == typeof value) return sanitizer.text(value);
364
+ if ('number' == typeof value && sanitizer.readsKeysAndNumbers) {
365
+ const text = String(value);
366
+ return sanitizer.text(text) === text ? value : REDACTED_VALUE;
367
+ }
368
+ if (Array.isArray(value)) return value.map((item)=>sanitizeValueWith(item, sanitizer));
316
369
  if (value instanceof Date) return value;
317
370
  if ('object' != typeof value) return value;
318
371
  const result = {};
319
- for (const [key, nestedValue] of Object.entries(value))result[key] = shouldRedactKey(key) ? REDACTED_VALUE : sanitizeValueWith(nestedValue, sanitizeStringFn);
372
+ for (const [key, nestedValue] of Object.entries(value)){
373
+ const capturedKey = sanitizer.readsKeysAndNumbers ? sanitizer.text(key) : key;
374
+ result[capturedKey] = shouldRedactKey(key) ? REDACTED_VALUE : sanitizeValueWith(nestedValue, sanitizer);
375
+ }
320
376
  return result;
321
377
  }
322
- export { redactPii, sanitizeCapturedValue, sanitizeFreeText, sanitizeFreeTextValue };
378
+ export { redactPii, sanitizeCapturedValue, sanitizeFreeText, sanitizeFreeTextValue, shouldRedactKey };
@@ -88,6 +88,8 @@ export declare class PostHogSpan implements Span {
88
88
  recordException(error: unknown): this;
89
89
  updateName(name: string): this;
90
90
  traceparent(): string | null;
91
+ get traceId(): string;
92
+ get spanId(): string;
91
93
  tracestate(): string | null;
92
94
  /** Context a child span inherits when this handle is its parent. */
93
95
  childContext(): {
@@ -130,6 +132,8 @@ export declare class NoopSpan implements Span {
130
132
  recordException(): this;
131
133
  updateName(): this;
132
134
  traceparent(): string | null;
135
+ get traceId(): string | null;
136
+ get spanId(): string | null;
133
137
  tracestate(): string | null;
134
138
  end(): void;
135
139
  }
@@ -146,6 +150,8 @@ export declare class PassThroughSpan extends NoopSpan {
146
150
  private readonly _tracestate?;
147
151
  constructor(_traceparent: string, _tracestate?: string | undefined);
148
152
  traceparent(): string;
153
+ get traceId(): string | null;
154
+ get spanId(): string | null;
149
155
  tracestate(): string | null;
150
156
  }
151
157
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"span.d.ts","sourceRoot":"","sources":["../../src/traces/span.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,IAAI,EAAE,cAAc,EAAE,kBAAkB,EAAE,QAAQ,EAAE,cAAc,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAA;AACvH,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,UAAU,CAAA;AACtC,OAAO,KAAK,EAAE,kBAAkB,EAAmB,UAAU,EAAE,MAAM,SAAS,CAAA;AAmB9E;;;GAGG;AACH,wBAAgB,YAAY,IAAI,MAAM,GAAG,SAAS,CAGjD;AAED,8FAA8F;AAC9F,MAAM,WAAW,WAAW;IAC1B,IAAI,EAAE,MAAM,CAAA;IACZ,IAAI,EAAE,MAAM,CAAA;CACb;AAED,MAAM,WAAW,QAAQ;IACvB,OAAO,EAAE,MAAM,CAAA;IACf,MAAM,EAAE,MAAM,CAAA;IACd,YAAY,CAAC,EAAE,MAAM,CAAA;IACrB,UAAU,CAAC,EAAE,MAAM,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GG;AACH,wBAAgB,aAAa,CAAC,KAAK,EAAE,OAAO,GAAG;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,MAAM,CAAC;IAAC,KAAK,CAAC,EAAE,MAAM,CAAA;CAAE,CAqB/F"}
@@ -176,6 +176,12 @@ class PostHogSpan {
176
176
  traceparent() {
177
177
  return (0, external_traceparent_js_namespaceObject.formatTraceparent)(this._traceId, this._spanId, this._traceFlags);
178
178
  }
179
+ get traceId() {
180
+ return this._traceId;
181
+ }
182
+ get spanId() {
183
+ return this._spanId;
184
+ }
179
185
  tracestate() {
180
186
  return this._traceState ?? null;
181
187
  }
@@ -315,6 +321,12 @@ class NoopSpan {
315
321
  traceparent() {
316
322
  return null;
317
323
  }
324
+ get traceId() {
325
+ return null;
326
+ }
327
+ get spanId() {
328
+ return null;
329
+ }
318
330
  tracestate() {
319
331
  return null;
320
332
  }
@@ -328,6 +340,12 @@ class PassThroughSpan extends NoopSpan {
328
340
  traceparent() {
329
341
  return this._traceparent;
330
342
  }
343
+ get traceId() {
344
+ return this._traceparent.split('-')[1] ?? null;
345
+ }
346
+ get spanId() {
347
+ return this._traceparent.split('-')[2] ?? null;
348
+ }
331
349
  tracestate() {
332
350
  return this._tracestate ?? null;
333
351
  }
@@ -133,6 +133,12 @@ class PostHogSpan {
133
133
  traceparent() {
134
134
  return formatTraceparent(this._traceId, this._spanId, this._traceFlags);
135
135
  }
136
+ get traceId() {
137
+ return this._traceId;
138
+ }
139
+ get spanId() {
140
+ return this._spanId;
141
+ }
136
142
  tracestate() {
137
143
  return this._traceState ?? null;
138
144
  }
@@ -272,6 +278,12 @@ class NoopSpan {
272
278
  traceparent() {
273
279
  return null;
274
280
  }
281
+ get traceId() {
282
+ return null;
283
+ }
284
+ get spanId() {
285
+ return null;
286
+ }
275
287
  tracestate() {
276
288
  return null;
277
289
  }
@@ -285,6 +297,12 @@ class PassThroughSpan extends NoopSpan {
285
297
  traceparent() {
286
298
  return this._traceparent;
287
299
  }
300
+ get traceId() {
301
+ return this._traceparent.split('-')[1] ?? null;
302
+ }
303
+ get spanId() {
304
+ return this._traceparent.split('-')[2] ?? null;
305
+ }
288
306
  tracestate() {
289
307
  return this._tracestate ?? null;
290
308
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@posthog/core",
3
- "version": "1.64.1",
3
+ "version": "1.66.0",
4
4
  "bugs": {
5
5
  "url": "https://github.com/PostHog/posthog-js/issues"
6
6
  },
@@ -72,7 +72,7 @@
72
72
  }
73
73
  },
74
74
  "dependencies": {
75
- "@posthog/types": "^1.421.0"
75
+ "@posthog/types": "^1.423.0"
76
76
  },
77
77
  "devDependencies": {
78
78
  "@rslib/core": "0.23.2",
@@ -2300,3 +2300,122 @@ describe('PostHogLogs', () => {
2300
2300
  })
2301
2301
  })
2302
2302
  })
2303
+
2304
+ describe('PostHogLogs consent and shared background flush', () => {
2305
+ const create = (instance: any, logger: Logger = createMockLogger(), config = resolveForTest()): PostHogLogs =>
2306
+ new PostHogLogs(
2307
+ instance,
2308
+ config,
2309
+ logger,
2310
+ getContextFor(instance),
2311
+ immediateOnReady,
2312
+ undefined,
2313
+ undefined,
2314
+ () => instance.consentWithdrawn === true
2315
+ )
2316
+
2317
+ it('discards queued records instead of exporting them after opt-out', async () => {
2318
+ const instance = createMockInstance()
2319
+ const logs = create(instance)
2320
+ logs.captureLog({ body: 'before opt-out' })
2321
+
2322
+ instance.consentWithdrawn = true
2323
+ await logs.flush()
2324
+
2325
+ expect(instance._sendLogsBatch).not.toHaveBeenCalled()
2326
+ expect(readQueue(instance)).toHaveLength(0)
2327
+
2328
+ // Opting back in does not resurrect what was captured before the withdrawal.
2329
+ instance.consentWithdrawn = false
2330
+ await logs.flush()
2331
+ expect(instance._sendLogsBatch).not.toHaveBeenCalled()
2332
+ })
2333
+
2334
+ it('stops a drain under way when the user opts out between batches', async () => {
2335
+ let releaseFirst: () => void = () => {}
2336
+ const instance = createMockInstance({
2337
+ _sendLogsBatch: vi.fn(
2338
+ () =>
2339
+ new Promise((resolve) => {
2340
+ releaseFirst = () => resolve({ kind: 'ok' })
2341
+ })
2342
+ ),
2343
+ })
2344
+ const logs = create(instance, createMockLogger(), resolveForTest({ maxBatchRecordsPerPost: 1 }))
2345
+ logs.captureLog({ body: 'first' })
2346
+ logs.captureLog({ body: 'second' })
2347
+
2348
+ const flushing = logs.flush()
2349
+ await Promise.resolve()
2350
+ instance.consentWithdrawn = true
2351
+ releaseFirst()
2352
+ await flushing
2353
+
2354
+ expect(instance._sendLogsBatch).toHaveBeenCalledTimes(1)
2355
+ expect(readQueue(instance)).toHaveLength(0)
2356
+ })
2357
+
2358
+ it('does not retry a 413-rejected batch after the user opts out', async () => {
2359
+ let rejectFirst: () => void = () => {}
2360
+ const instance = createMockInstance({
2361
+ _sendLogsBatch: vi.fn(
2362
+ () =>
2363
+ new Promise((resolve) => {
2364
+ rejectFirst = () => resolve({ kind: 'too-large' })
2365
+ })
2366
+ ),
2367
+ })
2368
+ const logs = create(instance, createMockLogger(), resolveForTest({ maxBatchRecordsPerPost: 4 }))
2369
+ logs.captureLog({ body: 'a' })
2370
+ logs.captureLog({ body: 'b' })
2371
+
2372
+ const flushing = logs.flush()
2373
+ await Promise.resolve()
2374
+ instance.consentWithdrawn = true
2375
+ rejectFirst()
2376
+ await flushing
2377
+
2378
+ expect(instance._sendLogsBatch).toHaveBeenCalledTimes(1)
2379
+ expect(readQueue(instance)).toHaveLength(0)
2380
+ })
2381
+
2382
+ it('shares one background wrapper across overlapping callers', async () => {
2383
+ let failSend: () => void = () => {}
2384
+ const instance = createMockInstance({
2385
+ _sendLogsBatch: vi.fn(
2386
+ () =>
2387
+ new Promise((resolve) => {
2388
+ failSend = () => resolve({ kind: 'retry-later', error: new Error('down') })
2389
+ })
2390
+ ),
2391
+ })
2392
+ const logger = createMockLogger()
2393
+ const logs = create(instance, logger)
2394
+ logs.captureLog({ body: 'slow' })
2395
+
2396
+ const first = logs.flushInBackground()
2397
+ const second = logs.flushInBackground()
2398
+ expect(second).toBe(first)
2399
+ await Promise.resolve()
2400
+ failSend()
2401
+ await Promise.all([first, second])
2402
+
2403
+ expect(instance._sendLogsBatch).toHaveBeenCalledTimes(1)
2404
+ expect(logger.error).toHaveBeenCalledTimes(1)
2405
+ })
2406
+
2407
+ it('keeps flushing a host whose optedOut is only a shutdown gate when no consent callback is given', async () => {
2408
+ const instance = createMockInstance({ optedOut: false })
2409
+ const logs = new PostHogLogs(
2410
+ instance,
2411
+ resolveForTest(),
2412
+ createMockLogger(),
2413
+ getContextFor(instance),
2414
+ immediateOnReady
2415
+ )
2416
+ logs.captureLog({ body: 'final flush' })
2417
+ instance.optedOut = true
2418
+ await logs.flush()
2419
+ expect(instance._sendLogsBatch).toHaveBeenCalledTimes(1)
2420
+ })
2421
+ })
package/src/logs/index.ts CHANGED
@@ -29,6 +29,9 @@ export class PostHogLogs {
29
29
  // A batch captures this when it is assembled, so it can tell that the records it is
30
30
  // holding no longer correspond to anything queued.
31
31
  private _queueGeneration = 0
32
+ // The `flushInBackground()` wrapper for the flush in flight, shared so overlapping
33
+ // callers count and log one failed POST once rather than once per caller.
34
+ private _backgroundFlushPromise: Promise<void> | null = null
32
35
  // Every path that can start a send checks this, not just the retry timer.
33
36
  private _retryAfter = new RetryAfterWindow()
34
37
  // Consecutive failed flushes; drives exponential backoff on the retry timer.
@@ -61,7 +64,12 @@ export class PostHogLogs {
61
64
  // OTLP instrumentation scope name. Overrides the `getLibraryId()` fallback
62
65
  // so a host can label a specific capture stream (e.g. 'console' for browser
63
66
  // console auto-capture). Defaults to `getLibraryId()` when omitted.
64
- private readonly _scopeName?: string
67
+ private readonly _scopeName?: string,
68
+ // True once the user has withdrawn consent. Checked before every flush iteration so
69
+ // queued records are dropped rather than exported, by a timer or a drain under way.
70
+ // Opt-in: a browser host's `optedOut` also reads true while it shuts down, when the
71
+ // final flush must still go out, so only a host that separates the two passes this.
72
+ private readonly _isConsentWithdrawn: () => boolean = () => false
65
73
  ) {
66
74
  this._maxBufferSize = _config.maxBufferSize
67
75
  // Never below the flush trigger: a smaller eviction cap would stop the
@@ -83,6 +91,11 @@ export class PostHogLogs {
83
91
  this._instance.setPersistedProperty(PostHogPersistedProperty.LogsQueue, [])
84
92
  }
85
93
 
94
+ /** True while the endpoint's `Retry-After` window is open, so a host's automatic flush can skip logs. */
95
+ get throttled(): boolean {
96
+ return this._retryAfter.isOpen()
97
+ }
98
+
86
99
  /**
87
100
  * Clears the flush timer and rate-cap state. The host owns the record queue
88
101
  * and clears it separately (the browser empties its in-memory store).
@@ -269,6 +282,9 @@ export class PostHogLogs {
269
282
  private async _flushInner(): Promise<void> {
270
283
  this._flushTimer.clear()
271
284
 
285
+ if (this._discardQueueIfConsentWithdrawn()) {
286
+ return
287
+ }
272
288
  let queue = this._instance.getPersistedProperty<BufferedLogEntry[]>(PostHogPersistedProperty.LogsQueue) ?? []
273
289
  if (queue.length === 0) {
274
290
  return
@@ -278,6 +294,11 @@ export class PostHogLogs {
278
294
  let sentCount = 0
279
295
 
280
296
  while (queue.length > 0 && sentCount < originalQueueLength) {
297
+ // Re-checked on every iteration, including a 413 shrink-and-retry that sends no
298
+ // progress: a send suspends, so the user can opt out while one is in flight.
299
+ if (this._discardQueueIfConsentWithdrawn()) {
300
+ return
301
+ }
281
302
  // Captured per batch, not per flush: a clear that lands between batches leaves
282
303
  // the next one assembled from an already-fresh queue, so that batch advances
283
304
  // normally instead of being retired for a purge it never held.
@@ -360,6 +381,21 @@ export class PostHogLogs {
360
381
  }
361
382
  }
362
383
 
384
+ /**
385
+ * Drops the queue once consent is withdrawn. Records carry the distinct id and
386
+ * session id, so whatever is still queued when the user opts out must not be
387
+ * exported, by a pending timer or by a drain already under way.
388
+ */
389
+ private _discardQueueIfConsentWithdrawn(): boolean {
390
+ if (!this._isConsentWithdrawn()) {
391
+ return false
392
+ }
393
+ if (this._hasQueuedRecords()) {
394
+ this.clearQueue()
395
+ }
396
+ return true
397
+ }
398
+
363
399
  private async _persistQueueAdvance(consumed: number): Promise<void> {
364
400
  // Re-read in case captures landed mid-flush. Subtract head records the FIFO cap
365
401
  // evicted during the send (already-sent records that left the queue), so we drop
@@ -481,8 +517,17 @@ export class PostHogLogs {
481
517
  })
482
518
  }
483
519
 
484
- private _flushInBackground(): void {
485
- void this.flush()
520
+ /**
521
+ * `flush()` for a host that drives logs from its own flush cycle. Never rejects, and when
522
+ * records remain (a failed send, or captures that landed mid-flush) re-arms the timer with
523
+ * backoff, as the pipeline's own timer flush does. A bare `flush()` clears the timer and
524
+ * leaves nothing to retry the records once traffic stops.
525
+ */
526
+ flushInBackground(): Promise<void> {
527
+ if (this._backgroundFlushPromise) {
528
+ return this._backgroundFlushPromise
529
+ }
530
+ const promise = this.flush()
486
531
  .then(
487
532
  () => {
488
533
  this._consecutiveFlushFailures = 0
@@ -498,9 +543,18 @@ export class PostHogLogs {
498
543
  // Records remaining (transient failure or mid-flush captures) would otherwise
499
544
  // sit undelivered on a quiet page; re-arm so the timer retries them, backing
500
545
  // off on consecutive failures.
546
+ if (this._backgroundFlushPromise === promise) {
547
+ this._backgroundFlushPromise = null
548
+ }
501
549
  if (!this._instance.isDisabled && this._hasQueuedRecords()) {
502
550
  this._flushTimer.armNoEarlierThan(this._nextFlushDelay())
503
551
  }
504
552
  })
553
+ this._backgroundFlushPromise = promise
554
+ return promise
555
+ }
556
+
557
+ private _flushInBackground(): void {
558
+ void this.flushInBackground()
505
559
  }
506
560
  }
package/src/privacy.ts CHANGED
@@ -104,11 +104,12 @@ const IPV6_PATTERN =
104
104
  // 9-digit IDs are never mistaken for an SSN.
105
105
  const US_SSN_PATTERN = /\b\d{3}[ .-]\d{2}[ .-]\d{4}\b/g
106
106
  // A run of >=13 digits optionally grouped by a single space, dot, dash, or
107
- // slash. This only marks the numeric region; `redactCardInMatch` then looks for
108
- // the actual card as a run of whole separator-delimited groups that passes Luhn,
109
- // so an adjacent field such as an expiry (`4111 1111 1111 1111 12/30`) is not
110
- // absorbed into a failing check that would leak the card.
111
- const CREDIT_CARD_CANDIDATE_PATTERN = /\b\d(?:[ ./-]?\d){12,}\b/g
107
+ // slash; see `findCardCandidate`. This only marks the numeric region;
108
+ // `redactCardInMatch` then looks for the actual card as a run of whole
109
+ // separator-delimited groups that passes Luhn, so an adjacent field such as an
110
+ // expiry (`4111 1111 1111 1111 12/30`) is not absorbed into a failing check that
111
+ // would leak the card.
112
+ const CARD_SEPARATORS = ' ./-'
112
113
  // Matches each separator-delimited digit group inside a card candidate.
113
114
  const DIGIT_GROUP_PATTERN = /\d+/g
114
115
  // Phone matching is structural rather than "any 10–15 digits", so dates
@@ -123,11 +124,8 @@ const PHONE_INTL_PATTERN = /(^|[^\w])(\+\d{1,3}(?:[ ./()-]{0,2}\d){7,13})(?![\w]
123
124
 
124
125
  type JsonRecord = Record<string, unknown>
125
126
 
126
- function isRecord(value: unknown): value is JsonRecord {
127
- return !!value && typeof value === 'object' && !Array.isArray(value)
128
- }
129
-
130
- function shouldRedactKey(key: string): boolean {
127
+ /** Whether a key names a credential, so its value is captured as `[redacted]` whatever it holds. */
128
+ export function shouldRedactKey(key: string): boolean {
131
129
  return SENSITIVE_KEY_PATTERN.test(key)
132
130
  }
133
131
 
@@ -600,6 +598,60 @@ function passesLuhn(digits: string): boolean {
600
598
  return sum % 10 === 0
601
599
  }
602
600
 
601
+ function isDigitAt(text: string, index: number): boolean {
602
+ const code = text.charCodeAt(index)
603
+ return code >= 48 && code <= 57
604
+ }
605
+
606
+ function isWordAt(text: string, index: number): boolean {
607
+ const code = text.charCodeAt(index)
608
+ return isDigitAt(text, index) || code === 95 || (code >= 65 && code <= 90) || (code >= 97 && code <= 122)
609
+ }
610
+
611
+ function digitsEnd(text: string, index: number): number {
612
+ let end = index
613
+ while (isDigitAt(text, end)) {
614
+ end++
615
+ }
616
+ return end
617
+ }
618
+
619
+ /**
620
+ * Where the next card candidate at or after `from` starts and ends: a run of 13
621
+ * or more digits in whole groups joined by one space, dot, dash, or slash, with
622
+ * no word character on either side. The run only marks the numeric region;
623
+ * {@link redactCardInMatch} finds the cards in it.
624
+ *
625
+ * A loop rather than a pattern: a backtracking pattern over a megabyte-long run
626
+ * of digit groups overflows the stack, and the throw drops the event.
627
+ */
628
+ function findCardCandidate(text: string, from: number): [start: number, end: number] | null {
629
+ for (let start = from; start < text.length; start++) {
630
+ if (!isDigitAt(text, start) || isWordAt(text, start - 1)) {
631
+ continue
632
+ }
633
+ let digits = 0
634
+ let end = -1
635
+ let groupStart = start
636
+ for (;;) {
637
+ const groupEnd = digitsEnd(text, groupStart)
638
+ digits += groupEnd - groupStart
639
+ if (digits >= 13 && !isWordAt(text, groupEnd)) {
640
+ end = groupEnd
641
+ }
642
+ groupStart = groupEnd + 1
643
+ if (!CARD_SEPARATORS.includes(text.charAt(groupEnd)) || !isDigitAt(text, groupStart)) {
644
+ break
645
+ }
646
+ }
647
+ if (end >= 0) {
648
+ return [start, end]
649
+ }
650
+ start = groupStart - 1
651
+ }
652
+ return null
653
+ }
654
+
603
655
  // A card candidate can span more than one card plus adjacent fields (e.g. an
604
656
  // expiry, or a second card). This redacts every card in it: scanning
605
657
  // left-to-right over the whole separator-delimited digit groups, at each start it
@@ -639,6 +691,16 @@ function redactCardInMatch(match: string): string {
639
691
  return output + match.slice(cursor)
640
692
  }
641
693
 
694
+ function redactCards(text: string): string {
695
+ let output = ''
696
+ let cursor = 0
697
+ for (let run = findCardCandidate(text, 0); run !== null; run = findCardCandidate(text, run[1])) {
698
+ output += text.slice(cursor, run[0]) + redactCardInMatch(text.slice(run[0], run[1]))
699
+ cursor = run[1]
700
+ }
701
+ return output + text.slice(cursor)
702
+ }
703
+
642
704
  /**
643
705
  * Redacts structured personal identifiers (emails, IP addresses, credit-card
644
706
  * numbers, US SSNs, and phone numbers) from a free-text string. Intended for the
@@ -653,7 +715,7 @@ export function redactPii(value: string): string {
653
715
  result = result.replace(EMAIL_PATTERN, REDACTED_VALUE)
654
716
  result = result.replace(IPV4_PATTERN, REDACTED_VALUE)
655
717
  result = result.replace(IPV6_PATTERN, `$1${REDACTED_VALUE}`)
656
- result = result.replace(CREDIT_CARD_CANDIDATE_PATTERN, redactCardInMatch)
718
+ result = redactCards(result)
657
719
  result = result.replace(US_SSN_PATTERN, REDACTED_VALUE)
658
720
  result = result.replace(PHONE_NANP_PATTERN, `$1${REDACTED_VALUE}`)
659
721
  result = result.replace(PHONE_INTL_PATTERN, `$1${REDACTED_VALUE}`)
@@ -661,29 +723,48 @@ export function redactPii(value: string): string {
661
723
  }
662
724
 
663
725
  export function sanitizeCapturedValue(value: unknown, options: TextSanitizationOptions): unknown {
664
- return sanitizeValueWith(value, (stringValue) => sanitizeString(stringValue, options))
726
+ return sanitizeValueWith(value, {
727
+ text: (stringValue) => sanitizeString(stringValue, options),
728
+ readsKeysAndNumbers: false,
729
+ })
665
730
  }
666
731
 
667
732
  /**
668
733
  * {@link sanitizeCapturedValue} with the intent-grade string pass
669
734
  * ({@link sanitizeFreeText}) on every string leaf, so nested agent-narrated
670
- * values get structured-PII redaction in the load-bearing order too.
735
+ * values get structured-PII redaction in the load-bearing order too. Keys and
736
+ * numbers are read as free text as well, since a value sent as JSON text carries
737
+ * them: a number that holds an identifier becomes `[redacted]`, so the text
738
+ * stays valid JSON.
671
739
  */
672
740
  export function sanitizeFreeTextValue(value: unknown, options: TextSanitizationOptions): unknown {
673
- return sanitizeValueWith(value, (stringValue) => sanitizeFreeText(stringValue, options))
741
+ return sanitizeValueWith(value, {
742
+ text: (stringValue) => sanitizeFreeText(stringValue, options),
743
+ readsKeysAndNumbers: true,
744
+ })
674
745
  }
675
746
 
676
- function sanitizeValueWith(value: unknown, sanitizeStringFn: (value: string) => string): unknown {
747
+ interface ValueSanitizer {
748
+ text: (value: string) => string
749
+ readsKeysAndNumbers: boolean
750
+ }
751
+
752
+ function sanitizeValueWith(value: unknown, sanitizer: ValueSanitizer): unknown {
677
753
  if (value == null) {
678
754
  return value
679
755
  }
680
756
 
681
757
  if (typeof value === 'string') {
682
- return sanitizeStringFn(value)
758
+ return sanitizer.text(value)
759
+ }
760
+
761
+ if (typeof value === 'number' && sanitizer.readsKeysAndNumbers) {
762
+ const text = String(value)
763
+ return sanitizer.text(text) === text ? value : REDACTED_VALUE
683
764
  }
684
765
 
685
766
  if (Array.isArray(value)) {
686
- return value.map((item) => sanitizeValueWith(item, sanitizeStringFn))
767
+ return value.map((item) => sanitizeValueWith(item, sanitizer))
687
768
  }
688
769
 
689
770
  if (value instanceof Date) {
@@ -696,7 +777,8 @@ function sanitizeValueWith(value: unknown, sanitizeStringFn: (value: string) =>
696
777
 
697
778
  const result: JsonRecord = {}
698
779
  for (const [key, nestedValue] of Object.entries(value)) {
699
- result[key] = shouldRedactKey(key) ? REDACTED_VALUE : sanitizeValueWith(nestedValue, sanitizeStringFn)
780
+ const capturedKey = sanitizer.readsKeysAndNumbers ? sanitizer.text(key) : key
781
+ result[capturedKey] = shouldRedactKey(key) ? REDACTED_VALUE : sanitizeValueWith(nestedValue, sanitizer)
700
782
  }
701
783
  return result
702
784
  }
@@ -1,4 +1,4 @@
1
- import { NOOP_SPAN, PostHogSpan, describeError, truncateAttributeValue } from './span'
1
+ import { NOOP_SPAN, PassThroughSpan, PostHogSpan, describeError, truncateAttributeValue } from './span'
2
2
  import { buildOtlpSpan } from './otlp'
3
3
  import { resolveTracesConfig } from './config'
4
4
  import type { SpanInit } from './span'
@@ -962,6 +962,18 @@ describe('PostHogSpan', () => {
962
962
  expect(createSpan().traceparent()).toBe(`00-${TRACE_ID}-${SPAN_ID}-01`)
963
963
  })
964
964
 
965
+ it('exposes the trace and span ids as getters', () => {
966
+ const span = createSpan()
967
+ expect(span.traceId).toBe(TRACE_ID)
968
+ expect(span.spanId).toBe(SPAN_ID)
969
+ })
970
+
971
+ it('reads the ids of a pass-through span from its traceparent', () => {
972
+ const span = new PassThroughSpan(`00-${TRACE_ID}-${SPAN_ID}-01`)
973
+ expect(span.traceId).toBe(TRACE_ID)
974
+ expect(span.spanId).toBe(SPAN_ID)
975
+ })
976
+
965
977
  it('returns null tracestate when it has none', () => {
966
978
  expect(createSpan().tracestate()).toBeNull()
967
979
  })
@@ -1008,6 +1020,8 @@ describe('NoopSpan', () => {
1008
1020
  // An id that was never recorded must not propagate to another service.
1009
1021
  expect(NOOP_SPAN.traceparent()).toBeNull()
1010
1022
  expect(NOOP_SPAN.tracestate()).toBeNull()
1023
+ expect(NOOP_SPAN.traceId).toBeNull()
1024
+ expect(NOOP_SPAN.spanId).toBeNull()
1011
1025
  })
1012
1026
  })
1013
1027
 
@@ -269,6 +269,14 @@ export class PostHogSpan implements Span {
269
269
  return formatTraceparent(this._traceId, this._spanId, this._traceFlags)
270
270
  }
271
271
 
272
+ get traceId(): string {
273
+ return this._traceId
274
+ }
275
+
276
+ get spanId(): string {
277
+ return this._spanId
278
+ }
279
+
272
280
  tracestate(): string | null {
273
281
  return this._traceState ?? null
274
282
  }
@@ -490,6 +498,12 @@ export class NoopSpan implements Span {
490
498
  traceparent(): string | null {
491
499
  return null
492
500
  }
501
+ get traceId(): string | null {
502
+ return null
503
+ }
504
+ get spanId(): string | null {
505
+ return null
506
+ }
493
507
  tracestate(): string | null {
494
508
  return null
495
509
  }
@@ -519,6 +533,15 @@ export class PassThroughSpan extends NoopSpan {
519
533
  return this._traceparent
520
534
  }
521
535
 
536
+ // `00-<traceId>-<spanId>-<flags>`: the inbound header is already normalized.
537
+ override get traceId(): string | null {
538
+ return this._traceparent.split('-')[1] ?? null
539
+ }
540
+
541
+ override get spanId(): string | null {
542
+ return this._traceparent.split('-')[2] ?? null
543
+ }
544
+
522
545
  override tracestate(): string | null {
523
546
  return this._tracestate ?? null
524
547
  }