@posthog/electron 0.0.0-stage → 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.
package/dist/main.cjs ADDED
@@ -0,0 +1,1683 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ let electron = require("electron");
3
+ let node_crypto = require("node:crypto");
4
+ let node_path = require("node:path");
5
+ let _posthog_core = require("@posthog/core");
6
+ let node_os = require("node:os");
7
+ let _posthog_core_utils = require("@posthog/core/utils");
8
+ let node_fs = require("node:fs");
9
+ //#region src/version.ts
10
+ const version = "0.1.0";
11
+ //#endregion
12
+ //#region src/shared/protocol.ts
13
+ const COMMAND_CHANNEL = "posthog:command:v1";
14
+ const STATE_CHANNEL = "posthog:state:v1";
15
+ const MAX_MESSAGE_BYTES = 262144;
16
+ function normalizeFlagResult(result) {
17
+ return structuredClone({
18
+ ...result,
19
+ enabled: result.variant === "" ? false : result.enabled
20
+ });
21
+ }
22
+ function isFlagContextCommand(command) {
23
+ return command.type === "setPersonPropertiesForFlags" || command.type === "setGroupPropertiesForFlags" || command.type === "resetPersonPropertiesForFlags" || command.type === "resetGroupPropertiesForFlags";
24
+ }
25
+ function isRecord(value) {
26
+ return typeof value === "object" && value !== null && !Array.isArray(value);
27
+ }
28
+ function assertJson(value, depth = 0, allowReservedKeys = false) {
29
+ let remaining = MAX_MESSAGE_BYTES;
30
+ const spend = (size) => {
31
+ remaining -= size;
32
+ if (remaining < 0) throw new Error("PostHog message exceeds 256 KiB");
33
+ };
34
+ const visit = (item, level) => {
35
+ if (level > 20) throw new Error("PostHog payload is too deeply nested");
36
+ spend(typeof item === "string" ? item.length + 2 : 1);
37
+ if (item === null || typeof item === "string" || typeof item === "boolean") return;
38
+ if (typeof item === "number" && Number.isFinite(item)) return;
39
+ if (Array.isArray(item)) {
40
+ for (const element of item) visit(element, level + 1);
41
+ return;
42
+ }
43
+ if (isRecord(item) && (Object.getPrototypeOf(item) === Object.prototype || Object.getPrototypeOf(item) === null)) {
44
+ for (const key in item) {
45
+ if (!Object.hasOwn(item, key)) continue;
46
+ spend(key.length + 3);
47
+ if (!allowReservedKeys && [
48
+ "__proto__",
49
+ "constructor",
50
+ "prototype"
51
+ ].includes(key)) throw new Error("Unsafe PostHog property key");
52
+ visit(item[key], level + 1);
53
+ }
54
+ return;
55
+ }
56
+ throw new Error("PostHog properties must be JSON serializable");
57
+ };
58
+ visit(value, depth);
59
+ }
60
+ function validateRequest(value) {
61
+ assertJson(value);
62
+ if (new TextEncoder().encode(JSON.stringify(value)).byteLength > 262144) throw new Error("PostHog message exceeds 256 KiB");
63
+ if (!isRecord(value) || value.version !== 1 || !Number.isSafeInteger(value.sequence) || value.sequence < 1 || !Number.isSafeInteger(value.generation) || !isRecord(value.command)) throw new Error("Invalid PostHog request");
64
+ const command = value.command;
65
+ const string = (key) => typeof command[key] === "string" && command[key].trim().length > 0;
66
+ const properties = () => command.properties === void 0 || isRecord(command.properties);
67
+ switch (command.type) {
68
+ case "hello":
69
+ case "reset":
70
+ case "optIn":
71
+ case "optOut":
72
+ case "reloadFeatureFlags":
73
+ case "loadAutocaptureConfig":
74
+ case "flush": return;
75
+ case "capture":
76
+ if (string("event") && !["$snapshot", "$exception"].includes(command.event) && properties()) return;
77
+ break;
78
+ case "alias":
79
+ if (string("alias")) return;
80
+ break;
81
+ case "screen":
82
+ if (string("name") && properties()) return;
83
+ break;
84
+ case "setPersonProperties":
85
+ if (properties() && (command.propertiesOnce === void 0 || isRecord(command.propertiesOnce))) return;
86
+ break;
87
+ case "setPersonPropertiesForFlags":
88
+ if (isRecord(command.properties) && typeof command.reloadFeatureFlags === "boolean") return;
89
+ break;
90
+ case "setGroupPropertiesForFlags":
91
+ if (isRecord(command.properties) && Object.values(command.properties).every(isRecord) && typeof command.reloadFeatureFlags === "boolean") return;
92
+ break;
93
+ case "resetPersonPropertiesForFlags":
94
+ case "resetGroupPropertiesForFlags":
95
+ if (typeof command.reloadFeatureFlags === "boolean") return;
96
+ break;
97
+ case "identify":
98
+ if (string("distinctId") && properties()) return;
99
+ break;
100
+ case "group":
101
+ if (string("groupType") && (string("groupKey") || typeof command.groupKey === "number") && properties()) return;
102
+ break;
103
+ case "register":
104
+ if (isRecord(command.properties)) return;
105
+ break;
106
+ case "exception":
107
+ if (isRecord(command.properties) && Array.isArray(command.properties.$exception_list) && command.properties.$exception_list.length > 0 && command.properties.$exception_list.every((exception) => isRecord(exception) && typeof exception.type === "string" && typeof exception.value === "string")) return;
108
+ break;
109
+ case "unregister":
110
+ if (string("key")) return;
111
+ break;
112
+ case "flag": if (string("key") && Number.isSafeInteger(command.flagRevision) && (command.value === null || typeof command.value === "boolean" || typeof command.value === "string")) return;
113
+ }
114
+ throw new Error("Invalid PostHog command");
115
+ }
116
+ function trustedUrl(url, allowedUrls) {
117
+ try {
118
+ const target = new URL(url);
119
+ target.hash = "";
120
+ if (target.protocol === "file:") target.pathname = target.pathname.replace(/%7e/gi, "~");
121
+ return allowedUrls.some((allowed) => {
122
+ const candidate = new URL(allowed);
123
+ candidate.hash = "";
124
+ if (candidate.protocol === "file:") candidate.pathname = candidate.pathname.replace(/%7e/gi, "~");
125
+ return candidate.href === target.href;
126
+ });
127
+ } catch {
128
+ return false;
129
+ }
130
+ }
131
+ //#endregion
132
+ //#region src/shared/autocapture.ts
133
+ /** Only these project settings may cross the bridge or enter Electron's config cache. */
134
+ function sanitizeAutocaptureConfig(value) {
135
+ if (!isRecord(value)) return {};
136
+ return {
137
+ ...typeof value.autocapture_opt_out === "boolean" ? { autocapture_opt_out: value.autocapture_opt_out } : {},
138
+ ...typeof value.elementsChainAsString === "boolean" ? { elementsChainAsString: value.elementsChainAsString } : {}
139
+ };
140
+ }
141
+ //#endregion
142
+ //#region src/main/client.ts
143
+ const AUTOCAPTURE_CONFIG_MAX_AGE_MS = 6e4;
144
+ var RetryLaterError = class extends Error {};
145
+ var ElectronCore = class extends _posthog_core.PostHogCore {
146
+ constructor(token, options, _storage, _notify, _report) {
147
+ super(token, {
148
+ ...options,
149
+ flushInterval: 0,
150
+ disableSurveys: true
151
+ });
152
+ this._storage = _storage;
153
+ this._notify = _notify;
154
+ this._report = _report;
155
+ this._autocaptureStatus = "pending";
156
+ this._stopped = false;
157
+ this._suspended = false;
158
+ this._identityEpoch = 0;
159
+ this._controllers = /* @__PURE__ */ new Set();
160
+ this._retryAt = 0;
161
+ this._failures = 0;
162
+ this._eventContext = {};
163
+ this._disableRemoteConfig = options.disableRemoteConfig ?? false;
164
+ this._appBuild = options.appBuild;
165
+ this._maxQueueAgeMs = options.maxQueueAgeMs ?? 6048e5;
166
+ this._flagsResponseTimeoutMs = options.featureFlagsRequestTimeoutMs ?? 1e4;
167
+ this._isInitialized = false;
168
+ this._initialization = this._initPromise = this._storage.load().then(() => {
169
+ if (this._stopped) return;
170
+ if (!this._storage.isOwned) {
171
+ this.disabled = true;
172
+ return;
173
+ }
174
+ this._isInitialized = true;
175
+ const cached = this.getPersistedProperty(_posthog_core.PostHogPersistedProperty.RemoteConfig);
176
+ if (cached !== void 0) this.setPersistedProperty(_posthog_core.PostHogPersistedProperty.RemoteConfig, sanitizeAutocaptureConfig(cached));
177
+ this.setupBootstrap(options);
178
+ this.resetSessionId();
179
+ this.getDistinctId();
180
+ this.getSessionId();
181
+ });
182
+ this.on("error", this._report);
183
+ }
184
+ ready() {
185
+ return this._initialization;
186
+ }
187
+ canIdentify() {
188
+ return !this.isDisabled && this._personProfiles !== "never";
189
+ }
190
+ getPersistedProperty(key) {
191
+ return this._storage.get(key);
192
+ }
193
+ setPersistedProperty(key, value) {
194
+ if (this._stopped || key === _posthog_core.PostHogPersistedProperty.SessionReplay) return;
195
+ this._storage.set(key, key === _posthog_core.PostHogPersistedProperty.RemoteConfig && value !== null ? sanitizeAutocaptureConfig(value) : value);
196
+ if (this._isInitialized && key !== _posthog_core.PostHogPersistedProperty.Queue && key !== _posthog_core.PostHogPersistedProperty.SessionLastTimestamp) this._notify();
197
+ }
198
+ getAutocaptureState() {
199
+ return {
200
+ ...sanitizeAutocaptureConfig(this.getPersistedProperty(_posthog_core.PostHogPersistedProperty.RemoteConfig)),
201
+ status: this._disableRemoteConfig ? "disabled" : this._autocaptureStatus,
202
+ ...this.isDisabled ? { autocapture_opt_out: true } : {}
203
+ };
204
+ }
205
+ loadAutocaptureConfig(forceRefresh = false) {
206
+ if (this._stopped || this.isDisabled || this.optedOut || this._disableRemoteConfig) return Promise.resolve();
207
+ if (this._autocaptureLoad) return this._autocaptureLoad;
208
+ if (!forceRefresh && this._autocaptureStatus === "loaded" && this._autocaptureLoadedAt !== void 0 && Date.now() - this._autocaptureLoadedAt < AUTOCAPTURE_CONFIG_MAX_AGE_MS) return Promise.resolve();
209
+ this._autocaptureLoad = this.getRemoteConfig().then((response) => {
210
+ if (this._stopped) return;
211
+ if (this.optedOut || this.isDisabled) {
212
+ this._autocaptureStatus = "failed";
213
+ return;
214
+ }
215
+ this._autocaptureStatus = response ? "loaded" : "failed";
216
+ if (response) {
217
+ this._autocaptureLoadedAt = Date.now();
218
+ this.setPersistedProperty(_posthog_core.PostHogPersistedProperty.RemoteConfig, {
219
+ ...sanitizeAutocaptureConfig(this.getPersistedProperty(_posthog_core.PostHogPersistedProperty.RemoteConfig)),
220
+ ...sanitizeAutocaptureConfig(response)
221
+ });
222
+ }
223
+ }).finally(() => {
224
+ this._autocaptureLoad = void 0;
225
+ if (!this._stopped) this._notify();
226
+ });
227
+ return this._autocaptureLoad;
228
+ }
229
+ capture(event, properties, options) {
230
+ if (this.optedOut || this._stopped) return;
231
+ super.capture(event, properties, options);
232
+ }
233
+ group(...args) {
234
+ if (this.optedOut || this._stopped) return;
235
+ super.group(...args);
236
+ }
237
+ async getFlagsForContext(...args) {
238
+ const epoch = this._identityEpoch;
239
+ const result = await super.getFlagsForContext(...args);
240
+ return this._stopped || epoch !== this._identityEpoch ? void 0 : result;
241
+ }
242
+ getLibraryId() {
243
+ return "posthog-electron";
244
+ }
245
+ getLibraryVersion() {
246
+ return version;
247
+ }
248
+ getCustomUserAgent() {
249
+ return `posthog-electron/${version}`;
250
+ }
251
+ getEvaluationRuntime() {
252
+ return "client";
253
+ }
254
+ getCommonEventProperties() {
255
+ return {
256
+ ...super.getCommonEventProperties(),
257
+ $electron_process: "main",
258
+ $app_name: electron.app.getName(),
259
+ $app_version: electron.app.getVersion(),
260
+ $os_name: process.platform === "darwin" ? "macOS" : process.platform === "win32" ? "Windows" : "Linux",
261
+ $os_version: process.getSystemVersion?.() ?? (0, node_os.release)(),
262
+ $device_type: "Desktop",
263
+ ...this._appBuild ? { $app_build: this._appBuild } : {},
264
+ ...this._eventContext
265
+ };
266
+ }
267
+ withContext(context, operation) {
268
+ const previous = this._eventContext;
269
+ this._eventContext = context;
270
+ try {
271
+ return operation();
272
+ } finally {
273
+ this._eventContext = previous;
274
+ }
275
+ }
276
+ invalidateIdentity() {
277
+ this._identityEpoch++;
278
+ for (const key of [
279
+ _posthog_core.PostHogPersistedProperty.FeatureFlagDetails,
280
+ _posthog_core.PostHogPersistedProperty.BootstrapFeatureFlagDetails,
281
+ _posthog_core.PostHogPersistedProperty.FeatureFlags,
282
+ _posthog_core.PostHogPersistedProperty.FeatureFlagPayloads,
283
+ _posthog_core.PostHogPersistedProperty.FlagsEndpointWasHit
284
+ ]) this.setPersistedProperty(key, null);
285
+ }
286
+ async fetch(url, options) {
287
+ if (this._stopped || !this._storage.isOwned || this._suspended) throw new Error("PostHog delivery is inactive");
288
+ const target = new URL(url);
289
+ const host = new URL(this.host);
290
+ const configHost = host.hostname === "us.i.posthog.com" ? "us-assets.i.posthog.com" : host.hostname === "eu.i.posthog.com" ? "eu-assets.i.posthog.com" : void 0;
291
+ if (!(configHost && host.protocol === "https:" && !host.port && host.pathname === "/" && target.href === `https://${configHost}/array/${this.projectToken}/config` && options.method === "GET") && (target.origin !== host.origin || !target.pathname.startsWith(host.pathname.replace(/\/$/, "") + "/"))) throw new Error("PostHog request outside configured host");
292
+ const flagsRequest = target.pathname.endsWith("/flags/") || target.pathname.endsWith("/flags");
293
+ const started = Date.now();
294
+ const controller = new AbortController();
295
+ let responseTimer;
296
+ const abort = () => controller.abort(options.signal?.reason);
297
+ options.signal?.addEventListener("abort", abort, { once: true });
298
+ if (options.signal?.aborted) abort();
299
+ this._controllers.add(controller);
300
+ const cleanup = () => {
301
+ clearTimeout(responseTimer);
302
+ options.signal?.removeEventListener("abort", abort);
303
+ controller.signal.removeEventListener("abort", cleanup);
304
+ this._controllers.delete(controller);
305
+ };
306
+ controller.signal.addEventListener("abort", cleanup, { once: true });
307
+ try {
308
+ await electron.app.whenReady();
309
+ if (this._stopped || controller.signal.aborted) throw new Error("PostHog request cancelled");
310
+ const response = await electron.session.fromPartition("posthog-electron").fetch(url, {
311
+ method: options.method,
312
+ headers: options.headers,
313
+ body: options.body,
314
+ signal: controller.signal,
315
+ credentials: "omit",
316
+ redirect: "error"
317
+ });
318
+ if (!response.body) cleanup();
319
+ else if (response.status < 200 || response.status >= 300) {
320
+ const timeout = flagsRequest ? this._flagsResponseTimeoutMs : this.requestTimeout;
321
+ responseTimer = setTimeout(() => {
322
+ controller.abort(/* @__PURE__ */ new Error("PostHog error response body deadline exceeded"));
323
+ response.body?.cancel().catch(() => {});
324
+ cleanup();
325
+ }, Math.max(0, timeout - (Date.now() - started)) + 1);
326
+ responseTimer.unref();
327
+ }
328
+ return {
329
+ status: response.status,
330
+ headers: response.headers,
331
+ body: response.body ? new ReadableStream({ cancel: async (reason) => {
332
+ try {
333
+ await response.body?.cancel(reason);
334
+ } finally {
335
+ cleanup();
336
+ }
337
+ } }) : null,
338
+ text: async () => {
339
+ try {
340
+ return await response.text();
341
+ } finally {
342
+ cleanup();
343
+ }
344
+ },
345
+ json: async () => {
346
+ try {
347
+ return await response.json();
348
+ } finally {
349
+ cleanup();
350
+ }
351
+ }
352
+ };
353
+ } catch (error) {
354
+ cleanup();
355
+ throw error;
356
+ }
357
+ }
358
+ shouldRetainBatchOnError(error) {
359
+ if (error instanceof RetryLaterError) return true;
360
+ const status = isRecord(error) ? error.status : void 0;
361
+ return (0, _posthog_core.isPostHogFetchNetworkError)(error) || status === 407 || status === 408 || status === 429 || typeof status === "number" && status >= 500;
362
+ }
363
+ async sendBatch(...args) {
364
+ if (this._stopped || this._suspended || !this._storage.isOwned || Date.now() < this._retryAt) throw new RetryLaterError("PostHog delivery paused");
365
+ try {
366
+ await this._storage.flush();
367
+ } catch (error) {
368
+ throw new RetryLaterError("PostHog storage write failed", { cause: error });
369
+ }
370
+ if (this._stopped || this._suspended) throw new RetryLaterError("PostHog delivery paused");
371
+ try {
372
+ const cutoff = Date.now() - this._maxQueueAgeMs;
373
+ const eligible = args[0].filter((message) => {
374
+ const timestamp = message?.timestamp;
375
+ return (typeof timestamp === "string" || timestamp instanceof Date) && new Date(timestamp).getTime() >= cutoff;
376
+ });
377
+ if (eligible.length) await super.sendBatch(eligible, args[1], args[2]);
378
+ this._failures = 0;
379
+ this._retryAt = 0;
380
+ } catch (error) {
381
+ if (this.shouldRetainBatchOnError(error)) {
382
+ this._failures++;
383
+ const retryAfter = isRecord(error) && typeof error.retryAfterMs === "number" ? error.retryAfterMs : 0;
384
+ const delay = Math.min(6e4, 1e3 * 2 ** Math.min(this._failures, 6)) * (.5 + Math.random() * .5);
385
+ this._retryAt = Date.now() + Math.max(retryAfter, delay);
386
+ }
387
+ throw error;
388
+ }
389
+ }
390
+ flushStorage() {
391
+ return this._storage.flush();
392
+ }
393
+ persist() {
394
+ return this._storage.flush();
395
+ }
396
+ suspend() {
397
+ this._suspended = true;
398
+ for (const controller of this._controllers) controller.abort();
399
+ }
400
+ resume() {
401
+ this._suspended = false;
402
+ }
403
+ stop() {
404
+ this._stopped = true;
405
+ this.disabled = true;
406
+ clearTimeout(this._flushTimer);
407
+ for (const controller of this._controllers) controller.abort();
408
+ this._controllers.clear();
409
+ return this._storage.stop();
410
+ }
411
+ };
412
+ //#endregion
413
+ //#region src/shared/exception-autocapture.ts
414
+ /** Never let reporting failures escape a runtime's global error dispatch. */
415
+ function createExceptionObserver(canCapture, capture, isIgnored = () => false) {
416
+ const limiter = new _posthog_core_utils.BucketedRateLimiter({
417
+ ...(0, _posthog_core_utils.resolveExceptionRateLimiterConfig)(),
418
+ refillInterval: 1e3,
419
+ _logger: (0, _posthog_core_utils.createLogger)("[PostHog]", () => {})
420
+ });
421
+ let capturing = false;
422
+ return (error, mechanism, source) => {
423
+ try {
424
+ if (capturing || !canCapture()) return;
425
+ capturing = true;
426
+ try {
427
+ if (isIgnored(error, mechanism) || limiter.consumeRateLimit("exceptions")) return;
428
+ capture(error, { $exception_source: source }, { mechanism: {
429
+ type: mechanism,
430
+ handled: false
431
+ } }).catch(() => {});
432
+ } finally {
433
+ capturing = false;
434
+ }
435
+ } catch {}
436
+ };
437
+ }
438
+ //#endregion
439
+ //#region src/main/exception-autocapture.ts
440
+ /**
441
+ * Monitor only by default: a rejection listener would change Node's default throw/exit behavior.
442
+ * `captureUnhandledRejections` opts in to that listener anyway, because Electron's main process
443
+ * only warns about rejections and never escalates them to the monitor.
444
+ */
445
+ function startProcessExceptionAutocapture(canCapture, capture, captureUnhandledRejections = false) {
446
+ const observe = createExceptionObserver(canCapture, capture, (error, mechanism) => mechanism === "onunhandledrejection" && isAbortError(error));
447
+ const monitor = (error, origin) => {
448
+ const rejection = origin === "unhandledRejection";
449
+ if (rejection && captureUnhandledRejections) return;
450
+ observe(error, rejection ? "onunhandledrejection" : "onuncaughtexception", rejection ? "node.process_unhandled_rejection" : "node.process_uncaught_exception");
451
+ };
452
+ const rejection = (reason) => observe(reason, "onunhandledrejection", "node.process_unhandled_rejection");
453
+ process.on("uncaughtExceptionMonitor", monitor);
454
+ if (captureUnhandledRejections) process.on("unhandledRejection", rejection);
455
+ return () => {
456
+ process.removeListener("uncaughtExceptionMonitor", monitor);
457
+ process.removeListener("unhandledRejection", rejection);
458
+ };
459
+ }
460
+ function isAbortError(reason) {
461
+ try {
462
+ return (typeof reason === "object" || typeof reason === "function") && reason !== null && reason.name === "AbortError";
463
+ } catch {
464
+ return false;
465
+ }
466
+ }
467
+ //#endregion
468
+ //#region src/main/storage.ts
469
+ const DEFAULT_MAX_STORAGE_BYTES = 5242880;
470
+ const DEFAULT_MAX_QUEUE_AGE_MS = 6048e5;
471
+ function isObject(value) {
472
+ return typeof value === "object" && value !== null && !Array.isArray(value);
473
+ }
474
+ function eventTime(item) {
475
+ return new Date(item.message.timestamp).getTime();
476
+ }
477
+ function isQueueItem(value) {
478
+ if (!isObject(value) || !Object.hasOwn(value, "message") || !isObject(value.message)) return false;
479
+ const message = value.message;
480
+ return Object.hasOwn(message, "timestamp") && (typeof message.timestamp === "string" || message.timestamp instanceof Date) && Number.isFinite(new Date(message.timestamp).getTime()) && Object.hasOwn(message, "event") && typeof message.event === "string" && Object.hasOwn(message, "distinct_id") && typeof message.distinct_id === "string" && Object.hasOwn(message, "properties") && isObject(message.properties);
481
+ }
482
+ /** Exclusively owned local storage. Call load before use; mutations must go through set. */
483
+ var ElectronStorage = class {
484
+ constructor(directory, options = {}) {
485
+ this.directory = directory;
486
+ this.options = options;
487
+ this.stopped = false;
488
+ this.owned = false;
489
+ this.owner = JSON.stringify({
490
+ host: (0, node_os.hostname)(),
491
+ pid: process.pid,
492
+ token: (0, node_crypto.randomUUID)()
493
+ });
494
+ this.values = Object.create(null);
495
+ this.serialized = JSON.stringify({
496
+ version: 1,
497
+ values: {}
498
+ });
499
+ this.revision = 0;
500
+ this.queueExpiresAt = Infinity;
501
+ this.persistedRevision = 0;
502
+ this.loaded = false;
503
+ this.finalized = false;
504
+ this.file = (0, node_path.join)(directory, "state.json");
505
+ this.maxStorageBytes = options.maxStorageBytes ?? DEFAULT_MAX_STORAGE_BYTES;
506
+ this.maxQueueAgeMs = options.maxQueueAgeMs ?? DEFAULT_MAX_QUEUE_AGE_MS;
507
+ if (!Number.isFinite(this.maxStorageBytes) || this.maxStorageBytes <= 0) throw new RangeError("maxStorageBytes must be positive and finite");
508
+ if (!Number.isFinite(this.maxQueueAgeMs) || this.maxQueueAgeMs < 0) throw new RangeError("maxQueueAgeMs must be nonnegative and finite");
509
+ }
510
+ async load() {
511
+ this.loading ??= this.loadState().finally(() => {
512
+ this.loaded = true;
513
+ });
514
+ await this.loading;
515
+ }
516
+ get isLoaded() {
517
+ return this.loaded;
518
+ }
519
+ get isOwned() {
520
+ return this.owned && !this.stopped;
521
+ }
522
+ async acquire() {
523
+ await node_fs.promises.mkdir(this.directory, {
524
+ recursive: true,
525
+ mode: 448
526
+ });
527
+ await node_fs.promises.chmod(this.directory, 448);
528
+ const lock = (0, node_path.join)(this.directory, ".owner");
529
+ try {
530
+ await node_fs.promises.writeFile(lock, this.owner, {
531
+ encoding: "utf8",
532
+ mode: 384,
533
+ flag: "wx"
534
+ });
535
+ } catch (error) {
536
+ if (error.code !== "EEXIST") throw error;
537
+ const previous = await node_fs.promises.readFile(lock, "utf8");
538
+ const owner = JSON.parse(previous);
539
+ if (!isObject(owner) || owner.host !== (0, node_os.hostname)() || !Number.isSafeInteger(owner.pid) || owner.pid <= 0 || typeof owner.token !== "string" || !/^[a-f0-9-]{36}$/.test(owner.token)) throw new Error("Unverifiable Electron storage ownership");
540
+ try {
541
+ process.kill(owner.pid, 0);
542
+ throw new Error("Electron storage is already owned by another process");
543
+ } catch (probeError) {
544
+ if (probeError.code !== "ESRCH") throw probeError;
545
+ }
546
+ await node_fs.promises.writeFile((0, node_path.join)(this.directory, `.reclaim-${owner.token}`), "", {
547
+ mode: 384,
548
+ flag: "wx"
549
+ });
550
+ if (await node_fs.promises.readFile(lock, "utf8") !== previous) throw new Error("Electron storage owner changed");
551
+ await node_fs.promises.unlink(lock);
552
+ await node_fs.promises.writeFile(lock, this.owner, {
553
+ encoding: "utf8",
554
+ mode: 384,
555
+ flag: "wx"
556
+ });
557
+ }
558
+ this.owned = true;
559
+ }
560
+ async loadState() {
561
+ try {
562
+ if (this.stopped) return;
563
+ await this.acquire();
564
+ if (this.stopped) return;
565
+ } catch (error) {
566
+ this.values = Object.assign(Object.create(null), { opted_out: true });
567
+ this.report(error);
568
+ return;
569
+ }
570
+ let text;
571
+ try {
572
+ text = await node_fs.promises.readFile(this.file, "utf8");
573
+ } catch (error) {
574
+ if (error.code === "ENOENT") return;
575
+ this.recover(error);
576
+ return;
577
+ }
578
+ if (this.stopped) return;
579
+ try {
580
+ const state = JSON.parse(text);
581
+ if (!isObject(state) || !Object.hasOwn(state, "version") || state.version !== 1 || !Object.hasOwn(state, "values") || !isObject(state.values) || Object.hasOwn(state.values, "opted_out") && typeof state.values.opted_out !== "boolean") throw new Error("Invalid Electron storage schema");
582
+ const bounded = this.bound(state.values);
583
+ this.values = bounded.values;
584
+ this.serialized = bounded.serialized;
585
+ this.queueExpiresAt = bounded.expiresAt;
586
+ if (this.serialized !== text) {
587
+ this.revision++;
588
+ this.scheduleWrite();
589
+ }
590
+ } catch (error) {
591
+ this.recover(error);
592
+ }
593
+ }
594
+ recover(error) {
595
+ if (this.stopped) return;
596
+ this.values = Object.assign(Object.create(null), { opted_out: true });
597
+ this.queueExpiresAt = Infinity;
598
+ this.serialized = JSON.stringify({
599
+ version: 1,
600
+ values: this.values
601
+ });
602
+ this.revision++;
603
+ this.report(error);
604
+ this.scheduleWrite();
605
+ }
606
+ get(key) {
607
+ if (key === "queue" && this.isOwned && Date.now() > this.queueExpiresAt) {
608
+ const bounded = this.bound(this.values);
609
+ if (bounded.serialized !== this.serialized) {
610
+ this.values = bounded.values;
611
+ this.serialized = bounded.serialized;
612
+ this.queueExpiresAt = bounded.expiresAt;
613
+ this.revision++;
614
+ this.scheduleWrite();
615
+ }
616
+ }
617
+ if (!Object.hasOwn(this.values, key)) return void 0;
618
+ const value = this.values[key];
619
+ return key === "queue" && Array.isArray(value) ? value.slice() : structuredClone(value);
620
+ }
621
+ set(key, value) {
622
+ if (!this.isOwned) return;
623
+ const next = Object.assign(Object.create(null), this.values);
624
+ try {
625
+ if (value === null) delete next[key];
626
+ else next[key] = structuredClone(value);
627
+ const bounded = this.bound(next);
628
+ this.values = bounded.values;
629
+ this.serialized = bounded.serialized;
630
+ this.queueExpiresAt = bounded.expiresAt;
631
+ } catch (error) {
632
+ this.report(error);
633
+ throw error;
634
+ }
635
+ this.revision++;
636
+ this.scheduleWrite();
637
+ }
638
+ /** Waits for atomic write completion, not an fsync/power-loss durability barrier. */
639
+ async flush() {
640
+ if (!this.isOwned) return;
641
+ if (Date.now() > this.queueExpiresAt) {
642
+ const bounded = this.bound(this.values);
643
+ this.values = bounded.values;
644
+ this.serialized = bounded.serialized;
645
+ this.queueExpiresAt = bounded.expiresAt;
646
+ this.revision++;
647
+ this.scheduleWrite();
648
+ }
649
+ if (!this.pending && this.persistedRevision < this.revision) this.scheduleWrite();
650
+ while (this.pending) await this.pending;
651
+ if (this.persistedRevision < this.revision && this.failure) throw this.failure.error;
652
+ }
653
+ bound(input) {
654
+ const values = Object.assign(Object.create(null), input);
655
+ let queue;
656
+ if (Object.hasOwn(values, "queue")) {
657
+ if (!Array.isArray(values.queue) || !values.queue.every(isQueueItem)) throw new Error("Invalid Electron event queue");
658
+ const cutoff = Date.now() - this.maxQueueAgeMs;
659
+ queue = values.queue.filter((item) => eventTime(item) >= cutoff);
660
+ values.queue = queue;
661
+ }
662
+ let serialized = JSON.stringify({
663
+ version: 1,
664
+ values
665
+ });
666
+ let bytes = Buffer.byteLength(serialized, "utf8");
667
+ if (bytes > this.maxStorageBytes && queue?.length) {
668
+ const oldest = queue.map((item, index) => ({
669
+ item,
670
+ index
671
+ })).sort((a, b) => eventTime(a.item) - eventTime(b.item));
672
+ const removed = /* @__PURE__ */ new Set();
673
+ for (const { item, index } of oldest) {
674
+ if (bytes <= this.maxStorageBytes) break;
675
+ bytes -= Buffer.byteLength(JSON.stringify(item), "utf8") + (queue.length - removed.size > 1 ? 1 : 0);
676
+ removed.add(index);
677
+ }
678
+ queue = queue.filter((_, index) => !removed.has(index));
679
+ values.queue = queue;
680
+ serialized = JSON.stringify({
681
+ version: 1,
682
+ values
683
+ });
684
+ }
685
+ if (Buffer.byteLength(serialized, "utf8") > this.maxStorageBytes) throw new RangeError("Electron storage exceeds maxStorageBytes after removing queued events");
686
+ const expiresAt = queue?.reduce((next, item) => Math.min(next, eventTime(item) + this.maxQueueAgeMs), Infinity) ?? Infinity;
687
+ return {
688
+ values,
689
+ serialized,
690
+ expiresAt
691
+ };
692
+ }
693
+ /** Final process-exit only: never race asynchronous loading, writing or ownership release. */
694
+ releaseOnExit() {
695
+ if (!this.owned || !this.loaded || this.stopping || this.stopped) return;
696
+ if (this.persistedRevision < this.revision) this.writeOnExit();
697
+ if (this.pending) return;
698
+ this.stopped = true;
699
+ const lock = (0, node_path.join)(this.directory, ".owner");
700
+ try {
701
+ if ((0, node_fs.readFileSync)(lock, "utf8") === this.owner) (0, node_fs.unlinkSync)(lock);
702
+ } catch (error) {
703
+ this.report(error);
704
+ } finally {
705
+ this.owned = false;
706
+ }
707
+ }
708
+ stop() {
709
+ this.stopped = true;
710
+ return this.stopping ??= (async () => {
711
+ await this.loading;
712
+ await this.pending?.catch(() => {});
713
+ if (!this.owned) return;
714
+ const lock = (0, node_path.join)(this.directory, ".owner");
715
+ try {
716
+ if (await node_fs.promises.readFile(lock, "utf8") === this.owner) await node_fs.promises.unlink(lock);
717
+ } catch (error) {
718
+ this.report(error);
719
+ } finally {
720
+ this.owned = false;
721
+ }
722
+ })();
723
+ }
724
+ scheduleWrite() {
725
+ if (!this.isOwned || this.pending) return;
726
+ this.failure = void 0;
727
+ let attemptedRevision = this.persistedRevision;
728
+ const pending = Promise.resolve().then(async () => {
729
+ while (!this.stopped && this.persistedRevision < this.revision) {
730
+ attemptedRevision = this.revision;
731
+ const serialized = this.serialized;
732
+ await this.write(serialized);
733
+ this.persistedRevision = Math.max(this.persistedRevision, attemptedRevision);
734
+ }
735
+ });
736
+ this.pending = pending;
737
+ pending.then(() => {
738
+ this.pending = void 0;
739
+ if (this.persistedRevision < this.revision) this.scheduleWrite();
740
+ }, (error) => {
741
+ this.failure = { error };
742
+ this.pending = void 0;
743
+ this.report(error);
744
+ if (attemptedRevision < this.revision) this.scheduleWrite();
745
+ });
746
+ }
747
+ writeOnExit() {
748
+ if (Buffer.byteLength(this.serialized, "utf8") > this.maxStorageBytes) {
749
+ this.report(/* @__PURE__ */ new RangeError("Electron storage exceeds maxStorageBytes"));
750
+ return;
751
+ }
752
+ if (this.renaming) {
753
+ let fd;
754
+ try {
755
+ fd = (0, node_fs.openSync)(this.renaming, "r+");
756
+ (0, node_fs.ftruncateSync)(fd, 0);
757
+ (0, node_fs.writeSync)(fd, this.serialized, 0, "utf8");
758
+ } catch (error) {
759
+ if (error.code !== "ENOENT") this.report(error);
760
+ } finally {
761
+ if (fd !== void 0) (0, node_fs.closeSync)(fd);
762
+ }
763
+ }
764
+ const temporary = (0, node_path.join)(this.directory, `.state-${(0, node_crypto.randomUUID)()}.tmp`);
765
+ try {
766
+ (0, node_fs.writeFileSync)(temporary, this.serialized, {
767
+ encoding: "utf8",
768
+ mode: 384,
769
+ flag: "wx"
770
+ });
771
+ (0, node_fs.renameSync)(temporary, this.file);
772
+ this.persistedRevision = this.revision;
773
+ this.finalized = true;
774
+ } catch (error) {
775
+ this.report(error);
776
+ try {
777
+ (0, node_fs.unlinkSync)(temporary);
778
+ } catch {}
779
+ }
780
+ }
781
+ async write(serialized) {
782
+ if (Buffer.byteLength(serialized, "utf8") > this.maxStorageBytes) throw new RangeError("Electron storage exceeds maxStorageBytes");
783
+ await node_fs.promises.mkdir(this.directory, {
784
+ recursive: true,
785
+ mode: 448
786
+ });
787
+ await node_fs.promises.chmod(this.directory, 448);
788
+ const temporary = (0, node_path.join)(this.directory, `.state-${(0, node_crypto.randomUUID)()}.tmp`);
789
+ try {
790
+ await node_fs.promises.writeFile(temporary, serialized, {
791
+ encoding: "utf8",
792
+ mode: 384,
793
+ flag: "wx"
794
+ });
795
+ if (this.finalized) return;
796
+ this.renaming = temporary;
797
+ await node_fs.promises.rename(temporary, this.file);
798
+ } finally {
799
+ if (this.renaming === temporary) this.renaming = void 0;
800
+ await node_fs.promises.unlink(temporary).catch((error) => {
801
+ if (error.code !== "ENOENT") this.report(error);
802
+ });
803
+ }
804
+ }
805
+ report(error) {
806
+ try {
807
+ this.options.onError?.(error);
808
+ } catch {}
809
+ }
810
+ };
811
+ //#endregion
812
+ //#region src/utility/protocol.ts
813
+ const UTILITY_CHANNEL = "posthog:utility:v1";
814
+ const UTILITY_TIMEOUT_MS = 1e4;
815
+ function envelope(message) {
816
+ return {
817
+ channel: UTILITY_CHANNEL,
818
+ version: 1,
819
+ ...message
820
+ };
821
+ }
822
+ function readEnvelope(value, direction = "to-main") {
823
+ if (!isRecord(value) || value.channel !== "posthog:utility:v1") return;
824
+ assertJson(value, 0, direction === "to-utility");
825
+ if (new TextEncoder().encode(JSON.stringify(value)).byteLength > 262144) throw new Error("PostHog utility message exceeds 256 KiB");
826
+ if (value.version !== 1) throw new Error("Unsupported PostHog utility protocol");
827
+ return value;
828
+ }
829
+ //#endregion
830
+ //#region src/utility/attach.ts
831
+ function attachUtilityProcess(child, execute, getState, removed) {
832
+ const token = (0, node_crypto.randomUUID)();
833
+ const context = {
834
+ $electron_process: "utility",
835
+ $utility_process_id: (0, node_crypto.randomUUID)()
836
+ };
837
+ let active = true;
838
+ let connected = false;
839
+ let sequence = 0;
840
+ let requests = 0;
841
+ let period = performance.now();
842
+ const pending = /* @__PURE__ */ new Set();
843
+ const authorize = () => {
844
+ if (!active) throw new Error("PostHog utility process disconnected");
845
+ };
846
+ const send = (message) => {
847
+ if (!active) return;
848
+ try {
849
+ const value = envelope(message);
850
+ readEnvelope(value, "to-utility");
851
+ child.postMessage(value);
852
+ } catch {
853
+ dispose();
854
+ }
855
+ };
856
+ const dispose = () => {
857
+ if (!active) return;
858
+ try {
859
+ child.postMessage(envelope({
860
+ kind: "closed",
861
+ token
862
+ }));
863
+ } catch {}
864
+ active = false;
865
+ clearTimeout(handshakeTimer);
866
+ child.removeListener("message", message);
867
+ child.removeListener("exit", dispose);
868
+ for (const reject of pending) reject(/* @__PURE__ */ new Error("PostHog utility process disconnected"));
869
+ pending.clear();
870
+ removed();
871
+ };
872
+ const message = (value) => {
873
+ if (!active) return;
874
+ let requestSequence;
875
+ try {
876
+ const data = readEnvelope(value);
877
+ if (!data) return;
878
+ if (performance.now() - period >= 1e3) {
879
+ period = performance.now();
880
+ requests = 0;
881
+ }
882
+ const rateLimited = ++requests > 100;
883
+ if (data.kind === "connect") {
884
+ if (rateLimited) throw new Error("PostHog utility rate limit exceeded");
885
+ connected = true;
886
+ send({
887
+ kind: "connected",
888
+ token
889
+ });
890
+ return;
891
+ }
892
+ if (!connected || data.kind !== "request" || data.token !== token) throw new Error("Invalid PostHog utility connection");
893
+ validateRequest(data.request);
894
+ const request = data.request;
895
+ requestSequence = request.sequence;
896
+ if (request.sequence !== sequence + 1) throw new Error("Out-of-order PostHog utility request");
897
+ if (request.sequence !== 1 && request.command.type === "hello") throw new Error("Duplicate PostHog utility handshake");
898
+ if (request.sequence === 1 && request.command.type !== "hello") throw new Error("PostHog utility handshake required");
899
+ sequence = request.sequence;
900
+ if (rateLimited) throw new Error("PostHog utility rate limit exceeded");
901
+ if (pending.size >= 100) throw new Error("Too many pending PostHog utility requests");
902
+ clearTimeout(handshakeTimer);
903
+ let rejectClosed;
904
+ const closed = new Promise((_resolve, reject) => {
905
+ rejectClosed = reject;
906
+ });
907
+ pending.add(rejectClosed);
908
+ Promise.race([execute(request.command, context, request.generation, authorize), closed]).then(() => {
909
+ authorize();
910
+ const response = {
911
+ ok: true,
912
+ state: getState()
913
+ };
914
+ send({
915
+ kind: "response",
916
+ token,
917
+ sequence: request.sequence,
918
+ response
919
+ });
920
+ }).catch((error) => {
921
+ send({
922
+ kind: "response",
923
+ token,
924
+ sequence: request.sequence,
925
+ response: {
926
+ ok: false,
927
+ error: error instanceof Error ? error.message : "PostHog utility request failed"
928
+ }
929
+ });
930
+ }).finally(() => pending.delete(rejectClosed));
931
+ } catch (error) {
932
+ if (requestSequence !== void 0) send({
933
+ kind: "response",
934
+ token,
935
+ sequence: requestSequence,
936
+ response: {
937
+ ok: false,
938
+ error: error instanceof Error ? error.message : "Invalid PostHog utility request"
939
+ }
940
+ });
941
+ else dispose();
942
+ }
943
+ };
944
+ const handshakeTimer = setTimeout(dispose, UTILITY_TIMEOUT_MS);
945
+ handshakeTimer.unref();
946
+ child.on("message", message);
947
+ child.once("exit", dispose);
948
+ return {
949
+ publish: (state) => {
950
+ if (connected) send({
951
+ kind: "state",
952
+ token,
953
+ state
954
+ });
955
+ },
956
+ dispose
957
+ };
958
+ }
959
+ //#endregion
960
+ //#region src/main/index.ts
961
+ let singleton;
962
+ let singletonOptions;
963
+ function snapshot(value) {
964
+ structuredClone(value);
965
+ return JSON.parse(JSON.stringify(value));
966
+ }
967
+ var PostHog = class {
968
+ constructor(_options) {
969
+ this._options = _options;
970
+ this._windows = /* @__PURE__ */ new Map();
971
+ this._utilities = /* @__PURE__ */ new Map();
972
+ this._revision = 0;
973
+ this._generation = 0;
974
+ this._closed = false;
975
+ this._closing = false;
976
+ this._notifyPending = false;
977
+ this._lastPublished = "";
978
+ this._flagRevision = 0;
979
+ this._lastFlags = "";
980
+ this._reportedPayloadErrors = /* @__PURE__ */ new Map();
981
+ this._foreground = false;
982
+ this._cleanups = [];
983
+ this._tail = Promise.resolve();
984
+ this._readyForSnapshots = false;
985
+ this._pendingConsent = 0;
986
+ this._consentToken = 0;
987
+ if (singleton) throw new Error("PostHog Electron is already initialized; use init()");
988
+ if (!this._options.projectToken?.trim()) throw new Error("PostHog projectToken is required");
989
+ const host = new URL(this._options.host ?? "https://us.i.posthog.com");
990
+ if (!["http:", "https:"].includes(host.protocol) || host.username || host.password || host.search || host.hash) throw new Error("PostHog host must be an HTTP(S) URL without credentials, query or fragment");
991
+ const namespace = (0, node_crypto.createHash)("sha256").update(this._options.projectToken.trim() + host.href).digest("hex").slice(0, 24);
992
+ const storage = new ElectronStorage((0, node_path.join)(this._options.storageDirectory ?? (0, node_path.join)(electron.app.getPath("userData"), "posthog"), namespace), {
993
+ maxStorageBytes: this._options.maxStorageBytes,
994
+ maxQueueAgeMs: this._options.maxQueueAgeMs,
995
+ onError: (error) => this._report(error)
996
+ });
997
+ this._core = new ElectronCore(this._options.projectToken, {
998
+ ...this._options,
999
+ host: host.href
1000
+ }, storage, () => this._scheduleState(), (error) => this._report(error));
1001
+ const exit = () => {
1002
+ if (this._requestedConsent && storage.isLoaded) this._core.setPersistedProperty(_posthog_core.PostHogPersistedProperty.OptedOut, this._requestedConsent.optedOut);
1003
+ storage.releaseOnExit();
1004
+ };
1005
+ process.once("exit", exit);
1006
+ this._cleanups.push(() => process.removeListener("exit", exit));
1007
+ singleton = this;
1008
+ singletonOptions = {
1009
+ projectToken: this._options.projectToken,
1010
+ host: this._options.host
1011
+ };
1012
+ electron.ipcMain.handle(COMMAND_CHANNEL, (event, request) => this._handle(event, request));
1013
+ this._ready = Promise.race([this._initialize(), new Promise((resolve) => {
1014
+ this._cancelReady = resolve;
1015
+ })]).then(() => {
1016
+ this._readyForSnapshots = true;
1017
+ });
1018
+ }
1019
+ _report(error) {
1020
+ try {
1021
+ this._options.onError?.(error);
1022
+ } catch {}
1023
+ }
1024
+ async _initialize() {
1025
+ await this._core.ready();
1026
+ if (this._closing || this._core.isDisabled) return;
1027
+ await electron.app.whenReady();
1028
+ if (this._closing) return;
1029
+ if (!this._closing && this._options.enableExceptionAutocapture === true) this._stopExceptionAutocapture = startProcessExceptionAutocapture(() => !this._closing && !this._core.isDisabled && !this._core.optedOut, (error, properties, hint) => this._captureException(error, properties, hint), this._options.captureUnhandledRejections === true);
1030
+ if (!this._core.isDisabled && this._options.captureAppLifecycleEvents !== false) {
1031
+ const previous = this._core.getPersistedProperty(_posthog_core.PostHogPersistedProperty.InstalledAppVersion);
1032
+ const previousBuild = this._core.getPersistedProperty(_posthog_core.PostHogPersistedProperty.InstalledAppBuild);
1033
+ const version = electron.app.getVersion();
1034
+ const build = this._options.appBuild;
1035
+ const properties = {
1036
+ $electron_version: process.versions.electron,
1037
+ $node_version: process.versions.node,
1038
+ $chromium_version: process.versions.chrome,
1039
+ ...build ? { $app_build: build } : {}
1040
+ };
1041
+ if (!previous) this._core.capture("Application Installed", properties);
1042
+ else if (previous !== version || previousBuild !== build) this._core.capture("Application Updated", {
1043
+ ...properties,
1044
+ previous_version: previous,
1045
+ ...previousBuild ? { previous_build: previousBuild } : {}
1046
+ });
1047
+ this._core.setPersistedProperty(_posthog_core.PostHogPersistedProperty.InstalledAppVersion, version);
1048
+ this._core.setPersistedProperty(_posthog_core.PostHogPersistedProperty.InstalledAppBuild, build ?? null);
1049
+ this._core.capture("Application Opened", { from_background: false });
1050
+ this._foreground = true;
1051
+ }
1052
+ const interval = this._options.flushInterval ?? 1e4;
1053
+ if (interval > 0) {
1054
+ this._timer = setInterval(() => {
1055
+ if (!this._closing) this._core.flush().catch((error) => this._report(error));
1056
+ }, interval);
1057
+ this._timer.unref();
1058
+ }
1059
+ const suspend = () => this._core.suspend();
1060
+ const resume = () => {
1061
+ this._core.resume();
1062
+ if (!this._closing) this.flush().catch((error) => this._report(error));
1063
+ };
1064
+ electron.powerMonitor.on("suspend", suspend);
1065
+ electron.powerMonitor.on("resume", resume);
1066
+ this._cleanups.push(() => {
1067
+ electron.powerMonitor.removeListener("suspend", suspend);
1068
+ electron.powerMonitor.removeListener("resume", resume);
1069
+ });
1070
+ const quit = (event) => {
1071
+ if (this._closed || event.defaultPrevented) return;
1072
+ queueMicrotask(() => {
1073
+ if (event.defaultPrevented) return;
1074
+ this.flush().catch((error) => this._report(error));
1075
+ });
1076
+ };
1077
+ electron.app.on("will-quit", quit);
1078
+ this._cleanups.push(() => electron.app.removeListener("will-quit", quit));
1079
+ if (this._core.preloadFeatureFlags && !this._core.isDisabled) this._core.reloadFeatureFlagsAsync().catch((error) => this._report(error));
1080
+ await this._core.persist().catch(() => {});
1081
+ this._scheduleState();
1082
+ }
1083
+ ready() {
1084
+ return this._ready;
1085
+ }
1086
+ async _run(operation, generation, authorize, changesConsent = false, shouldRun) {
1087
+ if (this._closing) throw new Error("PostHog is shut down");
1088
+ if (changesConsent) this._pendingConsent++;
1089
+ const pending = this._tail.then(async () => {
1090
+ await this._ready;
1091
+ if (this._closed) throw new Error("PostHog is shut down");
1092
+ if (generation !== void 0 && generation !== this._generation) throw new Error("Stale PostHog identity");
1093
+ authorize?.();
1094
+ if (shouldRun && !shouldRun()) return;
1095
+ await operation();
1096
+ await this._core.persist();
1097
+ this._scheduleState();
1098
+ }).finally(() => {
1099
+ if (changesConsent) this._pendingConsent--;
1100
+ });
1101
+ this._tail = pending.catch(() => {});
1102
+ return pending;
1103
+ }
1104
+ /**
1105
+ * Fire-and-forget: never throws or rejects. Storage failures are reported through `onError`; captures
1106
+ * after shutdown are dropped. A capture after an unawaited `identify()` or `reset()` uses the new identity.
1107
+ */
1108
+ capture(event, properties) {
1109
+ if (typeof event !== "string" || !event.trim() || event === "$snapshot") return;
1110
+ this._captureEvent(event, properties);
1111
+ }
1112
+ _captureEvent(event, properties, screenName) {
1113
+ let copy;
1114
+ try {
1115
+ copy = this._snapshotEventProperties(properties);
1116
+ } catch (error) {
1117
+ this._report(error);
1118
+ return;
1119
+ }
1120
+ this._run(() => {
1121
+ if (this._core.optedOut || this._core.isDisabled) return;
1122
+ let captured;
1123
+ try {
1124
+ captured = copy === void 0 ? void 0 : snapshot(copy);
1125
+ } catch (error) {
1126
+ this._report(error);
1127
+ return;
1128
+ }
1129
+ this._core.capture(event, screenName === void 0 ? captured : {
1130
+ ...captured,
1131
+ $screen_name: screenName
1132
+ });
1133
+ }).catch(() => {});
1134
+ }
1135
+ /**
1136
+ * Link the current distinct ID to an alias without switching identity or reloading flags.
1137
+ * Ignored when opted out or personProfiles is 'never'. Resolves after local persistence, not delivery.
1138
+ */
1139
+ alias(alias) {
1140
+ if (!alias?.trim()) return Promise.resolve();
1141
+ return this._run(() => this._alias(alias));
1142
+ }
1143
+ _alias(alias) {
1144
+ if (!this._core.optedOut) this._core.alias(alias);
1145
+ }
1146
+ _snapshotEventProperties(properties) {
1147
+ if (this._closing || !this._readyForSnapshots || this._pendingConsent || this._core.optedOut || this._core.isDisabled) return properties;
1148
+ return properties === void 0 ? void 0 : snapshot(properties);
1149
+ }
1150
+ /**
1151
+ * Capture an event-only $screen; name wins over properties.$screen_name without setting persistent screen context.
1152
+ * Fire-and-forget: never throws or rejects; ignored when opted out.
1153
+ */
1154
+ screen(name, properties) {
1155
+ if (typeof name !== "string" || !name.trim()) return;
1156
+ this._captureEvent("$screen", properties, name);
1157
+ }
1158
+ /**
1159
+ * Update the current person's $set/$set_once properties without changing identity; empty updates do nothing.
1160
+ * Also updates flag context. Resolves after local persistence, not delivery or the background flag refresh.
1161
+ * Ignored when opted out or personProfiles is 'never'.
1162
+ */
1163
+ async setPersonProperties(properties, propertiesOnce) {
1164
+ const set = this._snapshotEventProperties(properties);
1165
+ const once = this._snapshotEventProperties(propertiesOnce);
1166
+ return this._run(() => this._setPersonProperties(set, once));
1167
+ }
1168
+ _setPersonProperties(properties, propertiesOnce) {
1169
+ if (this._core.optedOut || this._core.isDisabled) return;
1170
+ const set = properties === void 0 ? void 0 : snapshot(properties);
1171
+ const once = propertiesOnce === void 0 ? void 0 : snapshot(propertiesOnce);
1172
+ this._core.setPersonProperties(set, once);
1173
+ }
1174
+ /**
1175
+ * Merge a call-time copy of local person overrides for flag evaluation, without updating the person profile.
1176
+ * Accepts nested $set/$set_once; empty input does nothing. Otherwise awaits persistence and, by default, a refresh attempt.
1177
+ * With false, only saves context; cached flag values stay unchanged until a reload.
1178
+ */
1179
+ async setPersonPropertiesForFlags(properties, reloadFeatureFlags = true) {
1180
+ const copy = snapshot(properties);
1181
+ return this._runFlagContext(() => this._setPersonPropertiesForFlags(copy, reloadFeatureFlags));
1182
+ }
1183
+ async _setPersonPropertiesForFlags(properties, reload) {
1184
+ if (!Object.keys(properties).length) return;
1185
+ this._core.setPersonPropertiesForFlags(properties, false);
1186
+ if (reload) await this._core.reloadFeatureFlagsAsync();
1187
+ }
1188
+ /**
1189
+ * Merge a call-time copy of local overrides by group type, without changing profiles or group membership.
1190
+ * Empty input does nothing. Otherwise awaits persistence and, by default, a flag refresh attempt.
1191
+ * With false, only saves context; cached flag values stay unchanged until a reload.
1192
+ */
1193
+ async setGroupPropertiesForFlags(properties, reloadFeatureFlags = true) {
1194
+ const copy = snapshot(properties);
1195
+ return this._runFlagContext(() => this._setGroupPropertiesForFlags(copy, reloadFeatureFlags));
1196
+ }
1197
+ async _setGroupPropertiesForFlags(properties, reload) {
1198
+ if (!Object.keys(properties).length) return;
1199
+ this._core.setGroupPropertiesForFlags(properties);
1200
+ if (reload) await this._core.reloadFeatureFlagsAsync();
1201
+ }
1202
+ /**
1203
+ * Clear all local person flag overrides, not profile data or identity. Resolves after persistence.
1204
+ * Cached flag values stay unchanged unless true is passed to also await a refresh attempt.
1205
+ */
1206
+ resetPersonPropertiesForFlags(reloadFeatureFlags = false) {
1207
+ return this._runFlagContext(() => this._resetPersonPropertiesForFlags(reloadFeatureFlags));
1208
+ }
1209
+ async _resetPersonPropertiesForFlags(reload) {
1210
+ this._core.resetPersonPropertiesForFlags();
1211
+ if (reload) await this._core.reloadFeatureFlagsAsync();
1212
+ }
1213
+ /**
1214
+ * Clear local flag overrides for every group type, not profiles or membership. Resolves after persistence.
1215
+ * Cached flag values stay unchanged unless true is passed to also await a refresh attempt.
1216
+ */
1217
+ resetGroupPropertiesForFlags(reloadFeatureFlags = false) {
1218
+ return this._runFlagContext(() => this._resetGroupPropertiesForFlags(reloadFeatureFlags));
1219
+ }
1220
+ async _resetGroupPropertiesForFlags(reload) {
1221
+ this._core.resetGroupPropertiesForFlags();
1222
+ if (reload) await this._core.reloadFeatureFlagsAsync();
1223
+ }
1224
+ async _runFlagContext(operation, generation, authorize) {
1225
+ let reloading = Promise.resolve();
1226
+ await this._run(() => {
1227
+ reloading = Promise.resolve(operation());
1228
+ reloading.catch(() => {});
1229
+ }, generation, authorize);
1230
+ await reloading;
1231
+ await this._core.persist();
1232
+ this._scheduleState();
1233
+ }
1234
+ identify(distinctId, properties) {
1235
+ if (!distinctId?.trim()) return Promise.resolve();
1236
+ return this._run(() => this._identify(distinctId, properties));
1237
+ }
1238
+ _identify(distinctId, properties) {
1239
+ if (!this._core.canIdentify()) {
1240
+ this._core.identify(distinctId, properties);
1241
+ return;
1242
+ }
1243
+ if (distinctId !== this._core.getDistinctId()) {
1244
+ this._generation++;
1245
+ this._core.invalidateIdentity();
1246
+ }
1247
+ this._core.identify(distinctId, properties);
1248
+ }
1249
+ reset() {
1250
+ return this._run(() => this._reset());
1251
+ }
1252
+ _reset() {
1253
+ this._generation++;
1254
+ this._core.invalidateIdentity();
1255
+ const optedOut = this._core.optedOut;
1256
+ this._core.reset([
1257
+ _posthog_core.PostHogPersistedProperty.OptedOut,
1258
+ _posthog_core.PostHogPersistedProperty.RemoteConfig,
1259
+ _posthog_core.PostHogPersistedProperty.InstalledAppVersion,
1260
+ _posthog_core.PostHogPersistedProperty.InstalledAppBuild
1261
+ ]);
1262
+ this._core.setPersistedProperty(_posthog_core.PostHogPersistedProperty.OptedOut, optedOut);
1263
+ this._core.getDistinctId();
1264
+ this._core.getSessionId();
1265
+ }
1266
+ group(type, key, properties) {
1267
+ return this._run(() => this._core.group(type, key, properties));
1268
+ }
1269
+ register(properties) {
1270
+ return this._run(() => this._core.register(properties));
1271
+ }
1272
+ unregister(key) {
1273
+ return this._run(() => this._core.unregister(key));
1274
+ }
1275
+ optIn() {
1276
+ return this._changeConsent(false);
1277
+ }
1278
+ optOut() {
1279
+ return this._changeConsent(true);
1280
+ }
1281
+ _changeConsent(optedOut, generation, authorize) {
1282
+ const requested = {
1283
+ optedOut,
1284
+ token: ++this._consentToken
1285
+ };
1286
+ if (!this._closing) this._requestedConsent = requested;
1287
+ return this._run(() => optedOut ? this._optOut() : this._core.optIn(), generation, authorize, true).finally(() => {
1288
+ if (this._requestedConsent === requested) this._requestedConsent = void 0;
1289
+ });
1290
+ }
1291
+ async _optOut() {
1292
+ this._generation++;
1293
+ await this._core.optOut();
1294
+ }
1295
+ /**
1296
+ * Fire-and-forget: never throws or rejects. Storage failures are reported through `onError`; reports after
1297
+ * shutdown or across an identity change are dropped.
1298
+ */
1299
+ captureException(error, properties) {
1300
+ this._captureException(error, properties).catch(() => {});
1301
+ }
1302
+ _captureException(error, properties, hint) {
1303
+ const canCapture = () => !this._core.isDisabled && !this._core.optedOut;
1304
+ if (!canCapture()) return Promise.resolve();
1305
+ return this._run(() => {
1306
+ if (this._core.optedOut || this._core.isDisabled) return;
1307
+ try {
1308
+ const exception = this._core.getErrorPropertiesBuilder().buildFromUnknown(error, hint);
1309
+ this._core.capture("$exception", {
1310
+ ...properties,
1311
+ ...exception
1312
+ }, { _originatedFromCaptureException: true });
1313
+ } catch (captureError) {
1314
+ this._report(captureError);
1315
+ }
1316
+ }, this._generation, void 0, false, canCapture);
1317
+ }
1318
+ getDistinctId() {
1319
+ return this._core.getDistinctId();
1320
+ }
1321
+ /** Return the shared anonymous ID, stable across identify and rotated by reset; await ready() first. */
1322
+ getAnonymousId() {
1323
+ return this._core.getAnonymousId();
1324
+ }
1325
+ /** Read cached consent; await ready() before relying on persisted consent. */
1326
+ hasOptedOutCapturing() {
1327
+ return this._core.optedOut;
1328
+ }
1329
+ getSessionId() {
1330
+ return this._core.isDisabled ? "" : this._core.getSessionId();
1331
+ }
1332
+ /**
1333
+ * Read the cached value without fetching. A missing key is false with a nonempty cache, otherwise undefined.
1334
+ * Reports a deduplicated exposure by default; sendFeatureFlagEvent: false suppresses it.
1335
+ */
1336
+ getFeatureFlag(key, options) {
1337
+ return this._core.getFeatureFlag(key, { sendEvent: options?.sendFeatureFlagEvent ?? options?.sendEvent });
1338
+ }
1339
+ isFeatureEnabled(key, options) {
1340
+ return this._core.isFeatureEnabled(key, {
1341
+ sendEvent: options?.sendFeatureFlagEvent ?? options?.sendEvent,
1342
+ defaultValue: options?.defaultValue
1343
+ });
1344
+ }
1345
+ /**
1346
+ * Return a copied cached result, or undefined for unknown/unavailable flags; never fetches.
1347
+ * Empty variants are disabled. Reports exposure by default; sendFeatureFlagEvent: false suppresses it.
1348
+ */
1349
+ getFeatureFlagResult(key, options) {
1350
+ const result = this._core.getFeatureFlagResult(key, { sendEvent: options?.sendFeatureFlagEvent ?? options?.sendEvent });
1351
+ return result === void 0 ? void 0 : this._copyFlagResult(result);
1352
+ }
1353
+ _copyFlagResult(result) {
1354
+ return normalizeFlagResult({
1355
+ ...result,
1356
+ payload: this.getFeatureFlagPayload(result.key) ?? null
1357
+ });
1358
+ }
1359
+ /** Return copied cached results (empty when unavailable), without fetching or reporting exposures. */
1360
+ getAllFeatureFlags() {
1361
+ const details = this._core.getFeatureFlagDetails();
1362
+ this._prunePayloadErrors(details);
1363
+ return (0, _posthog_core.flagDetailsToResults)(details?.flags ?? {}).map((result) => normalizeFlagResult({
1364
+ ...result,
1365
+ payload: this._decodeFlagPayload(result.key, details) ?? null
1366
+ }));
1367
+ }
1368
+ /**
1369
+ * Read a copied, decoded cached payload without fetching or reporting exposure.
1370
+ * Missing payloads are null once flags are loaded, otherwise undefined; strings are not decoded again.
1371
+ */
1372
+ getFeatureFlagPayload(key) {
1373
+ const details = this._core.getFeatureFlagDetails();
1374
+ this._prunePayloadErrors(details);
1375
+ return this._decodeFlagPayload(key, details);
1376
+ }
1377
+ _prunePayloadErrors(details) {
1378
+ for (const [reportedKey, reportedRaw] of this._reportedPayloadErrors) if (!details || !Object.prototype.hasOwnProperty.call(details.flags, reportedKey) || details.flags[reportedKey].metadata?.payload !== reportedRaw) this._reportedPayloadErrors.delete(reportedKey);
1379
+ }
1380
+ _decodeFlagPayload(key, details) {
1381
+ if (!details) return void 0;
1382
+ const raw = Object.prototype.hasOwnProperty.call(details.flags, key) ? details.flags[key].metadata?.payload : void 0;
1383
+ if (raw === void 0) return null;
1384
+ try {
1385
+ return JSON.parse(raw);
1386
+ } catch (error) {
1387
+ if (this._reportedPayloadErrors.get(key) !== raw) {
1388
+ this._reportedPayloadErrors.set(key, raw);
1389
+ this._report(new Error(`PostHog could not decode payload for flag "${key}"`, { cause: error }));
1390
+ }
1391
+ return null;
1392
+ }
1393
+ }
1394
+ get optedOut() {
1395
+ return this._core.optedOut;
1396
+ }
1397
+ /**
1398
+ * Refresh flags using the shared identity/context after earlier mutations, then persist and synchronize the cache.
1399
+ * A failed fetch normally retains cached flags and resolves; completion does not guarantee fresh values.
1400
+ */
1401
+ reloadFeatureFlags() {
1402
+ return this._reloadFeatureFlags();
1403
+ }
1404
+ /** Compatibility alias for reloadFeatureFlags(), with the same completion and failure semantics. */
1405
+ reloadFeatureFlagsAsync() {
1406
+ return this.reloadFeatureFlags();
1407
+ }
1408
+ async _reloadFeatureFlags(generation, authorize) {
1409
+ await this._ready;
1410
+ await this._tail;
1411
+ if (this._closing) return;
1412
+ if (generation !== void 0 && generation !== this._generation) throw new Error("Stale PostHog identity");
1413
+ authorize?.();
1414
+ await this._core.reloadFeatureFlagsAsync();
1415
+ await this._core.persist();
1416
+ this._scheduleState();
1417
+ }
1418
+ flush() {
1419
+ return this._flush();
1420
+ }
1421
+ async _flush(authorize) {
1422
+ await this._ready;
1423
+ await this._tail;
1424
+ if (this._closed) return;
1425
+ authorize?.();
1426
+ await this._core.flush();
1427
+ await this._core.persist();
1428
+ }
1429
+ getState() {
1430
+ const details = this._core.getFeatureFlagDetails();
1431
+ this._prunePayloadErrors(details);
1432
+ const flags = details?.featureFlags ?? {};
1433
+ const payloads = Object.create(null);
1434
+ for (const key of Object.keys(flags)) {
1435
+ const payload = this._decodeFlagPayload(key, details);
1436
+ if (payload !== void 0) payloads[key] = payload;
1437
+ }
1438
+ return structuredClone({
1439
+ revision: this._revision,
1440
+ generation: this._generation,
1441
+ distinctId: this._core.getDistinctId(),
1442
+ anonymousId: this._core.getAnonymousId(),
1443
+ sessionId: this._core.getPersistedProperty(_posthog_core.PostHogPersistedProperty.SessionId) ?? "",
1444
+ optedOut: this._core.optedOut,
1445
+ disabled: this._core.isDisabled,
1446
+ autocapture: this._core.getAutocaptureState(),
1447
+ featureFlags: flags,
1448
+ flagsLoaded: details !== void 0,
1449
+ flagRevision: this._flagRevision,
1450
+ featureFlagPayloads: payloads
1451
+ });
1452
+ }
1453
+ _scheduleState() {
1454
+ if (this._notifyPending || this._closed) return;
1455
+ this._notifyPending = true;
1456
+ queueMicrotask(() => {
1457
+ this._notifyPending = false;
1458
+ if (this._closed) return;
1459
+ const flags = JSON.stringify([this._core.getPersistedProperty(_posthog_core.PostHogPersistedProperty.FeatureFlagDetails), this._core.getPersistedProperty(_posthog_core.PostHogPersistedProperty.FlagsEndpointWasHit)]);
1460
+ if (flags !== this._lastFlags) {
1461
+ this._lastFlags = flags;
1462
+ this._flagRevision++;
1463
+ }
1464
+ const state = this.getState();
1465
+ const serialized = JSON.stringify({
1466
+ ...state,
1467
+ revision: 0
1468
+ });
1469
+ if (serialized === this._lastPublished) return;
1470
+ this._lastPublished = serialized;
1471
+ state.revision = ++this._revision;
1472
+ for (const registered of this._utilities.values()) registered.publish(state);
1473
+ for (const registered of this._windows.values()) if (!registered.contents.isDestroyed() && registered.frame !== void 0 && trustedUrl(registered.contents.getURL(), registered.allowedUrls)) registered.contents.mainFrame.send(STATE_CHANNEL, state);
1474
+ });
1475
+ }
1476
+ registerWindow(window, options) {
1477
+ if (!options.allowedUrls.length || options.allowedUrls.some((url) => !trustedUrl(url, [url]))) throw new Error("PostHog requires explicit trusted window URLs");
1478
+ const contents = window.webContents;
1479
+ this._windows.get(contents.id)?.dispose();
1480
+ const registration = {
1481
+ contents,
1482
+ allowedUrls: [...options.allowedUrls],
1483
+ sequence: 0,
1484
+ frame: void 0,
1485
+ requests: 0,
1486
+ period: performance.now(),
1487
+ dispose: () => {}
1488
+ };
1489
+ const navigation = () => {
1490
+ registration.sequence = 0;
1491
+ registration.frame = void 0;
1492
+ };
1493
+ const focus = () => {
1494
+ clearTimeout(this._focusTimer);
1495
+ this._updateFocus();
1496
+ };
1497
+ const blur = () => {
1498
+ clearTimeout(this._focusTimer);
1499
+ this._focusTimer = setTimeout(() => this._updateFocus(), 50);
1500
+ this._focusTimer.unref();
1501
+ };
1502
+ const dispose = () => {
1503
+ contents.removeListener("did-navigate", navigation);
1504
+ contents.removeListener("destroyed", dispose);
1505
+ window.removeListener("focus", focus);
1506
+ window.removeListener("blur", blur);
1507
+ this._windows.delete(contents.id);
1508
+ this._updateFocus();
1509
+ };
1510
+ registration.dispose = dispose;
1511
+ contents.on("did-navigate", navigation);
1512
+ contents.once("destroyed", dispose);
1513
+ window.on("focus", focus);
1514
+ window.on("blur", blur);
1515
+ this._windows.set(contents.id, registration);
1516
+ return dispose;
1517
+ }
1518
+ /** Register only a trusted utilityProcess.fork() result, immediately after forking. */
1519
+ registerUtilityProcess(child) {
1520
+ if (this._closing) throw new Error("PostHog is shut down");
1521
+ if (this._utilities.has(child)) throw new Error("PostHog utility process is already registered");
1522
+ const registration = attachUtilityProcess(child, (command, context, generation, authorize) => this._execute(command, context, generation, authorize), () => this.getState(), () => this._utilities.delete(child));
1523
+ this._utilities.set(child, registration);
1524
+ return registration.dispose;
1525
+ }
1526
+ _updateFocus() {
1527
+ if (this._closing || this._options.captureAppLifecycleEvents === false) return;
1528
+ const active = [...this._windows.values()].some(({ contents }) => !contents.isDestroyed() && contents.isFocused());
1529
+ if (this._foreground === active) return;
1530
+ const previous = this._foreground;
1531
+ this._foreground = active;
1532
+ if (active) {
1533
+ if (previous === false) this.capture("Application Opened", { from_background: true });
1534
+ } else this.capture("Application Backgrounded");
1535
+ }
1536
+ async _handle(event, value) {
1537
+ try {
1538
+ const registered = this._windows.get(event.sender.id);
1539
+ if (!registered || !event.senderFrame || event.senderFrame !== event.sender.mainFrame || !trustedUrl(event.senderFrame.url, registered.allowedUrls)) throw new Error("Unauthorized PostHog sender");
1540
+ if (performance.now() - registered.period >= 1e3) {
1541
+ registered.period = performance.now();
1542
+ registered.requests = 0;
1543
+ }
1544
+ if (++registered.requests > 100) throw new Error("PostHog renderer rate limit exceeded");
1545
+ validateRequest(value);
1546
+ if (value.command.type === "hello") {
1547
+ if (registered.frame === event.senderFrame.routingId && value.sequence <= registered.sequence) throw new Error("Duplicate PostHog request");
1548
+ registered.frame = event.senderFrame.routingId;
1549
+ } else if (registered.frame !== event.senderFrame.routingId) throw new Error("PostHog handshake required");
1550
+ if (value.sequence <= registered.sequence) throw new Error("Out-of-order PostHog request");
1551
+ registered.sequence = value.sequence;
1552
+ await this._ready;
1553
+ if (this._closing) throw new Error("PostHog is shut down");
1554
+ const command = value.command;
1555
+ if (command.type !== "hello" && command.type !== "flush" && command.type !== "optOut" && value.generation !== this._generation) throw new Error("Stale PostHog identity; synchronize before capturing");
1556
+ const context = {
1557
+ $electron_process: "renderer",
1558
+ $window_id: String(event.sender.id)
1559
+ };
1560
+ const authorize = () => {
1561
+ if (this._windows.get(event.sender.id) !== registered || registered.frame !== event.senderFrame?.routingId || !trustedUrl(event.sender.getURL(), registered.allowedUrls)) throw new Error("PostHog sender navigated or disconnected");
1562
+ };
1563
+ authorize();
1564
+ await this._execute(command, context, value.generation, authorize);
1565
+ return {
1566
+ ok: true,
1567
+ state: this.getState()
1568
+ };
1569
+ } catch (error) {
1570
+ return {
1571
+ ok: false,
1572
+ error: error instanceof Error ? error.message : "PostHog request failed"
1573
+ };
1574
+ }
1575
+ }
1576
+ async _execute(command, context, generation, authorize) {
1577
+ if (command.type === "hello") return this._run(() => {}, void 0, authorize);
1578
+ if (command.type === "flush") return this._flush(authorize);
1579
+ if (command.type === "reloadFeatureFlags") return this._reloadFeatureFlags(generation, authorize);
1580
+ if (command.type === "optOut") return this._changeConsent(true, void 0, authorize);
1581
+ if (command.type === "loadAutocaptureConfig") {
1582
+ await this._ready;
1583
+ await this._tail;
1584
+ if (this._closing) return;
1585
+ if (generation !== this._generation) throw new Error("Stale PostHog identity");
1586
+ authorize();
1587
+ await this._core.loadAutocaptureConfig();
1588
+ if (!this._closing) await this._core.persist();
1589
+ this._scheduleState();
1590
+ return;
1591
+ }
1592
+ const operation = () => this._core.withContext(context, () => {
1593
+ switch (command.type) {
1594
+ case "capture": return this._core.capture(command.event, {
1595
+ ...command.properties,
1596
+ ...context
1597
+ });
1598
+ case "alias": return this._alias(command.alias);
1599
+ case "screen": return this._core.capture("$screen", {
1600
+ ...command.properties,
1601
+ ...context,
1602
+ $screen_name: command.name
1603
+ });
1604
+ case "setPersonProperties": return this._setPersonProperties(command.properties, command.propertiesOnce);
1605
+ case "setPersonPropertiesForFlags": return this._setPersonPropertiesForFlags(command.properties, command.reloadFeatureFlags);
1606
+ case "setGroupPropertiesForFlags": return this._setGroupPropertiesForFlags(command.properties, command.reloadFeatureFlags);
1607
+ case "resetPersonPropertiesForFlags": return this._resetPersonPropertiesForFlags(command.reloadFeatureFlags);
1608
+ case "resetGroupPropertiesForFlags": return this._resetGroupPropertiesForFlags(command.reloadFeatureFlags);
1609
+ case "identify": return this._identify(command.distinctId, command.properties);
1610
+ case "reset": return this._reset();
1611
+ case "group": return this._core.group(command.groupType, command.groupKey, command.properties);
1612
+ case "register": return this._core.register(command.properties);
1613
+ case "unregister": return this._core.unregister(command.key);
1614
+ case "optIn": return this._core.optIn();
1615
+ case "flag":
1616
+ if (command.flagRevision === this._flagRevision && this._core.getFeatureFlag(command.key, { sendEvent: false }) === (command.value ?? void 0)) this._core.getFeatureFlag(command.key);
1617
+ return;
1618
+ case "exception": return this._core.capture("$exception", {
1619
+ ...command.properties,
1620
+ ...context
1621
+ }, { _originatedFromCaptureException: true });
1622
+ }
1623
+ });
1624
+ if (isFlagContextCommand(command)) return this._runFlagContext(operation, generation, authorize);
1625
+ return this._run(operation, generation, authorize, command.type === "optIn");
1626
+ }
1627
+ shutdown(timeoutMs = 2e3) {
1628
+ if (this._shutdownPromise) return this._shutdownPromise;
1629
+ this._closing = true;
1630
+ for (const registration of this._utilities.values()) registration.dispose();
1631
+ this._stopExceptionAutocapture?.();
1632
+ this._stopExceptionAutocapture = void 0;
1633
+ clearInterval(this._timer);
1634
+ clearTimeout(this._focusTimer);
1635
+ let timer;
1636
+ let cleanupPromise;
1637
+ const cleanup = () => {
1638
+ if (cleanupPromise) return cleanupPromise;
1639
+ this._closed = true;
1640
+ this._cancelReady();
1641
+ const stopped = this._core.stop();
1642
+ electron.ipcMain.removeHandler(COMMAND_CHANNEL);
1643
+ for (const cleanup of this._cleanups) cleanup();
1644
+ for (const registration of this._windows.values()) registration.dispose();
1645
+ if (singleton === this) singleton = void 0;
1646
+ return cleanupPromise = stopped;
1647
+ };
1648
+ const drain = async () => {
1649
+ await this._ready;
1650
+ if (this._closed) return;
1651
+ await this._tail;
1652
+ if (this._closed) return;
1653
+ await this._core.shutdown(timeoutMs);
1654
+ if (!this._closed) await this._core.persist();
1655
+ await cleanup();
1656
+ };
1657
+ this._shutdownPromise = Promise.race([drain().catch(async (error) => {
1658
+ this._report(error);
1659
+ await cleanup();
1660
+ }), new Promise((resolve) => {
1661
+ timer = setTimeout(() => {
1662
+ this._report(/* @__PURE__ */ new Error("PostHog shutdown timed out; unsent events remain in storage"));
1663
+ resolve();
1664
+ }, Math.max(0, timeoutMs));
1665
+ })]).finally(() => {
1666
+ clearTimeout(timer);
1667
+ cleanup().catch((error) => this._report(error));
1668
+ });
1669
+ return this._shutdownPromise;
1670
+ }
1671
+ };
1672
+ function init(options) {
1673
+ if (singleton) {
1674
+ if (singletonOptions?.projectToken !== options.projectToken || singletonOptions?.host !== options.host) throw new Error("PostHog Electron is already initialized for a different project");
1675
+ return singleton;
1676
+ }
1677
+ return new PostHog(options);
1678
+ }
1679
+ //#endregion
1680
+ exports.PostHog = PostHog;
1681
+ exports.init = init;
1682
+
1683
+ //# sourceMappingURL=main.cjs.map