@zharp/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.mjs ADDED
@@ -0,0 +1,750 @@
1
+ // ../../node_modules/.pnpm/tsup@8.5.1_postcss@8.5.33_typescript@5.9.3_yaml@2.9.1/node_modules/tsup/assets/esm_shims.js
2
+ import path from "path";
3
+ import { fileURLToPath } from "url";
4
+ var getFilename = () => fileURLToPath(import.meta.url);
5
+ var getDirname = () => path.dirname(getFilename());
6
+ var __dirname = /* @__PURE__ */ getDirname();
7
+
8
+ // src/main/index.ts
9
+ import { app, crashReporter, dialog, ipcMain, net, session as electronSession, webContents } from "electron";
10
+ import { randomUUID } from "crypto";
11
+ import { existsSync, mkdirSync as mkdirSync2, readFileSync as readFileSync2, writeFileSync as writeFileSync2 } from "fs";
12
+ import { release as osRelease } from "os";
13
+ import { dirname, join as join2 } from "path";
14
+ import { fileURLToPath as fileURLToPath2 } from "url";
15
+ import { Zharp as NodeZharp } from "@zharp/node";
16
+
17
+ // src/shared.ts
18
+ var CHANNEL = {
19
+ /** Sync: a window asks for the context as its SDK starts. */
20
+ context: "zharp:context",
21
+ /** Main → windows: the user or the session changed. */
22
+ changed: "zharp:context-changed",
23
+ /** A batch from a window, for main to send (invoke; resolves to the HTTP status). */
24
+ send: "zharp:send",
25
+ /** A window set or cleared the user. */
26
+ user: "zharp:user",
27
+ /** A window's user logged out: a new session for everyone. */
28
+ renew: "zharp:renew",
29
+ /** Something happened in a window: the session is still going. */
30
+ activity: "zharp:activity"
31
+ };
32
+
33
+ // src/version.ts
34
+ var VERSION = "0.1.0";
35
+
36
+ // src/main/outbox.ts
37
+ import { randomBytes } from "crypto";
38
+ import { mkdirSync, readdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "fs";
39
+ import { join } from "path";
40
+ import { gzipSync } from "zlib";
41
+ var MAX_FILES = 200;
42
+ var MAX_BYTES = 20 * 1024 * 1024;
43
+ var RETRY_MS = 3e4;
44
+ var MAX_RETRY_MS = 10 * 6e4;
45
+ var retryable = (status) => status === 0 || status === 429 || status >= 500;
46
+ var Outbox = class {
47
+ constructor(dir, endpoint, key, debug = () => {
48
+ }) {
49
+ this.dir = dir;
50
+ this.endpoint = endpoint;
51
+ this.key = key;
52
+ this.debug = debug;
53
+ }
54
+ dir;
55
+ endpoint;
56
+ key;
57
+ debug;
58
+ fetch = null;
59
+ timer = null;
60
+ failures = 0;
61
+ draining = null;
62
+ again = false;
63
+ rejected = false;
64
+ /** The network is usable (the app is ready): send what waited, then send as batches come. */
65
+ start(fetch) {
66
+ this.fetch = fetch;
67
+ try {
68
+ for (const name of readdirSync(this.dir).filter((n) => n.endsWith(".held"))) renameSync(join(this.dir, name), join(this.dir, name.slice(0, -".held".length)));
69
+ } catch {
70
+ }
71
+ void this.drain();
72
+ }
73
+ /**
74
+ * Send one batch now; kept on disk when it can't go. Resolves to the HTTP status, or 202 when
75
+ * it was kept: the window must not queue it again.
76
+ */
77
+ async send(signal, json) {
78
+ const body = gzipSync(json);
79
+ if (!this.fetch) return this.store(signal, body) ? 202 : 0;
80
+ const status = await this.post(signal, body);
81
+ if (!retryable(status)) return status;
82
+ this.schedule();
83
+ return this.store(signal, body) ? 202 : status;
84
+ }
85
+ /**
86
+ * Kept on disk but not sent yet, while main waits to know what to send (a crash event, until
87
+ * its minidump's upload is seen). One left by a run that ended meanwhile is sent at the next
88
+ * start, as it was written.
89
+ */
90
+ hold(signal, json) {
91
+ return this.store(signal, gzipSync(json), ".held");
92
+ }
93
+ /** Send a held batch now, as `json` (the held one replaced). */
94
+ release(name, json) {
95
+ if (name) rmSync(join(this.dir, name), { force: true });
96
+ const signal = name?.includes(".traces.") ? "traces" : "logs";
97
+ void this.sendDurably(signal, json);
98
+ }
99
+ /** Written first, then sent: for what must survive the app going down. */
100
+ async sendDurably(signal, json) {
101
+ const file = this.store(signal, gzipSync(json));
102
+ if (!this.fetch || !file) return;
103
+ await this.drain();
104
+ }
105
+ /** Send everything kept on disk, oldest first, until one can't go. */
106
+ drain() {
107
+ if (this.draining) {
108
+ this.again = true;
109
+ return this.draining;
110
+ }
111
+ this.draining = this.drainNow().finally(() => {
112
+ this.draining = null;
113
+ if (this.again) {
114
+ this.again = false;
115
+ void this.drain();
116
+ }
117
+ });
118
+ return this.draining;
119
+ }
120
+ async drainNow() {
121
+ if (!this.fetch) return;
122
+ const tried = /* @__PURE__ */ new Set();
123
+ for (; ; ) {
124
+ const names = this.files().filter((name) => !tried.has(name));
125
+ if (!names.length) return;
126
+ for (const name of names) {
127
+ tried.add(name);
128
+ const path2 = join(this.dir, name);
129
+ let body;
130
+ try {
131
+ body = readFileSync(path2);
132
+ } catch {
133
+ continue;
134
+ }
135
+ const signal = name.includes(".traces.") ? "traces" : "logs";
136
+ const status = await this.post(signal, body);
137
+ if (retryable(status)) {
138
+ this.failures++;
139
+ this.schedule();
140
+ return;
141
+ }
142
+ this.failures = 0;
143
+ rmSync(path2, { force: true });
144
+ }
145
+ }
146
+ }
147
+ async post(signal, body) {
148
+ if (this.rejected) return 401;
149
+ try {
150
+ const response = await this.fetch(`${this.endpoint}/v1/${signal}`, {
151
+ method: "POST",
152
+ headers: { "Content-Type": "application/json", "Content-Encoding": "gzip", Authorization: `Bearer ${this.key}` },
153
+ body
154
+ });
155
+ if ((response.status === 401 || response.status === 403) && !this.rejected) {
156
+ this.rejected = true;
157
+ console.warn(`[Zharp] The key was rejected (HTTP ${response.status}); nothing more will be sent from the windows. Check Zharp.init({ key }).`);
158
+ }
159
+ return response.status;
160
+ } catch (error) {
161
+ this.debug(`Couldn't send (${error?.message ?? error}); kept for later`);
162
+ return 0;
163
+ }
164
+ }
165
+ schedule() {
166
+ if (this.timer) return;
167
+ const delay = Math.min(RETRY_MS * 2 ** Math.max(0, this.failures - 1), MAX_RETRY_MS);
168
+ this.timer = setTimeout(() => {
169
+ this.timer = null;
170
+ void this.drain();
171
+ }, delay);
172
+ this.timer.unref?.();
173
+ }
174
+ /** The files waiting, oldest first. */
175
+ files() {
176
+ try {
177
+ return readdirSync(this.dir).filter((name) => name.endsWith(".json.gz")).sort();
178
+ } catch {
179
+ return [];
180
+ }
181
+ }
182
+ store(signal, body, suffix = "") {
183
+ try {
184
+ mkdirSync(this.dir, { recursive: true });
185
+ const name = `${String(Date.now()).padStart(14, "0")}-${randomBytes(4).toString("hex")}.${signal}.json.gz${suffix}`;
186
+ writeFileSync(join(this.dir, name), body);
187
+ this.trim();
188
+ return name;
189
+ } catch (error) {
190
+ this.debug(`Couldn't keep a batch on disk: ${error?.message ?? error}`);
191
+ return null;
192
+ }
193
+ }
194
+ trim() {
195
+ const files = this.files();
196
+ let total = 0;
197
+ const sizes = files.map((name) => {
198
+ try {
199
+ return statSync(join(this.dir, name)).size;
200
+ } catch {
201
+ return 0;
202
+ }
203
+ });
204
+ for (const size of sizes) total += size;
205
+ let i = 0;
206
+ while (i < files.length && (files.length - i > MAX_FILES || total > MAX_BYTES)) {
207
+ rmSync(join(this.dir, files[i]), { force: true });
208
+ total -= sizes[i];
209
+ i++;
210
+ }
211
+ }
212
+ };
213
+
214
+ // src/main/paths.ts
215
+ function escape(text) {
216
+ return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
217
+ }
218
+ function appPathRewrite(appPath, windows = /^[a-z]:[\\/]/i.test(appPath)) {
219
+ const trimmed = appPath.replace(/[\\/]+$/, "");
220
+ if (!trimmed || trimmed === "/" || trimmed.length < 4) return (text) => text;
221
+ const forward = trimmed.replace(/\\/g, "/");
222
+ const forms = /* @__PURE__ */ new Set([
223
+ trimmed,
224
+ trimmed.replace(/\\/g, "\\\\"),
225
+ forward,
226
+ encodeURI(forward)
227
+ ]);
228
+ const alternatives = [...forms].sort((a, b) => b.length - a.length).map(escape).join("|");
229
+ const pattern = new RegExp(String.raw`(?:file:\/\/\/?)?(?:${alternatives})(?:\.unpacked)?((?:(?:\\\\|\\|\/)[^\s()'":<>\\/]+)*)`, windows ? "gi" : "g");
230
+ return (text) => {
231
+ if (typeof text !== "string" || !text) return text;
232
+ return text.replace(pattern, (_whole, rest) => `app://${rest ? rest.replace(/(?:\\\\|\\)/g, "/") : "/"}`);
233
+ };
234
+ }
235
+
236
+ // src/main/index.ts
237
+ var DEFAULT_ENDPOINT = "https://api.zharp.io/api/v1/otlp";
238
+ var SEVERITY = { trace: 1, debug: 5, info: 9, warn: 13, error: 17, fatal: 21 };
239
+ function osName() {
240
+ return process.platform === "win32" ? "Windows" : process.platform === "darwin" ? "macOS" : process.platform === "linux" ? "Linux" : process.platform;
241
+ }
242
+ function osVersion() {
243
+ try {
244
+ return process.getSystemVersion?.() || osRelease();
245
+ } catch {
246
+ return osRelease();
247
+ }
248
+ }
249
+ function deviceIdIn(dir) {
250
+ const path2 = join2(dir, "device-id");
251
+ try {
252
+ const existing = readFileSync2(path2, "utf8").trim();
253
+ if (/^[\w-]{8,64}$/.test(existing)) return existing;
254
+ } catch {
255
+ }
256
+ const id = randomUUID();
257
+ try {
258
+ mkdirSync2(dir, { recursive: true });
259
+ writeFileSync2(path2, id);
260
+ } catch {
261
+ }
262
+ return id;
263
+ }
264
+ function here() {
265
+ try {
266
+ return typeof __dirname === "string" ? __dirname : dirname(fileURLToPath2(import.meta.url));
267
+ } catch {
268
+ return "";
269
+ }
270
+ }
271
+ function minidumpUrlFor(endpoint, key) {
272
+ const base = endpoint.replace(/\/+$/, "").replace(/\/otlp$/, "");
273
+ return `${base}/minidump?key=${encodeURIComponent(key)}`;
274
+ }
275
+ var str = (value) => ({ stringValue: String(value) });
276
+ var keyValues = (attributes) => Object.entries(attributes).filter(([, v]) => v !== void 0 && v !== null && v !== "").map(([key, value]) => ({ key, value: typeof value === "number" ? { intValue: String(value) } : str(value) }));
277
+ var ZharpElectron = class {
278
+ running = null;
279
+ user = null;
280
+ tags = {};
281
+ /** Crash reports already uploaded (earlier runs) or matched to a crash: never matched again. */
282
+ knownReports = /* @__PURE__ */ new Set();
283
+ /** `Zharp.log.info("Order placed", { orderId })` — and debug, warn, error, fatal, trace. */
284
+ log = NodeZharp.log;
285
+ get isActive() {
286
+ return this.running !== null;
287
+ }
288
+ /** The app's current session (shared by main and every window). */
289
+ get sessionId() {
290
+ return this.running ? this.currentSession(this.running).id : void 0;
291
+ }
292
+ /** This installation's ID (`device.id`). */
293
+ get deviceId() {
294
+ return this.running?.deviceId;
295
+ }
296
+ init(options = {}) {
297
+ try {
298
+ if (this.running) {
299
+ console.warn("[Zharp] Zharp.init() was called again \u2014 the first call's settings stay in effect.");
300
+ return;
301
+ }
302
+ if (process.type && process.type !== "browser") {
303
+ console.warn("[Zharp] @zharp/electron/main runs in the main process. In a window, use '@zharp/electron/renderer'.");
304
+ return;
305
+ }
306
+ const key = options.key || process.env.ZHARP_KEY || process.env.ZHARP_API_KEY;
307
+ if (!key) {
308
+ console.warn("[Zharp] Zharp.init({ key }) needs the app key from the Zharp dashboard. Nothing will be sent.");
309
+ return;
310
+ }
311
+ this.start(options, key);
312
+ } catch (error) {
313
+ console.warn(`[Zharp] Could not start: ${error?.message ?? error}`);
314
+ }
315
+ }
316
+ start(options, key) {
317
+ const endpoint = (options.endpoint || process.env.ZHARP_ENDPOINT || DEFAULT_ENDPOINT).replace(/\/+$/, "");
318
+ const service = options.service || app.getName();
319
+ const release = options.release || app.getVersion() || void 0;
320
+ const environment = options.environment || (app.isPackaged ? "production" : "development");
321
+ const dataDir = join2(app.getPath("userData"), "zharp");
322
+ const deviceId = deviceIdIn(dataDir);
323
+ const now = Date.now();
324
+ const debug = options.debug ? (message) => console.debug(`[Zharp] ${message}`) : () => {
325
+ };
326
+ const resource = {
327
+ "device.id": deviceId,
328
+ "os.name": osName(),
329
+ "os.version": osVersion(),
330
+ "host.arch": process.arch,
331
+ "electron.version": process.versions.electron ?? "",
332
+ "zharp.sdk.platform": "electron"
333
+ };
334
+ const running = {
335
+ options,
336
+ key,
337
+ endpoint,
338
+ service,
339
+ release,
340
+ environment,
341
+ deviceId,
342
+ session: { id: randomUUID(), started: now, lastActive: now },
343
+ timeoutMs: (options.sessionTimeoutMinutes ?? 30) * 6e4,
344
+ resource,
345
+ rewrite: appPathRewrite(app.getAppPath()),
346
+ outbox: new Outbox(join2(dataDir, "outbox"), endpoint, key, debug),
347
+ teardowns: []
348
+ };
349
+ this.running = running;
350
+ if (options.crashReporter !== false) this.startCrashReporter(running);
351
+ const { crashReporter: _c, minidumpUrl: _m, preload: _p, renderer: _r, sessionTimeoutMinutes: _s, captureUncaught, ...nodeOptions } = options;
352
+ const before = new Set(process.listeners("uncaughtException"));
353
+ const beforeRejection = new Set(process.listeners("unhandledRejection"));
354
+ NodeZharp.init({ ...nodeOptions, key, endpoint, service, release, environment, captureUncaught, rewritePaths: running.rewrite });
355
+ for (const [k, v] of Object.entries({ ...resource, "electron.process.type": "browser" })) NodeZharp.setTag(k, v);
356
+ NodeZharp.setTag("session.id", running.session.id);
357
+ for (const [k, v] of Object.entries(this.tags)) NodeZharp.setTag(k, v);
358
+ if (this.user) NodeZharp.setUser(this.user);
359
+ if (captureUncaught !== false) this.keepElectronsDialog(running, before, beforeRejection);
360
+ this.listen(running);
361
+ app.whenReady().then(() => {
362
+ if (this.running !== running) return;
363
+ running.outbox.start((url, init) => net.fetch(url, init));
364
+ if (options.preload !== false) this.addPreload(running);
365
+ }, () => {
366
+ });
367
+ }
368
+ // ── public API ────────────────────────────────────────────────────────
369
+ /**
370
+ * Who is using the app: `enduser.id` (and `enduser.email`, `enduser.name`) on everything main
371
+ * and every window send from now on, and on crash reports. Call it after login.
372
+ */
373
+ setUser(user) {
374
+ try {
375
+ this.user = user && user.id !== void 0 && user.id !== null && user.id !== "" ? { id: user.id, email: user.email, name: user.name } : null;
376
+ const running = this.running;
377
+ if (!running) return;
378
+ NodeZharp.setUser(this.user);
379
+ this.crashParameters();
380
+ this.broadcast(running);
381
+ } catch {
382
+ }
383
+ }
384
+ /** Forget the user and start a new session — call it on logout. */
385
+ clearUser() {
386
+ this.setUser(null);
387
+ if (this.running) this.renew(this.running);
388
+ }
389
+ /** An attribute on everything main sends from now on. `null` removes it. */
390
+ setTag(key, value) {
391
+ if (value === null || value === void 0) delete this.tags[key];
392
+ else this.tags[key] = value;
393
+ if (this.running) NodeZharp.setTag(key, value);
394
+ }
395
+ /** Report an error you caught in main. Sent as handled, grouped with its other occurrences. */
396
+ captureError(error, attributes) {
397
+ NodeZharp.captureError(error, attributes);
398
+ }
399
+ /** Run `fn` in a span named `name` (see @zharp/node). */
400
+ startSpan(name, fn, options) {
401
+ return NodeZharp.startSpan(name, fn, options);
402
+ }
403
+ /** Send everything waiting now: main's own, and the windows' batches kept on disk. */
404
+ async flush(timeoutMs = 5e3) {
405
+ const running = this.running;
406
+ if (!running) return;
407
+ let timer;
408
+ await Promise.race([
409
+ Promise.all([NodeZharp.flush(timeoutMs), running.outbox.drain()]).catch(() => {
410
+ }),
411
+ // Kept referenced: while quitting, an unreferenced timer may never fire.
412
+ new Promise((resolve) => timer = setTimeout(resolve, timeoutMs))
413
+ ]).finally(() => clearTimeout(timer));
414
+ }
415
+ /** Flush and stop. */
416
+ async close() {
417
+ const running = this.running;
418
+ if (!running) return;
419
+ await this.flush();
420
+ for (const undo of running.teardowns.splice(0)) {
421
+ try {
422
+ undo();
423
+ } catch {
424
+ }
425
+ }
426
+ await NodeZharp.shutdown().catch(() => {
427
+ });
428
+ this.running = null;
429
+ }
430
+ // ── internals ─────────────────────────────────────────────────────────
431
+ startCrashReporter(running) {
432
+ try {
433
+ const extra = {
434
+ "zharp.release": running.release ?? "",
435
+ "zharp.environment": running.environment ?? "",
436
+ "zharp.service": running.service,
437
+ "zharp.device_id": running.deviceId
438
+ };
439
+ for (const k of Object.keys(extra)) if (!extra[k]) delete extra[k];
440
+ crashReporter.start({
441
+ submitURL: running.options.minidumpUrl || minidumpUrlFor(running.endpoint, running.key),
442
+ productName: running.service,
443
+ uploadToServer: true,
444
+ compress: true,
445
+ // Every process's reports: the GPU process and utility processes too.
446
+ globalExtra: extra
447
+ });
448
+ for (const report of crashReporter.getUploadedReports()) this.knownReports.add(report.id);
449
+ this.crashParameters();
450
+ } catch (error) {
451
+ console.warn(`[Zharp] Couldn't start the crash reporter: ${error?.message ?? error}`);
452
+ }
453
+ }
454
+ /** The session and user on main's own crash reports (each window's preload labels its own). */
455
+ crashParameters() {
456
+ const running = this.running;
457
+ if (!running || running.options.crashReporter === false) return;
458
+ try {
459
+ crashReporter.addExtraParameter("zharp.session_id", running.session.id);
460
+ if (this.user) {
461
+ crashReporter.addExtraParameter("zharp.user.id", String(this.user.id));
462
+ if (this.user.email) crashReporter.addExtraParameter("zharp.user.email", this.user.email);
463
+ } else {
464
+ crashReporter.removeExtraParameter("zharp.user.id");
465
+ crashReporter.removeExtraParameter("zharp.user.email");
466
+ }
467
+ } catch {
468
+ }
469
+ }
470
+ currentSession(running) {
471
+ if (Date.now() - running.session.lastActive >= running.timeoutMs) this.renew(running);
472
+ return running.session;
473
+ }
474
+ touch(running) {
475
+ this.currentSession(running).lastActive = Date.now();
476
+ }
477
+ renew(running) {
478
+ const now = Date.now();
479
+ running.session = { id: randomUUID(), started: now, lastActive: now };
480
+ NodeZharp.setTag("session.id", running.session.id);
481
+ this.crashParameters();
482
+ this.broadcast(running);
483
+ }
484
+ context(running) {
485
+ const session = this.currentSession(running);
486
+ return {
487
+ key: running.key,
488
+ endpoint: running.endpoint,
489
+ service: running.service,
490
+ release: running.release,
491
+ environment: running.environment,
492
+ sessionId: session.id,
493
+ sessionStarted: session.started,
494
+ deviceId: running.deviceId,
495
+ user: this.user,
496
+ resource: running.resource,
497
+ renderer: running.options.renderer ?? {}
498
+ };
499
+ }
500
+ /** Every window hears that the session or the user changed. */
501
+ broadcast(running) {
502
+ const context = this.context(running);
503
+ for (const contents of webContents.getAllWebContents()) {
504
+ try {
505
+ if (!contents.isDestroyed()) contents.send(CHANNEL.changed, context);
506
+ } catch {
507
+ }
508
+ }
509
+ }
510
+ listen(running) {
511
+ const t = running.teardowns;
512
+ const on = (channel, listener) => {
513
+ ipcMain.on(channel, listener);
514
+ t.push(() => ipcMain.removeListener(channel, listener));
515
+ };
516
+ on(CHANNEL.context, (event) => {
517
+ event.returnValue = this.context(running);
518
+ });
519
+ on(CHANNEL.user, (_event, user) => this.setUser(user && typeof user === "object" ? user : null));
520
+ on(CHANNEL.renew, () => this.renew(running));
521
+ on(CHANNEL.activity, () => this.touch(running));
522
+ ipcMain.handle(CHANNEL.send, async (_event, signal, body) => {
523
+ if (signal !== "logs" && signal !== "traces" || typeof body !== "string" || body.length > 4e6) return 400;
524
+ this.touch(running);
525
+ return running.outbox.send(signal, running.rewrite(body));
526
+ });
527
+ t.push(() => ipcMain.removeHandler(CHANNEL.send));
528
+ const onRenderGone = (_event, contents, details) => {
529
+ if (details.reason === "clean-exit") return;
530
+ let url = "";
531
+ let title = "";
532
+ try {
533
+ url = contents.getURL();
534
+ title = contents.getTitle();
535
+ } catch {
536
+ }
537
+ this.processGone(running, "renderer", details.reason, details.exitCode, {
538
+ "url.full": running.rewrite(url),
539
+ "electron.window.title": title
540
+ });
541
+ };
542
+ const onChildGone = (_event, details) => {
543
+ if (details.reason === "clean-exit") return;
544
+ this.processGone(running, details.type, details.reason, details.exitCode, {
545
+ "electron.process.service_name": details.serviceName,
546
+ "electron.process.name": details.name
547
+ });
548
+ };
549
+ app.on("render-process-gone", onRenderGone);
550
+ app.on("child-process-gone", onChildGone);
551
+ t.push(() => app.removeListener("render-process-gone", onRenderGone), () => app.removeListener("child-process-gone", onChildGone));
552
+ const onFocus = (_event, window) => {
553
+ this.touch(running);
554
+ try {
555
+ NodeZharp.setTag("app.screen.name", window.getTitle() || `window ${window.id}`);
556
+ } catch {
557
+ }
558
+ };
559
+ app.on("browser-window-focus", onFocus);
560
+ t.push(() => app.removeListener("browser-window-focus", onFocus));
561
+ let flushed = false;
562
+ const onWillQuit = (event) => {
563
+ if (flushed) return;
564
+ flushed = true;
565
+ event.preventDefault();
566
+ const debug = running.options.debug ? (m) => console.debug(`[Zharp] ${m}`) : () => {
567
+ };
568
+ debug("Quitting: sending what is waiting first");
569
+ this.flush(2e3).finally(() => {
570
+ debug("Sent; quitting");
571
+ app.exit();
572
+ });
573
+ };
574
+ app.on("will-quit", onWillQuit);
575
+ t.push(() => app.removeListener("will-quit", onWillQuit));
576
+ const timer = setInterval(() => this.currentSession(running), 6e4);
577
+ timer.unref?.();
578
+ t.push(() => clearInterval(timer));
579
+ }
580
+ /**
581
+ * A process that went away, reported from main, which is still running.
582
+ *
583
+ * When it crashed and the crash reporter is on, Electron's crash reporter uploads its minidump
584
+ * too — the crash with its native stack, as its own issue. The two would be one crash counted
585
+ * twice, so main waits for that upload (Zharp answers it with the crash's ID, which Electron
586
+ * lists in getUploadedReports): once it's there, this is sent as a log line naming the crash
587
+ * (`zharp.minidump_id`) instead of a second error. Without a dump (killed, out of memory, the
588
+ * crash reporter off, the upload failing), it's sent as the error. Either way it's on disk
589
+ * first, so an app that goes down meanwhile sends the error on its next start.
590
+ */
591
+ processGone(running, type, reason, exitCode, attributes) {
592
+ try {
593
+ const goneAt = Date.now();
594
+ const kind = type === "renderer" ? "Renderer" : type === "GPU" ? "GPU" : type;
595
+ const exceptionType = `${kind.replace(/s+/g, "")}ProcessGone`;
596
+ const what = type === "renderer" ? "A window" : `The ${type} process`;
597
+ const how = reason === "crashed" ? "crashed" : reason === "oom" ? "ran out of memory" : reason === "killed" ? "was killed" : reason === "launch-failed" ? "couldn't start" : reason === "integrity-failure" ? "failed its code integrity check" : `exited abnormally`;
598
+ const message = `${what} ${how} (${reason}, exit code ${exitCode})`;
599
+ const time = `${goneAt}000000`;
600
+ const user = this.user;
601
+ const context = {
602
+ ...this.tags,
603
+ ...attributes,
604
+ "zharp.mechanism": type === "renderer" ? "render-process-gone" : "child-process-gone",
605
+ "electron.process.type": type,
606
+ "electron.process.reason": reason,
607
+ "electron.process.exit_code": exitCode,
608
+ "session.id": running.session.id,
609
+ "enduser.id": user ? String(user.id) : void 0,
610
+ "enduser.email": user?.email,
611
+ "enduser.name": user?.name
612
+ };
613
+ const envelope = (record) => JSON.stringify({
614
+ resourceLogs: [
615
+ {
616
+ resource: {
617
+ attributes: keyValues({
618
+ "service.name": running.service,
619
+ "service.version": running.release,
620
+ "deployment.environment.name": running.environment,
621
+ "telemetry.sdk.name": "zharp",
622
+ "telemetry.sdk.language": "nodejs",
623
+ "telemetry.sdk.version": VERSION,
624
+ ...running.resource
625
+ })
626
+ },
627
+ scopeLogs: [{ scope: { name: "@zharp/electron", version: VERSION }, logRecords: [record] }]
628
+ }
629
+ ]
630
+ });
631
+ const asError = envelope({
632
+ timeUnixNano: time,
633
+ observedTimeUnixNano: time,
634
+ severityNumber: SEVERITY.fatal,
635
+ severityText: "FATAL",
636
+ body: str(`${exceptionType}: ${message}`),
637
+ attributes: keyValues({ ...context, "exception.type": exceptionType, "exception.message": message, "zharp.handled": "false" })
638
+ });
639
+ const asLine = (minidumpId) => envelope({
640
+ timeUnixNano: time,
641
+ observedTimeUnixNano: time,
642
+ severityNumber: SEVERITY.warn,
643
+ severityText: "WARN",
644
+ body: str(`${message}; its crash report is ${minidumpId}`),
645
+ attributes: keyValues({ ...context, "zharp.minidump_id": minidumpId })
646
+ });
647
+ const dumpExpected = reason === "crashed" && running.options.crashReporter !== false;
648
+ if (!dumpExpected) {
649
+ void running.outbox.sendDurably("logs", asError);
650
+ return;
651
+ }
652
+ const held = running.outbox.hold("logs", asError);
653
+ void this.minidumpUploaded().then((id) => {
654
+ running.outbox.release(held, id ? asLine(id) : asError);
655
+ });
656
+ } catch {
657
+ }
658
+ }
659
+ /**
660
+ * The ID Zharp gave the next crash report Electron uploads, waiting up to 15 seconds for it. A
661
+ * report is new when it wasn't in the list when Zharp started or claimed by an earlier crash.
662
+ */
663
+ async minidumpUploaded() {
664
+ const deadline = Date.now() + 15e3;
665
+ while (Date.now() < deadline) {
666
+ try {
667
+ for (const report of crashReporter.getUploadedReports()) {
668
+ if (this.knownReports.has(report.id)) continue;
669
+ this.knownReports.add(report.id);
670
+ return report.id;
671
+ }
672
+ } catch {
673
+ return null;
674
+ }
675
+ await new Promise((resolve) => setTimeout(resolve, 500));
676
+ }
677
+ return null;
678
+ }
679
+ /**
680
+ * Electron shows a dialog for an uncaught exception in main — but only while no one else
681
+ * listens, and @zharp/node does. So once Zharp has reported it, the dialog is shown as Electron
682
+ * would have, unless the app has a listener of its own. An unhandled rejection is reported and
683
+ * left as Electron leaves it (printed), never turned into an exit.
684
+ */
685
+ keepElectronsDialog(running, before, beforeRejection) {
686
+ const nodeOnes = new Set(process.listeners("uncaughtException").filter((l) => !before.has(l)));
687
+ const nodeRejection = new Set(process.listeners("unhandledRejection").filter((l) => !beforeRejection.has(l)));
688
+ const onException = (error) => {
689
+ const others = process.listeners("uncaughtException").filter((l) => l !== onException && !nodeOnes.has(l));
690
+ if (others.length > 1) return;
691
+ const stack = error instanceof Error ? error.stack || `${error.name}: ${error.message}` : String(error);
692
+ this.flush(2e3).finally(() => {
693
+ try {
694
+ dialog.showErrorBox("A JavaScript error occurred in the main process", `Uncaught Exception:
695
+ ${stack}`);
696
+ } catch {
697
+ process.stderr.write(`Uncaught Exception:
698
+ ${stack}
699
+ `);
700
+ }
701
+ });
702
+ };
703
+ const onRejection = (reason) => {
704
+ const others = process.listeners("unhandledRejection").filter((l) => l !== onRejection && !nodeRejection.has(l));
705
+ if (others.length) return;
706
+ const text = reason instanceof Error ? reason.stack || String(reason) : String(reason);
707
+ process.stderr.write(`(electron) Unhandled promise rejection in the main process:
708
+ ${text}
709
+ `);
710
+ };
711
+ process.on("uncaughtException", onException);
712
+ process.on("unhandledRejection", onRejection);
713
+ running.teardowns.push(() => process.off("uncaughtException", onException), () => process.off("unhandledRejection", onRejection));
714
+ }
715
+ /** The windows' preload, added to every session (the default one and any partition). */
716
+ addPreload(running) {
717
+ const file = join2(here(), "preload.js");
718
+ if (!existsSync(file)) {
719
+ if (running.options.debug) console.debug(`[Zharp] No preload at ${file} (main is bundled?): import '@zharp/electron/preload' in your own preload.`);
720
+ return;
721
+ }
722
+ const done = /* @__PURE__ */ new WeakSet();
723
+ const add = (s) => {
724
+ if (done.has(s)) return;
725
+ done.add(s);
726
+ try {
727
+ if (typeof s.registerPreloadScript === "function") s.registerPreloadScript({ type: "frame", id: "zharp-electron", filePath: file });
728
+ else s.setPreloads([...s.getPreloads(), file]);
729
+ } catch (error) {
730
+ if (running.options.debug) console.debug(`[Zharp] Couldn't add the preload: ${error?.message ?? error}`);
731
+ }
732
+ };
733
+ add(electronSession.defaultSession);
734
+ const onSession = (s) => add(s);
735
+ app.on("session-created", onSession);
736
+ running.teardowns.push(() => app.removeListener("session-created", onSession));
737
+ }
738
+ };
739
+ var g = globalThis;
740
+ var Zharp = g.__ZHARP_ELECTRON__ ?? (g.__ZHARP_ELECTRON__ = new ZharpElectron());
741
+ var main_default = Zharp;
742
+ export {
743
+ DEFAULT_ENDPOINT,
744
+ VERSION,
745
+ Zharp,
746
+ ZharpElectron,
747
+ main_default as default,
748
+ minidumpUrlFor
749
+ };
750
+ //# sourceMappingURL=main.mjs.map