-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathdetector.test.ts
More file actions
613 lines (532 loc) · 23.5 KB
/
detector.test.ts
File metadata and controls
613 lines (532 loc) · 23.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
import * as fs from "node:fs";
import * as path from "node:path";
import { beforeAll, describe, expect, test } from "vitest";
import { PostHogDetector } from "./detector.js";
import type { PostHogCall, PostHogInitCall, VariantBranch } from "./types.js";
const GRAMMARS_DIR = path.join(__dirname, "..", "grammars");
const hasGrammars = fs.existsSync(
path.join(GRAMMARS_DIR, "tree-sitter-javascript.wasm"),
);
// Skip all tree-sitter tests if grammars aren't built
const describeWithGrammars = hasGrammars ? describe : describe.skip;
function simpleCalls(calls: PostHogCall[]) {
return calls.map((c) => ({ line: c.line, method: c.method, key: c.key }));
}
function simpleBranches(branches: VariantBranch[]) {
return branches.map((b) => ({
flagKey: b.flagKey,
variantKey: b.variantKey,
conditionLine: b.conditionLine,
}));
}
function simpleInits(inits: PostHogInitCall[]) {
return inits.map((i) => ({
token: i.token,
tokenLine: i.tokenLine,
apiHost: i.apiHost,
}));
}
describeWithGrammars("PostHogDetector", () => {
let detector: PostHogDetector;
beforeAll(() => {
detector = new PostHogDetector();
detector.updateConfig({
additionalClientNames: [],
additionalFlagFunctions: [
"useFeatureFlag",
"useFeatureFlagPayload",
"useFeatureFlagVariantKey",
],
detectNestedClients: true,
});
});
// ═══════════════════════════════════════════════════
// JavaScript — findPostHogCalls
// ═══════════════════════════════════════════════════
describe("JavaScript — findPostHogCalls", () => {
test("detects flag and capture methods", async () => {
const code = [
`const flag = posthog.getFeatureFlag('my-flag');`,
`const on = posthog.isFeatureEnabled('beta');`,
`posthog.capture('purchase');`,
].join("\n");
const calls = await detector.findPostHogCalls(code, "javascript");
expect(simpleCalls(calls)).toEqual([
{ line: 0, method: "getFeatureFlag", key: "my-flag" },
{ line: 1, method: "isFeatureEnabled", key: "beta" },
{ line: 2, method: "capture", key: "purchase" },
]);
});
test("detects client alias", async () => {
const code = [`const ph = posthog;`, `ph.capture('aliased-event');`].join(
"\n",
);
const calls = await detector.findPostHogCalls(code, "javascript");
expect(simpleCalls(calls)).toEqual([
{ line: 1, method: "capture", key: "aliased-event" },
]);
});
test("detects constructor alias (new PostHog)", async () => {
const code = [
`const client = new PostHog('phc_token');`,
`client.capture('ctor-event');`,
].join("\n");
const calls = await detector.findPostHogCalls(code, "javascript");
expect(simpleCalls(calls)).toEqual([
{ line: 1, method: "capture", key: "ctor-event" },
]);
});
test("detects Node SDK capture with object argument", async () => {
const code = [
`const client = new PostHog('phc_token');`,
`client.capture({ distinctId: 'u1', event: 'node-event' });`,
].join("\n");
const calls = await detector.findPostHogCalls(code, "javascript");
expect(simpleCalls(calls)).toEqual([
{ line: 1, method: "capture", key: "node-event" },
]);
});
test("detects React hooks (bare function calls)", async () => {
const code = [
`const flag = useFeatureFlag('hook-flag');`,
`const payload = useFeatureFlagPayload('hook-payload');`,
].join("\n");
const calls = await detector.findPostHogCalls(code, "javascript");
expect(simpleCalls(calls)).toEqual([
{ line: 0, method: "useFeatureFlag", key: "hook-flag" },
{ line: 1, method: "useFeatureFlagPayload", key: "hook-payload" },
]);
});
test("detects nested client (window.posthog)", async () => {
const code = `window.posthog.capture('nested-event');`;
const calls = await detector.findPostHogCalls(code, "javascript");
expect(simpleCalls(calls)).toEqual([
{ line: 0, method: "capture", key: "nested-event" },
]);
});
test("detects dynamic capture calls", async () => {
const code = `posthog.capture(getEventName());`;
const calls = await detector.findPostHogCalls(code, "javascript");
expect(calls).toHaveLength(1);
expect(calls[0].dynamic).toBe(true);
});
});
// ═══════════════════════════════════════════════════
// JavaScript — findVariantBranches
// ═══════════════════════════════════════════════════
describe("JavaScript — findVariantBranches", () => {
test("detects if/else chain from variable", async () => {
const code = [
`const v = posthog.getFeatureFlag('exp');`,
`if (v === 'control') {`,
` console.log('a');`,
`} else {`,
` console.log('c');`,
`}`,
].join("\n");
const branches = await detector.findVariantBranches(code, "javascript");
expect(simpleBranches(branches)).toEqual([
{ flagKey: "exp", variantKey: "control", conditionLine: 1 },
{ flagKey: "exp", variantKey: "else", conditionLine: 3 },
]);
});
test("detects boolean flag check (true/false, not else)", async () => {
const code = [
`const on = posthog.isFeatureEnabled('feat');`,
`if (on) {`,
` console.log('yes');`,
`} else {`,
` console.log('no');`,
`}`,
].join("\n");
const branches = await detector.findVariantBranches(code, "javascript");
expect(simpleBranches(branches)).toEqual([
{ flagKey: "feat", variantKey: "true", conditionLine: 1 },
{ flagKey: "feat", variantKey: "false", conditionLine: 3 },
]);
});
test("detects inline flag comparison", async () => {
const code = [
`if (posthog.getFeatureFlag('ab') === 'v1') {`,
` console.log('v1');`,
`}`,
].join("\n");
const branches = await detector.findVariantBranches(code, "javascript");
expect(simpleBranches(branches)).toEqual([
{ flagKey: "ab", variantKey: "v1", conditionLine: 0 },
]);
});
test("detects hook variable branches", async () => {
const code = [
`const variant = useFeatureFlag('exp');`,
`if (variant === 'a') {`,
` do_a();`,
`} else {`,
` do_b();`,
`}`,
].join("\n");
const branches = await detector.findVariantBranches(code, "javascript");
expect(simpleBranches(branches)).toEqual([
{ flagKey: "exp", variantKey: "a", conditionLine: 1 },
{ flagKey: "exp", variantKey: "else", conditionLine: 3 },
]);
});
test("negated boolean resolves correctly", async () => {
const code = [
`const enabled = posthog.isFeatureEnabled('feat');`,
`if (!enabled) {`,
` off();`,
`} else {`,
` on();`,
`}`,
].join("\n");
const branches = await detector.findVariantBranches(code, "javascript");
const variants = branches
.filter((b) => b.flagKey === "feat")
.map((b) => b.variantKey)
.sort();
expect(variants).toEqual(["false", "true"]);
});
});
// ═══════════════════════════════════════════════════
// JavaScript — findInitCalls
// ═══════════════════════════════════════════════════
describe("JavaScript — findInitCalls", () => {
test("detects posthog.init()", async () => {
const code = `posthog.init('phc_abc', { api_host: 'https://us.i.posthog.com' });`;
const inits = await detector.findInitCalls(code, "javascript");
expect(simpleInits(inits)).toEqual([
{ token: "phc_abc", tokenLine: 0, apiHost: "https://us.i.posthog.com" },
]);
});
test("detects new PostHog() constructor", async () => {
const code = `const client = new PostHog('phc_xyz', { host: 'https://eu.posthog.com' });`;
const inits = await detector.findInitCalls(code, "javascript");
expect(simpleInits(inits)).toEqual([
{ token: "phc_xyz", tokenLine: 0, apiHost: "https://eu.posthog.com" },
]);
});
});
// ═══════════════════════════════════════════════════
// Python
// ═══════════════════════════════════════════════════
describe("Python — findPostHogCalls", () => {
test("detects flag methods", async () => {
const code = [
`flag = posthog.get_feature_flag("my-flag", "user-1")`,
`enabled = posthog.is_feature_enabled("beta", "user-1")`,
`payload = posthog.get_feature_flag_payload("cfg", "user-1")`,
].join("\n");
const calls = await detector.findPostHogCalls(code, "python");
expect(simpleCalls(calls)).toEqual([
{ line: 0, method: "get_feature_flag", key: "my-flag" },
{ line: 1, method: "is_feature_enabled", key: "beta" },
{ line: 2, method: "get_feature_flag_payload", key: "cfg" },
]);
});
test("detects capture with positional args (event is 2nd)", async () => {
const code = `posthog.capture("user-1", "purchase_completed")`;
const calls = await detector.findPostHogCalls(code, "python");
const capture = calls.find(
(c) => c.method === "capture" && c.key === "purchase_completed",
);
expect(capture).toBeDefined();
});
test("detects capture with keyword args", async () => {
const code = `posthog.capture(distinct_id="user-1", event="signup")`;
const calls = await detector.findPostHogCalls(code, "python");
const capture = calls.find(
(c) => c.method === "capture" && c.key === "signup",
);
expect(capture).toBeDefined();
});
test("detects constructor alias", async () => {
const code = [
`client = Posthog("phc_token", host="https://us.posthog.com")`,
`client.capture("user-1", "ctor-event")`,
].join("\n");
const calls = await detector.findPostHogCalls(code, "python");
const event = calls.find(
(c) => c.method === "capture" && c.key === "ctor-event",
);
expect(event).toBeDefined();
expect(event?.line).toBe(1);
});
});
describe("Python — findVariantBranches", () => {
test("detects if/elif/else chain", async () => {
const code = [
`flag = posthog.get_feature_flag("exp", "u1")`,
`if flag == "control":`,
` print("a")`,
`elif flag == "test":`,
` print("b")`,
`else:`,
` print("c")`,
].join("\n");
const branches = await detector.findVariantBranches(code, "python");
const control = branches.find((b) => b.variantKey === "control");
const test_ = branches.find((b) => b.variantKey === "test");
expect(control).toBeDefined();
expect(test_).toBeDefined();
expect(control?.conditionLine).toBe(1);
expect(test_?.conditionLine).toBe(3);
});
test("detects boolean enabled check", async () => {
const code = [
`on = posthog.is_feature_enabled("feat", "u1")`,
`if on:`,
` print("yes")`,
`else:`,
` print("no")`,
].join("\n");
const branches = await detector.findVariantBranches(code, "python");
expect(simpleBranches(branches)).toEqual([
{ flagKey: "feat", variantKey: "true", conditionLine: 1 },
{ flagKey: "feat", variantKey: "false", conditionLine: 3 },
]);
});
});
// ═══════════════════════════════════════════════════
// Go
// ═══════════════════════════════════════════════════
describe("Go — findPostHogCalls", () => {
test("detects flag methods", async () => {
const code = [
`package main`,
``,
`func main() {`,
` flag, _ := client.GetFeatureFlag("my-flag", "user-1")`,
` enabled, _ := client.IsFeatureEnabled("beta", "user-1")`,
`}`,
].join("\n");
const calls = await detector.findPostHogCalls(code, "go");
expect(simpleCalls(calls)).toEqual([
{ line: 3, method: "GetFeatureFlag", key: "my-flag" },
{ line: 4, method: "IsFeatureEnabled", key: "beta" },
]);
});
test("detects struct-based Enqueue capture", async () => {
const code = [
`package main`,
``,
`func main() {`,
` client.Enqueue(posthog.Capture{Event: "purchase"})`,
`}`,
].join("\n");
const calls = await detector.findPostHogCalls(code, "go");
const capture = calls.find(
(c) => c.method === "capture" && c.key === "purchase",
);
expect(capture).toBeDefined();
});
});
// ═══════════════════════════════════════════════════
// Ruby
// ═══════════════════════════════════════════════════
describe("Ruby — findPostHogCalls", () => {
test("detects flag methods", async () => {
const code = `enabled = client.is_feature_enabled('my-flag', 'user-1')`;
const calls = await detector.findPostHogCalls(code, "ruby");
expect(simpleCalls(calls)).toEqual([
{ line: 0, method: "is_feature_enabled", key: "my-flag" },
]);
});
test("detects keyword-arg capture", async () => {
const code = `client.capture(distinct_id: 'user-1', event: 'purchase')`;
const calls = await detector.findPostHogCalls(code, "ruby");
const capture = calls.find(
(c) => c.method === "capture" && c.key === "purchase",
);
expect(capture).toBeDefined();
});
});
// ═══════════════════════════════════════════════════
// Cross-language parity
// ═══════════════════════════════════════════════════
describe("Cross-language parity", () => {
test("same flag detected in JS and Python", async () => {
const jsCode = `const flag = posthog.getFeatureFlag('shared-flag');`;
const pyCode = `flag = posthog.get_feature_flag("shared-flag", "u1")`;
const jsCalls = await detector.findPostHogCalls(jsCode, "javascript");
const pyCalls = await detector.findPostHogCalls(pyCode, "python");
expect(jsCalls.find((c) => c.key === "shared-flag")).toBeDefined();
expect(pyCalls.find((c) => c.key === "shared-flag")).toBeDefined();
});
test("same event detected in JS and Python", async () => {
const jsCode = `posthog.capture('shared-event');`;
const pyCode = `posthog.capture("u1", "shared-event")`;
const jsCalls = await detector.findPostHogCalls(jsCode, "javascript");
const pyCalls = await detector.findPostHogCalls(pyCode, "python");
expect(jsCalls.find((c) => c.key === "shared-event")).toBeDefined();
expect(pyCalls.find((c) => c.key === "shared-event")).toBeDefined();
});
});
// ═══════════════════════════════════════════════════
// TypeScript
// ═══════════════════════════════════════════════════
describe("TypeScript — findPostHogCalls", () => {
test("detects basic calls", async () => {
const code = [
`const flag = posthog.getFeatureFlag('ts-flag');`,
`posthog.capture('ts-event');`,
].join("\n");
const calls = await detector.findPostHogCalls(code, "typescript");
// TS grammar may not parse identically in all environments.
// Match the VSCode extension's original test behavior:
// "if it loads, verify correctness; if not, skip gracefully"
if (calls.length === 0) {
return;
}
expect(simpleCalls(calls)).toEqual([
{ line: 0, method: "getFeatureFlag", key: "ts-flag" },
{ line: 1, method: "capture", key: "ts-event" },
]);
});
});
// ═══════════════════════════════════════════════════
// Python — additional findPostHogCalls / findInitCalls
// ═══════════════════════════════════════════════════
describe("Python — findPostHogCalls (capture)", () => {
test("detects capture with positional event arg", async () => {
const code = `posthog.capture('user_id', 'purchase')`;
const calls = await detector.findPostHogCalls(code, "python");
const capture = calls.find(
(c) => c.method === "capture" && c.key === "purchase",
);
expect(capture).toBeDefined();
});
test("detects flag method get_feature_flag", async () => {
const code = `posthog.get_feature_flag('my-flag')`;
const calls = await detector.findPostHogCalls(code, "python");
expect(simpleCalls(calls)).toEqual([
{ line: 0, method: "get_feature_flag", key: "my-flag" },
]);
});
});
describe("Python — findInitCalls", () => {
test("detects positional constructor Posthog('phc_token')", async () => {
const code = `Posthog('phc_token')`;
const inits = await detector.findInitCalls(code, "python");
expect(inits).toHaveLength(1);
expect(inits[0].token).toBe("phc_token");
});
test("detects keyword constructor with api_key and host", async () => {
const code = `Posthog(api_key='phc_token', host='https://app.posthog.com')`;
const inits = await detector.findInitCalls(code, "python");
expect(inits).toHaveLength(1);
expect(inits[0].token).toBe("phc_token");
expect(inits[0].apiHost).toBe("https://app.posthog.com");
});
});
// ═══════════════════════════════════════════════════
// Go — additional findPostHogCalls / findInitCalls
// ═══════════════════════════════════════════════════
describe("Go — findPostHogCalls (capture & flags)", () => {
test("detects struct-based Enqueue capture", async () => {
const code = [
`package main`,
``,
`func main() {`,
` client.Enqueue(posthog.Capture{Event: "purchase"})`,
`}`,
].join("\n");
const calls = await detector.findPostHogCalls(code, "go");
const capture = calls.find(
(c) => c.method === "capture" && c.key === "purchase",
);
expect(capture).toBeDefined();
});
test("detects flag method GetFeatureFlag", async () => {
const code = [
`package main`,
``,
`func main() {`,
` client.GetFeatureFlag(posthog.FeatureFlagPayload{Key: "my-flag"})`,
`}`,
].join("\n");
const calls = await detector.findPostHogCalls(code, "go");
const flag = calls.find(
(c) => c.method === "GetFeatureFlag" && c.key === "my-flag",
);
expect(flag).toBeDefined();
});
});
describe("Go — findInitCalls", () => {
test("detects posthog.New constructor", async () => {
const code = [
`package main`,
``,
`func main() {`,
` client := posthog.New("phc_token")`,
`}`,
].join("\n");
const inits = await detector.findInitCalls(code, "go");
expect(inits).toHaveLength(1);
expect(inits[0].token).toBe("phc_token");
});
test("detects posthog.NewWithConfig constructor", async () => {
const code = [
`package main`,
``,
`func main() {`,
` client, _ := posthog.NewWithConfig("phc_token", posthog.Config{Endpoint: "https://app.posthog.com"})`,
`}`,
].join("\n");
const inits = await detector.findInitCalls(code, "go");
expect(inits).toHaveLength(1);
expect(inits[0].token).toBe("phc_token");
expect(inits[0].apiHost).toBe("https://app.posthog.com");
});
});
// ═══════════════════════════════════════════════════
// Ruby — additional findPostHogCalls / findInitCalls
// ═══════════════════════════════════════════════════
describe("Ruby — findPostHogCalls (capture & flags)", () => {
test("detects capture with keyword args", async () => {
const code = `client.capture(distinct_id: 'user', event: 'purchase')`;
const calls = await detector.findPostHogCalls(code, "ruby");
const capture = calls.find(
(c) => c.method === "capture" && c.key === "purchase",
);
expect(capture).toBeDefined();
});
test("detects flag method get_feature_flag", async () => {
const code = `client.get_feature_flag('my-flag')`;
const calls = await detector.findPostHogCalls(code, "ruby");
const flag = calls.find(
(c) => c.method === "get_feature_flag" && c.key === "my-flag",
);
expect(flag).toBeDefined();
});
});
describe("Ruby — findInitCalls", () => {
test("detects PostHog::Client.new constructor", async () => {
const code = `client = PostHog::Client.new(api_key: 'phc_token')`;
const inits = await detector.findInitCalls(code, "ruby");
expect(inits).toHaveLength(1);
expect(inits[0].token).toBe("phc_token");
});
});
// ═══════════════════════════════════════════════════
// Negative / edge cases
// ═══════════════════════════════════════════════════
describe("Negative / edge cases", () => {
test("unsupported language returns empty arrays", async () => {
const code = `posthog.capture('event')`;
const calls = await detector.findPostHogCalls(code, "haskell");
const inits = await detector.findInitCalls(code, "haskell");
expect(calls).toEqual([]);
expect(inits).toEqual([]);
});
test("non-PostHog client names are ignored", async () => {
const code = `other.capture('event')`;
const jsCalls = await detector.findPostHogCalls(code, "javascript");
const pyCalls = await detector.findPostHogCalls(code, "python");
const rbCalls = await detector.findPostHogCalls(code, "ruby");
expect(jsCalls).toEqual([]);
expect(pyCalls).toEqual([]);
expect(rbCalls).toEqual([]);
});
});
});