@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/CHANGELOG.md +12 -0
- package/LICENSE +417 -0
- package/MIGRATION.md +54 -0
- package/README.md +313 -2
- package/dist/main.cjs +1683 -0
- package/dist/main.cjs.map +1 -0
- package/dist/main.d.ts +224 -0
- package/dist/main.mjs +1681 -0
- package/dist/main.mjs.map +1 -0
- package/dist/preload-helper.cjs +22 -0
- package/dist/preload-helper.cjs.map +1 -0
- package/dist/preload-helper.d.ts +5 -0
- package/dist/preload-helper.mjs +21 -0
- package/dist/preload-helper.mjs.map +1 -0
- package/dist/preload.cjs +24 -0
- package/dist/preload.cjs.map +1 -0
- package/dist/preload.d.ts +1 -0
- package/dist/preload.mjs +23 -0
- package/dist/preload.mjs.map +1 -0
- package/dist/react.cjs +73 -0
- package/dist/react.cjs.map +1 -0
- package/dist/react.d.ts +17 -0
- package/dist/react.mjs +68 -0
- package/dist/react.mjs.map +1 -0
- package/dist/renderer.cjs +591 -0
- package/dist/renderer.cjs.map +1 -0
- package/dist/renderer.d.ts +258 -0
- package/dist/renderer.mjs +589 -0
- package/dist/renderer.mjs.map +1 -0
- package/dist/utility.cjs +770 -0
- package/dist/utility.cjs.map +1 -0
- package/dist/utility.d.ts +266 -0
- package/dist/utility.mjs +768 -0
- package/dist/utility.mjs.map +1 -0
- package/package.json +105 -3
package/dist/utility.mjs
ADDED
|
@@ -0,0 +1,768 @@
|
|
|
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 MAX_MESSAGE_BYTES = 262144;
|
|
50
|
+
function isFlagContextCommand(command) {
|
|
51
|
+
return command.type === "setPersonPropertiesForFlags" || command.type === "setGroupPropertiesForFlags" || command.type === "resetPersonPropertiesForFlags" || command.type === "resetGroupPropertiesForFlags";
|
|
52
|
+
}
|
|
53
|
+
function isRecord(value) {
|
|
54
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
55
|
+
}
|
|
56
|
+
function assertJson(value, depth = 0, allowReservedKeys = false) {
|
|
57
|
+
let remaining = MAX_MESSAGE_BYTES;
|
|
58
|
+
const spend = (size) => {
|
|
59
|
+
remaining -= size;
|
|
60
|
+
if (remaining < 0) throw new Error("PostHog message exceeds 256 KiB");
|
|
61
|
+
};
|
|
62
|
+
const visit = (item, level) => {
|
|
63
|
+
if (level > 20) throw new Error("PostHog payload is too deeply nested");
|
|
64
|
+
spend(typeof item === "string" ? item.length + 2 : 1);
|
|
65
|
+
if (item === null || typeof item === "string" || typeof item === "boolean") return;
|
|
66
|
+
if (typeof item === "number" && Number.isFinite(item)) return;
|
|
67
|
+
if (Array.isArray(item)) {
|
|
68
|
+
for (const element of item) visit(element, level + 1);
|
|
69
|
+
return;
|
|
70
|
+
}
|
|
71
|
+
if (isRecord(item) && (Object.getPrototypeOf(item) === Object.prototype || Object.getPrototypeOf(item) === null)) {
|
|
72
|
+
for (const key in item) {
|
|
73
|
+
if (!Object.hasOwn(item, key)) continue;
|
|
74
|
+
spend(key.length + 3);
|
|
75
|
+
if (!allowReservedKeys && [
|
|
76
|
+
"__proto__",
|
|
77
|
+
"constructor",
|
|
78
|
+
"prototype"
|
|
79
|
+
].includes(key)) throw new Error("Unsafe PostHog property key");
|
|
80
|
+
visit(item[key], level + 1);
|
|
81
|
+
}
|
|
82
|
+
return;
|
|
83
|
+
}
|
|
84
|
+
throw new Error("PostHog properties must be JSON serializable");
|
|
85
|
+
};
|
|
86
|
+
visit(value, depth);
|
|
87
|
+
}
|
|
88
|
+
//#endregion
|
|
89
|
+
//#region src/renderer/autocapture.ts
|
|
90
|
+
const AUTOCAPTURE_CONFIG_KEYS = [
|
|
91
|
+
"maskAllText",
|
|
92
|
+
"maskAllElementAttributes",
|
|
93
|
+
"disableCaptureUrlHashes",
|
|
94
|
+
"url_allowlist",
|
|
95
|
+
"url_ignorelist",
|
|
96
|
+
"dom_event_allowlist",
|
|
97
|
+
"element_allowlist",
|
|
98
|
+
"css_selector_allowlist",
|
|
99
|
+
"css_selector_ignorelist",
|
|
100
|
+
"element_attribute_ignorelist"
|
|
101
|
+
];
|
|
102
|
+
/** Volatile extension state only; main owns the durable project config cache. */
|
|
103
|
+
var AutocaptureStore = class {
|
|
104
|
+
constructor() {
|
|
105
|
+
this.values = /* @__PURE__ */ new Map();
|
|
106
|
+
}
|
|
107
|
+
initialize() {}
|
|
108
|
+
get(key) {
|
|
109
|
+
if (typeof key === "string") return this.values.get(key);
|
|
110
|
+
return Object.fromEntries(key.filter((name) => this.values.has(name)).map((name) => [name, this.values.get(name)]));
|
|
111
|
+
}
|
|
112
|
+
set(key, value) {
|
|
113
|
+
if (typeof key === "string") this.values.set(key, value);
|
|
114
|
+
else for (const [name, item] of Object.entries(key)) this.values.set(name, item);
|
|
115
|
+
}
|
|
116
|
+
remove(keys) {
|
|
117
|
+
for (const key of typeof keys === "string" ? [keys] : keys) this.values.delete(key);
|
|
118
|
+
}
|
|
119
|
+
};
|
|
120
|
+
var RendererAutocapture = class {
|
|
121
|
+
constructor(host, config) {
|
|
122
|
+
this.host = host;
|
|
123
|
+
this.config = config;
|
|
124
|
+
this.disposed = false;
|
|
125
|
+
this.active = false;
|
|
126
|
+
this.loading = false;
|
|
127
|
+
this.retryDelay = 1e3;
|
|
128
|
+
}
|
|
129
|
+
update(paused) {
|
|
130
|
+
if (this.disposed) return;
|
|
131
|
+
const state = this.host.getState();
|
|
132
|
+
if (paused || state.optedOut || state.generation !== this.generation) this.stop();
|
|
133
|
+
if (paused || state.optedOut) return;
|
|
134
|
+
this.active = true;
|
|
135
|
+
this.generation = state.generation;
|
|
136
|
+
if (!this.extension) {
|
|
137
|
+
const kv = new AutocaptureStore();
|
|
138
|
+
if (typeof state.autocapture?.autocapture_opt_out === "boolean") kv.set(AUTOCAPTURE_DISABLED_SERVER_SIDE, state.autocapture.autocapture_opt_out);
|
|
139
|
+
const extension = new Autocapture({ refresh: (config) => {
|
|
140
|
+
for (const key of AUTOCAPTURE_CONFIG_KEYS) if (this.config[key] !== void 0) Object.assign(config, { [key]: this.config[key] });
|
|
141
|
+
const current = this.host.getState();
|
|
142
|
+
config.enabled = !this.disposed && !current.optedOut && current.autocapture?.status !== "pending";
|
|
143
|
+
config.remoteRequestsDisabled = current.autocapture?.status === "disabled";
|
|
144
|
+
} });
|
|
145
|
+
this.extension = extension;
|
|
146
|
+
const host = this.host;
|
|
147
|
+
const adapter = {
|
|
148
|
+
get distinctId() {
|
|
149
|
+
return host.getState().distinctId;
|
|
150
|
+
},
|
|
151
|
+
kv,
|
|
152
|
+
onRemoteConfig: (listener) => {
|
|
153
|
+
this.remoteListener = listener;
|
|
154
|
+
return { dispose: () => {
|
|
155
|
+
this.remoteListener = void 0;
|
|
156
|
+
} };
|
|
157
|
+
},
|
|
158
|
+
capture: (event, properties) => {
|
|
159
|
+
host.capture(event, properties ?? void 0);
|
|
160
|
+
return true;
|
|
161
|
+
}
|
|
162
|
+
};
|
|
163
|
+
try {
|
|
164
|
+
extension.setup(adapter);
|
|
165
|
+
} catch (error) {
|
|
166
|
+
this.stop();
|
|
167
|
+
host.onError(error);
|
|
168
|
+
return;
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
const remote = state.autocapture;
|
|
172
|
+
if (remote?.status === "loaded") this.remoteListener?.({
|
|
173
|
+
ok: true,
|
|
174
|
+
config: remote
|
|
175
|
+
});
|
|
176
|
+
if (remote?.status === "failed") {
|
|
177
|
+
if (remote.elementsChainAsString) this.remoteListener?.({
|
|
178
|
+
ok: true,
|
|
179
|
+
config: {
|
|
180
|
+
elementsChainAsString: remote.elementsChainAsString,
|
|
181
|
+
...typeof remote.autocapture_opt_out === "boolean" ? { autocapture_opt_out: remote.autocapture_opt_out } : {}
|
|
182
|
+
}
|
|
183
|
+
});
|
|
184
|
+
this.remoteListener?.({ ok: false });
|
|
185
|
+
}
|
|
186
|
+
if (remote?.status === "disabled") this.extension?.startIfEnabled();
|
|
187
|
+
if (remote?.status === "loaded" || remote?.status === "disabled") {
|
|
188
|
+
clearTimeout(this.retryTimer);
|
|
189
|
+
this.retryTimer = void 0;
|
|
190
|
+
this.retryDelay = 1e3;
|
|
191
|
+
}
|
|
192
|
+
if (this.requestedGeneration !== state.generation && remote?.status !== "disabled") this.loadConfig();
|
|
193
|
+
else if (remote?.status === "failed") this.scheduleRetry();
|
|
194
|
+
}
|
|
195
|
+
loadConfig() {
|
|
196
|
+
if (this.disposed || !this.active || this.loading) return;
|
|
197
|
+
this.loading = true;
|
|
198
|
+
this.requestedGeneration = this.host.getState().generation;
|
|
199
|
+
this.host.loadConfig().catch((error) => this.host.onError(error)).finally(() => {
|
|
200
|
+
this.loading = false;
|
|
201
|
+
if (this.disposed || !this.active) return;
|
|
202
|
+
if (this.requestedGeneration !== this.host.getState().generation) this.update(false);
|
|
203
|
+
else this.scheduleRetry();
|
|
204
|
+
});
|
|
205
|
+
}
|
|
206
|
+
scheduleRetry() {
|
|
207
|
+
const status = this.host.getState().autocapture?.status;
|
|
208
|
+
if (this.disposed || !this.active || this.loading || this.retryTimer || status === "loaded" || status === "disabled") return;
|
|
209
|
+
this.retryTimer = setTimeout(() => {
|
|
210
|
+
this.retryTimer = void 0;
|
|
211
|
+
this.loadConfig();
|
|
212
|
+
}, this.retryDelay);
|
|
213
|
+
this.retryDelay = Math.min(this.retryDelay * 2, 6e4);
|
|
214
|
+
}
|
|
215
|
+
stop() {
|
|
216
|
+
this.active = false;
|
|
217
|
+
clearTimeout(this.retryTimer);
|
|
218
|
+
this.retryTimer = void 0;
|
|
219
|
+
this.retryDelay = 1e3;
|
|
220
|
+
this.requestedGeneration = void 0;
|
|
221
|
+
this.extension?.dispose();
|
|
222
|
+
this.extension = void 0;
|
|
223
|
+
this.remoteListener = void 0;
|
|
224
|
+
}
|
|
225
|
+
dispose() {
|
|
226
|
+
this.disposed = true;
|
|
227
|
+
this.stop();
|
|
228
|
+
}
|
|
229
|
+
};
|
|
230
|
+
//#endregion
|
|
231
|
+
//#region src/renderer/index.ts
|
|
232
|
+
const bridgeSequences = /* @__PURE__ */ new WeakMap();
|
|
233
|
+
var PostHog$1 = class {
|
|
234
|
+
constructor(_bridge, _options = {}) {
|
|
235
|
+
this._bridge = _bridge;
|
|
236
|
+
this._options = _options;
|
|
237
|
+
this._autocapturePauses = 0;
|
|
238
|
+
this._pendingOptOuts = 0;
|
|
239
|
+
this._reportedFlags = /* @__PURE__ */ new Set();
|
|
240
|
+
this._tail = Promise.resolve();
|
|
241
|
+
this._listeners = /* @__PURE__ */ new Set();
|
|
242
|
+
this._disposed = false;
|
|
243
|
+
this._builder = new ErrorPropertiesBuilder([
|
|
244
|
+
new ErrorEventCoercer(),
|
|
245
|
+
new PromiseRejectionEventCoercer(),
|
|
246
|
+
new ErrorCoercer(),
|
|
247
|
+
new ObjectCoercer(),
|
|
248
|
+
new StringCoercer(),
|
|
249
|
+
new PrimitiveCoercer()
|
|
250
|
+
], createDefaultStackParser());
|
|
251
|
+
this._inOnError = false;
|
|
252
|
+
this._reportedFailures = /* @__PURE__ */ new WeakSet();
|
|
253
|
+
if (_options.autocapture) this._autocapture = new RendererAutocapture({
|
|
254
|
+
getState: () => {
|
|
255
|
+
const state = this._state;
|
|
256
|
+
if (!state) throw new Error("PostHog renderer is not ready");
|
|
257
|
+
return {
|
|
258
|
+
generation: state.generation,
|
|
259
|
+
distinctId: state.distinctId,
|
|
260
|
+
optedOut: state.optedOut,
|
|
261
|
+
autocapture: state.autocapture
|
|
262
|
+
};
|
|
263
|
+
},
|
|
264
|
+
capture: (event, properties) => this.capture(event, properties),
|
|
265
|
+
loadConfig: () => this._send({ type: "loadAutocaptureConfig" }),
|
|
266
|
+
onError: (error) => this._report(error)
|
|
267
|
+
}, typeof _options.autocapture === "object" ? _options.autocapture : {});
|
|
268
|
+
this._unsubscribe = this._bridge.subscribe((state) => this._update(state));
|
|
269
|
+
}
|
|
270
|
+
_update(state) {
|
|
271
|
+
if (this._disposed || this._state && state.revision <= this._state.revision) return;
|
|
272
|
+
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();
|
|
273
|
+
this._state = structuredClone(state);
|
|
274
|
+
this._autocapture?.update(this._autocapturePauses > 0);
|
|
275
|
+
for (const listener of this._listeners) try {
|
|
276
|
+
listener(this.getState());
|
|
277
|
+
} catch {}
|
|
278
|
+
}
|
|
279
|
+
async _send(command) {
|
|
280
|
+
const generation = this._state?.generation ?? 0;
|
|
281
|
+
structuredClone(command);
|
|
282
|
+
const snapshot = JSON.parse(JSON.stringify(command));
|
|
283
|
+
const dispatched = this._tail.then(() => {
|
|
284
|
+
if (this._disposed) throw new Error("PostHog renderer has been disposed");
|
|
285
|
+
if (command.type === "exception" && !this._canCaptureException()) return { response: void 0 };
|
|
286
|
+
const sequence = (bridgeSequences.get(this._bridge) ?? 0) + 1;
|
|
287
|
+
bridgeSequences.set(this._bridge, sequence);
|
|
288
|
+
return { response: this._bridge.request({
|
|
289
|
+
version: 1,
|
|
290
|
+
sequence,
|
|
291
|
+
generation,
|
|
292
|
+
command: snapshot
|
|
293
|
+
}) };
|
|
294
|
+
});
|
|
295
|
+
const operation = dispatched.then(async ({ response: pending }) => {
|
|
296
|
+
if (!pending) return;
|
|
297
|
+
const response = await pending;
|
|
298
|
+
if (!response.ok) throw new Error(response.error);
|
|
299
|
+
this._update(response.state);
|
|
300
|
+
});
|
|
301
|
+
const networkBound = command.type === "flush" || command.type === "reloadFeatureFlags" || command.type === "loadAutocaptureConfig" || isFlagContextCommand(command) && command.reloadFeatureFlags;
|
|
302
|
+
this._tail = (networkBound ? dispatched : operation).catch(() => {});
|
|
303
|
+
return operation;
|
|
304
|
+
}
|
|
305
|
+
_pauseAutocapture(command) {
|
|
306
|
+
this._autocapturePauses++;
|
|
307
|
+
if (this._state) this._autocapture?.update(true);
|
|
308
|
+
return this._send(command).finally(() => {
|
|
309
|
+
this._autocapturePauses--;
|
|
310
|
+
if (this._state) this._autocapture?.update(this._autocapturePauses > 0);
|
|
311
|
+
});
|
|
312
|
+
}
|
|
313
|
+
async ready() {
|
|
314
|
+
if (this._disposed) throw new Error("PostHog renderer has been disposed");
|
|
315
|
+
await (this._ready ??= this._send({ type: "hello" }).catch((error) => {
|
|
316
|
+
this._ready = void 0;
|
|
317
|
+
throw error;
|
|
318
|
+
}));
|
|
319
|
+
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));
|
|
320
|
+
}
|
|
321
|
+
_report(error) {
|
|
322
|
+
const inOnError = this._inOnError;
|
|
323
|
+
this._inOnError = true;
|
|
324
|
+
try {
|
|
325
|
+
const result = this._options.onError?.(error);
|
|
326
|
+
if (typeof result?.then === "function") Promise.resolve(result).catch(() => {});
|
|
327
|
+
} catch {} finally {
|
|
328
|
+
this._inOnError = inOnError;
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
_reportFailure(promise, quiet = this._inOnError) {
|
|
332
|
+
promise.catch((error) => {
|
|
333
|
+
if (quiet) return;
|
|
334
|
+
if (typeof error === "object" && error !== null) this._reportedFailures.add(error);
|
|
335
|
+
this._report(error);
|
|
336
|
+
});
|
|
337
|
+
}
|
|
338
|
+
/** Fire-and-forget: never throws or rejects. Failed requests are reported through `onError`. */
|
|
339
|
+
capture(event, properties) {
|
|
340
|
+
if (typeof event !== "string" || this.hasOptedOutCapturing()) return;
|
|
341
|
+
this._reportFailure(this._send({
|
|
342
|
+
type: "capture",
|
|
343
|
+
event,
|
|
344
|
+
...properties ? { properties } : {}
|
|
345
|
+
}));
|
|
346
|
+
}
|
|
347
|
+
/**
|
|
348
|
+
* Link the current distinct ID to an alias without switching identity or reloading flags.
|
|
349
|
+
* Ignored when opted out or personProfiles is 'never'. Resolves after local persistence, not delivery.
|
|
350
|
+
*/
|
|
351
|
+
alias(alias) {
|
|
352
|
+
if (!alias?.trim()) return Promise.resolve();
|
|
353
|
+
if (this.hasOptedOutCapturing()) return Promise.resolve();
|
|
354
|
+
return this._send({
|
|
355
|
+
type: "alias",
|
|
356
|
+
alias
|
|
357
|
+
});
|
|
358
|
+
}
|
|
359
|
+
/**
|
|
360
|
+
* Capture an event-only $screen; name wins over properties.$screen_name without setting persistent screen context.
|
|
361
|
+
* Fire-and-forget: never throws or rejects; ignored when opted out.
|
|
362
|
+
*/
|
|
363
|
+
screen(name, properties) {
|
|
364
|
+
if (typeof name !== "string" || !name.trim()) return;
|
|
365
|
+
if (this.hasOptedOutCapturing()) return;
|
|
366
|
+
this._reportFailure(this._send({
|
|
367
|
+
type: "screen",
|
|
368
|
+
name,
|
|
369
|
+
...properties ? { properties } : {}
|
|
370
|
+
}));
|
|
371
|
+
}
|
|
372
|
+
/**
|
|
373
|
+
* Update the current person's $set/$set_once properties without changing identity; empty updates do nothing.
|
|
374
|
+
* Also updates flag context. Resolves after local persistence, not delivery or the background flag refresh.
|
|
375
|
+
* Ignored when opted out or personProfiles is 'never'.
|
|
376
|
+
*/
|
|
377
|
+
setPersonProperties(properties, propertiesOnce) {
|
|
378
|
+
if (this.hasOptedOutCapturing()) return Promise.resolve();
|
|
379
|
+
return this._send({
|
|
380
|
+
type: "setPersonProperties",
|
|
381
|
+
...properties ? { properties } : {},
|
|
382
|
+
...propertiesOnce ? { propertiesOnce } : {}
|
|
383
|
+
});
|
|
384
|
+
}
|
|
385
|
+
/**
|
|
386
|
+
* Merge a call-time copy of local person overrides for flag evaluation, without updating the person profile.
|
|
387
|
+
* Accepts nested $set/$set_once; empty input does nothing. Otherwise awaits persistence and, by default, a refresh attempt.
|
|
388
|
+
* With false, only saves context; cached flag values stay unchanged until a reload.
|
|
389
|
+
*/
|
|
390
|
+
setPersonPropertiesForFlags(properties, reloadFeatureFlags = true) {
|
|
391
|
+
return this._send({
|
|
392
|
+
type: "setPersonPropertiesForFlags",
|
|
393
|
+
properties,
|
|
394
|
+
reloadFeatureFlags
|
|
395
|
+
});
|
|
396
|
+
}
|
|
397
|
+
/**
|
|
398
|
+
* Merge a call-time copy of local overrides by group type, without changing profiles or group membership.
|
|
399
|
+
* Empty input does nothing. Otherwise awaits persistence and, by default, a flag refresh attempt.
|
|
400
|
+
* With false, only saves context; cached flag values stay unchanged until a reload.
|
|
401
|
+
*/
|
|
402
|
+
setGroupPropertiesForFlags(properties, reloadFeatureFlags = true) {
|
|
403
|
+
return this._send({
|
|
404
|
+
type: "setGroupPropertiesForFlags",
|
|
405
|
+
properties,
|
|
406
|
+
reloadFeatureFlags
|
|
407
|
+
});
|
|
408
|
+
}
|
|
409
|
+
/**
|
|
410
|
+
* Clear all local person flag overrides, not profile data or identity. Resolves after persistence.
|
|
411
|
+
* Cached flag values stay unchanged unless true is passed to also await a refresh attempt.
|
|
412
|
+
*/
|
|
413
|
+
resetPersonPropertiesForFlags(reloadFeatureFlags = false) {
|
|
414
|
+
return this._send({
|
|
415
|
+
type: "resetPersonPropertiesForFlags",
|
|
416
|
+
reloadFeatureFlags
|
|
417
|
+
});
|
|
418
|
+
}
|
|
419
|
+
/**
|
|
420
|
+
* Clear local flag overrides for every group type, not profiles or membership. Resolves after persistence.
|
|
421
|
+
* Cached flag values stay unchanged unless true is passed to also await a refresh attempt.
|
|
422
|
+
*/
|
|
423
|
+
resetGroupPropertiesForFlags(reloadFeatureFlags = false) {
|
|
424
|
+
return this._send({
|
|
425
|
+
type: "resetGroupPropertiesForFlags",
|
|
426
|
+
reloadFeatureFlags
|
|
427
|
+
});
|
|
428
|
+
}
|
|
429
|
+
identify(distinctId, properties) {
|
|
430
|
+
return this._pauseAutocapture({
|
|
431
|
+
type: "identify",
|
|
432
|
+
distinctId,
|
|
433
|
+
...properties ? { properties } : {}
|
|
434
|
+
});
|
|
435
|
+
}
|
|
436
|
+
reset() {
|
|
437
|
+
return this._pauseAutocapture({ type: "reset" });
|
|
438
|
+
}
|
|
439
|
+
group(groupType, groupKey, properties) {
|
|
440
|
+
if (this.hasOptedOutCapturing()) return Promise.resolve();
|
|
441
|
+
return this._send({
|
|
442
|
+
type: "group",
|
|
443
|
+
groupType,
|
|
444
|
+
groupKey,
|
|
445
|
+
...properties ? { properties } : {}
|
|
446
|
+
});
|
|
447
|
+
}
|
|
448
|
+
register(properties) {
|
|
449
|
+
return this._send({
|
|
450
|
+
type: "register",
|
|
451
|
+
properties
|
|
452
|
+
});
|
|
453
|
+
}
|
|
454
|
+
unregister(key) {
|
|
455
|
+
return this._send({
|
|
456
|
+
type: "unregister",
|
|
457
|
+
key
|
|
458
|
+
});
|
|
459
|
+
}
|
|
460
|
+
optIn() {
|
|
461
|
+
return this._send({ type: "optIn" });
|
|
462
|
+
}
|
|
463
|
+
optOut() {
|
|
464
|
+
this._pendingOptOuts++;
|
|
465
|
+
return this._pauseAutocapture({ type: "optOut" }).finally(() => {
|
|
466
|
+
this._pendingOptOuts--;
|
|
467
|
+
});
|
|
468
|
+
}
|
|
469
|
+
/**
|
|
470
|
+
* Refresh flags using the shared identity/context after earlier mutations, then persist and synchronize the cache.
|
|
471
|
+
* A failed fetch normally retains cached flags and resolves; completion does not guarantee fresh values.
|
|
472
|
+
*/
|
|
473
|
+
reloadFeatureFlags() {
|
|
474
|
+
return this._send({ type: "reloadFeatureFlags" });
|
|
475
|
+
}
|
|
476
|
+
/** Compatibility alias for reloadFeatureFlags(), with the same completion and failure semantics. */
|
|
477
|
+
reloadFeatureFlagsAsync() {
|
|
478
|
+
return this.reloadFeatureFlags();
|
|
479
|
+
}
|
|
480
|
+
flush() {
|
|
481
|
+
return this._send({ type: "flush" });
|
|
482
|
+
}
|
|
483
|
+
/** Fire-and-forget: never throws or rejects. Failed requests are reported through `onError`. */
|
|
484
|
+
captureException(error, properties) {
|
|
485
|
+
const reported = typeof error === "object" && error !== null && this._reportedFailures.has(error);
|
|
486
|
+
this._reportFailure(this._captureException(error, properties), this._inOnError || reported);
|
|
487
|
+
}
|
|
488
|
+
_canCaptureException() {
|
|
489
|
+
return !this._disposed && !this._pendingOptOuts && !this._state?.disabled && !this.hasOptedOutCapturing();
|
|
490
|
+
}
|
|
491
|
+
_captureException(error, properties, hint) {
|
|
492
|
+
if (!this._canCaptureException()) return Promise.resolve();
|
|
493
|
+
try {
|
|
494
|
+
const exception = this._builder.buildFromUnknown(error, hint);
|
|
495
|
+
return this._send({
|
|
496
|
+
type: "exception",
|
|
497
|
+
properties: {
|
|
498
|
+
...properties,
|
|
499
|
+
...exception
|
|
500
|
+
}
|
|
501
|
+
});
|
|
502
|
+
} catch {
|
|
503
|
+
return Promise.resolve();
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
getDistinctId() {
|
|
507
|
+
return this._state?.distinctId ?? "";
|
|
508
|
+
}
|
|
509
|
+
/** Return the shared anonymous ID, stable across identify and rotated by reset; '' before synchronization. */
|
|
510
|
+
getAnonymousId() {
|
|
511
|
+
return this._state?.anonymousId ?? "";
|
|
512
|
+
}
|
|
513
|
+
/** Cached consent state; conservatively true until the first synchronized snapshot. */
|
|
514
|
+
get optedOut() {
|
|
515
|
+
return this.hasOptedOutCapturing();
|
|
516
|
+
}
|
|
517
|
+
getSessionId() {
|
|
518
|
+
return this._state?.sessionId ?? "";
|
|
519
|
+
}
|
|
520
|
+
hasOptedOutCapturing() {
|
|
521
|
+
return this._state?.optedOut ?? true;
|
|
522
|
+
}
|
|
523
|
+
/**
|
|
524
|
+
* Read the cached value without fetching. A missing key is false with a nonempty cache, otherwise undefined.
|
|
525
|
+
* Reports a deduplicated exposure for the observed snapshot by default; sendFeatureFlagEvent: false suppresses it.
|
|
526
|
+
*/
|
|
527
|
+
getFeatureFlag(key, options) {
|
|
528
|
+
const flags = this._state?.featureFlags;
|
|
529
|
+
const value = flags && Object.prototype.hasOwnProperty.call(flags, key) ? flags[key] : flags && Object.keys(flags).length > 0 ? false : void 0;
|
|
530
|
+
if ((options?.sendFeatureFlagEvent ?? options?.sendEvent) !== false && this._state) {
|
|
531
|
+
const reportedFlags = this._reportedFlags;
|
|
532
|
+
const reportKey = JSON.stringify([key, value ?? null]);
|
|
533
|
+
if (!reportedFlags.has(reportKey)) {
|
|
534
|
+
reportedFlags.add(reportKey);
|
|
535
|
+
this._send({
|
|
536
|
+
type: "flag",
|
|
537
|
+
key,
|
|
538
|
+
flagRevision: this._state.flagRevision,
|
|
539
|
+
value: value ?? null
|
|
540
|
+
}).catch(() => reportedFlags.delete(reportKey));
|
|
541
|
+
}
|
|
542
|
+
}
|
|
543
|
+
return value;
|
|
544
|
+
}
|
|
545
|
+
isFeatureEnabled(key, options) {
|
|
546
|
+
if (options?.defaultValue !== void 0) {
|
|
547
|
+
const result = this.getFeatureFlagResult(key, options);
|
|
548
|
+
return result === void 0 ? options.defaultValue : Boolean(result.variant ?? result.enabled);
|
|
549
|
+
}
|
|
550
|
+
const value = this.getFeatureFlag(key, options);
|
|
551
|
+
return value === void 0 ? void 0 : Boolean(value);
|
|
552
|
+
}
|
|
553
|
+
/**
|
|
554
|
+
* Return a copied cached result, or undefined for unknown/unavailable flags; never fetches.
|
|
555
|
+
* Empty variants are disabled. Reports exposure by default; sendFeatureFlagEvent: false suppresses it.
|
|
556
|
+
*/
|
|
557
|
+
getFeatureFlagResult(key, options) {
|
|
558
|
+
this.getFeatureFlag(key, options);
|
|
559
|
+
if (!this._state || !Object.prototype.hasOwnProperty.call(this._state.featureFlags, key)) return void 0;
|
|
560
|
+
const value = this._state.featureFlags[key];
|
|
561
|
+
return {
|
|
562
|
+
key,
|
|
563
|
+
enabled: Boolean(value),
|
|
564
|
+
...typeof value === "string" ? { variant: value } : {},
|
|
565
|
+
payload: this.getFeatureFlagPayload(key) ?? null
|
|
566
|
+
};
|
|
567
|
+
}
|
|
568
|
+
/** Return copied cached results (empty when unavailable), without fetching or reporting exposures. */
|
|
569
|
+
getAllFeatureFlags() {
|
|
570
|
+
return Object.keys(this._state?.featureFlags ?? {}).map((key) => this.getFeatureFlagResult(key, { sendFeatureFlagEvent: false }));
|
|
571
|
+
}
|
|
572
|
+
/**
|
|
573
|
+
* Read a copied, decoded cached payload without fetching or reporting exposure.
|
|
574
|
+
* Missing payloads are null once flags are loaded, otherwise undefined; strings are not decoded again.
|
|
575
|
+
*/
|
|
576
|
+
getFeatureFlagPayload(key) {
|
|
577
|
+
const payloads = this._state?.featureFlagPayloads;
|
|
578
|
+
const value = payloads && Object.prototype.hasOwnProperty.call(payloads, key) ? payloads[key] : void 0;
|
|
579
|
+
return value === void 0 ? this._state?.flagsLoaded ? null : void 0 : structuredClone(value);
|
|
580
|
+
}
|
|
581
|
+
getState() {
|
|
582
|
+
if (!this._state) throw new Error("PostHog renderer is not ready");
|
|
583
|
+
return structuredClone(this._state);
|
|
584
|
+
}
|
|
585
|
+
onStateChange(callback) {
|
|
586
|
+
this._listeners.add(callback);
|
|
587
|
+
if (this._state) callback(this.getState());
|
|
588
|
+
return () => this._listeners.delete(callback);
|
|
589
|
+
}
|
|
590
|
+
dispose() {
|
|
591
|
+
if (this._disposed) return;
|
|
592
|
+
this._disposed = true;
|
|
593
|
+
this._stopExceptionAutocapture?.();
|
|
594
|
+
this._stopExceptionAutocapture = void 0;
|
|
595
|
+
this._autocapture?.dispose();
|
|
596
|
+
this._unsubscribe();
|
|
597
|
+
this._listeners.clear();
|
|
598
|
+
this._reportedFlags.clear();
|
|
599
|
+
if (singleton$1 === this) singleton$1 = void 0;
|
|
600
|
+
}
|
|
601
|
+
};
|
|
602
|
+
let singleton$1;
|
|
603
|
+
//#endregion
|
|
604
|
+
//#region src/utility/protocol.ts
|
|
605
|
+
const UTILITY_CHANNEL = "posthog:utility:v1";
|
|
606
|
+
const UTILITY_TIMEOUT_MS = 1e4;
|
|
607
|
+
function envelope(message) {
|
|
608
|
+
return {
|
|
609
|
+
channel: UTILITY_CHANNEL,
|
|
610
|
+
version: 1,
|
|
611
|
+
...message
|
|
612
|
+
};
|
|
613
|
+
}
|
|
614
|
+
function readEnvelope(value, direction = "to-main") {
|
|
615
|
+
if (!isRecord(value) || value.channel !== "posthog:utility:v1") return;
|
|
616
|
+
assertJson(value, 0, direction === "to-utility");
|
|
617
|
+
if (new TextEncoder().encode(JSON.stringify(value)).byteLength > 262144) throw new Error("PostHog utility message exceeds 256 KiB");
|
|
618
|
+
if (value.version !== 1) throw new Error("Unsupported PostHog utility protocol");
|
|
619
|
+
return value;
|
|
620
|
+
}
|
|
621
|
+
function isState(value) {
|
|
622
|
+
return isRecord(value) && [
|
|
623
|
+
"revision",
|
|
624
|
+
"generation",
|
|
625
|
+
"flagRevision"
|
|
626
|
+
].every((key) => Number.isSafeInteger(value[key]) && value[key] >= 0) && [
|
|
627
|
+
"distinctId",
|
|
628
|
+
"anonymousId",
|
|
629
|
+
"sessionId"
|
|
630
|
+
].every((key) => typeof value[key] === "string") && typeof value.optedOut === "boolean" && (value.flagsLoaded === void 0 || typeof value.flagsLoaded === "boolean") && isRecord(value.featureFlags) && Object.values(value.featureFlags).every((flag) => typeof flag === "boolean" || typeof flag === "string") && isRecord(value.featureFlagPayloads);
|
|
631
|
+
}
|
|
632
|
+
function isResponse(value) {
|
|
633
|
+
return isRecord(value) && (value.ok === true && isState(value.state) || value.ok === false && typeof value.error === "string");
|
|
634
|
+
}
|
|
635
|
+
//#endregion
|
|
636
|
+
//#region src/utility/bridge.ts
|
|
637
|
+
function createUtilityBridge(port) {
|
|
638
|
+
let token;
|
|
639
|
+
let closed = false;
|
|
640
|
+
const listeners = /* @__PURE__ */ new Set();
|
|
641
|
+
const pending = /* @__PURE__ */ new Map();
|
|
642
|
+
let connectedResolve;
|
|
643
|
+
let connectedReject;
|
|
644
|
+
const connected = new Promise((resolve, reject) => {
|
|
645
|
+
connectedResolve = resolve;
|
|
646
|
+
connectedReject = reject;
|
|
647
|
+
});
|
|
648
|
+
connected.catch(() => {});
|
|
649
|
+
const timer = setTimeout(() => close(/* @__PURE__ */ new Error("PostHog utility connection timed out")), UTILITY_TIMEOUT_MS);
|
|
650
|
+
const close = (error) => {
|
|
651
|
+
if (closed) return;
|
|
652
|
+
closed = true;
|
|
653
|
+
clearTimeout(timer);
|
|
654
|
+
port.removeListener("message", message);
|
|
655
|
+
connectedReject(error);
|
|
656
|
+
for (const operation of pending.values()) {
|
|
657
|
+
clearTimeout(operation.timer);
|
|
658
|
+
operation.reject(error);
|
|
659
|
+
}
|
|
660
|
+
pending.clear();
|
|
661
|
+
listeners.clear();
|
|
662
|
+
};
|
|
663
|
+
const message = (event) => {
|
|
664
|
+
try {
|
|
665
|
+
const data = readEnvelope(event.data, "to-utility");
|
|
666
|
+
if (!data) return;
|
|
667
|
+
if (data.kind === "connected" && typeof data.token === "string" && data.token.length <= 128) {
|
|
668
|
+
if (token && token !== data.token) throw new Error("PostHog utility connection changed");
|
|
669
|
+
token = data.token;
|
|
670
|
+
clearTimeout(timer);
|
|
671
|
+
connectedResolve();
|
|
672
|
+
return;
|
|
673
|
+
}
|
|
674
|
+
if (!token || data.token !== token) throw new Error("Invalid PostHog utility connection");
|
|
675
|
+
if (data.kind === "closed") close(/* @__PURE__ */ new Error("PostHog utility connection closed"));
|
|
676
|
+
else if (data.kind === "state" && isState(data.state)) for (const listener of listeners) listener(data.state);
|
|
677
|
+
else if (data.kind === "response" && Number.isSafeInteger(data.sequence) && isResponse(data.response)) {
|
|
678
|
+
const operation = pending.get(data.sequence);
|
|
679
|
+
if (!operation) return;
|
|
680
|
+
pending.delete(data.sequence);
|
|
681
|
+
clearTimeout(operation.timer);
|
|
682
|
+
operation.resolve(data.response);
|
|
683
|
+
} else throw new Error("Invalid PostHog utility message");
|
|
684
|
+
} catch (error) {
|
|
685
|
+
close(error instanceof Error ? error : /* @__PURE__ */ new Error("Invalid PostHog utility message"));
|
|
686
|
+
}
|
|
687
|
+
};
|
|
688
|
+
port.on("message", message);
|
|
689
|
+
try {
|
|
690
|
+
port.postMessage(envelope({ kind: "connect" }));
|
|
691
|
+
} catch {
|
|
692
|
+
close(/* @__PURE__ */ new Error("PostHog parentPort unavailable"));
|
|
693
|
+
}
|
|
694
|
+
return {
|
|
695
|
+
request: async (request) => {
|
|
696
|
+
await connected;
|
|
697
|
+
if (closed) throw new Error("PostHog utility connection closed");
|
|
698
|
+
return new Promise((resolve, reject) => {
|
|
699
|
+
const timeout = setTimeout(() => {
|
|
700
|
+
if (pending.get(request.sequence)?.timer !== timeout) return;
|
|
701
|
+
pending.delete(request.sequence);
|
|
702
|
+
reject(/* @__PURE__ */ new Error("PostHog utility request timed out"));
|
|
703
|
+
}, UTILITY_TIMEOUT_MS);
|
|
704
|
+
pending.set(request.sequence, {
|
|
705
|
+
resolve,
|
|
706
|
+
reject,
|
|
707
|
+
timer: timeout
|
|
708
|
+
});
|
|
709
|
+
try {
|
|
710
|
+
const value = envelope({
|
|
711
|
+
kind: "request",
|
|
712
|
+
token,
|
|
713
|
+
request
|
|
714
|
+
});
|
|
715
|
+
readEnvelope(value);
|
|
716
|
+
port.postMessage(value);
|
|
717
|
+
} catch (error) {
|
|
718
|
+
pending.delete(request.sequence);
|
|
719
|
+
clearTimeout(timeout);
|
|
720
|
+
const failure = error instanceof Error ? error : /* @__PURE__ */ new Error("PostHog utility request failed");
|
|
721
|
+
reject(failure);
|
|
722
|
+
close(failure);
|
|
723
|
+
}
|
|
724
|
+
});
|
|
725
|
+
},
|
|
726
|
+
subscribe: (callback) => {
|
|
727
|
+
listeners.add(callback);
|
|
728
|
+
return () => {
|
|
729
|
+
listeners.delete(callback);
|
|
730
|
+
close(/* @__PURE__ */ new Error("PostHog utility client disposed"));
|
|
731
|
+
};
|
|
732
|
+
}
|
|
733
|
+
};
|
|
734
|
+
}
|
|
735
|
+
//#endregion
|
|
736
|
+
//#region src/utility/index.ts
|
|
737
|
+
/** A trusted utility facade. Identity, consent, storage and delivery belong to main. */
|
|
738
|
+
var PostHog = class extends PostHog$1 {
|
|
739
|
+
constructor(options = {}) {
|
|
740
|
+
if (!process.parentPort) throw new Error("PostHog utility requires Electron utilityProcess.parentPort");
|
|
741
|
+
super(createUtilityBridge(process.parentPort), { onError: options.onError });
|
|
742
|
+
}
|
|
743
|
+
dispose() {
|
|
744
|
+
super.dispose();
|
|
745
|
+
if (singleton === this) singleton = void 0;
|
|
746
|
+
}
|
|
747
|
+
};
|
|
748
|
+
let singleton;
|
|
749
|
+
let initializing;
|
|
750
|
+
function init(options = {}) {
|
|
751
|
+
if (initializing) return initializing;
|
|
752
|
+
if (singleton) return Promise.resolve(singleton);
|
|
753
|
+
const client = new PostHog(options);
|
|
754
|
+
initializing = client.ready().then(() => {
|
|
755
|
+
singleton = client;
|
|
756
|
+
return client;
|
|
757
|
+
}).catch((error) => {
|
|
758
|
+
client.dispose();
|
|
759
|
+
throw error;
|
|
760
|
+
}).finally(() => {
|
|
761
|
+
initializing = void 0;
|
|
762
|
+
});
|
|
763
|
+
return initializing;
|
|
764
|
+
}
|
|
765
|
+
//#endregion
|
|
766
|
+
export { PostHog, init };
|
|
767
|
+
|
|
768
|
+
//# sourceMappingURL=utility.mjs.map
|