@posthog/electron 0.0.1 → 0.1.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.
@@ -0,0 +1,589 @@
1
+ import { ErrorCoercer, ErrorEventCoercer, ErrorPropertiesBuilder, ObjectCoercer, PrimitiveCoercer, PromiseRejectionEventCoercer, StringCoercer, createDefaultStackParser } from "@posthog/core/error-tracking";
2
+ import { BucketedRateLimiter, createLogger, resolveExceptionRateLimiterConfig } from "@posthog/core/utils";
3
+ import { Autocapture } from "@posthog/browser-common/autocapture";
4
+ import { AUTOCAPTURE_DISABLED_SERVER_SIDE } from "@posthog/browser-common/constants";
5
+ //#region src/shared/exception-autocapture.ts
6
+ /** Never let reporting failures escape a runtime's global error dispatch. */
7
+ function createExceptionObserver(canCapture, capture, isIgnored = () => false) {
8
+ const limiter = new BucketedRateLimiter({
9
+ ...resolveExceptionRateLimiterConfig(),
10
+ refillInterval: 1e3,
11
+ _logger: createLogger("[PostHog]", () => {})
12
+ });
13
+ let capturing = false;
14
+ return (error, mechanism, source) => {
15
+ try {
16
+ if (capturing || !canCapture()) return;
17
+ capturing = true;
18
+ try {
19
+ if (isIgnored(error, mechanism) || limiter.consumeRateLimit("exceptions")) return;
20
+ capture(error, { $exception_source: source }, { mechanism: {
21
+ type: mechanism,
22
+ handled: false
23
+ } }).catch(() => {});
24
+ } finally {
25
+ capturing = false;
26
+ }
27
+ } catch {}
28
+ };
29
+ }
30
+ //#endregion
31
+ //#region src/renderer/exception-autocapture.ts
32
+ function startRendererExceptionAutocapture(canCapture, capture) {
33
+ const observe = createExceptionObserver(canCapture, capture);
34
+ const error = (event) => {
35
+ if (event instanceof ErrorEvent) observe(event, "onerror", "browser.window_onerror");
36
+ };
37
+ const rejection = (event) => {
38
+ observe(event, "onunhandledrejection", "browser.unhandledrejection");
39
+ };
40
+ window.addEventListener("error", error);
41
+ window.addEventListener("unhandledrejection", rejection);
42
+ return () => {
43
+ window.removeEventListener("error", error);
44
+ window.removeEventListener("unhandledrejection", rejection);
45
+ };
46
+ }
47
+ //#endregion
48
+ //#region src/shared/protocol.ts
49
+ const BRIDGE_KEY = "__POSTHOG_ELECTRON__";
50
+ function isFlagContextCommand(command) {
51
+ return command.type === "setPersonPropertiesForFlags" || command.type === "setGroupPropertiesForFlags" || command.type === "resetPersonPropertiesForFlags" || command.type === "resetGroupPropertiesForFlags";
52
+ }
53
+ //#endregion
54
+ //#region src/renderer/autocapture.ts
55
+ const AUTOCAPTURE_CONFIG_KEYS = [
56
+ "maskAllText",
57
+ "maskAllElementAttributes",
58
+ "disableCaptureUrlHashes",
59
+ "url_allowlist",
60
+ "url_ignorelist",
61
+ "dom_event_allowlist",
62
+ "element_allowlist",
63
+ "css_selector_allowlist",
64
+ "css_selector_ignorelist",
65
+ "element_attribute_ignorelist"
66
+ ];
67
+ /** Volatile extension state only; main owns the durable project config cache. */
68
+ var AutocaptureStore = class {
69
+ constructor() {
70
+ this.values = /* @__PURE__ */ new Map();
71
+ }
72
+ initialize() {}
73
+ get(key) {
74
+ if (typeof key === "string") return this.values.get(key);
75
+ return Object.fromEntries(key.filter((name) => this.values.has(name)).map((name) => [name, this.values.get(name)]));
76
+ }
77
+ set(key, value) {
78
+ if (typeof key === "string") this.values.set(key, value);
79
+ else for (const [name, item] of Object.entries(key)) this.values.set(name, item);
80
+ }
81
+ remove(keys) {
82
+ for (const key of typeof keys === "string" ? [keys] : keys) this.values.delete(key);
83
+ }
84
+ };
85
+ var RendererAutocapture = class {
86
+ constructor(host, config) {
87
+ this.host = host;
88
+ this.config = config;
89
+ this.disposed = false;
90
+ this.active = false;
91
+ this.loading = false;
92
+ this.retryDelay = 1e3;
93
+ }
94
+ update(paused) {
95
+ if (this.disposed) return;
96
+ const state = this.host.getState();
97
+ if (paused || state.optedOut || state.generation !== this.generation) this.stop();
98
+ if (paused || state.optedOut) return;
99
+ this.active = true;
100
+ this.generation = state.generation;
101
+ if (!this.extension) {
102
+ const kv = new AutocaptureStore();
103
+ if (typeof state.autocapture?.autocapture_opt_out === "boolean") kv.set(AUTOCAPTURE_DISABLED_SERVER_SIDE, state.autocapture.autocapture_opt_out);
104
+ const extension = new Autocapture({ refresh: (config) => {
105
+ for (const key of AUTOCAPTURE_CONFIG_KEYS) if (this.config[key] !== void 0) Object.assign(config, { [key]: this.config[key] });
106
+ const current = this.host.getState();
107
+ config.enabled = !this.disposed && !current.optedOut && current.autocapture?.status !== "pending";
108
+ config.remoteRequestsDisabled = current.autocapture?.status === "disabled";
109
+ } });
110
+ this.extension = extension;
111
+ const host = this.host;
112
+ const adapter = {
113
+ get distinctId() {
114
+ return host.getState().distinctId;
115
+ },
116
+ kv,
117
+ onRemoteConfig: (listener) => {
118
+ this.remoteListener = listener;
119
+ return { dispose: () => {
120
+ this.remoteListener = void 0;
121
+ } };
122
+ },
123
+ capture: (event, properties) => {
124
+ host.capture(event, properties ?? void 0);
125
+ return true;
126
+ }
127
+ };
128
+ try {
129
+ extension.setup(adapter);
130
+ } catch (error) {
131
+ this.stop();
132
+ host.onError(error);
133
+ return;
134
+ }
135
+ }
136
+ const remote = state.autocapture;
137
+ if (remote?.status === "loaded") this.remoteListener?.({
138
+ ok: true,
139
+ config: remote
140
+ });
141
+ if (remote?.status === "failed") {
142
+ if (remote.elementsChainAsString) this.remoteListener?.({
143
+ ok: true,
144
+ config: {
145
+ elementsChainAsString: remote.elementsChainAsString,
146
+ ...typeof remote.autocapture_opt_out === "boolean" ? { autocapture_opt_out: remote.autocapture_opt_out } : {}
147
+ }
148
+ });
149
+ this.remoteListener?.({ ok: false });
150
+ }
151
+ if (remote?.status === "disabled") this.extension?.startIfEnabled();
152
+ if (remote?.status === "loaded" || remote?.status === "disabled") {
153
+ clearTimeout(this.retryTimer);
154
+ this.retryTimer = void 0;
155
+ this.retryDelay = 1e3;
156
+ }
157
+ if (this.requestedGeneration !== state.generation && remote?.status !== "disabled") this.loadConfig();
158
+ else if (remote?.status === "failed") this.scheduleRetry();
159
+ }
160
+ loadConfig() {
161
+ if (this.disposed || !this.active || this.loading) return;
162
+ this.loading = true;
163
+ this.requestedGeneration = this.host.getState().generation;
164
+ this.host.loadConfig().catch((error) => this.host.onError(error)).finally(() => {
165
+ this.loading = false;
166
+ if (this.disposed || !this.active) return;
167
+ if (this.requestedGeneration !== this.host.getState().generation) this.update(false);
168
+ else this.scheduleRetry();
169
+ });
170
+ }
171
+ scheduleRetry() {
172
+ const status = this.host.getState().autocapture?.status;
173
+ if (this.disposed || !this.active || this.loading || this.retryTimer || status === "loaded" || status === "disabled") return;
174
+ this.retryTimer = setTimeout(() => {
175
+ this.retryTimer = void 0;
176
+ this.loadConfig();
177
+ }, this.retryDelay);
178
+ this.retryDelay = Math.min(this.retryDelay * 2, 6e4);
179
+ }
180
+ stop() {
181
+ this.active = false;
182
+ clearTimeout(this.retryTimer);
183
+ this.retryTimer = void 0;
184
+ this.retryDelay = 1e3;
185
+ this.requestedGeneration = void 0;
186
+ this.extension?.dispose();
187
+ this.extension = void 0;
188
+ this.remoteListener = void 0;
189
+ }
190
+ dispose() {
191
+ this.disposed = true;
192
+ this.stop();
193
+ }
194
+ };
195
+ //#endregion
196
+ //#region src/renderer/index.ts
197
+ const bridgeSequences = /* @__PURE__ */ new WeakMap();
198
+ var PostHog = class {
199
+ constructor(_bridge, _options = {}) {
200
+ this._bridge = _bridge;
201
+ this._options = _options;
202
+ this._autocapturePauses = 0;
203
+ this._pendingOptOuts = 0;
204
+ this._reportedFlags = /* @__PURE__ */ new Set();
205
+ this._tail = Promise.resolve();
206
+ this._listeners = /* @__PURE__ */ new Set();
207
+ this._disposed = false;
208
+ this._builder = new ErrorPropertiesBuilder([
209
+ new ErrorEventCoercer(),
210
+ new PromiseRejectionEventCoercer(),
211
+ new ErrorCoercer(),
212
+ new ObjectCoercer(),
213
+ new StringCoercer(),
214
+ new PrimitiveCoercer()
215
+ ], createDefaultStackParser());
216
+ this._inOnError = false;
217
+ this._reportedFailures = /* @__PURE__ */ new WeakSet();
218
+ if (_options.autocapture) this._autocapture = new RendererAutocapture({
219
+ getState: () => {
220
+ const state = this._state;
221
+ if (!state) throw new Error("PostHog renderer is not ready");
222
+ return {
223
+ generation: state.generation,
224
+ distinctId: state.distinctId,
225
+ optedOut: state.optedOut,
226
+ autocapture: state.autocapture
227
+ };
228
+ },
229
+ capture: (event, properties) => this.capture(event, properties),
230
+ loadConfig: () => this._send({ type: "loadAutocaptureConfig" }),
231
+ onError: (error) => this._report(error)
232
+ }, typeof _options.autocapture === "object" ? _options.autocapture : {});
233
+ this._unsubscribe = this._bridge.subscribe((state) => this._update(state));
234
+ }
235
+ _update(state) {
236
+ if (this._disposed || this._state && state.revision <= this._state.revision) return;
237
+ if (this._state?.generation !== state.generation || this._state?.flagRevision !== state.flagRevision || this._state?.sessionId !== state.sessionId || this._state?.optedOut !== state.optedOut) this._reportedFlags = /* @__PURE__ */ new Set();
238
+ this._state = structuredClone(state);
239
+ this._autocapture?.update(this._autocapturePauses > 0);
240
+ for (const listener of this._listeners) try {
241
+ listener(this.getState());
242
+ } catch {}
243
+ }
244
+ async _send(command) {
245
+ const generation = this._state?.generation ?? 0;
246
+ structuredClone(command);
247
+ const snapshot = JSON.parse(JSON.stringify(command));
248
+ const dispatched = this._tail.then(() => {
249
+ if (this._disposed) throw new Error("PostHog renderer has been disposed");
250
+ if (command.type === "exception" && !this._canCaptureException()) return { response: void 0 };
251
+ const sequence = (bridgeSequences.get(this._bridge) ?? 0) + 1;
252
+ bridgeSequences.set(this._bridge, sequence);
253
+ return { response: this._bridge.request({
254
+ version: 1,
255
+ sequence,
256
+ generation,
257
+ command: snapshot
258
+ }) };
259
+ });
260
+ const operation = dispatched.then(async ({ response: pending }) => {
261
+ if (!pending) return;
262
+ const response = await pending;
263
+ if (!response.ok) throw new Error(response.error);
264
+ this._update(response.state);
265
+ });
266
+ const networkBound = command.type === "flush" || command.type === "reloadFeatureFlags" || command.type === "loadAutocaptureConfig" || isFlagContextCommand(command) && command.reloadFeatureFlags;
267
+ this._tail = (networkBound ? dispatched : operation).catch(() => {});
268
+ return operation;
269
+ }
270
+ _pauseAutocapture(command) {
271
+ this._autocapturePauses++;
272
+ if (this._state) this._autocapture?.update(true);
273
+ return this._send(command).finally(() => {
274
+ this._autocapturePauses--;
275
+ if (this._state) this._autocapture?.update(this._autocapturePauses > 0);
276
+ });
277
+ }
278
+ async ready() {
279
+ if (this._disposed) throw new Error("PostHog renderer has been disposed");
280
+ await (this._ready ??= this._send({ type: "hello" }).catch((error) => {
281
+ this._ready = void 0;
282
+ throw error;
283
+ }));
284
+ if (!this._disposed && !this._stopExceptionAutocapture && this._options.enableExceptionAutocapture === true && typeof window !== "undefined") this._stopExceptionAutocapture = startRendererExceptionAutocapture(() => this._canCaptureException(), (error, properties, hint) => this._captureException(error, properties, hint));
285
+ }
286
+ _report(error) {
287
+ const inOnError = this._inOnError;
288
+ this._inOnError = true;
289
+ try {
290
+ const result = this._options.onError?.(error);
291
+ if (typeof result?.then === "function") Promise.resolve(result).catch(() => {});
292
+ } catch {} finally {
293
+ this._inOnError = inOnError;
294
+ }
295
+ }
296
+ _reportFailure(promise, quiet = this._inOnError) {
297
+ promise.catch((error) => {
298
+ if (quiet) return;
299
+ if (typeof error === "object" && error !== null) this._reportedFailures.add(error);
300
+ this._report(error);
301
+ });
302
+ }
303
+ /** Fire-and-forget: never throws or rejects. Failed requests are reported through `onError`. */
304
+ capture(event, properties) {
305
+ if (typeof event !== "string" || this.hasOptedOutCapturing()) return;
306
+ this._reportFailure(this._send({
307
+ type: "capture",
308
+ event,
309
+ ...properties ? { properties } : {}
310
+ }));
311
+ }
312
+ /**
313
+ * Link the current distinct ID to an alias without switching identity or reloading flags.
314
+ * Ignored when opted out or personProfiles is 'never'. Resolves after local persistence, not delivery.
315
+ */
316
+ alias(alias) {
317
+ if (!alias?.trim()) return Promise.resolve();
318
+ if (this.hasOptedOutCapturing()) return Promise.resolve();
319
+ return this._send({
320
+ type: "alias",
321
+ alias
322
+ });
323
+ }
324
+ /**
325
+ * Capture an event-only $screen; name wins over properties.$screen_name without setting persistent screen context.
326
+ * Fire-and-forget: never throws or rejects; ignored when opted out.
327
+ */
328
+ screen(name, properties) {
329
+ if (typeof name !== "string" || !name.trim()) return;
330
+ if (this.hasOptedOutCapturing()) return;
331
+ this._reportFailure(this._send({
332
+ type: "screen",
333
+ name,
334
+ ...properties ? { properties } : {}
335
+ }));
336
+ }
337
+ /**
338
+ * Update the current person's $set/$set_once properties without changing identity; empty updates do nothing.
339
+ * Also updates flag context. Resolves after local persistence, not delivery or the background flag refresh.
340
+ * Ignored when opted out or personProfiles is 'never'.
341
+ */
342
+ setPersonProperties(properties, propertiesOnce) {
343
+ if (this.hasOptedOutCapturing()) return Promise.resolve();
344
+ return this._send({
345
+ type: "setPersonProperties",
346
+ ...properties ? { properties } : {},
347
+ ...propertiesOnce ? { propertiesOnce } : {}
348
+ });
349
+ }
350
+ /**
351
+ * Merge a call-time copy of local person overrides for flag evaluation, without updating the person profile.
352
+ * Accepts nested $set/$set_once; empty input does nothing. Otherwise awaits persistence and, by default, a refresh attempt.
353
+ * With false, only saves context; cached flag values stay unchanged until a reload.
354
+ */
355
+ setPersonPropertiesForFlags(properties, reloadFeatureFlags = true) {
356
+ return this._send({
357
+ type: "setPersonPropertiesForFlags",
358
+ properties,
359
+ reloadFeatureFlags
360
+ });
361
+ }
362
+ /**
363
+ * Merge a call-time copy of local overrides by group type, without changing profiles or group membership.
364
+ * Empty input does nothing. Otherwise awaits persistence and, by default, a flag refresh attempt.
365
+ * With false, only saves context; cached flag values stay unchanged until a reload.
366
+ */
367
+ setGroupPropertiesForFlags(properties, reloadFeatureFlags = true) {
368
+ return this._send({
369
+ type: "setGroupPropertiesForFlags",
370
+ properties,
371
+ reloadFeatureFlags
372
+ });
373
+ }
374
+ /**
375
+ * Clear all local person flag overrides, not profile data or identity. Resolves after persistence.
376
+ * Cached flag values stay unchanged unless true is passed to also await a refresh attempt.
377
+ */
378
+ resetPersonPropertiesForFlags(reloadFeatureFlags = false) {
379
+ return this._send({
380
+ type: "resetPersonPropertiesForFlags",
381
+ reloadFeatureFlags
382
+ });
383
+ }
384
+ /**
385
+ * Clear local flag overrides for every group type, not profiles or membership. Resolves after persistence.
386
+ * Cached flag values stay unchanged unless true is passed to also await a refresh attempt.
387
+ */
388
+ resetGroupPropertiesForFlags(reloadFeatureFlags = false) {
389
+ return this._send({
390
+ type: "resetGroupPropertiesForFlags",
391
+ reloadFeatureFlags
392
+ });
393
+ }
394
+ identify(distinctId, properties) {
395
+ return this._pauseAutocapture({
396
+ type: "identify",
397
+ distinctId,
398
+ ...properties ? { properties } : {}
399
+ });
400
+ }
401
+ reset() {
402
+ return this._pauseAutocapture({ type: "reset" });
403
+ }
404
+ group(groupType, groupKey, properties) {
405
+ if (this.hasOptedOutCapturing()) return Promise.resolve();
406
+ return this._send({
407
+ type: "group",
408
+ groupType,
409
+ groupKey,
410
+ ...properties ? { properties } : {}
411
+ });
412
+ }
413
+ register(properties) {
414
+ return this._send({
415
+ type: "register",
416
+ properties
417
+ });
418
+ }
419
+ unregister(key) {
420
+ return this._send({
421
+ type: "unregister",
422
+ key
423
+ });
424
+ }
425
+ optIn() {
426
+ return this._send({ type: "optIn" });
427
+ }
428
+ optOut() {
429
+ this._pendingOptOuts++;
430
+ return this._pauseAutocapture({ type: "optOut" }).finally(() => {
431
+ this._pendingOptOuts--;
432
+ });
433
+ }
434
+ /**
435
+ * Refresh flags using the shared identity/context after earlier mutations, then persist and synchronize the cache.
436
+ * A failed fetch normally retains cached flags and resolves; completion does not guarantee fresh values.
437
+ */
438
+ reloadFeatureFlags() {
439
+ return this._send({ type: "reloadFeatureFlags" });
440
+ }
441
+ /** Compatibility alias for reloadFeatureFlags(), with the same completion and failure semantics. */
442
+ reloadFeatureFlagsAsync() {
443
+ return this.reloadFeatureFlags();
444
+ }
445
+ flush() {
446
+ return this._send({ type: "flush" });
447
+ }
448
+ /** Fire-and-forget: never throws or rejects. Failed requests are reported through `onError`. */
449
+ captureException(error, properties) {
450
+ const reported = typeof error === "object" && error !== null && this._reportedFailures.has(error);
451
+ this._reportFailure(this._captureException(error, properties), this._inOnError || reported);
452
+ }
453
+ _canCaptureException() {
454
+ return !this._disposed && !this._pendingOptOuts && !this._state?.disabled && !this.hasOptedOutCapturing();
455
+ }
456
+ _captureException(error, properties, hint) {
457
+ if (!this._canCaptureException()) return Promise.resolve();
458
+ try {
459
+ const exception = this._builder.buildFromUnknown(error, hint);
460
+ return this._send({
461
+ type: "exception",
462
+ properties: {
463
+ ...properties,
464
+ ...exception
465
+ }
466
+ });
467
+ } catch {
468
+ return Promise.resolve();
469
+ }
470
+ }
471
+ getDistinctId() {
472
+ return this._state?.distinctId ?? "";
473
+ }
474
+ /** Return the shared anonymous ID, stable across identify and rotated by reset; '' before synchronization. */
475
+ getAnonymousId() {
476
+ return this._state?.anonymousId ?? "";
477
+ }
478
+ /** Cached consent state; conservatively true until the first synchronized snapshot. */
479
+ get optedOut() {
480
+ return this.hasOptedOutCapturing();
481
+ }
482
+ getSessionId() {
483
+ return this._state?.sessionId ?? "";
484
+ }
485
+ hasOptedOutCapturing() {
486
+ return this._state?.optedOut ?? true;
487
+ }
488
+ /**
489
+ * Read the cached value without fetching. A missing key is false with a nonempty cache, otherwise undefined.
490
+ * Reports a deduplicated exposure for the observed snapshot by default; sendFeatureFlagEvent: false suppresses it.
491
+ */
492
+ getFeatureFlag(key, options) {
493
+ const flags = this._state?.featureFlags;
494
+ const value = flags && Object.prototype.hasOwnProperty.call(flags, key) ? flags[key] : flags && Object.keys(flags).length > 0 ? false : void 0;
495
+ if ((options?.sendFeatureFlagEvent ?? options?.sendEvent) !== false && this._state) {
496
+ const reportedFlags = this._reportedFlags;
497
+ const reportKey = JSON.stringify([key, value ?? null]);
498
+ if (!reportedFlags.has(reportKey)) {
499
+ reportedFlags.add(reportKey);
500
+ this._send({
501
+ type: "flag",
502
+ key,
503
+ flagRevision: this._state.flagRevision,
504
+ value: value ?? null
505
+ }).catch(() => reportedFlags.delete(reportKey));
506
+ }
507
+ }
508
+ return value;
509
+ }
510
+ isFeatureEnabled(key, options) {
511
+ if (options?.defaultValue !== void 0) {
512
+ const result = this.getFeatureFlagResult(key, options);
513
+ return result === void 0 ? options.defaultValue : Boolean(result.variant ?? result.enabled);
514
+ }
515
+ const value = this.getFeatureFlag(key, options);
516
+ return value === void 0 ? void 0 : Boolean(value);
517
+ }
518
+ /**
519
+ * Return a copied cached result, or undefined for unknown/unavailable flags; never fetches.
520
+ * Empty variants are disabled. Reports exposure by default; sendFeatureFlagEvent: false suppresses it.
521
+ */
522
+ getFeatureFlagResult(key, options) {
523
+ this.getFeatureFlag(key, options);
524
+ if (!this._state || !Object.prototype.hasOwnProperty.call(this._state.featureFlags, key)) return void 0;
525
+ const value = this._state.featureFlags[key];
526
+ return {
527
+ key,
528
+ enabled: Boolean(value),
529
+ ...typeof value === "string" ? { variant: value } : {},
530
+ payload: this.getFeatureFlagPayload(key) ?? null
531
+ };
532
+ }
533
+ /** Return copied cached results (empty when unavailable), without fetching or reporting exposures. */
534
+ getAllFeatureFlags() {
535
+ return Object.keys(this._state?.featureFlags ?? {}).map((key) => this.getFeatureFlagResult(key, { sendFeatureFlagEvent: false }));
536
+ }
537
+ /**
538
+ * Read a copied, decoded cached payload without fetching or reporting exposure.
539
+ * Missing payloads are null once flags are loaded, otherwise undefined; strings are not decoded again.
540
+ */
541
+ getFeatureFlagPayload(key) {
542
+ const payloads = this._state?.featureFlagPayloads;
543
+ const value = payloads && Object.prototype.hasOwnProperty.call(payloads, key) ? payloads[key] : void 0;
544
+ return value === void 0 ? this._state?.flagsLoaded ? null : void 0 : structuredClone(value);
545
+ }
546
+ getState() {
547
+ if (!this._state) throw new Error("PostHog renderer is not ready");
548
+ return structuredClone(this._state);
549
+ }
550
+ onStateChange(callback) {
551
+ this._listeners.add(callback);
552
+ if (this._state) callback(this.getState());
553
+ return () => this._listeners.delete(callback);
554
+ }
555
+ dispose() {
556
+ if (this._disposed) return;
557
+ this._disposed = true;
558
+ this._stopExceptionAutocapture?.();
559
+ this._stopExceptionAutocapture = void 0;
560
+ this._autocapture?.dispose();
561
+ this._unsubscribe();
562
+ this._listeners.clear();
563
+ this._reportedFlags.clear();
564
+ if (singleton === this) singleton = void 0;
565
+ }
566
+ };
567
+ let singleton;
568
+ let initializing;
569
+ function init(options = {}) {
570
+ if (initializing) return initializing;
571
+ if (singleton) return Promise.resolve(singleton);
572
+ const bridge = globalThis[BRIDGE_KEY];
573
+ if (!bridge) return Promise.reject(/* @__PURE__ */ new Error("PostHog preload bridge is missing; configure your Electron preload"));
574
+ const client = new PostHog(bridge, options);
575
+ initializing = client.ready().then(() => {
576
+ singleton = client;
577
+ return client;
578
+ }).catch((error) => {
579
+ client.dispose();
580
+ throw error;
581
+ }).finally(() => {
582
+ initializing = void 0;
583
+ });
584
+ return initializing;
585
+ }
586
+ //#endregion
587
+ export { PostHog, init };
588
+
589
+ //# sourceMappingURL=renderer.mjs.map