@zuplo/cli 7.15.0 → 7.15.3

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 (126) hide show
  1. package/LICENSE.third-party.txt +236 -0
  2. package/LICENSE.txt +5 -78
  3. package/README.md +18 -3
  4. package/node_modules/@modelcontextprotocol/client/node_modules/jose/dist/webapi/jwks/remote.js +1 -1
  5. package/node_modules/@modelcontextprotocol/client/node_modules/jose/dist/webapi/lib/jwt_claims_set.js +2 -0
  6. package/node_modules/@modelcontextprotocol/client/node_modules/jose/package.json +1 -1
  7. package/node_modules/@modelcontextprotocol/sdk/node_modules/jose/dist/webapi/jwks/remote.js +1 -1
  8. package/node_modules/@modelcontextprotocol/sdk/node_modules/jose/dist/webapi/lib/jwt_claims_set.js +2 -0
  9. package/node_modules/@modelcontextprotocol/sdk/node_modules/jose/package.json +1 -1
  10. package/node_modules/@posthog/core/dist/featureFlagLocalEvaluation.d.ts.map +1 -1
  11. package/node_modules/@posthog/core/dist/featureFlagLocalEvaluation.js +17 -2
  12. package/node_modules/@posthog/core/dist/featureFlagLocalEvaluation.mjs +17 -2
  13. package/node_modules/@posthog/core/dist/logs/index.d.ts +18 -1
  14. package/node_modules/@posthog/core/dist/logs/index.d.ts.map +1 -1
  15. package/node_modules/@posthog/core/dist/logs/index.js +22 -3
  16. package/node_modules/@posthog/core/dist/logs/index.mjs +22 -3
  17. package/node_modules/@posthog/core/dist/metrics/index.d.ts +9 -0
  18. package/node_modules/@posthog/core/dist/metrics/index.d.ts.map +1 -1
  19. package/node_modules/@posthog/core/dist/metrics/index.js +13 -0
  20. package/node_modules/@posthog/core/dist/metrics/index.mjs +13 -0
  21. package/node_modules/@posthog/core/dist/privacy.d.ts +6 -1
  22. package/node_modules/@posthog/core/dist/privacy.d.ts.map +1 -1
  23. package/node_modules/@posthog/core/dist/privacy.js +69 -10
  24. package/node_modules/@posthog/core/dist/privacy.mjs +65 -9
  25. package/node_modules/@posthog/core/dist/traces/span.d.ts +6 -0
  26. package/node_modules/@posthog/core/dist/traces/span.d.ts.map +1 -1
  27. package/node_modules/@posthog/core/dist/traces/span.js +18 -0
  28. package/node_modules/@posthog/core/dist/traces/span.mjs +18 -0
  29. package/node_modules/@posthog/core/package.json +2 -2
  30. package/node_modules/@posthog/core/src/featureFlagLocalEvaluation.ts +23 -2
  31. package/node_modules/@posthog/core/src/logs/index.spec.ts +119 -0
  32. package/node_modules/@posthog/core/src/logs/index.ts +57 -3
  33. package/node_modules/@posthog/core/src/metrics/index.spec.ts +70 -0
  34. package/node_modules/@posthog/core/src/metrics/index.ts +30 -0
  35. package/node_modules/@posthog/core/src/privacy.ts +100 -18
  36. package/node_modules/@posthog/core/src/traces/span.spec.ts +15 -1
  37. package/node_modules/@posthog/core/src/traces/span.ts +23 -0
  38. package/node_modules/@posthog/types/dist/posthog-config.d.ts +4 -0
  39. package/node_modules/@posthog/types/dist/posthog-config.d.ts.map +1 -1
  40. package/node_modules/@posthog/types/dist/traces.d.ts +10 -0
  41. package/node_modules/@posthog/types/dist/traces.d.ts.map +1 -1
  42. package/node_modules/@posthog/types/package.json +1 -1
  43. package/node_modules/@posthog/types/src/posthog-config.ts +4 -0
  44. package/node_modules/@posthog/types/src/traces.ts +12 -0
  45. package/node_modules/@zuplo/core/LICENSE.third-party.txt +622 -0
  46. package/node_modules/@zuplo/core/LICENSE.txt +5 -78
  47. package/node_modules/@zuplo/core/README.md +7 -0
  48. package/node_modules/@zuplo/core/constants.minified.js +7 -20
  49. package/node_modules/@zuplo/core/customer.cli.minified.js +243 -256
  50. package/node_modules/@zuplo/core/index.minified.js +248 -261
  51. package/node_modules/@zuplo/core/package.json +4 -2
  52. package/node_modules/@zuplo/core/zeno.js +7 -20
  53. package/node_modules/@zuplo/graphql/LICENSE.third-party.txt +29 -0
  54. package/node_modules/@zuplo/graphql/LICENSE.txt +5 -78
  55. package/node_modules/@zuplo/graphql/README.md +7 -0
  56. package/node_modules/@zuplo/graphql/out/esm/index.js +7 -20
  57. package/node_modules/@zuplo/graphql/out/esm/index.js.map +1 -1
  58. package/node_modules/@zuplo/graphql/package.json +3 -2
  59. package/node_modules/@zuplo/openapi-tools/LICENSE.txt +7 -0
  60. package/node_modules/@zuplo/openapi-tools/README.md +7 -0
  61. package/node_modules/@zuplo/openapi-tools/package.json +3 -2
  62. package/node_modules/@zuplo/otel/LICENSE.third-party.txt +243 -0
  63. package/node_modules/@zuplo/otel/LICENSE.txt +5 -78
  64. package/node_modules/@zuplo/otel/README.md +33 -0
  65. package/node_modules/@zuplo/otel/out/esm/chunk-6YAK7LGJ.js +13 -0
  66. package/node_modules/@zuplo/otel/out/esm/chunk-6YAK7LGJ.js.map +1 -0
  67. package/node_modules/@zuplo/otel/out/esm/index.js +8 -21
  68. package/node_modules/@zuplo/otel/out/types/index.d.ts +41 -0
  69. package/node_modules/@zuplo/otel/package.json +3 -2
  70. package/node_modules/@zuplo/runtime/LICENSE.third-party.txt +511 -0
  71. package/node_modules/@zuplo/runtime/LICENSE.txt +5 -78
  72. package/node_modules/@zuplo/runtime/README.md +7 -0
  73. package/node_modules/@zuplo/runtime/out/esm/chunk-5JGLAPFA.js +13 -0
  74. package/node_modules/@zuplo/runtime/out/esm/chunk-5JGLAPFA.js.map +1 -0
  75. package/node_modules/@zuplo/runtime/out/esm/{chunk-SX6JF7A6.js → chunk-AJ3MMWJS.js} +9 -22
  76. package/node_modules/@zuplo/runtime/out/esm/chunk-AJ3MMWJS.js.map +1 -0
  77. package/node_modules/@zuplo/runtime/out/esm/chunk-BH4DKEES.js +13 -0
  78. package/node_modules/@zuplo/runtime/out/esm/chunk-BH4DKEES.js.map +1 -0
  79. package/node_modules/@zuplo/runtime/out/esm/chunk-G42UYZ6V.js +24 -0
  80. package/node_modules/@zuplo/runtime/out/esm/{chunk-M4IZPJP6.js.map → chunk-G42UYZ6V.js.map} +1 -1
  81. package/node_modules/@zuplo/runtime/out/esm/chunk-OE2WMJXK.js +431 -0
  82. package/node_modules/@zuplo/runtime/out/esm/chunk-OE2WMJXK.js.map +1 -0
  83. package/node_modules/@zuplo/runtime/out/esm/chunk-R6UNMRUU.js +13 -0
  84. package/node_modules/@zuplo/runtime/out/esm/chunk-R6UNMRUU.js.map +1 -0
  85. package/node_modules/@zuplo/runtime/out/esm/{chunk-GWGCD6Z7.js → chunk-T2WKOG7J.js} +9 -22
  86. package/node_modules/@zuplo/runtime/out/esm/chunk-T2WKOG7J.js.map +1 -0
  87. package/node_modules/@zuplo/runtime/out/esm/{chunk-HTXNM72E.js → chunk-TOJD4RET.js} +9 -22
  88. package/node_modules/@zuplo/runtime/out/esm/chunk-TOJD4RET.js.map +1 -0
  89. package/node_modules/@zuplo/runtime/out/esm/chunk-VXPFMOL5.js +13 -0
  90. package/node_modules/@zuplo/runtime/out/esm/chunk-VXPFMOL5.js.map +1 -0
  91. package/node_modules/@zuplo/runtime/out/esm/index.js +8 -21
  92. package/node_modules/@zuplo/runtime/out/esm/index.js.map +1 -1
  93. package/node_modules/@zuplo/runtime/out/esm/internal/index.js +8 -21
  94. package/node_modules/@zuplo/runtime/out/esm/mcp/messages/index.js +8 -21
  95. package/node_modules/@zuplo/runtime/out/esm/mcp-gateway/index.js +11 -39
  96. package/node_modules/@zuplo/runtime/out/esm/mcp-gateway/index.js.map +1 -1
  97. package/node_modules/@zuplo/runtime/out/esm/mocks/index.js +8 -21
  98. package/node_modules/@zuplo/runtime/out/esm/mocks/index.js.map +1 -1
  99. package/node_modules/@zuplo/runtime/out/esm/sdks/aws/index.js +8 -21
  100. package/node_modules/@zuplo/runtime/out/esm/sdks/aws/index.js.map +1 -1
  101. package/node_modules/@zuplo/runtime/out/types/index.d.ts +248 -6
  102. package/node_modules/@zuplo/runtime/out/types/internal/index.d.ts +101 -0
  103. package/node_modules/@zuplo/runtime/out/types/mcp-gateway/index.d.ts +127 -0
  104. package/node_modules/@zuplo/runtime/package.json +3 -2
  105. package/node_modules/express-rate-limit/dist/index.cjs +33 -4
  106. package/node_modules/express-rate-limit/dist/index.mjs +33 -4
  107. package/node_modules/express-rate-limit/package.json +1 -1
  108. package/package.json +12 -11
  109. package/node_modules/@zuplo/otel/out/esm/chunk-PVCAT62X.js +0 -26
  110. package/node_modules/@zuplo/otel/out/esm/chunk-PVCAT62X.js.map +0 -1
  111. package/node_modules/@zuplo/runtime/out/esm/chunk-A3QGJZO7.js +0 -26
  112. package/node_modules/@zuplo/runtime/out/esm/chunk-A3QGJZO7.js.map +0 -1
  113. package/node_modules/@zuplo/runtime/out/esm/chunk-F4G3YEN2.js +0 -429
  114. package/node_modules/@zuplo/runtime/out/esm/chunk-F4G3YEN2.js.map +0 -1
  115. package/node_modules/@zuplo/runtime/out/esm/chunk-GWGCD6Z7.js.map +0 -1
  116. package/node_modules/@zuplo/runtime/out/esm/chunk-HTXNM72E.js.map +0 -1
  117. package/node_modules/@zuplo/runtime/out/esm/chunk-M4IZPJP6.js +0 -37
  118. package/node_modules/@zuplo/runtime/out/esm/chunk-SX6JF7A6.js.map +0 -1
  119. package/node_modules/@zuplo/runtime/out/esm/chunk-TYV53J3B.js +0 -26
  120. package/node_modules/@zuplo/runtime/out/esm/chunk-TYV53J3B.js.map +0 -1
  121. package/node_modules/@zuplo/runtime/out/esm/chunk-UKQQD2JN.js +0 -26
  122. package/node_modules/@zuplo/runtime/out/esm/chunk-UKQQD2JN.js.map +0 -1
  123. package/node_modules/@zuplo/runtime/out/esm/chunk-VP5Q3DEN.js +0 -26
  124. package/node_modules/@zuplo/runtime/out/esm/chunk-VP5Q3DEN.js.map +0 -1
  125. /package/node_modules/@zuplo/runtime/out/esm/{chunk-M4IZPJP6.js.LEGAL.txt → chunk-G42UYZ6V.js.LEGAL.txt} +0 -0
  126. /package/node_modules/@zuplo/runtime/out/esm/{chunk-F4G3YEN2.js.LEGAL.txt → chunk-OE2WMJXK.js.LEGAL.txt} +0 -0
@@ -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
+ })
@@ -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
  }
@@ -59,6 +59,76 @@ describe('PostHogMetrics', () => {
59
59
  vi.useRealTimers()
60
60
  })
61
61
 
62
+ describe('flushCoalesced', () => {
63
+ it('keeps at most one send in flight and one queued behind it, and sends every sample', async () => {
64
+ let resolveSend!: (o: SendMetricsBatchOutcome) => void
65
+ mockInstance._sendMetricsBatch
66
+ .mockImplementationOnce(() => new Promise<SendMetricsBatchOutcome>((r) => (resolveSend = r)))
67
+ .mockResolvedValue({ kind: 'ok' })
68
+ const metrics = createMetrics()
69
+
70
+ metrics.count('requests', 1)
71
+ const first = metrics.flushCoalesced()
72
+ await Promise.resolve()
73
+ await Promise.resolve()
74
+ expect(mockInstance._sendMetricsBatch).toHaveBeenCalledTimes(1)
75
+
76
+ // Many requests finish while the first send is in flight: they share one queued flush.
77
+ const queued = [1, 2, 3, 4, 5].map(() => {
78
+ metrics.count('requests', 1)
79
+ return metrics.flushCoalesced()
80
+ })
81
+ expect(new Set(queued).size).toBe(1)
82
+
83
+ resolveSend({ kind: 'ok' })
84
+ await Promise.all([first, ...queued])
85
+ expect(mockInstance._sendMetricsBatch).toHaveBeenCalledTimes(2)
86
+ expect(sentMetrics().reduce((sum, m) => sum + m.sum!.dataPoints[0].asDouble!, 0)).toBe(6)
87
+ })
88
+
89
+ it('does not start a queued flush when the send it waited behind starts a backoff', async () => {
90
+ let resolveSend!: (o: SendMetricsBatchOutcome) => void
91
+ mockInstance._sendMetricsBatch
92
+ .mockImplementationOnce(() => new Promise<SendMetricsBatchOutcome>((r) => (resolveSend = r)))
93
+ .mockResolvedValue({ kind: 'ok' })
94
+ const metrics = createMetrics()
95
+
96
+ metrics.count('requests', 1)
97
+ const first = metrics.flushCoalesced()
98
+ await Promise.resolve()
99
+ await Promise.resolve()
100
+ metrics.count('requests', 1)
101
+ const queued = metrics.flushCoalesced()
102
+
103
+ resolveSend({ kind: 'retry-later', error: new Error('429'), retryAfterMs: 300_000 })
104
+ await Promise.all([first, queued])
105
+ expect(mockInstance._sendMetricsBatch).toHaveBeenCalledTimes(1)
106
+
107
+ // The retry timer delivers the retained samples once the backoff ends.
108
+ await vi.advanceTimersByTimeAsync(300_000)
109
+ expect(mockInstance._sendMetricsBatch).toHaveBeenCalledTimes(2)
110
+ const retried = sentPayloads()[1].resourceMetrics[0].scopeMetrics[0].metrics
111
+ expect(retried[0].sum!.dataPoints[0].asDouble).toBe(2)
112
+ })
113
+
114
+ it('does not send while a failed send is backing off', async () => {
115
+ mockInstance._sendMetricsBatch.mockResolvedValueOnce({
116
+ kind: 'retry-later',
117
+ error: new Error('429'),
118
+ retryAfterMs: 300_000,
119
+ })
120
+ const metrics = createMetrics()
121
+ metrics.count('requests', 1)
122
+ await metrics.flushCoalesced()
123
+ expect(mockInstance._sendMetricsBatch).toHaveBeenCalledTimes(1)
124
+
125
+ metrics.count('requests', 1)
126
+ await metrics.flushCoalesced()
127
+ await metrics.flushCoalesced()
128
+ expect(mockInstance._sendMetricsBatch).toHaveBeenCalledTimes(1)
129
+ })
130
+ })
131
+
62
132
  describe('aggregation semantics', () => {
63
133
  it('sums count samples for the same series into one delta data point', async () => {
64
134
  const metrics = createMetrics()
@@ -90,6 +90,8 @@ export class PostHogMetrics {
90
90
  // Serializes flushes — a manual flush() during an in-flight timer flush
91
91
  // queues behind it instead of racing it for the same window.
92
92
  private _flushPromise: Promise<void> | null = null
93
+ // The one flush `flushCoalesced()` has queued but not yet started.
94
+ private _queuedFlush: Promise<void> | null = null
93
95
  // One cardinality warning per window, however many series get dropped.
94
96
  private _seriesCapWarned = false
95
97
  // Type seen per metric name this window; reusing a name with a different
@@ -157,6 +159,33 @@ export class PostHogMetrics {
157
159
  return p
158
160
  }
159
161
 
162
+ /**
163
+ * A flush for callers that ask once per unit of work (a served request, say) rather than once per window.
164
+ * Callers share one queued flush, so at most one send is in flight and one waits behind it however often
165
+ * this is called, and every sample captured before the call is in one of them. While a failed send is
166
+ * backing off it starts nothing and the retry timer owns the next send.
167
+ */
168
+ flushCoalesced(): Promise<void> {
169
+ if (this._isBackingOff()) {
170
+ return this._flushPromise ?? Promise.resolve()
171
+ }
172
+ if (!this._queuedFlush) {
173
+ // Starts after any send in flight, so samples captured while it runs are in this one.
174
+ this._queuedFlush = (this._flushPromise ?? Promise.resolve())
175
+ .catch(() => {})
176
+ .then(() => {
177
+ this._queuedFlush = null
178
+ // The send it waited behind may have failed and started a backoff.
179
+ return this._isBackingOff() ? undefined : this.flush()
180
+ })
181
+ }
182
+ return this._queuedFlush
183
+ }
184
+
185
+ private _isBackingOff(): boolean {
186
+ return this._consecutiveFlushFailures > 0 || this._retryAfter.remainingMs() > 0
187
+ }
188
+
160
189
  /**
161
190
  * Synchronously snapshots the current window into an OTLP payload and
162
191
  * resets it, bypassing the flush serializer entirely — for unload-time
@@ -181,6 +210,7 @@ export class PostHogMetrics {
181
210
  this._flushJitter = NO_JITTER
182
211
  this._flushTimer.clear()
183
212
  this._flushPromise = null
213
+ this._queuedFlush = null
184
214
  this._startWindow()
185
215
  this._boundsByHistogram = new Map()
186
216
  this._boundsCapWarned = false
@@ -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
  }
@@ -1712,6 +1712,10 @@ export interface PostHogConfig {
1712
1712
  * If this is set to `true`, PostHog will set `$browser_type` to either `bot` or `browser` for all events,
1713
1713
  * but will process all events as if they were from a browser.
1714
1714
  *
1715
+ * When the filter drops events, a one-time warning is written to the console (even without debug mode).
1716
+ * The filter applies to events only; logs sent with `captureLog` bypass it.
1717
+ * Set this to `true` behind a test flag for end-to-end tests (Playwright, Puppeteer).
1718
+ *
1715
1719
  * @default false
1716
1720
  */
1717
1721
  opt_out_useragent_filter: boolean;