@posthog/core 1.70.0 → 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 (117) 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/featureFlagUtils.d.ts +7 -5
  35. package/dist/featureFlagUtils.d.ts.map +1 -1
  36. package/dist/featureFlagUtils.js +17 -11
  37. package/dist/featureFlagUtils.mjs +14 -11
  38. package/dist/index.d.ts +1 -1
  39. package/dist/index.d.ts.map +1 -1
  40. package/dist/index.js +27 -16
  41. package/dist/index.mjs +1 -1
  42. package/dist/posthog-core-stateless.d.ts +40 -3
  43. package/dist/posthog-core-stateless.d.ts.map +1 -1
  44. package/dist/posthog-core-stateless.js +87 -19
  45. package/dist/posthog-core-stateless.mjs +87 -19
  46. package/dist/posthog-core.d.ts +138 -53
  47. package/dist/posthog-core.d.ts.map +1 -1
  48. package/dist/posthog-core.js +341 -115
  49. package/dist/posthog-core.mjs +338 -115
  50. package/dist/types.d.ts +24 -1
  51. package/dist/types.d.ts.map +1 -1
  52. package/dist/utils/index.d.ts +1 -1
  53. package/dist/utils/index.d.ts.map +1 -1
  54. package/dist/utils/index.js +25 -12
  55. package/dist/utils/index.mjs +1 -1
  56. package/dist/utils/json-utils.d.ts +11 -1
  57. package/dist/utils/json-utils.d.ts.map +1 -1
  58. package/dist/utils/json-utils.js +50 -2
  59. package/dist/utils/json-utils.mjs +46 -1
  60. package/package.json +12 -2
  61. package/src/capture-v1/compression.ts +50 -0
  62. package/src/capture-v1/errors.ts +91 -0
  63. package/src/capture-v1/index.ts +34 -0
  64. package/src/capture-v1/sender.ts +779 -0
  65. package/src/capture-v1/serialize.ts +113 -0
  66. package/src/capture-v1/transform.ts +135 -0
  67. package/src/capture-v1/types.ts +59 -0
  68. package/src/capture-v1/uuid.ts +53 -0
  69. package/src/featureFlagUtils.ts +22 -10
  70. package/src/index.ts +1 -0
  71. package/src/posthog-core-stateless.ts +166 -30
  72. package/src/posthog-core.ts +615 -178
  73. package/src/types.ts +21 -1
  74. package/src/utils/index.ts +1 -1
  75. package/src/utils/json-utils.ts +64 -1
  76. package/src/error-tracking/chunk-ids.spec.ts +0 -77
  77. package/src/error-tracking/coercers/error-event-coercer.spec.ts +0 -142
  78. package/src/error-tracking/coercers/promise-rejection-event.spec.ts +0 -77
  79. package/src/error-tracking/coercers/string-coercer.spec.ts +0 -26
  80. package/src/error-tracking/error-properties-builder.aggregate-errors.spec.ts +0 -412
  81. package/src/error-tracking/error-properties-builder.coerce.spec.ts +0 -337
  82. package/src/error-tracking/error-properties-builder.metadata.spec.ts +0 -318
  83. package/src/error-tracking/error-properties-builder.parse.spec.ts +0 -37
  84. package/src/error-tracking/exception-steps.spec.ts +0 -115
  85. package/src/error-tracking/parsers/base.spec.ts +0 -156
  86. package/src/error-tracking/parsers/index.spec.ts +0 -270
  87. package/src/error-tracking/parsers/node.spec.ts +0 -34
  88. package/src/error-tracking/release.spec.ts +0 -34
  89. package/src/logs/index.spec.ts +0 -2421
  90. package/src/logs/logs-utils.spec.ts +0 -266
  91. package/src/metrics/index.spec.ts +0 -1249
  92. package/src/surveys/activation.spec.ts +0 -61
  93. package/src/surveys/events.spec.ts +0 -183
  94. package/src/surveys/keys.spec.ts +0 -29
  95. package/src/surveys/property-matching.spec.ts +0 -539
  96. package/src/surveys/shuffling.spec.ts +0 -51
  97. package/src/surveys/translations.spec.ts +0 -274
  98. package/src/surveys/validation.spec.ts +0 -168
  99. package/src/traces/config.spec.ts +0 -271
  100. package/src/traces/ids.spec.ts +0 -115
  101. package/src/traces/index.spec.ts +0 -3287
  102. package/src/traces/live-spans.spec.ts +0 -69
  103. package/src/traces/otlp.spec.ts +0 -368
  104. package/src/traces/span.spec.ts +0 -1137
  105. package/src/traces/traceparent.spec.ts +0 -184
  106. package/src/utils/bot-detection.spec.ts +0 -107
  107. package/src/utils/bucketed-rate-limiter.spec.ts +0 -327
  108. package/src/utils/json-utils.spec.ts +0 -115
  109. package/src/utils/named-error.spec.ts +0 -36
  110. package/src/utils/number-utils.spec.ts +0 -212
  111. package/src/utils/otlp-any-value.spec.ts +0 -376
  112. package/src/utils/otlp-resource.spec.ts +0 -171
  113. package/src/utils/promise-queue.spec.ts +0 -55
  114. package/src/utils/string-utils.spec.ts +0 -158
  115. package/src/utils/type-utils.spec.ts +0 -38
  116. package/src/utils/webview-app-utils.spec.ts +0 -118
  117. package/src/vendor/uuidv7.spec.ts +0 -26
@@ -1,539 +0,0 @@
1
- import type { MockInstance } from 'vitest'
2
- import type { PropertyFilters, PropertyOperator } from '../types'
3
- import {
4
- hasNestedQuantifier,
5
- isMatchingRegex,
6
- isValidRegex,
7
- matchPropertyFilters,
8
- propertyComparisons,
9
- } from './property-matching'
10
-
11
- const operators: PropertyOperator[] = [
12
- 'exact',
13
- 'is_not',
14
- 'regex',
15
- 'not_regex',
16
- 'icontains',
17
- 'not_icontains',
18
- 'gt',
19
- 'lt',
20
- ]
21
-
22
- const filter = (operator: PropertyOperator, values: string[]): PropertyFilters => ({
23
- property: { operator, values },
24
- })
25
-
26
- describe('shared property matching contract', () => {
27
- describe('regex validation', () => {
28
- it('validates and matches regular expressions without throwing', () => {
29
- expect(isValidRegex('^/docs/.*')).toBe(true)
30
- expect(isMatchingRegex('/docs/getting-started', '^/docs/')).toBe(true)
31
- expect(isMatchingRegex('/pricing', '^/docs/')).toBe(false)
32
- })
33
-
34
- it('returns false for invalid regular expressions', () => {
35
- expect(isValidRegex('[invalid')).toBe(false)
36
- expect(isMatchingRegex('anything', '[invalid')).toBe(false)
37
- })
38
-
39
- it.each([
40
- ['^/docs/.*', '/docs/a', true],
41
- ['^(foo|bar)+$', 'foobarfoo', true],
42
- ['^(?:ab)+$', 'ababab', true],
43
- ['^a+b*$', 'aab', true],
44
- ['\\(a+\\)+', '(aa)))', true],
45
- ['[(a+)]+', 'a+)', true],
46
- ['^(a+)?b$', 'aab', true],
47
- ['^(a+){1}$', 'aaa', true],
48
- ['example\\.com', 'admin@example.org', false],
49
- ['^foo$', 'foo\n', false],
50
- ])('keeps matching for safe pattern %s against %j', (pattern, value, expected) => {
51
- expect(isMatchingRegex(value, pattern)).toBe(expected)
52
- expect(isMatchingRegex(value, pattern)).toBe(expected)
53
- })
54
- })
55
-
56
- describe('nested quantifier guard', () => {
57
- let warnSpy: MockInstance<Parameters<typeof console.warn>, void>
58
-
59
- // The shared setup fakes timers, which freezes Date.now and would make the timing checks vacuous.
60
- beforeAll(() => {
61
- vi.useRealTimers()
62
- })
63
-
64
- afterAll(() => {
65
- vi.useFakeTimers()
66
- })
67
-
68
- beforeEach(() => {
69
- warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})
70
- })
71
-
72
- afterEach(() => {
73
- warnSpy.mockRestore()
74
- })
75
-
76
- it.each([
77
- '^(a+)+$',
78
- '(a*)*',
79
- '(?:x+y?)+',
80
- '((ab)+)+',
81
- '(a+){2,}',
82
- '(a+){2}',
83
- '^(a?a?)+$',
84
- '^(a{0,1}a{0,1})+$',
85
- '(a{2,3})+',
86
- '(a+?)+',
87
- '(a{2,3}?)+',
88
- '^(a+){3}$',
89
- '^(a+){0,3}$',
90
- '(?:.+/)+',
91
- '([^/]+/?)+',
92
- '(a|b+)+',
93
- '(x+x+)+',
94
- '(?:[^:]+)+',
95
- '(?:a[^/]*/[^/]*)+',
96
- '(?:/[^/]+.)+',
97
- '(\\u0041[A-Z]+)+',
98
- '(?=a+)+',
99
- '(a{1,2})+',
100
- '^(a?){26}a{26}$',
101
- '^(a{1,10}){10}$',
102
- '^(?:a{1,3}){20}$',
103
- '^(\\w{1,8}){10}$',
104
- '^(a{1,10}){1,10}$',
105
- '^(\\d{1,3}\\d{1,3}){1,5}$',
106
- '(?:a?){24}b',
107
- '(?:a{1,2}){30}b',
108
- '(?:a{0,2}){20}b',
109
- '(?:[a-z]{1,3}){15}!',
110
- ])('flags %s', (pattern) => {
111
- expect(hasNestedQuantifier(pattern)).toBe(true)
112
- })
113
-
114
- it.each([
115
- '^(a+)?$',
116
- '(a+){1}',
117
- '(a)+',
118
- '(a+)b+',
119
- '\\(a+\\)+',
120
- '[(a+)]+',
121
- '(a|a)*',
122
- '(?<n>a)+',
123
- '(a+)?',
124
- 'a+?',
125
- '(ab){2}',
126
- '^(\\d{3})+$',
127
- '(a{2})+',
128
- '(a{2,2})+',
129
- '(a)+?',
130
- '(\\d+\\.)+',
131
- '(a[)]+)+',
132
- '^https://example\\.com/admin(?:/[^/]+)*$',
133
- '^https?://([a-z0-9-]+\\.)+example\\.com$',
134
- '^([0-9]{1,3}\\.){3}[0-9]{1,3}$',
135
- '^(\\d{1,2}/){2}\\d{4}$',
136
- '^[A-Za-z]{2,3}(-[A-Za-z0-9]{2,8}){0,3}$',
137
- '(?<seg>/[^/]+)*',
138
- ])('does not flag %s', (pattern) => {
139
- expect(hasNestedQuantifier(pattern)).toBe(false)
140
- })
141
-
142
- it.each([
143
- ['^(?:/[^/]+/?)+$', true],
144
- ['^(?:/[^/]+/{0})+$', true],
145
- ['^(?:/[^/]+[^/]+/)+$', true],
146
- ['^(?:[^/]+//[^/]+)+$', true],
147
- ['^(?:/[^/]+/[^/]+)+$', false],
148
- ['^(?:/[^/]*/[^/]*)+$', false],
149
- ])('counts variable terms between every pair of delimiters in %s', (pattern, expected) => {
150
- expect(hasNestedQuantifier(pattern)).toBe(expected)
151
- })
152
-
153
- describe('guard cost on long patterns', () => {
154
- const distinctLiterals = (count: number, from = 0x4e00): string[] =>
155
- Array.from({ length: count }, (_, i) => String.fromCharCode(from + i))
156
-
157
- const countRegExpConstructions = (run: () => void): number => {
158
- const OriginalRegExp = globalThis.RegExp
159
- let constructions = 0
160
- globalThis.RegExp = new Proxy(OriginalRegExp, {
161
- construct(target, args, newTarget) {
162
- constructions++
163
- return Reflect.construct(target, args, newTarget)
164
- },
165
- })
166
- try {
167
- run()
168
- } finally {
169
- globalThis.RegExp = OriginalRegExp
170
- }
171
- return constructions
172
- }
173
-
174
- it.each([
175
- ['a long repeated literal run', '^(' + 'ab'.repeat(1000) + '.*)+$', true],
176
- ['a long single-literal run', '^(' + 'a'.repeat(16000) + '.*)+$', true],
177
- ['thousands of distinct literals', '^(' + distinctLiterals(3000).join('') + '.*)+$', true],
178
- [
179
- 'thousands of paired literals',
180
- '^(' +
181
- distinctLiterals(2000)
182
- .map((literal) => literal + literal)
183
- .join('') +
184
- '[0-9]*[0-9]*)+$',
185
- true,
186
- ],
187
- ['a long delimiter-split group', '^(' + 'ab'.repeat(1000) + '[^/]+/)+$', false],
188
- ])('compiles each distinct term once for %s', (_, pattern, expected) => {
189
- let flagged: boolean | undefined
190
- const constructions = countRegExpConstructions(() => {
191
- flagged = hasNestedQuantifier(pattern)
192
- })
193
- expect(flagged).toBe(expected)
194
- expect(constructions).toBeLessThanOrEqual(1)
195
- })
196
-
197
- it('still matches a long delimiter-split group', () => {
198
- expect(isMatchingRegex('ab'.repeat(1000) + 'z/', '^(' + 'ab'.repeat(1000) + '[^/]+/)+$')).toBe(true)
199
- })
200
-
201
- it('rejects a delimiter-split group once its checks exceed the budget', () => {
202
- const pattern = (ranges: number): string =>
203
- '^(?:' +
204
- distinctLiterals(ranges)
205
- .map((end) => `[\\u4e00-${end}]`)
206
- .join('') +
207
- distinctLiterals(100, 0x100).join('') +
208
- '\\d+)+$'
209
-
210
- expect(hasNestedQuantifier(pattern(99))).toBe(false)
211
- expect(hasNestedQuantifier(pattern(100))).toBe(true)
212
- })
213
- })
214
-
215
- it('matches delimiter-split patterns without Array.prototype.findIndex', async () => {
216
- // A fresh module has an empty compile cache, so the guard really runs without findIndex.
217
- const isMatching = await freshIsMatchingRegex()
218
- const originalFindIndex = Array.prototype.findIndex
219
- try {
220
- ;(Array.prototype as { findIndex?: unknown }).findIndex = undefined
221
- expect(isMatching('https://example.com/admin/users', '^https://example\\.com/admin(?:/[^/]+)*$')).toBe(true)
222
- expect(isMatching('192.168.1.10', '^([0-9]{1,3}\\.){3}[0-9]{1,3}$')).toBe(true)
223
- } finally {
224
- Array.prototype.findIndex = originalFindIndex
225
- }
226
- })
227
-
228
- it.each([
229
- ['^(?i:(?:a[A-Z]+)+)$', true],
230
- ['^(?s:(?:\\n.+)+)x$', true],
231
- ['^(?i-s:(?:a[A-Z]+)+)$', true],
232
- ['^(?s-i:(?:\\n.+)+)x$', true],
233
- ['^(?i:(?:(?:a[A-Z]+)+)+)$', true],
234
- ['(?i:a[A-Z]+)+', true],
235
- ['^(?-i:(?:a[A-Z]+)+)$', false],
236
- ['^(?i:(?-i:(?:a[A-Z]+)+))$', false],
237
- ['^(?m:(?:a[A-Z]+)+)$', false],
238
- ['^(?i:(?:/[^/]+)*)$', false],
239
- ['^(?:a[A-Z]+)+(?i:b)$', false],
240
- ])('checks delimiters of %s under its inline modifiers', (pattern, expected) => {
241
- expect(hasNestedQuantifier(pattern)).toBe(expected)
242
- })
243
-
244
- it('treats case variants of a delimiter as other terms that can match it under the i modifier', () => {
245
- expect(hasNestedQuantifier('^(?:a[^a]+A)+$')).toBe(false)
246
- expect(hasNestedQuantifier('^(?i:(?:a[^a]+A)+)$')).toBe(true)
247
- })
248
-
249
- it('returns no match quickly for catastrophic backtracking input', () => {
250
- const start = Date.now()
251
- expect(isMatchingRegex('a'.repeat(40) + '!', '^(a+)+$')).toBe(false)
252
- expect(propertyComparisons.regex(['^(b+)+$'], ['b'.repeat(40) + '!'])).toBe(false)
253
- expect(propertyComparisons.not_regex(['^(c+)+$'], ['c'.repeat(40) + '!'])).toBe(false)
254
- expect(Date.now() - start).toBeLessThan(500)
255
- })
256
-
257
- it('returns no match quickly for catastrophic backtracking through optional terms', () => {
258
- const start = Date.now()
259
- expect(isMatchingRegex('a'.repeat(30) + '!', '^(a?a?)+$')).toBe(false)
260
- expect(Date.now() - start).toBeLessThan(500)
261
- })
262
-
263
- it.each([
264
- ['^([0-9]{1,3}\\.){3}[0-9]{1,3}$', '192.168.1.10', true],
265
- ['^([0-9]{1,3}\\.){3}[0-9]{1,3}$', '1'.repeat(5000) + '.', false],
266
- ['^https://example\\.com/admin(?:/[^/]+)*$', 'https://example.com/admin/users/42', true],
267
- ['^https://example\\.com/admin(?:/[^/]+)*$', 'https://example.com/admin' + '/aaaa'.repeat(5000) + '/', false],
268
- ['^https?://([a-z0-9-]+\\.)+example\\.com$', 'https://app.eu.example.com', true],
269
- ['^https?://([a-z0-9-]+\\.)+example\\.com$', 'https://' + 'a.'.repeat(5000) + 'example.co', false],
270
- ['^[A-Za-z]{2,3}(-[A-Za-z0-9]{2,8}){0,3}$', 'en-US', true],
271
- ['^(\\d{1,2}/){2}\\d{4}$', '12/31/2026', true],
272
- ])('matches bounded or delimiter-split pattern %s quickly', (pattern, value, expected) => {
273
- const start = Date.now()
274
- expect(isMatchingRegex(value, pattern)).toBe(expected)
275
- expect(Date.now() - start).toBeLessThan(500)
276
- })
277
-
278
- it('returns no match quickly for a bounded repeat of a variable-length group', () => {
279
- const start = Date.now()
280
- expect(isMatchingRegex('a'.repeat(30) + '!', '^(\\w{1,8}){10}$')).toBe(false)
281
- expect(Date.now() - start).toBeLessThan(500)
282
- })
283
-
284
- it('lets not_regex pass for a delimiter-split pattern that does not match', () => {
285
- expect(
286
- propertyComparisons.not_regex(['^https://example\\.com/admin(?:/[^/]+)*$'], ['https://example.com/pricing'])
287
- ).toBe(true)
288
- })
289
-
290
- it('never lets an unsafe not_regex target pass, even with no values', () => {
291
- expect(propertyComparisons.not_regex(['^(a+)+$'], [])).toBe(false)
292
- expect(propertyComparisons.not_regex([], [])).toBe(true)
293
- expect(propertyComparisons.not_regex([], ['value'])).toBe(true)
294
- })
295
-
296
- it.each([null, undefined, 42, /^(a+)+$/])('treats a non-string pattern %s as invalid', (pattern) => {
297
- expect(() => isMatchingRegex('aa', pattern as unknown as string)).not.toThrow()
298
- expect(isMatchingRegex('aa', pattern as unknown as string)).toBe(false)
299
- expect(isMatchingRegex('Desktop', pattern as unknown as string)).toBe(false)
300
- })
301
-
302
- it('never lets a rejected pattern pass a regex or not_regex filter', () => {
303
- expect(isMatchingRegex('dd', '^(d+)+$')).toBe(false)
304
- expect(propertyComparisons.regex(['^(d+)+$'], ['dd'])).toBe(false)
305
- expect(propertyComparisons.not_regex(['^(d+)+$'], ['dd'])).toBe(false)
306
- expect(propertyComparisons.not_regex(['^(d+)+$'], ['zz'])).toBe(false)
307
- })
308
-
309
- it('does not let a rejected pattern pass not_regex on a protected URL', () => {
310
- const pattern = '^https://example\\.com/admin(?:/.+)*$'
311
- expect(new RegExp(pattern).test('https://example.com/admin/customer')).toBe(true)
312
- expect(propertyComparisons.not_regex([pattern], ['https://example.com/admin/customer'])).toBe(false)
313
- })
314
-
315
- it('keeps invalid patterns as non-matches that pass not_regex', () => {
316
- expect(propertyComparisons.regex(['('], ['value'])).toBe(false)
317
- expect(propertyComparisons.not_regex(['('], ['value'])).toBe(true)
318
- })
319
-
320
- // Warning suppression is module state, so each test needs a fresh module.
321
- const freshIsMatchingRegex = async (): Promise<typeof isMatchingRegex> => {
322
- vi.resetModules()
323
- return (await import('./property-matching')).isMatchingRegex
324
- }
325
-
326
- it('warns once per rejected pattern', async () => {
327
- const isMatching = await freshIsMatchingRegex()
328
-
329
- isMatching('x', '^(warn\\w+)+$')
330
- isMatching('y', '^(warn\\w+)+$')
331
- isMatching('z', '^(other\\w+)+$')
332
-
333
- expect(warnSpy).toHaveBeenCalledTimes(2)
334
- expect(warnSpy).toHaveBeenCalledWith('[PostHog]', expect.stringContaining('^(warn\\w+)+$'))
335
- })
336
-
337
- it('keeps warning suppression independent of cache eviction and bounded to 100 warnings', async () => {
338
- vi.resetModules()
339
- const { propertyComparisons: fresh } = await import('./property-matching')
340
- const patterns = Array.from({ length: 101 }, (_, i) => `^https://customer\\.example/(?:segment${i}\\w+)+$`)
341
- const cumulativeWarnings: number[] = []
342
-
343
- for (let sweep = 0; sweep < 3; sweep++) {
344
- patterns.forEach((pattern) => fresh.regex([pattern], ['https://customer.example/x']))
345
- cumulativeWarnings.push(warnSpy.mock.calls.length)
346
- }
347
-
348
- expect(cumulativeWarnings).toEqual([100, 100, 100])
349
- })
350
-
351
- it('does not throw when console methods are missing', async () => {
352
- const originalDebug = console.debug
353
- const originalWarn = console.warn
354
- try {
355
- ;(console as { debug?: unknown }).debug = undefined
356
- ;(console as { warn?: unknown }).warn = undefined
357
- const isMatching = await freshIsMatchingRegex()
358
- expect(() => isMatching('x', '^(nodebug\\w+)+$')).not.toThrow()
359
- expect(isMatching('x', '^(nodebug\\w+)+$')).toBe(false)
360
- } finally {
361
- console.debug = originalDebug
362
- console.warn = originalWarn
363
- }
364
- })
365
-
366
- it('warns through the original console method behind __rrweb_original__ wrappers', async () => {
367
- const wrapper = Object.assign(vi.fn(), { __rrweb_original__: warnSpy })
368
- const originalWarn = console.warn
369
- console.warn = wrapper as unknown as typeof console.warn
370
- try {
371
- const isMatching = await freshIsMatchingRegex()
372
- isMatching('x', '^(wrapped\\w+)+$')
373
- } finally {
374
- console.warn = originalWarn
375
- }
376
-
377
- expect(wrapper).not.toHaveBeenCalled()
378
- expect(warnSpy).toHaveBeenCalledWith('[PostHog]', expect.stringContaining('^(wrapped\\w+)+$'))
379
- })
380
-
381
- it('does not warn for invalid or safe patterns', async () => {
382
- const isMatching = await freshIsMatchingRegex()
383
-
384
- isMatching('x', '[invalid')
385
- isMatching('x', '^x+$')
386
-
387
- expect(warnSpy).not.toHaveBeenCalled()
388
- })
389
- })
390
-
391
- describe('property comparisons', () => {
392
- it.each<{
393
- operator: PropertyOperator
394
- targets: string[]
395
- values: string[]
396
- expected: boolean
397
- }>([
398
- { operator: 'exact', targets: ['premium'], values: ['basic', 'premium'], expected: true },
399
- { operator: 'exact', targets: ['premium'], values: ['basic', 'trial'], expected: false },
400
- { operator: 'is_not', targets: ['basic', 'trial'], values: ['premium', 'enterprise'], expected: true },
401
- { operator: 'is_not', targets: ['basic', 'trial'], values: ['premium', 'trial'], expected: false },
402
- { operator: 'regex', targets: ['^/app/', '^/docs/'], values: ['/home', '/docs/start'], expected: true },
403
- { operator: 'regex', targets: ['^/app/', '^/docs/'], values: ['/home', '/pricing'], expected: false },
404
- { operator: 'not_regex', targets: ['^/app/', '^/docs/'], values: ['/home', '/pricing'], expected: true },
405
- { operator: 'not_regex', targets: ['^/app/', '^/docs/'], values: ['/home', '/docs/start'], expected: false },
406
- { operator: 'icontains', targets: ['CHECKOUT'], values: ['home', 'Start Checkout'], expected: true },
407
- { operator: 'icontains', targets: ['CHECKOUT'], values: ['home', 'pricing'], expected: false },
408
- { operator: 'not_icontains', targets: ['SPAM', 'BOT'], values: ['welcome', 'human'], expected: true },
409
- { operator: 'not_icontains', targets: ['SPAM', 'BOT'], values: ['welcome', 'chatBot'], expected: false },
410
- { operator: 'gt', targets: ['10', '20'], values: ['9', '21'], expected: true },
411
- { operator: 'gt', targets: ['10', '20'], values: ['8', '9'], expected: false },
412
- { operator: 'lt', targets: ['10', '20'], values: ['21', '9'], expected: true },
413
- { operator: 'lt', targets: ['10', '20'], values: ['20', '21'], expected: false },
414
- ])('$operator preserves its array quantifier semantics', ({ operator, targets, values, expected }) => {
415
- expect(propertyComparisons[operator](targets, values)).toBe(expected)
416
- })
417
-
418
- it.each<{
419
- operator: PropertyOperator
420
- expected: boolean
421
- }>([
422
- { operator: 'exact', expected: false },
423
- { operator: 'is_not', expected: true },
424
- { operator: 'regex', expected: false },
425
- { operator: 'not_regex', expected: true },
426
- { operator: 'icontains', expected: false },
427
- { operator: 'not_icontains', expected: true },
428
- { operator: 'gt', expected: false },
429
- { operator: 'lt', expected: false },
430
- ])('$operator preserves empty-target behavior', ({ operator, expected }) => {
431
- expect(propertyComparisons[operator]([], ['value'])).toBe(expected)
432
- })
433
-
434
- it('preserves parseFloat numeric coercion', () => {
435
- expect(propertyComparisons.gt(['9widgets'], ['10items'])).toBe(true)
436
- expect(propertyComparisons.lt(['10items'], ['9widgets'])).toBe(true)
437
- expect(propertyComparisons.gt(['9'], ['not a number'])).toBe(false)
438
- expect(propertyComparisons.gt(['not a number'], ['10'])).toBe(false)
439
- expect(propertyComparisons.lt(['10'], ['10items'])).toBe(false)
440
- })
441
-
442
- it('treats invalid regexes as non-matches before applying negative quantifiers', () => {
443
- expect(propertyComparisons.regex(['[invalid'], ['value'])).toBe(false)
444
- expect(propertyComparisons.not_regex(['[invalid'], ['value'])).toBe(true)
445
- })
446
- })
447
-
448
- describe('map-level matching', () => {
449
- it('matches absent and empty filter maps', () => {
450
- expect(matchPropertyFilters(undefined, undefined)).toBe(true)
451
- expect(matchPropertyFilters({}, undefined)).toBe(true)
452
- })
453
-
454
- it('requires every configured property filter to match', () => {
455
- expect(
456
- matchPropertyFilters(
457
- {
458
- plan: { values: ['premium'], operator: 'exact' },
459
- role: { values: ['admin'], operator: 'is_not' },
460
- },
461
- { plan: 'premium', role: 'member' }
462
- )
463
- ).toBe(true)
464
- expect(
465
- matchPropertyFilters(
466
- {
467
- plan: { values: ['premium'], operator: 'exact' },
468
- role: { values: ['admin'], operator: 'is_not' },
469
- },
470
- { plan: 'premium', role: 'admin' }
471
- )
472
- ).toBe(false)
473
- })
474
-
475
- it.each(operators)('rejects missing and null values for %s, including negative operators', (operator) => {
476
- expect(matchPropertyFilters(filter(operator, ['target']), {})).toBe(false)
477
- expect(matchPropertyFilters(filter(operator, ['target']), { property: undefined })).toBe(false)
478
- expect(matchPropertyFilters(filter(operator, ['target']), { property: null })).toBe(false)
479
- })
480
-
481
- it('coerces each event property to one string value', () => {
482
- expect(matchPropertyFilters(filter('exact', ['5']), { property: 5 })).toBe(true)
483
- expect(matchPropertyFilters(filter('exact', ['true']), { property: true })).toBe(true)
484
- expect(matchPropertyFilters(filter('exact', ['premium,vip']), { property: ['premium', 'vip'] })).toBe(true)
485
- })
486
-
487
- it('coerces filter values to strings before matching', () => {
488
- // Filter values come off the /surveys JSON response untyped at runtime, so a
489
- // numeric filter value must not reach `.toLowerCase()` as a number.
490
- const numericFilter = filter('icontains', [100 as unknown as string])
491
- expect(matchPropertyFilters(numericFilter, { property: 100 })).toBe(true)
492
- })
493
-
494
- it.each<{
495
- operator: PropertyOperator
496
- value: string
497
- expected: boolean
498
- }>([
499
- { operator: 'exact', value: 'target', expected: true },
500
- { operator: 'is_not', value: 'other', expected: true },
501
- { operator: 'regex', value: '/docs/start', expected: true },
502
- { operator: 'not_regex', value: '/pricing', expected: true },
503
- { operator: 'icontains', value: 'TARGET value', expected: true },
504
- { operator: 'not_icontains', value: 'other value', expected: true },
505
- { operator: 'gt', value: '11items', expected: true },
506
- { operator: 'lt', value: '9items', expected: true },
507
- ])('uses the shared $operator comparison', ({ operator, value, expected }) => {
508
- const target =
509
- operator === 'regex' || operator === 'not_regex'
510
- ? '^/docs/'
511
- : operator === 'gt' || operator === 'lt'
512
- ? '10items'
513
- : 'target'
514
- expect(matchPropertyFilters(filter(operator, [target]), { property: value })).toBe(expected)
515
- })
516
-
517
- it('returns false for invalid regex and numeric targets', () => {
518
- expect(matchPropertyFilters(filter('regex', ['[invalid']), { property: 'value' })).toBe(false)
519
- expect(matchPropertyFilters(filter('gt', ['not a number']), { property: '10' })).toBe(false)
520
- expect(matchPropertyFilters(filter('lt', ['not a number']), { property: '10' })).toBe(false)
521
- })
522
-
523
- it('preserves empty-target behavior through the map matcher', () => {
524
- expect(matchPropertyFilters(filter('exact', []), { property: 'value' })).toBe(false)
525
- expect(matchPropertyFilters(filter('regex', []), { property: 'value' })).toBe(false)
526
- expect(matchPropertyFilters(filter('icontains', []), { property: 'value' })).toBe(false)
527
- expect(matchPropertyFilters(filter('gt', []), { property: '10' })).toBe(false)
528
- expect(matchPropertyFilters(filter('lt', []), { property: '10' })).toBe(false)
529
- expect(matchPropertyFilters(filter('is_not', []), { property: 'value' })).toBe(true)
530
- expect(matchPropertyFilters(filter('not_regex', []), { property: 'value' })).toBe(true)
531
- expect(matchPropertyFilters(filter('not_icontains', []), { property: 'value' })).toBe(true)
532
- })
533
-
534
- it('returns false for an unknown operator from malformed remote data', () => {
535
- const malformedFilters = filter('unknown' as PropertyOperator, ['target'])
536
- expect(matchPropertyFilters(malformedFilters, { property: 'target' })).toBe(false)
537
- })
538
- })
539
- })
@@ -1,51 +0,0 @@
1
- import { afterEach, describe, expect, it, vi } from 'vitest'
2
- import { SurveyQuestionType } from '../types'
3
- import { getDisplayOrderChoices, shuffle } from './shuffling'
4
-
5
- afterEach(() => vi.restoreAllMocks())
6
-
7
- describe('survey choice shuffling', () => {
8
- const question = (choices: string[], shuffleOptions = true, hasOpenChoice = false) => ({
9
- type: SurveyQuestionType.SingleChoice as const,
10
- question: 'Pick one',
11
- choices,
12
- shuffleOptions,
13
- hasOpenChoice,
14
- })
15
-
16
- it('uses Fisher-Yates without mutating the input', () => {
17
- vi.spyOn(Math, 'random').mockReturnValue(0)
18
- const source = Object.freeze(['a', 'b', 'c'])
19
- expect(shuffle(source)).toEqual(['b', 'c', 'a'])
20
- expect(source).toEqual(['a', 'b', 'c'])
21
- })
22
-
23
- it.each([false, true])('keeps Other last without mutating choices (open=%s)', (hasOpenChoice) => {
24
- vi.spyOn(Math, 'random').mockReturnValue(0)
25
- const source = question(['a', 'b', 'c', ...(hasOpenChoice ? ['Other'] : [])], true, hasOpenChoice)
26
- Object.freeze(source.choices)
27
- Object.freeze(source)
28
- expect(getDisplayOrderChoices(source)).toEqual(['b', 'c', 'a', ...(hasOpenChoice ? ['Other'] : [])])
29
- expect(getDisplayOrderChoices(source)).toEqual(['b', 'c', 'a', ...(hasOpenChoice ? ['Other'] : [])])
30
- })
31
-
32
- it('reverses the regular choices if randomness leaves their order unchanged', () => {
33
- vi.spyOn(Math, 'random').mockReturnValue(0.999999)
34
- expect(getDisplayOrderChoices(question(['a', 'b', 'c', 'Other'], true, true))).toEqual(['c', 'b', 'a', 'Other'])
35
- })
36
-
37
- it.each([false, undefined])('preserves configured order when shuffleOptions=%s', (shuffleOptions) => {
38
- const source = { ...question(['a', 'b', 'Other'], false, true), shuffleOptions }
39
- expect(getDisplayOrderChoices(source)).toBe(source.choices)
40
- })
41
-
42
- it.each([[], ['Other'], ['a', 'Other'], ['a', 'a', 'Other'], ['a', 'b', '']])(
43
- 'retains every choice in %j',
44
- (...choices) => {
45
- const source = question(choices, true, true)
46
- const result = getDisplayOrderChoices(source)
47
- expect([...result].sort()).toEqual([...choices].sort())
48
- if (choices.length) expect(result[result.length - 1]).toBe(choices[choices.length - 1])
49
- }
50
- )
51
- })