@posthog/core 1.69.9 → 1.71.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 (122) hide show
  1. package/capture-v1/package.json +6 -0
  2. package/dist/capture-v1/compression.d.ts +18 -0
  3. package/dist/capture-v1/compression.d.ts.map +1 -0
  4. package/dist/capture-v1/compression.js +70 -0
  5. package/dist/capture-v1/compression.mjs +26 -0
  6. package/dist/capture-v1/errors.d.ts +48 -0
  7. package/dist/capture-v1/errors.d.ts.map +1 -0
  8. package/dist/capture-v1/errors.js +82 -0
  9. package/dist/capture-v1/errors.mjs +38 -0
  10. package/dist/capture-v1/index.d.ts +15 -0
  11. package/dist/capture-v1/index.d.ts.map +1 -0
  12. package/dist/capture-v1/index.js +88 -0
  13. package/dist/capture-v1/index.mjs +7 -0
  14. package/dist/capture-v1/sender.d.ts +150 -0
  15. package/dist/capture-v1/sender.d.ts.map +1 -0
  16. package/dist/capture-v1/sender.js +554 -0
  17. package/dist/capture-v1/sender.mjs +507 -0
  18. package/dist/capture-v1/serialize.d.ts +30 -0
  19. package/dist/capture-v1/serialize.d.ts.map +1 -0
  20. package/dist/capture-v1/serialize.js +106 -0
  21. package/dist/capture-v1/serialize.mjs +59 -0
  22. package/dist/capture-v1/transform.d.ts +19 -0
  23. package/dist/capture-v1/transform.d.ts.map +1 -0
  24. package/dist/capture-v1/transform.js +118 -0
  25. package/dist/capture-v1/transform.mjs +77 -0
  26. package/dist/capture-v1/types.d.ts +52 -0
  27. package/dist/capture-v1/types.d.ts.map +1 -0
  28. package/dist/capture-v1/types.js +44 -0
  29. package/dist/capture-v1/types.mjs +3 -0
  30. package/dist/capture-v1/uuid.d.ts +9 -0
  31. package/dist/capture-v1/uuid.d.ts.map +1 -0
  32. package/dist/capture-v1/uuid.js +75 -0
  33. package/dist/capture-v1/uuid.mjs +34 -0
  34. package/dist/featureFlagLocalEvaluation.d.ts +2 -0
  35. package/dist/featureFlagLocalEvaluation.d.ts.map +1 -1
  36. package/dist/featureFlagLocalEvaluation.js +38 -0
  37. package/dist/featureFlagLocalEvaluation.mjs +38 -0
  38. package/dist/featureFlagUtils.d.ts +7 -5
  39. package/dist/featureFlagUtils.d.ts.map +1 -1
  40. package/dist/featureFlagUtils.js +17 -11
  41. package/dist/featureFlagUtils.mjs +14 -11
  42. package/dist/index.d.ts +1 -1
  43. package/dist/index.d.ts.map +1 -1
  44. package/dist/index.js +27 -16
  45. package/dist/index.mjs +1 -1
  46. package/dist/posthog-core-stateless.d.ts +44 -7
  47. package/dist/posthog-core-stateless.d.ts.map +1 -1
  48. package/dist/posthog-core-stateless.js +103 -24
  49. package/dist/posthog-core-stateless.mjs +103 -24
  50. package/dist/posthog-core.d.ts +138 -53
  51. package/dist/posthog-core.d.ts.map +1 -1
  52. package/dist/posthog-core.js +341 -115
  53. package/dist/posthog-core.mjs +338 -115
  54. package/dist/types.d.ts +33 -1
  55. package/dist/types.d.ts.map +1 -1
  56. package/dist/utils/index.d.ts +1 -1
  57. package/dist/utils/index.d.ts.map +1 -1
  58. package/dist/utils/index.js +25 -12
  59. package/dist/utils/index.mjs +1 -1
  60. package/dist/utils/json-utils.d.ts +11 -1
  61. package/dist/utils/json-utils.d.ts.map +1 -1
  62. package/dist/utils/json-utils.js +50 -2
  63. package/dist/utils/json-utils.mjs +46 -1
  64. package/package.json +13 -3
  65. package/src/capture-v1/compression.ts +50 -0
  66. package/src/capture-v1/errors.ts +91 -0
  67. package/src/capture-v1/index.ts +34 -0
  68. package/src/capture-v1/sender.ts +779 -0
  69. package/src/capture-v1/serialize.ts +113 -0
  70. package/src/capture-v1/transform.ts +135 -0
  71. package/src/capture-v1/types.ts +59 -0
  72. package/src/capture-v1/uuid.ts +53 -0
  73. package/src/featureFlagLocalEvaluation.ts +51 -0
  74. package/src/featureFlagUtils.ts +22 -10
  75. package/src/index.ts +1 -0
  76. package/src/posthog-core-stateless.ts +190 -35
  77. package/src/posthog-core.ts +615 -178
  78. package/src/types.ts +31 -1
  79. package/src/utils/index.ts +1 -1
  80. package/src/utils/json-utils.ts +64 -1
  81. package/src/error-tracking/chunk-ids.spec.ts +0 -77
  82. package/src/error-tracking/coercers/error-event-coercer.spec.ts +0 -142
  83. package/src/error-tracking/coercers/promise-rejection-event.spec.ts +0 -77
  84. package/src/error-tracking/coercers/string-coercer.spec.ts +0 -26
  85. package/src/error-tracking/error-properties-builder.aggregate-errors.spec.ts +0 -412
  86. package/src/error-tracking/error-properties-builder.coerce.spec.ts +0 -337
  87. package/src/error-tracking/error-properties-builder.metadata.spec.ts +0 -318
  88. package/src/error-tracking/error-properties-builder.parse.spec.ts +0 -37
  89. package/src/error-tracking/exception-steps.spec.ts +0 -115
  90. package/src/error-tracking/parsers/base.spec.ts +0 -156
  91. package/src/error-tracking/parsers/index.spec.ts +0 -270
  92. package/src/error-tracking/parsers/node.spec.ts +0 -34
  93. package/src/error-tracking/release.spec.ts +0 -34
  94. package/src/logs/index.spec.ts +0 -2421
  95. package/src/logs/logs-utils.spec.ts +0 -266
  96. package/src/metrics/index.spec.ts +0 -1249
  97. package/src/surveys/activation.spec.ts +0 -61
  98. package/src/surveys/events.spec.ts +0 -183
  99. package/src/surveys/keys.spec.ts +0 -29
  100. package/src/surveys/property-matching.spec.ts +0 -539
  101. package/src/surveys/shuffling.spec.ts +0 -51
  102. package/src/surveys/translations.spec.ts +0 -274
  103. package/src/surveys/validation.spec.ts +0 -168
  104. package/src/traces/config.spec.ts +0 -271
  105. package/src/traces/ids.spec.ts +0 -115
  106. package/src/traces/index.spec.ts +0 -3287
  107. package/src/traces/live-spans.spec.ts +0 -69
  108. package/src/traces/otlp.spec.ts +0 -368
  109. package/src/traces/span.spec.ts +0 -1137
  110. package/src/traces/traceparent.spec.ts +0 -184
  111. package/src/utils/bot-detection.spec.ts +0 -107
  112. package/src/utils/bucketed-rate-limiter.spec.ts +0 -327
  113. package/src/utils/json-utils.spec.ts +0 -115
  114. package/src/utils/named-error.spec.ts +0 -36
  115. package/src/utils/number-utils.spec.ts +0 -212
  116. package/src/utils/otlp-any-value.spec.ts +0 -376
  117. package/src/utils/otlp-resource.spec.ts +0 -171
  118. package/src/utils/promise-queue.spec.ts +0 -55
  119. package/src/utils/string-utils.spec.ts +0 -158
  120. package/src/utils/type-utils.spec.ts +0 -38
  121. package/src/utils/webview-app-utils.spec.ts +0 -118
  122. package/src/vendor/uuidv7.spec.ts +0 -26
@@ -1,376 +0,0 @@
1
- import type { LogAttributeValue } from '@posthog/types'
2
- import { toOtlpAnyValue, toOtlpKeyValueList } from './otlp-any-value'
3
-
4
- describe('otlp-any-value', () => {
5
- describe('toOtlpAnyValue', () => {
6
- it('converts strings', () => {
7
- expect(toOtlpAnyValue('hello')).toEqual({ stringValue: 'hello' })
8
- })
9
-
10
- it('converts integers to decimal strings', () => {
11
- expect(toOtlpAnyValue(42)).toEqual({ intValue: '42' })
12
- expect(toOtlpAnyValue(0)).toEqual({ intValue: '0' })
13
- expect(toOtlpAnyValue(-7)).toEqual({ intValue: '-7' })
14
- })
15
-
16
- // Spec: outside int64 it is a stringValue, never an intValue.
17
- it('converts integers outside int64 to stringValue', () => {
18
- expect(toOtlpAnyValue(2 ** 63)).toEqual({ stringValue: '9223372036854775808' })
19
- expect(toOtlpAnyValue(-(2 ** 64))).toEqual({ stringValue: '-18446744073709551616' })
20
- expect(toOtlpAnyValue(1e21)).toEqual({ stringValue: '1000000000000000000000' })
21
- })
22
-
23
- it('logs a debug line when an integer falls outside int64', () => {
24
- const logger = { debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn(), critical: vi.fn() }
25
- toOtlpAnyValue(2 ** 63, logger as any)
26
- expect(logger.debug).toHaveBeenCalledWith(expect.stringContaining('outside the int64 range'))
27
- })
28
-
29
- it('keeps int64 min as intValue', () => {
30
- // In range, but `String` renders it 192 below int64 min, so the decimal
31
- // has to come from BigInt.
32
- expect(toOtlpAnyValue(-(2 ** 63))).toEqual({ intValue: '-9223372036854775808' })
33
- })
34
-
35
- it('keeps large in-range integers exact', () => {
36
- expect(toOtlpAnyValue(Number.MAX_SAFE_INTEGER)).toEqual({ intValue: '9007199254740991' })
37
- // The largest double below 2^63 — no double exists between the two.
38
- expect(toOtlpAnyValue(9223372036854774784)).toEqual({ intValue: '9223372036854774784' })
39
- expect(toOtlpAnyValue(2 ** 62)).toEqual({ intValue: '4611686018427387904' })
40
- })
41
-
42
- it('converts a bigint inside int64 to a stringified intValue', () => {
43
- // Span attributes accept bigint; a log attribute reaching here is typed
44
- // out but still encodes correctly.
45
- expect(toOtlpAnyValue(9007199254740993n as unknown as LogAttributeValue)).toEqual({
46
- intValue: '9007199254740993',
47
- })
48
- })
49
-
50
- it('converts a bigint beyond int64 to a string, with a warning', () => {
51
- const logger = { debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn(), critical: vi.fn() }
52
- expect(toOtlpAnyValue(18446744073709551616n as unknown as LogAttributeValue, logger as any)).toEqual({
53
- stringValue: '18446744073709551616',
54
- })
55
- expect(logger.debug).toHaveBeenCalled()
56
- })
57
-
58
- it('converts floats to doubleValue', () => {
59
- expect(toOtlpAnyValue(3.14)).toEqual({ doubleValue: 3.14 })
60
- })
61
-
62
- it('converts booleans', () => {
63
- expect(toOtlpAnyValue(true)).toEqual({ boolValue: true })
64
- expect(toOtlpAnyValue(false)).toEqual({ boolValue: false })
65
- })
66
-
67
- // JSON has no representation for non-finite floats; without explicit
68
- // handling, JSON.stringify silently turns them into `null` and the value
69
- // is lost server-side.
70
- it('converts NaN to stringValue', () => {
71
- expect(toOtlpAnyValue(NaN)).toEqual({ stringValue: 'NaN' })
72
- })
73
-
74
- it('converts +Infinity to stringValue', () => {
75
- expect(toOtlpAnyValue(Infinity)).toEqual({ stringValue: 'Infinity' })
76
- })
77
-
78
- it('converts -Infinity to stringValue', () => {
79
- expect(toOtlpAnyValue(-Infinity)).toEqual({ stringValue: '-Infinity' })
80
- })
81
-
82
- it('converts arrays of strings to arrayValue', () => {
83
- expect(toOtlpAnyValue(['a', 'b'])).toEqual({
84
- arrayValue: { values: [{ stringValue: 'a' }, { stringValue: 'b' }] },
85
- })
86
- })
87
-
88
- it('converts mixed primitive arrays recursively', () => {
89
- expect(toOtlpAnyValue([1, 'x', true])).toEqual({
90
- arrayValue: {
91
- values: [{ intValue: '1' }, { stringValue: 'x' }, { boolValue: true }],
92
- },
93
- })
94
- })
95
-
96
- it('converts plain objects to kvlistValue', () => {
97
- expect(toOtlpAnyValue({ a: 1, b: 'two' })).toEqual({
98
- kvlistValue: {
99
- values: [
100
- { key: 'a', value: { intValue: '1' } },
101
- { key: 'b', value: { stringValue: 'two' } },
102
- ],
103
- },
104
- })
105
- })
106
-
107
- it('converts nested objects recursively', () => {
108
- expect(toOtlpAnyValue({ outer: { inner: 1 } })).toEqual({
109
- kvlistValue: {
110
- values: [
111
- {
112
- key: 'outer',
113
- value: { kvlistValue: { values: [{ key: 'inner', value: { intValue: '1' } }] } },
114
- },
115
- ],
116
- },
117
- })
118
- })
119
-
120
- it('drops null and undefined keys inside objects', () => {
121
- expect(toOtlpAnyValue({ kept: 1, gone: null, alsoGone: undefined })).toEqual({
122
- kvlistValue: { values: [{ key: 'kept', value: { intValue: '1' } }] },
123
- })
124
- })
125
-
126
- // Not in LogAttributeValue, but reachable at runtime from untyped callers.
127
- it('encodes Dates as ISO strings', () => {
128
- expect(toOtlpAnyValue(new Date('2026-08-20T10:00:00.000Z') as unknown as LogAttributeValue)).toEqual({
129
- stringValue: '2026-08-20T10:00:00.000Z',
130
- })
131
- })
132
-
133
- it('marks circular references instead of recursing', () => {
134
- const cyclic: Record<string, unknown> = { name: 'root' }
135
- cyclic.self = cyclic
136
- expect(toOtlpAnyValue(cyclic)).toEqual({
137
- kvlistValue: {
138
- values: [
139
- { key: 'name', value: { stringValue: 'root' } },
140
- { key: 'self', value: { stringValue: '[Circular]' } },
141
- ],
142
- },
143
- })
144
- })
145
-
146
- // An escaping error would surface in the caller's application code.
147
- it('does not throw on an object nested past the depth cap', () => {
148
- let deep: Record<string, unknown> = { end: true }
149
- for (let i = 0; i < 25000; i++) {
150
- deep = { next: deep }
151
- }
152
- expect(() => toOtlpAnyValue(deep)).not.toThrow()
153
- })
154
-
155
- it('truncates at exactly 20 levels instead of recursing', () => {
156
- let deep: Record<string, unknown> = { end: true }
157
- for (let i = 0; i < 25; i++) {
158
- deep = { next: deep }
159
- }
160
- const encoded = JSON.stringify(toOtlpAnyValue(deep))
161
- expect(encoded).toContain('[Truncated]')
162
- expect(encoded.split('"next"').length - 1).toBe(20)
163
- })
164
-
165
- it('marks a throwing getter without losing the rest of the object', () => {
166
- const attrs = {
167
- ok: 1,
168
- get bad(): number {
169
- throw new Error('getter blew up')
170
- },
171
- }
172
- expect(() => toOtlpKeyValueList(attrs)).not.toThrow()
173
- expect(toOtlpKeyValueList(attrs)).toEqual([
174
- { key: 'ok', value: { intValue: '1' } },
175
- { key: 'bad', value: { stringValue: '[Unserializable]' } },
176
- ])
177
- })
178
-
179
- // for...in walks the prototype chain once own keys are exhausted.
180
- it('ignores inherited enumerable properties', () => {
181
- const inherited: Record<string, unknown> = Object.create({ fromPrototype: 'leaked' })
182
- inherited.own = 1
183
- expect(toOtlpAnyValue(inherited)).toEqual({
184
- kvlistValue: { values: [{ key: 'own', value: { intValue: '1' } }] },
185
- })
186
- })
187
-
188
- // `String(fn)` would put the function's source text on the wire.
189
- it('marks function and symbol values instead of stringifying them', () => {
190
- expect(toOtlpAnyValue({ handler: () => 1, retries: 2 } as unknown as LogAttributeValue)).toEqual({
191
- kvlistValue: {
192
- values: [
193
- { key: 'handler', value: { stringValue: '[Function]' } },
194
- { key: 'retries', value: { intValue: '2' } },
195
- ],
196
- },
197
- })
198
- expect(toOtlpAnyValue({ sym: Symbol('x') } as unknown as LogAttributeValue)).toEqual({
199
- kvlistValue: { values: [{ key: 'sym', value: { stringValue: 'Symbol(x)' } }] },
200
- })
201
- })
202
-
203
- // dayjs, Decimal, ORM documents.
204
- it('honours toJSON', () => {
205
- const wrapped = { toJSON: () => ({ amount: 5 }) }
206
- expect(toOtlpAnyValue(wrapped as unknown as LogAttributeValue)).toEqual({
207
- kvlistValue: { values: [{ key: 'amount', value: { intValue: '5' } }] },
208
- })
209
- })
210
-
211
- it('falls back to the plain walk when toJSON throws', () => {
212
- const wrapped = {
213
- kept: 1,
214
- toJSON: () => {
215
- throw new Error('nope')
216
- },
217
- }
218
- expect(toOtlpAnyValue(wrapped as unknown as LogAttributeValue)).toEqual({
219
- kvlistValue: {
220
- values: [
221
- { key: 'kept', value: { intValue: '1' } },
222
- { key: 'toJSON', value: { stringValue: '[Function]' } },
223
- ],
224
- },
225
- })
226
- })
227
-
228
- // A toJSON returning its own object is a cycle like any other.
229
- it('marks a cycle that runs through toJSON', () => {
230
- const cyclic: Record<string, unknown> = {}
231
- cyclic.toJSON = () => ({ inner: cyclic })
232
- expect(toOtlpAnyValue(cyclic)).toEqual({
233
- kvlistValue: { values: [{ key: 'inner', value: { stringValue: '[Circular]' } }] },
234
- })
235
- })
236
-
237
- // Both `null` and `{}` here are rejected for the whole request; iOS and
238
- // Android drop them too.
239
- it('drops holes and nullish elements from arrays', () => {
240
- // oxlint-disable-next-line no-sparse-arrays
241
- expect(toOtlpAnyValue([1, , 3])).toEqual({
242
- arrayValue: { values: [{ intValue: '1' }, { intValue: '3' }] },
243
- })
244
- expect(toOtlpAnyValue([1, null, undefined, 3])).toEqual({
245
- arrayValue: { values: [{ intValue: '1' }, { intValue: '3' }] },
246
- })
247
- })
248
-
249
- it('stops encoding array items once the node budget is spent', () => {
250
- const row: Record<string, number> = {}
251
- for (let i = 0; i < 20; i++) {
252
- row[`k${i}`] = i
253
- }
254
- const wide = Array.from({ length: 1000 }, () => ({ ...row }))
255
- const values = toOtlpAnyValue(wide).arrayValue!.values
256
- expect(values[values.length - 1]).toEqual({ stringValue: '[Truncated]' })
257
- // One marker, not one per unencodable item.
258
- expect(values.filter((v) => v.stringValue === '[Truncated]')).toHaveLength(1)
259
- })
260
-
261
- it('caps a shared object graph instead of expanding it', () => {
262
- let graph: Record<string, unknown> = { leaf: true }
263
- for (let i = 0; i < 20; i++) {
264
- graph = { a: graph, b: graph }
265
- }
266
- const encoded = JSON.stringify(toOtlpAnyValue(graph))
267
- expect(encoded).toContain('[Truncated]')
268
- expect(encoded.length).toBeLessThan(1_000_000)
269
- })
270
-
271
- it('caps a very wide object without inventing an attribute key', () => {
272
- const wide: Record<string, number> = {}
273
- for (let i = 0; i < 5000; i++) {
274
- wide[`k${i}`] = i
275
- }
276
- const logger = { debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn(), critical: vi.fn() }
277
- const values = toOtlpAnyValue(wide, logger as any).kvlistValue!.values
278
- expect(values).toHaveLength(1000)
279
- expect(values.every((v) => v.key.startsWith('k'))).toBe(true)
280
- expect(logger.debug).toHaveBeenCalledWith(expect.stringContaining('truncated'))
281
- })
282
-
283
- // Why the encoder does not delegate to toJsonSafeValue: that maps them to null.
284
- it('keeps non-finite floats as strings inside nested objects', () => {
285
- expect(toOtlpAnyValue({ nested: { ratio: NaN } })).toEqual({
286
- kvlistValue: {
287
- values: [
288
- {
289
- key: 'nested',
290
- value: { kvlistValue: { values: [{ key: 'ratio', value: { stringValue: 'NaN' } }] } },
291
- },
292
- ],
293
- },
294
- })
295
- })
296
-
297
- // A lone surrogate survives JSON.stringify as a \uD800 escape, which the
298
- // server rejects for the whole request.
299
- it('replaces unpaired surrogates in values and keys', () => {
300
- expect(toOtlpAnyValue('ok\ud83d')).toEqual({ stringValue: 'ok\ufffd' })
301
- expect(toOtlpAnyValue({ nested: 'ok\ud83d' })).toEqual({
302
- kvlistValue: { values: [{ key: 'nested', value: { stringValue: 'ok\ufffd' } }] },
303
- })
304
- expect(toOtlpKeyValueList({ 'key\ud83d': 1 })).toEqual([{ key: 'key\ufffd', value: { intValue: '1' } }])
305
- })
306
-
307
- it('encodes empty containers with an explicit values array', () => {
308
- expect(toOtlpAnyValue({})).toEqual({ kvlistValue: { values: [] } })
309
- expect(toOtlpAnyValue([])).toEqual({ arrayValue: { values: [] } })
310
- })
311
-
312
- it('keeps a Date whose toISOString is overridden out of the wire format', () => {
313
- const broken = new Date('2026-08-20T10:00:00.000Z')
314
-
315
- ;(broken as any).toISOString = () => ({})
316
- expect(typeof toOtlpAnyValue(broken as unknown as LogAttributeValue).stringValue).toBe('string')
317
- })
318
-
319
- it('encodes sibling references to one object twice, not as circular', () => {
320
- const shared = { id: 1 }
321
- expect(toOtlpAnyValue({ a: shared, b: shared })).toEqual({
322
- kvlistValue: {
323
- values: [
324
- { key: 'a', value: { kvlistValue: { values: [{ key: 'id', value: { intValue: '1' } }] } } },
325
- { key: 'b', value: { kvlistValue: { values: [{ key: 'id', value: { intValue: '1' } }] } } },
326
- ],
327
- },
328
- })
329
- })
330
- })
331
-
332
- describe('toOtlpKeyValueList', () => {
333
- it('converts a record to key-value list', () => {
334
- expect(
335
- toOtlpKeyValueList({
336
- name: 'test',
337
- count: 5,
338
- active: true,
339
- })
340
- ).toEqual([
341
- { key: 'name', value: { stringValue: 'test' } },
342
- { key: 'count', value: { intValue: '5' } },
343
- { key: 'active', value: { boolValue: true } },
344
- ])
345
- })
346
-
347
- it('handles empty record', () => {
348
- expect(toOtlpKeyValueList({})).toEqual([])
349
- })
350
-
351
- it('skips null and undefined values', () => {
352
- expect(
353
- toOtlpKeyValueList({
354
- kept: 'yes',
355
- nullish: null,
356
- missing: undefined,
357
- })
358
- ).toEqual([{ key: 'kept', value: { stringValue: 'yes' } }])
359
- })
360
-
361
- it('skips an empty key, which OTLP does not allow', () => {
362
- expect(toOtlpKeyValueList({ '': 'nameless', kept: 'yes' })).toEqual([
363
- { key: 'kept', value: { stringValue: 'yes' } },
364
- ])
365
- })
366
-
367
- it('skips an empty key nested inside a value', () => {
368
- expect(toOtlpKeyValueList({ outer: { '': 'nameless', kept: 'yes' } })).toEqual([
369
- {
370
- key: 'outer',
371
- value: { kvlistValue: { values: [{ key: 'kept', value: { stringValue: 'yes' } }] } },
372
- },
373
- ])
374
- })
375
- })
376
- })
@@ -1,171 +0,0 @@
1
- import { buildOtlpLogsPayload, buildResourceAttributes } from '../logs/logs-utils'
2
- import type { ResolvedPostHogLogsConfig } from '../logs/types'
3
- import { buildMetricsResourceAttributes, buildOtlpMetricsPayload } from '../metrics/metrics-utils'
4
- import type { ResolvedPostHogMetricsConfig } from '../metrics/types'
5
- import { buildOtlpTracesPayload, buildTracesResourceAttributes } from '../traces/otlp'
6
- import type { ResolvedTracesConfig } from '../traces/types'
7
- import { normalizeOsName, osResourceAttributes } from './otlp-resource'
8
-
9
- const shared = {
10
- serviceName: 'checkout',
11
- serviceVersion: '2.1.0',
12
- environment: 'production',
13
- resourceAttributes: { 'host.name': 'web-01' },
14
- }
15
-
16
- const conflicting = {
17
- serviceName: 'checkout',
18
- serviceVersion: '2.1.0',
19
- environment: 'production',
20
- resourceAttributes: {
21
- 'service.name': 'hijacked',
22
- 'service.version': '0.0.0',
23
- 'deployment.environment': 'hijacked-env',
24
- 'telemetry.sdk.name': 'hijacked-sdk',
25
- 'telemetry.sdk.version': '0.0.0',
26
- 'host.name': 'web-01',
27
- },
28
- }
29
-
30
- const allThree = (partial: object): Record<string, unknown>[] => [
31
- buildResourceAttributes(partial as ResolvedPostHogLogsConfig, 'posthog-node', '1.0.0'),
32
- buildMetricsResourceAttributes(partial as ResolvedPostHogMetricsConfig, 'posthog-node', '1.0.0'),
33
- buildTracesResourceAttributes(partial as ResolvedTracesConfig, 'posthog-node', '1.0.0'),
34
- ]
35
-
36
- describe('shared OTLP resource attributes', () => {
37
- it.each([
38
- ['a fully populated config', shared],
39
- ['a config with conflicting user attributes', conflicting],
40
- ['an empty config', {}],
41
- ])('produces the same attributes for logs, metrics and traces given %s', (_label, config) => {
42
- const [logs, metrics, traces] = allThree(config)
43
- expect(metrics).toEqual(logs)
44
- expect(traces).toEqual(logs)
45
- expect(Object.keys(metrics)).toEqual(Object.keys(logs))
46
- expect(Object.keys(traces)).toEqual(Object.keys(logs))
47
- })
48
-
49
- it('layers the identity keys over user resource attributes', () => {
50
- for (const attributes of allThree(conflicting)) {
51
- expect(attributes).toEqual({
52
- 'service.name': 'checkout',
53
- 'service.version': '2.1.0',
54
- 'deployment.environment': 'production',
55
- 'telemetry.sdk.name': 'posthog-node',
56
- 'telemetry.sdk.version': '1.0.0',
57
- 'host.name': 'web-01',
58
- })
59
- }
60
- })
61
-
62
- it('keeps user resource attributes that do not collide', () => {
63
- for (const attributes of allThree(shared)) {
64
- expect(attributes).toEqual({
65
- 'host.name': 'web-01',
66
- 'service.name': 'checkout',
67
- 'deployment.environment': 'production',
68
- 'service.version': '2.1.0',
69
- 'telemetry.sdk.name': 'posthog-node',
70
- 'telemetry.sdk.version': '1.0.0',
71
- })
72
- }
73
- })
74
-
75
- it('falls back to unknown_service and omits unset optional keys', () => {
76
- for (const attributes of allThree({})) {
77
- expect(attributes).toEqual({
78
- 'service.name': 'unknown_service',
79
- 'telemetry.sdk.name': 'posthog-node',
80
- 'telemetry.sdk.version': '1.0.0',
81
- })
82
- }
83
- })
84
-
85
- it.each([
86
- ['a named key', 'payload'],
87
- // Integer-like keys enumerate ahead of every string key, whatever the insertion order.
88
- ['an integer-like key', '0'],
89
- ])('keeps the identity keys when %s exhausts the encoder budget', (_label, key) => {
90
- const identity = { serviceName: 'checkout', serviceVersion: '2.1.0', environment: 'production' }
91
- const [logs, metrics, traces] = allThree({
92
- ...identity,
93
- resourceAttributes: { [key]: Array.from({ length: 10 }, () => Array(1000).fill(1)) },
94
- })
95
- const encoded = [
96
- buildOtlpLogsPayload([], logs as any, 's', '1').resourceLogs[0].resource.attributes,
97
- buildOtlpMetricsPayload([], metrics as any, 's', '1').resourceMetrics[0].resource.attributes,
98
- buildOtlpTracesPayload([], traces as any, 's', '1').resourceSpans[0].resource.attributes,
99
- ]
100
- // Every key the builder sets on its own, so one added there without being
101
- // reserved fails here.
102
- const sdkSet = Object.entries(
103
- buildTracesResourceAttributes(identity as ResolvedTracesConfig, 'posthog-node', '1.0.0')
104
- )
105
- expect(sdkSet.map(([sdkKey]) => sdkKey)).toEqual([
106
- 'service.name',
107
- 'deployment.environment',
108
- 'service.version',
109
- 'telemetry.sdk.name',
110
- 'telemetry.sdk.version',
111
- ])
112
- for (const attributes of encoded) {
113
- expect(attributes.map((attribute) => attribute.key)).toEqual([key, ...sdkSet.map(([sdkKey]) => sdkKey)])
114
- for (const [sdkKey, sdkValue] of sdkSet) {
115
- expect(attributes).toContainEqual({ key: sdkKey, value: { stringValue: sdkValue } })
116
- }
117
- }
118
- })
119
- })
120
-
121
- describe('osResourceAttributes', () => {
122
- it.each([
123
- // node:os platform() identifiers rather than os.name values
124
- ['darwin', 'macOS'],
125
- ['win32', 'Windows'],
126
- ['linux', 'Linux'],
127
- ['android', 'Android'],
128
- ['freebsd', 'FreeBSD'],
129
- ['openbsd', 'OpenBSD'],
130
- ['netbsd', 'NetBSD'],
131
- ['sunos', 'SunOS'],
132
- ['aix', 'AIX'],
133
- ['haiku', 'Haiku'],
134
- ['cygwin', 'Windows'],
135
- // detectOS spellings
136
- ['Mac OS X', 'macOS'],
137
- ['iOS', 'iOS'],
138
- ['Android', 'Android'],
139
- ['Windows', 'Windows'],
140
- ['Linux', 'Linux'],
141
- ])('normalizes %s to %s', (raw, expected) => {
142
- expect(normalizeOsName(raw)).toBe(expected)
143
- })
144
-
145
- it('passes an unmapped name through rather than dropping it', () => {
146
- expect(normalizeOsName('Plan 9')).toBe('Plan 9')
147
- expect(normalizeOsName('constructor')).toBe('constructor')
148
- })
149
-
150
- it.each([undefined, ''])('returns undefined for %p', (raw) => {
151
- expect(normalizeOsName(raw)).toBeUndefined()
152
- })
153
-
154
- it('agrees with the names posthog-ios and posthog-android already send', () => {
155
- // Both SDKs ship these values today; a divergence here splits one filter in two.
156
- expect(normalizeOsName('darwin')).toBe('macOS')
157
- expect(normalizeOsName('Mac OS X')).toBe('macOS')
158
- expect(normalizeOsName('iOS')).toBe('iOS')
159
- expect(normalizeOsName('Android')).toBe('Android')
160
- })
161
-
162
- it('omits either key rather than emitting it empty', () => {
163
- expect(osResourceAttributes('darwin', undefined)).toEqual({ 'os.name': 'macOS' })
164
- expect(osResourceAttributes(undefined, '14.0')).toEqual({ 'os.version': '14.0' })
165
- expect(osResourceAttributes('', '')).toEqual({})
166
- expect(osResourceAttributes('win32', '10.0.26100')).toEqual({
167
- 'os.name': 'Windows',
168
- 'os.version': '10.0.26100',
169
- })
170
- })
171
- })
@@ -1,55 +0,0 @@
1
- import { PromiseQueue } from './promise-queue'
2
-
3
- function buildPromise(time: number): Promise<number> {
4
- return new Promise((res, rej) => setTimeout(() => res(42), time))
5
- }
6
-
7
- function buildRecursivePromise(time: number, cb: () => void) {
8
- return new Promise((res, rej) => {
9
- setTimeout(() => {
10
- cb()
11
- res(42)
12
- }, time)
13
- })
14
- }
15
-
16
- describe('promise-queue', () => {
17
- beforeAll(() => vi.useRealTimers())
18
- afterAll(() => vi.useFakeTimers())
19
-
20
- it('should exit directly if the queue is empty', async () => {
21
- const queue = new PromiseQueue()
22
- expect(queue.length).toBe(0)
23
- expect(queue.join()).resolves.toBe(undefined)
24
- })
25
-
26
- it('should add a promise to the queue', async () => {
27
- const queue = new PromiseQueue()
28
- queue.add(buildPromise(100))
29
- expect(queue.length).toBe(1)
30
- await queue.join()
31
- expect(queue.length).toBe(0)
32
- })
33
-
34
- it('should wait even when promises create other promises', async () => {
35
- const queue = new PromiseQueue()
36
- const addSpy = vi.spyOn(queue, 'add')
37
- queue.add(
38
- buildRecursivePromise(100, () => {
39
- queue.add(buildPromise(100))
40
- })
41
- )
42
- expect(queue.length).toBe(1)
43
- await queue.join()
44
- expect(queue.length).toBe(0)
45
- expect(addSpy).toHaveBeenCalledTimes(2)
46
- })
47
-
48
- it('it should reject if a promise reject', async () => {
49
- const queue = new PromiseQueue()
50
- queue.add(Promise.reject(new Error('test')))
51
- expect(queue.length).toBe(1)
52
- await expect(queue.join()).rejects.toHaveProperty('message', 'test')
53
- expect(queue.length).toBe(0)
54
- })
55
- })