Skip to content

Commit 2075bc9

Browse files
🐛 Fix posthog import crashing in vscode.dev (#31)
1 parent d72b866 commit 2075bc9

2 files changed

Lines changed: 12 additions & 4 deletions

File tree

src/utils/telemetry/client.ts

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { PostHog } from "posthog-node"
1+
import type { PostHog } from "posthog-node"
22
import type { TelemetryConfig } from "./types"
33

44
const POSTHOG_API_KEY = process.env.POSTHOG_API_KEY || ""
@@ -29,15 +29,23 @@ export class TelemetryClient {
2929
private sessionStartTime: number | null = null
3030

3131
/* c8 ignore start -- requires PostHog API key */
32-
init(config: TelemetryConfig): void {
32+
async init(config: TelemetryConfig): Promise<void> {
3333
if (this.initialized || !config.isEnabled() || !POSTHOG_API_KEY) return
3434

3535
this.config = config
3636
this.userId = config.userId
3737
this.sessionId = crypto.randomUUID()
3838
this.sessionStartTime = Date.now()
3939

40-
this.posthog = new PostHog(POSTHOG_API_KEY, {
40+
let PostHogClass: typeof PostHog
41+
try {
42+
;({ PostHog: PostHogClass } = await import("posthog-node"))
43+
} catch {
44+
// posthog-node is unavailable (e.g. browser/web context)
45+
return
46+
}
47+
48+
this.posthog = new PostHogClass(POSTHOG_API_KEY, {
4149
host: POSTHOG_HOST,
4250
disableGeoip: true,
4351
flushAt: FLUSH_AT,

src/utils/telemetry/vscode.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -91,7 +91,7 @@ export async function initVSCodeTelemetry(
9191
vscode.extensions.getExtension("FastAPILabs.fastapi-vscode")?.packageJSON
9292
?.version ?? "unknown"
9393

94-
client.init({
94+
await client.init({
9595
userId,
9696
clientInfo: getClientInfo(),
9797
extensionVersion,

0 commit comments

Comments
 (0)