@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.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../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","../src/main/index.ts","../src/shared.ts","../src/version.ts","../src/main/outbox.ts","../src/main/paths.ts"],"sourcesContent":["// Shim globals in esm bundle\nimport path from 'node:path'\nimport { fileURLToPath } from 'node:url'\n\nconst getFilename = () => fileURLToPath(import.meta.url)\nconst getDirname = () => path.dirname(getFilename())\n\nexport const __dirname = /* @__PURE__ */ getDirname()\nexport const __filename = /* @__PURE__ */ getFilename()\n","/**\r\n * @zharp/electron/main: Zharp in an Electron app's main process, and the hub for its windows.\r\n *\r\n * import { Zharp } from '@zharp/electron/main';\r\n * Zharp.init({ key: 'zpk_…' });\r\n *\r\n * Call it first in main, before `app.whenReady()`. It:\r\n *\r\n * - starts @zharp/node: main's errors (counted once, with the code that ran), its requests with\r\n * their headers, failed queries, logs when asked for;\r\n * - starts Electron's crash reporter with Zharp's minidump endpoint, so a native crash in any\r\n * process (main, a window, the GPU process) arrives with its dump, walked with Electron's own\r\n * symbols on Zharp's side;\r\n * - reports a window's or a helper process's crash at once (\"render-process-gone\",\r\n * \"child-process-gone\"), kept on disk until it's sent;\r\n * - keeps one session for the whole app, a device ID per installation, and the user, and hands\r\n * them to every window;\r\n * - adds its preload to every session, so `@zharp/electron/renderer` in a window can send\r\n * through main: one queue, on disk while offline, and no outside URL in the page's CSP.\r\n *\r\n * Stacks are written with the install folder as `app:///` (`app:///dist/main.js`), so every\r\n * install groups into the same issue.\r\n */\r\nimport { app, BrowserWindow, crashReporter, dialog, ipcMain, net, session as electronSession, webContents, type Session, type WebContents } from 'electron';\r\nimport { randomUUID } from 'node:crypto';\r\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';\r\nimport { release as osRelease } from 'node:os';\r\nimport { dirname, join } from 'node:path';\r\nimport { fileURLToPath } from 'node:url';\r\nimport { Zharp as NodeZharp, type NodeOptions } from '@zharp/node';\r\nimport { CHANNEL, type User, type WindowContext } from '../shared';\r\nimport { VERSION } from '../version';\r\nimport { Outbox, type Signal } from './outbox';\r\nimport { appPathRewrite } from './paths';\r\n\r\nexport type { User as ZharpUser } from '../shared';\r\n\r\nexport const DEFAULT_ENDPOINT = 'https://api.zharp.io/api/v1/otlp';\r\nconst SEVERITY = { trace: 1, debug: 5, info: 9, warn: 13, error: 17, fatal: 21 } as const;\r\ntype Level = keyof typeof SEVERITY;\r\ntype Attributes = Record<string, unknown>;\r\ntype LogFn = (message: unknown, attributes?: Attributes) => void;\r\n\r\nexport interface ElectronOptions extends Omit<NodeOptions, 'rewritePaths' | 'captureUncaught'> {\r\n /** The app's key from the Zharp dashboard (`zpk_…`). It can only send, so it's safe to ship in the app. */\r\n key?: string;\r\n /** `service.name`. Default: the app's name (`app.getName()`). */\r\n service?: string;\r\n /** `service.version`. Default: the app's version (`app.getVersion()`), which is also what its crash reports carry. */\r\n release?: string;\r\n /** `deployment.environment.name`. Default: `production` in a packaged app, `development` otherwise. */\r\n environment?: string;\r\n /**\r\n * Native crashes: Electron's crash reporter (Crashpad) sends a minidump of any process that\r\n * crashes to Zharp. Default **true**. `false` leaves the crash reporter alone, for an app that\r\n * starts it itself.\r\n */\r\n crashReporter?: boolean;\r\n /** Where minidumps go. Default: Zharp's minidump endpoint next to `endpoint`. */\r\n minidumpUrl?: string;\r\n /**\r\n * Add the windows' preload to every session. Default **true**. When main is bundled and\r\n * node_modules isn't shipped, import '@zharp/electron/preload' in your own preload instead.\r\n */\r\n preload?: boolean;\r\n /**\r\n * Settings for every window's SDK (`@zharp/electron/renderer`): `tracingOrigins`,\r\n * `captureBodies`, `captureConsole`, `sampleRate`… A window's own `Zharp.init({…})` adds to them.\r\n */\r\n renderer?: Record<string, unknown>;\r\n /** Minutes without activity in any window before a new session starts. Default 30. */\r\n sessionTimeoutMinutes?: number;\r\n /** Report uncaught exceptions and unhandled rejections in main. Default true. */\r\n captureUncaught?: boolean;\r\n}\r\n\r\ninterface Running {\r\n options: ElectronOptions;\r\n key: string;\r\n endpoint: string;\r\n service: string;\r\n release?: string;\r\n environment?: string;\r\n deviceId: string;\r\n session: { id: string; started: number; lastActive: number };\r\n timeoutMs: number;\r\n resource: Record<string, string>;\r\n rewrite: (text: string) => string;\r\n outbox: Outbox;\r\n teardowns: Array<() => void>;\r\n}\r\n\r\nfunction osName(): string {\r\n return process.platform === 'win32' ? 'Windows' : process.platform === 'darwin' ? 'macOS' : process.platform === 'linux' ? 'Linux' : process.platform;\r\n}\r\n\r\nfunction osVersion(): string {\r\n try {\r\n return (process as any).getSystemVersion?.() || osRelease();\r\n } catch {\r\n return osRelease();\r\n }\r\n}\r\n\r\n/** The installation's ID: made once, kept in userData. */\r\nfunction deviceIdIn(dir: string): string {\r\n const path = join(dir, 'device-id');\r\n try {\r\n const existing = readFileSync(path, 'utf8').trim();\r\n if (/^[\\w-]{8,64}$/.test(existing)) return existing;\r\n } catch {\r\n // First run.\r\n }\r\n const id = randomUUID();\r\n try {\r\n mkdirSync(dir, { recursive: true });\r\n writeFileSync(path, id);\r\n } catch {\r\n // Not writable: this run's ID only.\r\n }\r\n return id;\r\n}\r\n\r\n/** This file's folder, in the CommonJS and the ES build: the preload sits next to it. */\r\nfunction here(): string {\r\n try {\r\n return typeof __dirname === 'string' ? __dirname : dirname(fileURLToPath(import.meta.url));\r\n } catch {\r\n return '';\r\n }\r\n}\r\n\r\n/** `https://api.zharp.io/api/v1/otlp` → `https://api.zharp.io/api/v1/minidump`. */\r\nexport function minidumpUrlFor(endpoint: string, key: string): string {\r\n const base = endpoint.replace(/\\/+$/, '').replace(/\\/otlp$/, '');\r\n return `${base}/minidump?key=${encodeURIComponent(key)}`;\r\n}\r\n\r\nconst str = (value: unknown) => ({ stringValue: String(value) });\r\nconst keyValues = (attributes: Record<string, unknown>) =>\r\n Object.entries(attributes)\r\n .filter(([, v]) => v !== undefined && v !== null && v !== '')\r\n .map(([key, value]) => ({ key, value: typeof value === 'number' ? { intValue: String(value) } : str(value) }));\r\n\r\nexport class ZharpElectron {\r\n private running: Running | null = null;\r\n private user: User | null = null;\r\n private readonly tags: Record<string, string | number | boolean> = {};\r\n /** Crash reports already uploaded (earlier runs) or matched to a crash: never matched again. */\r\n private readonly knownReports = new Set<string>();\r\n\r\n /** `Zharp.log.info(\"Order placed\", { orderId })` — and debug, warn, error, fatal, trace. */\r\n readonly log: Record<Level, LogFn> = NodeZharp.log;\r\n\r\n get isActive(): boolean {\r\n return this.running !== null;\r\n }\r\n\r\n /** The app's current session (shared by main and every window). */\r\n get sessionId(): string | undefined {\r\n return this.running ? this.currentSession(this.running).id : undefined;\r\n }\r\n\r\n /** This installation's ID (`device.id`). */\r\n get deviceId(): string | undefined {\r\n return this.running?.deviceId;\r\n }\r\n\r\n init(options: ElectronOptions = {}): void {\r\n try {\r\n if (this.running) {\r\n console.warn(\"[Zharp] Zharp.init() was called again — the first call's settings stay in effect.\");\r\n return;\r\n }\r\n if (process.type && process.type !== 'browser') {\r\n console.warn(\"[Zharp] @zharp/electron/main runs in the main process. In a window, use '@zharp/electron/renderer'.\");\r\n return;\r\n }\r\n const key = options.key || process.env.ZHARP_KEY || process.env.ZHARP_API_KEY;\r\n if (!key) {\r\n console.warn('[Zharp] Zharp.init({ key }) needs the app key from the Zharp dashboard. Nothing will be sent.');\r\n return;\r\n }\r\n this.start(options, key);\r\n } catch (error) {\r\n console.warn(`[Zharp] Could not start: ${(error as Error)?.message ?? error}`);\r\n }\r\n }\r\n\r\n private start(options: ElectronOptions, key: string): void {\r\n const endpoint = (options.endpoint || process.env.ZHARP_ENDPOINT || DEFAULT_ENDPOINT).replace(/\\/+$/, '');\r\n const service = options.service || app.getName();\r\n const release = options.release || app.getVersion() || undefined;\r\n const environment = options.environment || (app.isPackaged ? 'production' : 'development');\r\n const dataDir = join(app.getPath('userData'), 'zharp');\r\n const deviceId = deviceIdIn(dataDir);\r\n const now = Date.now();\r\n const debug = options.debug ? (message: string) => console.debug(`[Zharp] ${message}`) : () => {};\r\n const resource = {\r\n 'device.id': deviceId,\r\n 'os.name': osName(),\r\n 'os.version': osVersion(),\r\n 'host.arch': process.arch,\r\n 'electron.version': process.versions.electron ?? '',\r\n 'zharp.sdk.platform': 'electron',\r\n };\r\n const running: Running = {\r\n options,\r\n key,\r\n endpoint,\r\n service,\r\n release,\r\n environment,\r\n deviceId,\r\n session: { id: randomUUID(), started: now, lastActive: now },\r\n timeoutMs: (options.sessionTimeoutMinutes ?? 30) * 60_000,\r\n resource,\r\n rewrite: appPathRewrite(app.getAppPath()),\r\n outbox: new Outbox(join(dataDir, 'outbox'), endpoint, key, debug),\r\n teardowns: [],\r\n };\r\n this.running = running;\r\n\r\n // Native crashes first: the earlier the crash reporter runs, the fewer crashes it misses.\r\n if (options.crashReporter !== false) this.startCrashReporter(running);\r\n\r\n // The main process is Node: everything @zharp/node does, with the install folder out of stacks.\r\n const { crashReporter: _c, minidumpUrl: _m, preload: _p, renderer: _r, sessionTimeoutMinutes: _s, captureUncaught, ...nodeOptions } = options;\r\n const before = new Set(process.listeners('uncaughtException'));\r\n const beforeRejection = new Set(process.listeners('unhandledRejection'));\r\n NodeZharp.init({ ...nodeOptions, key, endpoint, service, release, environment, captureUncaught, rewritePaths: running.rewrite });\r\n for (const [k, v] of Object.entries({ ...resource, 'electron.process.type': 'browser' })) NodeZharp.setTag(k, v);\r\n NodeZharp.setTag('session.id', running.session.id);\r\n for (const [k, v] of Object.entries(this.tags)) NodeZharp.setTag(k, v);\r\n if (this.user) NodeZharp.setUser(this.user);\r\n if (captureUncaught !== false) this.keepElectronsDialog(running, before, beforeRejection);\r\n\r\n this.listen(running);\r\n app.whenReady().then(() => {\r\n if (this.running !== running) return;\r\n running.outbox.start((url, init) => net.fetch(url, init as any));\r\n if (options.preload !== false) this.addPreload(running);\r\n }, () => {});\r\n }\r\n\r\n // ── public API ────────────────────────────────────────────────────────\r\n\r\n /**\r\n * Who is using the app: `enduser.id` (and `enduser.email`, `enduser.name`) on everything main\r\n * and every window send from now on, and on crash reports. Call it after login.\r\n */\r\n setUser(user: User | null): void {\r\n try {\r\n this.user = user && user.id !== undefined && user.id !== null && user.id !== '' ? { id: user.id, email: user.email, name: user.name } : null;\r\n const running = this.running;\r\n if (!running) return;\r\n NodeZharp.setUser(this.user);\r\n this.crashParameters();\r\n this.broadcast(running);\r\n } catch {\r\n // Never throw into the app.\r\n }\r\n }\r\n\r\n /** Forget the user and start a new session — call it on logout. */\r\n clearUser(): void {\r\n this.setUser(null);\r\n if (this.running) this.renew(this.running);\r\n }\r\n\r\n /** An attribute on everything main sends from now on. `null` removes it. */\r\n setTag(key: string, value: string | number | boolean | null | undefined): void {\r\n if (value === null || value === undefined) delete this.tags[key];\r\n else this.tags[key] = value;\r\n if (this.running) NodeZharp.setTag(key, value);\r\n }\r\n\r\n /** Report an error you caught in main. Sent as handled, grouped with its other occurrences. */\r\n captureError(error: unknown, attributes?: Attributes): void {\r\n NodeZharp.captureError(error, attributes);\r\n }\r\n\r\n /** Run `fn` in a span named `name` (see @zharp/node). */\r\n startSpan<T>(name: string, fn: (span: any) => T, options?: Parameters<typeof NodeZharp.startSpan>[2]): T {\r\n return NodeZharp.startSpan(name, fn, options);\r\n }\r\n\r\n /** Send everything waiting now: main's own, and the windows' batches kept on disk. */\r\n async flush(timeoutMs = 5_000): Promise<void> {\r\n const running = this.running;\r\n if (!running) return;\r\n let timer: ReturnType<typeof setTimeout> | undefined;\r\n await Promise.race([\r\n Promise.all([NodeZharp.flush(timeoutMs), running.outbox.drain()]).catch(() => {}),\r\n // Kept referenced: while quitting, an unreferenced timer may never fire.\r\n new Promise((resolve) => (timer = setTimeout(resolve, timeoutMs))),\r\n ]).finally(() => clearTimeout(timer));\r\n }\r\n\r\n /** Flush and stop. */\r\n async close(): Promise<void> {\r\n const running = this.running;\r\n if (!running) return;\r\n await this.flush();\r\n for (const undo of running.teardowns.splice(0)) {\r\n try {\r\n undo();\r\n } catch {\r\n // Keep going.\r\n }\r\n }\r\n await NodeZharp.shutdown().catch(() => {});\r\n this.running = null;\r\n }\r\n\r\n // ── internals ─────────────────────────────────────────────────────────\r\n\r\n private startCrashReporter(running: Running): void {\r\n try {\r\n const extra: Record<string, string> = {\r\n 'zharp.release': running.release ?? '',\r\n 'zharp.environment': running.environment ?? '',\r\n 'zharp.service': running.service,\r\n 'zharp.device_id': running.deviceId,\r\n };\r\n for (const k of Object.keys(extra)) if (!extra[k]) delete extra[k];\r\n crashReporter.start({\r\n submitURL: running.options.minidumpUrl || minidumpUrlFor(running.endpoint, running.key),\r\n productName: running.service,\r\n uploadToServer: true,\r\n compress: true,\r\n // Every process's reports: the GPU process and utility processes too.\r\n globalExtra: extra,\r\n });\r\n for (const report of crashReporter.getUploadedReports()) this.knownReports.add(report.id);\r\n this.crashParameters();\r\n } catch (error) {\r\n console.warn(`[Zharp] Couldn't start the crash reporter: ${(error as Error)?.message ?? error}`);\r\n }\r\n }\r\n\r\n /** The session and user on main's own crash reports (each window's preload labels its own). */\r\n private crashParameters(): void {\r\n const running = this.running;\r\n if (!running || running.options.crashReporter === false) return;\r\n try {\r\n crashReporter.addExtraParameter('zharp.session_id', running.session.id);\r\n if (this.user) {\r\n crashReporter.addExtraParameter('zharp.user.id', String(this.user.id));\r\n if (this.user.email) crashReporter.addExtraParameter('zharp.user.email', this.user.email);\r\n } else {\r\n crashReporter.removeExtraParameter('zharp.user.id');\r\n crashReporter.removeExtraParameter('zharp.user.email');\r\n }\r\n } catch {\r\n // Not started.\r\n }\r\n }\r\n\r\n private currentSession(running: Running): Running['session'] {\r\n if (Date.now() - running.session.lastActive >= running.timeoutMs) this.renew(running);\r\n return running.session;\r\n }\r\n\r\n private touch(running: Running): void {\r\n this.currentSession(running).lastActive = Date.now();\r\n }\r\n\r\n private renew(running: Running): void {\r\n const now = Date.now();\r\n running.session = { id: randomUUID(), started: now, lastActive: now };\r\n NodeZharp.setTag('session.id', running.session.id);\r\n this.crashParameters();\r\n this.broadcast(running);\r\n }\r\n\r\n private context(running: Running): WindowContext {\r\n const session = this.currentSession(running);\r\n return {\r\n key: running.key,\r\n endpoint: running.endpoint,\r\n service: running.service,\r\n release: running.release,\r\n environment: running.environment,\r\n sessionId: session.id,\r\n sessionStarted: session.started,\r\n deviceId: running.deviceId,\r\n user: this.user,\r\n resource: running.resource,\r\n renderer: running.options.renderer ?? {},\r\n };\r\n }\r\n\r\n /** Every window hears that the session or the user changed. */\r\n private broadcast(running: Running): void {\r\n const context = this.context(running);\r\n for (const contents of webContents.getAllWebContents()) {\r\n try {\r\n if (!contents.isDestroyed()) contents.send(CHANNEL.changed, context);\r\n } catch {\r\n // A window going away.\r\n }\r\n }\r\n }\r\n\r\n private listen(running: Running): void {\r\n const t = running.teardowns;\r\n const on = (channel: string, listener: (...args: any[]) => void) => {\r\n ipcMain.on(channel, listener);\r\n t.push(() => ipcMain.removeListener(channel, listener));\r\n };\r\n on(CHANNEL.context, (event) => {\r\n event.returnValue = this.context(running);\r\n });\r\n on(CHANNEL.user, (_event, user: User | null) => this.setUser(user && typeof user === 'object' ? user : null));\r\n on(CHANNEL.renew, () => this.renew(running));\r\n on(CHANNEL.activity, () => this.touch(running));\r\n ipcMain.handle(CHANNEL.send, async (_event, signal: unknown, body: unknown) => {\r\n if ((signal !== 'logs' && signal !== 'traces') || typeof body !== 'string' || body.length > 4_000_000) return 400;\r\n this.touch(running);\r\n return running.outbox.send(signal as Signal, running.rewrite(body));\r\n });\r\n t.push(() => ipcMain.removeHandler(CHANNEL.send));\r\n\r\n // A window or a helper process went away abnormally: reported now, from main, which is still\r\n // running. Its minidump (when it crashed) arrives separately, with the native stack.\r\n const onRenderGone = (_event: unknown, contents: WebContents, details: { reason: string; exitCode: number }) => {\r\n if (details.reason === 'clean-exit') return;\r\n let url = '';\r\n let title = '';\r\n try {\r\n url = contents.getURL();\r\n title = contents.getTitle();\r\n } catch {\r\n // Already destroyed.\r\n }\r\n this.processGone(running, 'renderer', details.reason, details.exitCode, {\r\n 'url.full': running.rewrite(url),\r\n 'electron.window.title': title,\r\n });\r\n };\r\n const onChildGone = (_event: unknown, details: { type: string; reason: string; exitCode: number; serviceName?: string; name?: string }) => {\r\n if (details.reason === 'clean-exit') return;\r\n this.processGone(running, details.type, details.reason, details.exitCode, {\r\n 'electron.process.service_name': details.serviceName,\r\n 'electron.process.name': details.name,\r\n });\r\n };\r\n app.on('render-process-gone', onRenderGone as any);\r\n app.on('child-process-gone', onChildGone as any);\r\n t.push(() => app.removeListener('render-process-gone', onRenderGone as any), () => app.removeListener('child-process-gone', onChildGone as any));\r\n\r\n // Windows as screens: the focused window's title on what main sends.\r\n const onFocus = (_event: unknown, window: BrowserWindow) => {\r\n this.touch(running);\r\n try {\r\n NodeZharp.setTag('app.screen.name', window.getTitle() || `window ${window.id}`);\r\n } catch {\r\n // Destroyed.\r\n }\r\n };\r\n app.on('browser-window-focus', onFocus as any);\r\n t.push(() => app.removeListener('browser-window-focus', onFocus as any));\r\n\r\n // Quitting: what's waiting goes out first (two seconds at most).\r\n let flushed = false;\r\n const onWillQuit = (event: { preventDefault(): void }) => {\r\n if (flushed) return;\r\n flushed = true;\r\n event.preventDefault();\r\n const debug = running.options.debug ? (m: string) => console.debug(`[Zharp] ${m}`) : () => {};\r\n debug('Quitting: sending what is waiting first');\r\n this.flush(2_000).finally(() => {\r\n debug('Sent; quitting');\r\n // The quit was already under way (every will-quit listener has run): finish it. A second\r\n // app.quit() here is sometimes ignored, leaving the app running with no windows.\r\n app.exit();\r\n });\r\n };\r\n app.on('will-quit', onWillQuit as any);\r\n t.push(() => app.removeListener('will-quit', onWillQuit as any));\r\n\r\n const timer = setInterval(() => this.currentSession(running), 60_000);\r\n timer.unref?.();\r\n t.push(() => clearInterval(timer));\r\n }\r\n\r\n /**\r\n * A process that went away, reported from main, which is still running.\r\n *\r\n * When it crashed and the crash reporter is on, Electron's crash reporter uploads its minidump\r\n * too — the crash with its native stack, as its own issue. The two would be one crash counted\r\n * twice, so main waits for that upload (Zharp answers it with the crash's ID, which Electron\r\n * lists in getUploadedReports): once it's there, this is sent as a log line naming the crash\r\n * (`zharp.minidump_id`) instead of a second error. Without a dump (killed, out of memory, the\r\n * crash reporter off, the upload failing), it's sent as the error. Either way it's on disk\r\n * first, so an app that goes down meanwhile sends the error on its next start.\r\n */\r\n private processGone(running: Running, type: string, reason: string, exitCode: number, attributes: Attributes): void {\r\n try {\r\n const goneAt = Date.now();\r\n const kind = type === 'renderer' ? 'Renderer' : type === 'GPU' ? 'GPU' : type;\r\n const exceptionType = `${kind.replace(/s+/g, '')}ProcessGone`;\r\n const what = type === 'renderer' ? 'A window' : `The ${type} process`;\r\n const how =\r\n 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`;\r\n const message = `${what} ${how} (${reason}, exit code ${exitCode})`;\r\n const time = `${goneAt}000000`;\r\n const user = this.user;\r\n const context = {\r\n ...this.tags,\r\n ...attributes,\r\n 'zharp.mechanism': type === 'renderer' ? 'render-process-gone' : 'child-process-gone',\r\n 'electron.process.type': type,\r\n 'electron.process.reason': reason,\r\n 'electron.process.exit_code': exitCode,\r\n 'session.id': running.session.id,\r\n 'enduser.id': user ? String(user.id) : undefined,\r\n 'enduser.email': user?.email,\r\n 'enduser.name': user?.name,\r\n };\r\n const envelope = (record: unknown) =>\r\n JSON.stringify({\r\n resourceLogs: [\r\n {\r\n resource: {\r\n attributes: keyValues({\r\n 'service.name': running.service,\r\n 'service.version': running.release,\r\n 'deployment.environment.name': running.environment,\r\n 'telemetry.sdk.name': 'zharp',\r\n 'telemetry.sdk.language': 'nodejs',\r\n 'telemetry.sdk.version': VERSION,\r\n ...running.resource,\r\n }),\r\n },\r\n scopeLogs: [{ scope: { name: '@zharp/electron', version: VERSION }, logRecords: [record] }],\r\n },\r\n ],\r\n });\r\n const asError = envelope({\r\n timeUnixNano: time,\r\n observedTimeUnixNano: time,\r\n severityNumber: SEVERITY.fatal,\r\n severityText: 'FATAL',\r\n body: str(`${exceptionType}: ${message}`),\r\n attributes: keyValues({ ...context, 'exception.type': exceptionType, 'exception.message': message, 'zharp.handled': 'false' }),\r\n });\r\n const asLine = (minidumpId: string) =>\r\n envelope({\r\n timeUnixNano: time,\r\n observedTimeUnixNano: time,\r\n severityNumber: SEVERITY.warn,\r\n severityText: 'WARN',\r\n body: str(`${message}; its crash report is ${minidumpId}`),\r\n attributes: keyValues({ ...context, 'zharp.minidump_id': minidumpId }),\r\n });\r\n\r\n const dumpExpected = reason === 'crashed' && running.options.crashReporter !== false;\r\n if (!dumpExpected) {\r\n void running.outbox.sendDurably('logs', asError);\r\n return;\r\n }\r\n const held = running.outbox.hold('logs', asError);\r\n void this.minidumpUploaded().then((id) => {\r\n running.outbox.release(held, id ? asLine(id) : asError);\r\n });\r\n } catch {\r\n // Never throw into the app.\r\n }\r\n }\r\n\r\n /**\r\n * The ID Zharp gave the next crash report Electron uploads, waiting up to 15 seconds for it. A\r\n * report is new when it wasn't in the list when Zharp started or claimed by an earlier crash.\r\n */\r\n private async minidumpUploaded(): Promise<string | null> {\r\n const deadline = Date.now() + 15_000;\r\n while (Date.now() < deadline) {\r\n try {\r\n for (const report of crashReporter.getUploadedReports()) {\r\n if (this.knownReports.has(report.id)) continue;\r\n this.knownReports.add(report.id);\r\n return report.id;\r\n }\r\n } catch {\r\n return null;\r\n }\r\n await new Promise((resolve) => setTimeout(resolve, 500));\r\n }\r\n return null;\r\n }\r\n\r\n /**\r\n * Electron shows a dialog for an uncaught exception in main — but only while no one else\r\n * listens, and @zharp/node does. So once Zharp has reported it, the dialog is shown as Electron\r\n * would have, unless the app has a listener of its own. An unhandled rejection is reported and\r\n * left as Electron leaves it (printed), never turned into an exit.\r\n */\r\n private keepElectronsDialog(running: Running, before: Set<Function>, beforeRejection: Set<Function>): void {\r\n const nodeOnes = new Set(process.listeners('uncaughtException').filter((l) => !before.has(l)));\r\n const nodeRejection = new Set(process.listeners('unhandledRejection').filter((l) => !beforeRejection.has(l)));\r\n const onException = (error: unknown) => {\r\n const others = process.listeners('uncaughtException').filter((l) => l !== onException && !nodeOnes.has(l));\r\n // Electron's own default listener is one of the others; an app's would be a second.\r\n if (others.length > 1) return;\r\n const stack = error instanceof Error ? error.stack || `${error.name}: ${error.message}` : String(error);\r\n this.flush(2_000).finally(() => {\r\n try {\r\n dialog.showErrorBox('A JavaScript error occurred in the main process', `Uncaught Exception:\\n${stack}`);\r\n } catch {\r\n process.stderr.write(`Uncaught Exception:\\n${stack}\\n`);\r\n }\r\n });\r\n };\r\n const onRejection = (reason: unknown) => {\r\n const others = process.listeners('unhandledRejection').filter((l) => l !== onRejection && !nodeRejection.has(l));\r\n if (others.length) return;\r\n const text = reason instanceof Error ? reason.stack || String(reason) : String(reason);\r\n process.stderr.write(`(electron) Unhandled promise rejection in the main process:\\n${text}\\n`);\r\n };\r\n process.on('uncaughtException', onException);\r\n process.on('unhandledRejection', onRejection);\r\n running.teardowns.push(() => process.off('uncaughtException', onException), () => process.off('unhandledRejection', onRejection));\r\n }\r\n\r\n /** The windows' preload, added to every session (the default one and any partition). */\r\n private addPreload(running: Running): void {\r\n const file = join(here(), 'preload.js');\r\n if (!existsSync(file)) {\r\n if (running.options.debug) console.debug(`[Zharp] No preload at ${file} (main is bundled?): import '@zharp/electron/preload' in your own preload.`);\r\n return;\r\n }\r\n const done = new WeakSet<Session>();\r\n const add = (s: Session) => {\r\n if (done.has(s)) return;\r\n done.add(s);\r\n try {\r\n if (typeof (s as any).registerPreloadScript === 'function') (s as any).registerPreloadScript({ type: 'frame', id: 'zharp-electron', filePath: file });\r\n else s.setPreloads([...s.getPreloads(), file]);\r\n } catch (error) {\r\n if (running.options.debug) console.debug(`[Zharp] Couldn't add the preload: ${(error as Error)?.message ?? error}`);\r\n }\r\n };\r\n add(electronSession.defaultSession);\r\n const onSession = (s: Session) => add(s);\r\n app.on('session-created', onSession);\r\n running.teardowns.push(() => app.removeListener('session-created', onSession));\r\n }\r\n}\r\n\r\n// One per process, kept on globalThis: the CommonJS and ES builds must reach the same one.\r\nconst g = globalThis as any;\r\nexport const Zharp: ZharpElectron = g.__ZHARP_ELECTRON__ ?? (g.__ZHARP_ELECTRON__ = new ZharpElectron());\r\nexport default Zharp;\r\nexport { VERSION };\r\n","/**\r\n * What the three entries agree on: the IPC channels between the main process and each window's\r\n * preload, and what main tells a window when it starts.\r\n */\r\n\r\nexport const CHANNEL = {\r\n /** Sync: a window asks for the context as its SDK starts. */\r\n context: 'zharp:context',\r\n /** Main → windows: the user or the session changed. */\r\n changed: 'zharp:context-changed',\r\n /** A batch from a window, for main to send (invoke; resolves to the HTTP status). */\r\n send: 'zharp:send',\r\n /** A window set or cleared the user. */\r\n user: 'zharp:user',\r\n /** A window's user logged out: a new session for everyone. */\r\n renew: 'zharp:renew',\r\n /** Something happened in a window: the session is still going. */\r\n activity: 'zharp:activity',\r\n} as const;\r\n\r\nexport interface User {\r\n id: string | number;\r\n email?: string;\r\n name?: string;\r\n}\r\n\r\n/** What a window's SDK starts from: the app's settings, and the one session all windows share. */\r\nexport interface WindowContext {\r\n key: string;\r\n endpoint: string;\r\n service: string;\r\n release?: string;\r\n environment?: string;\r\n sessionId: string;\r\n sessionStarted: number;\r\n deviceId: string;\r\n user: User | null;\r\n /** Resource attributes every window sends: the Electron version, the OS, the device. */\r\n resource: Record<string, string>;\r\n /** Defaults for the windows, from the main process's `renderer` option. */\r\n renderer: Record<string, unknown>;\r\n}\r\n\r\n/** The bridge the preload puts on the page, as `window.__zharpElectron`. */\r\nexport interface Bridge {\r\n context(): WindowContext | null;\r\n send(signal: string, body: string): Promise<number>;\r\n setUser(user: User | null): void;\r\n renew(): void;\r\n activity(): void;\r\n onChange(listener: (context: WindowContext) => void): void;\r\n}\r\n\r\nexport const BRIDGE_GLOBAL = '__zharpElectron';\r\n","/** Sent as `telemetry.sdk.version` and the scope's version. Bumped with package.json. */\r\nexport const VERSION = '0.1.0';\r\n","/**\r\n * What the main process sends for the windows, and its own crash events: each batch is sent with\r\n * Electron's network stack (the system's proxy settings, no Node instrumentation to trace it),\r\n * and kept on disk under `userData/zharp/outbox` when it can't go — offline, the server busy, the\r\n * app not ready yet. What's kept is sent at the next start, and every minute or so meanwhile.\r\n *\r\n * A crash event is written to disk before it is sent, so one that doesn't get out before the app\r\n * goes down is sent on the next launch.\r\n *\r\n * Capped at 200 batches and 20 MB; past that the oldest go.\r\n */\r\nimport { randomBytes } from 'node:crypto';\r\nimport { mkdirSync, readdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';\r\nimport { join } from 'node:path';\r\nimport { gzipSync } from 'node:zlib';\r\n\r\nexport type Signal = 'traces' | 'logs';\r\nexport type Fetch = (url: string, init: { method: string; headers: Record<string, string>; body: Uint8Array }) => Promise<{ status: number }>;\r\n\r\nconst MAX_FILES = 200;\r\nconst MAX_BYTES = 20 * 1024 * 1024;\r\nconst RETRY_MS = 30_000;\r\nconst MAX_RETRY_MS = 10 * 60_000;\r\n\r\nconst retryable = (status: number) => status === 0 || status === 429 || status >= 500;\r\n\r\nexport class Outbox {\r\n private fetch: Fetch | null = null;\r\n private timer: ReturnType<typeof setTimeout> | null = null;\r\n private failures = 0;\r\n private draining: Promise<void> | null = null;\r\n private again = false;\r\n private rejected = false;\r\n\r\n constructor(\r\n private readonly dir: string,\r\n private readonly endpoint: string,\r\n private readonly key: string,\r\n private readonly debug: (message: string) => void = () => {},\r\n ) {}\r\n\r\n /** The network is usable (the app is ready): send what waited, then send as batches come. */\r\n start(fetch: Fetch): void {\r\n this.fetch = fetch;\r\n // Held by a run that ended before deciding: sent as they were written.\r\n try {\r\n 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)));\r\n } catch {\r\n // No folder yet.\r\n }\r\n void this.drain();\r\n }\r\n\r\n /**\r\n * Send one batch now; kept on disk when it can't go. Resolves to the HTTP status, or 202 when\r\n * it was kept: the window must not queue it again.\r\n */\r\n async send(signal: Signal, json: string): Promise<number> {\r\n const body = gzipSync(json);\r\n if (!this.fetch) return this.store(signal, body) ? 202 : 0;\r\n const status = await this.post(signal, body);\r\n if (!retryable(status)) return status;\r\n this.schedule();\r\n return this.store(signal, body) ? 202 : status;\r\n }\r\n\r\n /**\r\n * Kept on disk but not sent yet, while main waits to know what to send (a crash event, until\r\n * its minidump's upload is seen). One left by a run that ended meanwhile is sent at the next\r\n * start, as it was written.\r\n */\r\n hold(signal: Signal, json: string): string | null {\r\n return this.store(signal, gzipSync(json), '.held');\r\n }\r\n\r\n /** Send a held batch now, as `json` (the held one replaced). */\r\n release(name: string | null, json: string): void {\r\n if (name) rmSync(join(this.dir, name), { force: true });\r\n const signal: Signal = name?.includes('.traces.') ? 'traces' : 'logs';\r\n void this.sendDurably(signal, json);\r\n }\r\n\r\n /** Written first, then sent: for what must survive the app going down. */\r\n async sendDurably(signal: Signal, json: string): Promise<void> {\r\n const file = this.store(signal, gzipSync(json));\r\n if (!this.fetch || !file) return;\r\n await this.drain();\r\n }\r\n\r\n /** Send everything kept on disk, oldest first, until one can't go. */\r\n drain(): Promise<void> {\r\n // One at a time; asked again meanwhile, it runs once more after, for what was written since.\r\n if (this.draining) {\r\n this.again = true;\r\n return this.draining;\r\n }\r\n this.draining = this.drainNow().finally(() => {\r\n this.draining = null;\r\n if (this.again) {\r\n this.again = false;\r\n void this.drain();\r\n }\r\n });\r\n return this.draining;\r\n }\r\n\r\n private async drainNow(): Promise<void> {\r\n if (!this.fetch) return;\r\n // Until the folder is empty: a batch written while this runs (a crash event) is sent too.\r\n const tried = new Set<string>();\r\n for (;;) {\r\n const names = this.files().filter((name) => !tried.has(name));\r\n if (!names.length) return;\r\n for (const name of names) {\r\n tried.add(name);\r\n const path = join(this.dir, name);\r\n let body: Buffer;\r\n try {\r\n body = readFileSync(path);\r\n } catch {\r\n continue;\r\n }\r\n const signal: Signal = name.includes('.traces.') ? 'traces' : 'logs';\r\n const status = await this.post(signal, body);\r\n if (retryable(status)) {\r\n this.failures++;\r\n this.schedule();\r\n return;\r\n }\r\n this.failures = 0;\r\n // Delivered, or refused for good: either way it's done.\r\n rmSync(path, { force: true });\r\n }\r\n }\r\n }\r\n\r\n private async post(signal: Signal, body: Uint8Array): Promise<number> {\r\n if (this.rejected) return 401;\r\n try {\r\n const response = await this.fetch!(`${this.endpoint}/v1/${signal}`, {\r\n method: 'POST',\r\n headers: { 'Content-Type': 'application/json', 'Content-Encoding': 'gzip', Authorization: `Bearer ${this.key}` },\r\n body,\r\n });\r\n if ((response.status === 401 || response.status === 403) && !this.rejected) {\r\n this.rejected = true;\r\n console.warn(`[Zharp] The key was rejected (HTTP ${response.status}); nothing more will be sent from the windows. Check Zharp.init({ key }).`);\r\n }\r\n return response.status;\r\n } catch (error) {\r\n this.debug(`Couldn't send (${(error as Error)?.message ?? error}); kept for later`);\r\n return 0;\r\n }\r\n }\r\n\r\n private schedule(): void {\r\n if (this.timer) return;\r\n const delay = Math.min(RETRY_MS * 2 ** Math.max(0, this.failures - 1), MAX_RETRY_MS);\r\n this.timer = setTimeout(() => {\r\n this.timer = null;\r\n void this.drain();\r\n }, delay);\r\n this.timer.unref?.();\r\n }\r\n\r\n /** The files waiting, oldest first. */\r\n private files(): string[] {\r\n try {\r\n return readdirSync(this.dir).filter((name) => name.endsWith('.json.gz')).sort();\r\n } catch {\r\n return [];\r\n }\r\n }\r\n\r\n private store(signal: Signal, body: Buffer, suffix = ''): string | null {\r\n try {\r\n mkdirSync(this.dir, { recursive: true });\r\n // Time first, so names sort oldest first; the random part keeps two in one millisecond apart.\r\n const name = `${String(Date.now()).padStart(14, '0')}-${randomBytes(4).toString('hex')}.${signal}.json.gz${suffix}`;\r\n writeFileSync(join(this.dir, name), body);\r\n this.trim();\r\n return name;\r\n } catch (error) {\r\n this.debug(`Couldn't keep a batch on disk: ${(error as Error)?.message ?? error}`);\r\n return null;\r\n }\r\n }\r\n\r\n private trim(): void {\r\n const files = this.files();\r\n let total = 0;\r\n const sizes = files.map((name) => {\r\n try {\r\n return statSync(join(this.dir, name)).size;\r\n } catch {\r\n return 0;\r\n }\r\n });\r\n for (const size of sizes) total += size;\r\n let i = 0;\r\n while (i < files.length && (files.length - i > MAX_FILES || total > MAX_BYTES)) {\r\n rmSync(join(this.dir, files[i]), { force: true });\r\n total -= sizes[i];\r\n i++;\r\n }\r\n }\r\n}\r\n","/**\r\n * The app's install folder taken out of stacks and URLs: everything up to `app.asar` (or the app\r\n * folder when it isn't packed) becomes `app://`, so\r\n *\r\n * file:///C:/Users/ana/AppData/Local/Programs/shop/resources/app.asar/dist/renderer.js:1:2\r\n * /Applications/Shop.app/Contents/Resources/app.asar/dist/renderer.js:1:2\r\n *\r\n * both read `app:///dist/renderer.js:1:2`. Errors from every install group into one issue, and\r\n * no one's user folder leaves their computer. The rest of the path keeps forward slashes.\r\n */\r\n\r\nfunction escape(text: string): string {\r\n return text.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\r\n}\r\n\r\n/**\r\n * A rewrite for the app at `appPath` (`app.getAppPath()`). It matches the path as Node writes it\r\n * (`C:\\…\\app.asar`), as a file URL (`file:///C:/…/app.asar`, spaces as `%20`), and either one\r\n * inside JSON (backslashes doubled), with `.unpacked` after it too.\r\n */\r\nexport function appPathRewrite(appPath: string, windows = /^[a-z]:[\\\\/]/i.test(appPath)): (text: string) => string {\r\n const trimmed = appPath.replace(/[\\\\/]+$/, '');\r\n if (!trimmed || trimmed === '/' || trimmed.length < 4) return (text) => text;\r\n const forward = trimmed.replace(/\\\\/g, '/');\r\n const forms = new Set<string>([\r\n trimmed,\r\n trimmed.replace(/\\\\/g, '\\\\\\\\'),\r\n forward,\r\n encodeURI(forward),\r\n ]);\r\n // Longest first, so the escaped form wins over the plain one inside JSON.\r\n const alternatives = [...forms].sort((a, b) => b.length - a.length).map(escape).join('|');\r\n const pattern = new RegExp(String.raw`(?:file:\\/\\/\\/?)?(?:${alternatives})(?:\\.unpacked)?((?:(?:\\\\\\\\|\\\\|\\/)[^\\s()'\":<>\\\\/]+)*)`, windows ? 'gi' : 'g');\r\n return (text) => {\r\n if (typeof text !== 'string' || !text) return text;\r\n return text.replace(pattern, (_whole, rest: string | undefined) => `app://${rest ? rest.replace(/(?:\\\\\\\\|\\\\)/g, '/') : '/'}`);\r\n };\r\n}\r\n"],"mappings":";AACA,OAAO,UAAU;AACjB,SAAS,qBAAqB;AAE9B,IAAM,cAAc,MAAM,cAAc,YAAY,GAAG;AACvD,IAAM,aAAa,MAAM,KAAK,QAAQ,YAAY,CAAC;AAE5C,IAAM,YAA4B,2BAAW;;;ACgBpD,SAAS,KAAoB,eAAe,QAAQ,SAAS,KAAK,WAAW,iBAAiB,mBAAmD;AACjJ,SAAS,kBAAkB;AAC3B,SAAS,YAAY,aAAAA,YAAW,gBAAAC,eAAc,iBAAAC,sBAAqB;AACnE,SAAS,WAAW,iBAAiB;AACrC,SAAS,SAAS,QAAAC,aAAY;AAC9B,SAAS,iBAAAC,sBAAqB;AAC9B,SAAS,SAAS,iBAAmC;;;ACxB9C,IAAM,UAAU;AAAA;AAAA,EAErB,SAAS;AAAA;AAAA,EAET,SAAS;AAAA;AAAA,EAET,MAAM;AAAA;AAAA,EAEN,MAAM;AAAA;AAAA,EAEN,OAAO;AAAA;AAAA,EAEP,UAAU;AACZ;;;ACjBO,IAAM,UAAU;;;ACUvB,SAAS,mBAAmB;AAC5B,SAAS,WAAW,aAAa,cAAc,YAAY,QAAQ,UAAU,qBAAqB;AAClG,SAAS,YAAY;AACrB,SAAS,gBAAgB;AAKzB,IAAM,YAAY;AAClB,IAAM,YAAY,KAAK,OAAO;AAC9B,IAAM,WAAW;AACjB,IAAM,eAAe,KAAK;AAE1B,IAAM,YAAY,CAAC,WAAmB,WAAW,KAAK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YAAY;AACtC,QAAI,CAAC,WAAW,IAAI,GAAG;AACrB,UAAI,QAAQ,QAAQ,MAAO,SAAQ,MAAM,yBAAyB,IAAI,4EAA4E;AAClJ;AAAA,IACF;AACA,UAAM,OAAO,oBAAI,QAAiB;AAClC,UAAM,MAAM,CAAC,MAAe;AAC1B,UAAI,KAAK,IAAI,CAAC,EAAG;AACjB,WAAK,IAAI,CAAC;AACV,UAAI;AACF,YAAI,OAAQ,EAAU,0BAA0B,WAAY,CAAC,EAAU,sBAAsB,EAAE,MAAM,SAAS,IAAI,kBAAkB,UAAU,KAAK,CAAC;AAAA,YAC/I,GAAE,YAAY,CAAC,GAAG,EAAE,YAAY,GAAG,IAAI,CAAC;AAAA,MAC/C,SAAS,OAAO;AACd,YAAI,QAAQ,QAAQ,MAAO,SAAQ,MAAM,qCAAsC,OAAiB,WAAW,KAAK,EAAE;AAAA,MACpH;AAAA,IACF;AACA,QAAI,gBAAgB,cAAc;AAClC,UAAM,YAAY,CAAC,MAAe,IAAI,CAAC;AACvC,QAAI,GAAG,mBAAmB,SAAS;AACnC,YAAQ,UAAU,KAAK,MAAM,IAAI,eAAe,mBAAmB,SAAS,CAAC;AAAA,EAC/E;AACF;AAGA,IAAM,IAAI;AACH,IAAM,QAAuB,EAAE,uBAAuB,EAAE,qBAAqB,IAAI,cAAc;AACtG,IAAO,eAAQ;","names":["mkdirSync","readFileSync","writeFileSync","join","fileURLToPath","path","path","join","readFileSync","mkdirSync","writeFileSync","fileURLToPath"]}
@@ -0,0 +1,2 @@
1
+
2
+ export { }
@@ -0,0 +1,84 @@
1
+ "use strict";
2
+
3
+ // src/preload/index.ts
4
+ var import_electron = require("electron");
5
+
6
+ // src/shared.ts
7
+ var CHANNEL = {
8
+ /** Sync: a window asks for the context as its SDK starts. */
9
+ context: "zharp:context",
10
+ /** Main → windows: the user or the session changed. */
11
+ changed: "zharp:context-changed",
12
+ /** A batch from a window, for main to send (invoke; resolves to the HTTP status). */
13
+ send: "zharp:send",
14
+ /** A window set or cleared the user. */
15
+ user: "zharp:user",
16
+ /** A window's user logged out: a new session for everyone. */
17
+ renew: "zharp:renew",
18
+ /** Something happened in a window: the session is still going. */
19
+ activity: "zharp:activity"
20
+ };
21
+ var BRIDGE_GLOBAL = "__zharpElectron";
22
+
23
+ // src/preload/index.ts
24
+ var g = globalThis;
25
+ function crashParameters(context) {
26
+ if (!context) return;
27
+ try {
28
+ import_electron.crashReporter.addExtraParameter("zharp.session_id", context.sessionId);
29
+ if (context.user) {
30
+ import_electron.crashReporter.addExtraParameter("zharp.user.id", String(context.user.id));
31
+ if (context.user.email) import_electron.crashReporter.addExtraParameter("zharp.user.email", context.user.email);
32
+ } else {
33
+ import_electron.crashReporter.removeExtraParameter("zharp.user.id");
34
+ import_electron.crashReporter.removeExtraParameter("zharp.user.email");
35
+ }
36
+ } catch {
37
+ }
38
+ }
39
+ if (!g.__zharpPreloaded) {
40
+ g.__zharpPreloaded = true;
41
+ let context = null;
42
+ const listeners = [];
43
+ const read = () => {
44
+ if (context) return context;
45
+ try {
46
+ context = import_electron.ipcRenderer.sendSync(CHANNEL.context) ?? null;
47
+ } catch {
48
+ context = null;
49
+ }
50
+ crashParameters(context);
51
+ return context;
52
+ };
53
+ import_electron.ipcRenderer.on(CHANNEL.changed, (_event, next) => {
54
+ context = next;
55
+ crashParameters(next);
56
+ for (const listener of listeners) {
57
+ try {
58
+ listener(next);
59
+ } catch {
60
+ }
61
+ }
62
+ });
63
+ let lastActivity = 0;
64
+ const bridge = {
65
+ context: read,
66
+ send: (signal, body) => import_electron.ipcRenderer.invoke(CHANNEL.send, signal, body).catch(() => 0),
67
+ setUser: (user) => import_electron.ipcRenderer.send(CHANNEL.user, user),
68
+ renew: () => import_electron.ipcRenderer.send(CHANNEL.renew),
69
+ activity: () => {
70
+ const now = Date.now();
71
+ if (now - lastActivity < 1e4) return;
72
+ lastActivity = now;
73
+ import_electron.ipcRenderer.send(CHANNEL.activity);
74
+ },
75
+ onChange: (listener) => void listeners.push(listener)
76
+ };
77
+ read();
78
+ try {
79
+ import_electron.contextBridge.exposeInMainWorld(BRIDGE_GLOBAL, bridge);
80
+ } catch {
81
+ globalThis[BRIDGE_GLOBAL] = bridge;
82
+ }
83
+ }
84
+ //# sourceMappingURL=preload.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/preload/index.ts","../src/shared.ts"],"sourcesContent":["/**\r\n * @zharp/electron/preload: the bridge a window's SDK sends through.\r\n *\r\n * `Zharp.init()` in the main process adds this file to every session's preloads by itself; import\r\n * it from your own preload only when main is bundled (Electron Forge + Vite or webpack, where\r\n * node_modules aren't shipped and the file can't be found):\r\n *\r\n * // preload.ts\r\n * import '@zharp/electron/preload';\r\n *\r\n * Built as one CommonJS file that needs nothing but electron, so it runs in a sandboxed preload.\r\n * It exposes `window.__zharpElectron` (through contextBridge when the window is isolated): the\r\n * context main started with, a way to hand main a batch, and the user. It also puts the session\r\n * and user on this renderer's crash reports.\r\n */\r\nimport { contextBridge, crashReporter, ipcRenderer } from 'electron';\r\nimport { BRIDGE_GLOBAL, CHANNEL, type Bridge, type User, type WindowContext } from '../shared';\r\n\r\nconst g = globalThis as any;\r\n\r\nfunction crashParameters(context: WindowContext | null): void {\r\n if (!context) return;\r\n try {\r\n crashReporter.addExtraParameter('zharp.session_id', context.sessionId);\r\n if (context.user) {\r\n crashReporter.addExtraParameter('zharp.user.id', String(context.user.id));\r\n if (context.user.email) crashReporter.addExtraParameter('zharp.user.email', context.user.email);\r\n } else {\r\n crashReporter.removeExtraParameter('zharp.user.id');\r\n crashReporter.removeExtraParameter('zharp.user.email');\r\n }\r\n } catch {\r\n // The crash reporter isn't running (crashReporter: false): nothing to label.\r\n }\r\n}\r\n\r\n// Once per window, whether it came from the session's preloads, the app's own preload, or both.\r\nif (!g.__zharpPreloaded) {\r\n g.__zharpPreloaded = true;\r\n let context: WindowContext | null = null;\r\n const listeners: Array<(context: WindowContext) => void> = [];\r\n\r\n const read = (): WindowContext | null => {\r\n if (context) return context;\r\n try {\r\n context = ipcRenderer.sendSync(CHANNEL.context) ?? null;\r\n } catch {\r\n context = null;\r\n }\r\n crashParameters(context);\r\n return context;\r\n };\r\n\r\n ipcRenderer.on(CHANNEL.changed, (_event, next: WindowContext) => {\r\n context = next;\r\n crashParameters(next);\r\n for (const listener of listeners) {\r\n try {\r\n listener(next);\r\n } catch {\r\n // A listener's failure isn't the bridge's.\r\n }\r\n }\r\n });\r\n\r\n let lastActivity = 0;\r\n const bridge: Bridge = {\r\n context: read,\r\n send: (signal: string, body: string) => ipcRenderer.invoke(CHANNEL.send, signal, body).catch(() => 0),\r\n setUser: (user: User | null) => ipcRenderer.send(CHANNEL.user, user),\r\n renew: () => ipcRenderer.send(CHANNEL.renew),\r\n activity: () => {\r\n // Main only needs to hear it now and then: the session times out after minutes, not seconds.\r\n const now = Date.now();\r\n if (now - lastActivity < 10_000) return;\r\n lastActivity = now;\r\n ipcRenderer.send(CHANNEL.activity);\r\n },\r\n onChange: (listener) => void listeners.push(listener),\r\n };\r\n\r\n read();\r\n try {\r\n contextBridge.exposeInMainWorld(BRIDGE_GLOBAL, bridge);\r\n } catch {\r\n // Not isolated (contextIsolation: false): the preload shares the page's window.\r\n (globalThis as any)[BRIDGE_GLOBAL] = bridge;\r\n }\r\n}\r\n","/**\r\n * What the three entries agree on: the IPC channels between the main process and each window's\r\n * preload, and what main tells a window when it starts.\r\n */\r\n\r\nexport const CHANNEL = {\r\n /** Sync: a window asks for the context as its SDK starts. */\r\n context: 'zharp:context',\r\n /** Main → windows: the user or the session changed. */\r\n changed: 'zharp:context-changed',\r\n /** A batch from a window, for main to send (invoke; resolves to the HTTP status). */\r\n send: 'zharp:send',\r\n /** A window set or cleared the user. */\r\n user: 'zharp:user',\r\n /** A window's user logged out: a new session for everyone. */\r\n renew: 'zharp:renew',\r\n /** Something happened in a window: the session is still going. */\r\n activity: 'zharp:activity',\r\n} as const;\r\n\r\nexport interface User {\r\n id: string | number;\r\n email?: string;\r\n name?: string;\r\n}\r\n\r\n/** What a window's SDK starts from: the app's settings, and the one session all windows share. */\r\nexport interface WindowContext {\r\n key: string;\r\n endpoint: string;\r\n service: string;\r\n release?: string;\r\n environment?: string;\r\n sessionId: string;\r\n sessionStarted: number;\r\n deviceId: string;\r\n user: User | null;\r\n /** Resource attributes every window sends: the Electron version, the OS, the device. */\r\n resource: Record<string, string>;\r\n /** Defaults for the windows, from the main process's `renderer` option. */\r\n renderer: Record<string, unknown>;\r\n}\r\n\r\n/** The bridge the preload puts on the page, as `window.__zharpElectron`. */\r\nexport interface Bridge {\r\n context(): WindowContext | null;\r\n send(signal: string, body: string): Promise<number>;\r\n setUser(user: User | null): void;\r\n renew(): void;\r\n activity(): void;\r\n onChange(listener: (context: WindowContext) => void): void;\r\n}\r\n\r\nexport const BRIDGE_GLOBAL = '__zharpElectron';\r\n"],"mappings":";;;AAeA,sBAA0D;;;ACVnD,IAAM,UAAU;AAAA;AAAA,EAErB,SAAS;AAAA;AAAA,EAET,SAAS;AAAA;AAAA,EAET,MAAM;AAAA;AAAA,EAEN,MAAM;AAAA;AAAA,EAEN,OAAO;AAAA;AAAA,EAEP,UAAU;AACZ;AAmCO,IAAM,gBAAgB;;;ADnC7B,IAAM,IAAI;AAEV,SAAS,gBAAgB,SAAqC;AAC5D,MAAI,CAAC,QAAS;AACd,MAAI;AACF,kCAAc,kBAAkB,oBAAoB,QAAQ,SAAS;AACrE,QAAI,QAAQ,MAAM;AAChB,oCAAc,kBAAkB,iBAAiB,OAAO,QAAQ,KAAK,EAAE,CAAC;AACxE,UAAI,QAAQ,KAAK,MAAO,+BAAc,kBAAkB,oBAAoB,QAAQ,KAAK,KAAK;AAAA,IAChG,OAAO;AACL,oCAAc,qBAAqB,eAAe;AAClD,oCAAc,qBAAqB,kBAAkB;AAAA,IACvD;AAAA,EACF,QAAQ;AAAA,EAER;AACF;AAGA,IAAI,CAAC,EAAE,kBAAkB;AACvB,IAAE,mBAAmB;AACrB,MAAI,UAAgC;AACpC,QAAM,YAAqD,CAAC;AAE5D,QAAM,OAAO,MAA4B;AACvC,QAAI,QAAS,QAAO;AACpB,QAAI;AACF,gBAAU,4BAAY,SAAS,QAAQ,OAAO,KAAK;AAAA,IACrD,QAAQ;AACN,gBAAU;AAAA,IACZ;AACA,oBAAgB,OAAO;AACvB,WAAO;AAAA,EACT;AAEA,8BAAY,GAAG,QAAQ,SAAS,CAAC,QAAQ,SAAwB;AAC/D,cAAU;AACV,oBAAgB,IAAI;AACpB,eAAW,YAAY,WAAW;AAChC,UAAI;AACF,iBAAS,IAAI;AAAA,MACf,QAAQ;AAAA,MAER;AAAA,IACF;AAAA,EACF,CAAC;AAED,MAAI,eAAe;AACnB,QAAM,SAAiB;AAAA,IACrB,SAAS;AAAA,IACT,MAAM,CAAC,QAAgB,SAAiB,4BAAY,OAAO,QAAQ,MAAM,QAAQ,IAAI,EAAE,MAAM,MAAM,CAAC;AAAA,IACpG,SAAS,CAAC,SAAsB,4BAAY,KAAK,QAAQ,MAAM,IAAI;AAAA,IACnE,OAAO,MAAM,4BAAY,KAAK,QAAQ,KAAK;AAAA,IAC3C,UAAU,MAAM;AAEd,YAAM,MAAM,KAAK,IAAI;AACrB,UAAI,MAAM,eAAe,IAAQ;AACjC,qBAAe;AACf,kCAAY,KAAK,QAAQ,QAAQ;AAAA,IACnC;AAAA,IACA,UAAU,CAAC,aAAa,KAAK,UAAU,KAAK,QAAQ;AAAA,EACtD;AAEA,OAAK;AACL,MAAI;AACF,kCAAc,kBAAkB,eAAe,MAAM;AAAA,EACvD,QAAQ;AAEN,IAAC,WAAmB,aAAa,IAAI;AAAA,EACvC;AACF;","names":[]}
@@ -0,0 +1,3 @@
1
+
2
+ //# sourceMappingURL=recorder-GORYW5VD.mjs.map
3
+ //# sourceMappingURL=recorder-GORYW5VD.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"names":[],"mappings":"","file":"recorder-GORYW5VD.mjs"}
@@ -0,0 +1,315 @@
1
+ /** Anything JSON can hold. Objects and arrays are sent as they are and shown as JSON. */
2
+ type Attributes = Record<string, unknown>;
3
+ interface ZharpUser {
4
+ /** Sent as `enduser.id`. An ID or an email — whatever identifies the person in your app. */
5
+ id: string | number;
6
+ /** Sent as `enduser.email`. */
7
+ email?: string;
8
+ /** Sent as `enduser.name`. */
9
+ name?: string;
10
+ }
11
+ /** One recorded rrweb event, as `replay.beforeSend` sees it. Declared here so the main types never load rrweb. */
12
+ interface ReplayEvent {
13
+ type: number;
14
+ data: unknown;
15
+ timestamp: number;
16
+ [key: string]: unknown;
17
+ }
18
+ interface ReplayOptions {
19
+ /**
20
+ * Fraction of sessions recorded from start to end, 0 to 1. Default 0. Decided once per
21
+ * session; a session that is not sampled never downloads the recorder.
22
+ */
23
+ sampleRate?: number;
24
+ /**
25
+ * Fraction of the remaining sessions that keep the last minute in memory and upload it —
26
+ * with the rest of the session — only when an error happens. Default 0. `1.0` means every
27
+ * session with an error comes with a replay, at no upload cost for the ones without.
28
+ */
29
+ onErrorSampleRate?: number;
30
+ /**
31
+ * Mask what is typed into every input, textarea and select. Default **true**. Turning it off
32
+ * sends passwords and card numbers unless `blockSelector` covers them.
33
+ */
34
+ maskAllInputs?: boolean;
35
+ /** Mask all text on the page, not just inputs. Default false. */
36
+ maskAllText?: boolean;
37
+ /** Elements left out of the recording entirely (a payment iframe, a private document). */
38
+ blockSelector?: string;
39
+ /** Elements whose text is masked. */
40
+ maskTextSelector?: string;
41
+ /** Called with each batch before it is sent. Return false to drop it. */
42
+ beforeSend?: (events: ReplayEvent[]) => boolean;
43
+ /**
44
+ * Where the script-tag build loads the recorder from. Default: `zharp-replay.min.js` next to
45
+ * `zharp.min.js`. Bundled builds ignore it — the recorder is a lazily imported chunk there.
46
+ */
47
+ recorderUrl?: string;
48
+ }
49
+ /** `captureBodies`: which request and response bodies go on request spans. */
50
+ interface CaptureBodiesOptions {
51
+ /** `errors` (default): failed requests only (status 400 and above, or no response). `all`: every request. */
52
+ mode?: 'errors' | 'all';
53
+ /** Characters kept per body. Default 32768 (32 KB), at most 131072 (128 KB). */
54
+ maxSize?: number;
55
+ /**
56
+ * More keys whose values are replaced with `[Filtered]`, on top of the built-in ones. A string
57
+ * matches a key ignoring case, `-` and `_`; a RegExp is tested against the key as it is.
58
+ */
59
+ redactKeys?: Array<string | RegExp>;
60
+ /**
61
+ * Which requests have their bodies captured, matched like `tracingOrigins`. Default:
62
+ * same-origin requests and `tracingOrigins` — your own APIs, never third parties.
63
+ */
64
+ urls?: Array<string | RegExp>;
65
+ }
66
+ /** `true` is `'errors'`. */
67
+ type CaptureBodies = boolean | 'errors' | 'all' | CaptureBodiesOptions;
68
+ interface BrowserOptions {
69
+ /** The app's key from the Zharp dashboard (`zpk_…`). Safe to ship in a page: it can only send. */
70
+ key: string;
71
+ /** `service.name`, e.g. `checkout-web`. */
72
+ service?: string;
73
+ /** `deployment.environment.name`, e.g. `production`. */
74
+ environment?: string;
75
+ /** `service.version`, e.g. `web@2.3.0` or a commit SHA. */
76
+ release?: string;
77
+ /** Default `https://api.zharp.io/api/v1/otlp`. */
78
+ endpoint?: string;
79
+ /**
80
+ * Hosts (or URL prefixes, or patterns) that get `traceparent` and `baggage` headers, so their
81
+ * spans join the page's trace. Same-origin requests always do. Nothing else does: an unknown
82
+ * header on a third-party request can make it fail CORS.
83
+ *
84
+ * `"api.example.com"` matches that host on any port and scheme; `"https://api.example.com/v2"`
85
+ * matches URLs starting with it; a RegExp is tested against the full URL.
86
+ */
87
+ tracingOrigins?: Array<string | RegExp>;
88
+ /**
89
+ * Traces. Default **true**. `false` is logs only: logs, errors, the user, the session and tags
90
+ * are sent as usual, but no spans are made (no page load, navigation, click or request spans),
91
+ * `fetch` and `XMLHttpRequest` are not patched, and no `traceparent` or `baggage` header is
92
+ * added to any request. `startSpan` just runs its callback. Session replay is independent —
93
+ * it follows `replay` either way; without traces a replay simply has no trace ids linked to it.
94
+ */
95
+ tracing?: boolean;
96
+ /** Fraction of traces to keep, 0 to 1. Default 1. Errors, logs and replays are not affected. */
97
+ sampleRate?: number;
98
+ /** Session replay. Off unless a sample rate is set. */
99
+ replay?: ReplayOptions;
100
+ /**
101
+ * Copy `console.*` calls into Zharp as logs: `true` for all levels, or a list such as
102
+ * `["warn", "error"]`. Default **off** — a page's console is mostly other people's libraries.
103
+ */
104
+ captureConsole?: boolean | Array<'debug' | 'log' | 'info' | 'warn' | 'error'>;
105
+ /**
106
+ * Send the page's logs: its `console` output, every level (or the levels `captureConsole`
107
+ * lists). Default **off**, as in every Zharp SDK. Errors, `Zharp.log`, traces, sessions and
108
+ * replays are sent either way. The same as `captureConsole: true`.
109
+ */
110
+ logs?: boolean;
111
+ /** Spans for clicks that lead to requests. Default true. */
112
+ interactions?: boolean;
113
+ /**
114
+ * Request and response bodies on request spans. Default **off**. `'errors'` (or `true`) keeps
115
+ * them for failed requests only (status 400 and above, or no response); `'all'` for every
116
+ * request. Only your own APIs — same-origin and `tracingOrigins` — unless `urls` is set.
117
+ * Text is capped at 32 KB; files, inline images and binary bodies are described (name, type,
118
+ * size), never sent. Field names are always kept; values under secret-looking keys
119
+ * (`password`, `token`, `authorization`, `card`, …) are replaced with `[Filtered]` before
120
+ * anything is sent. Other personal data in a body is sent as it is: add its keys to `redactKeys`.
121
+ *
122
+ * captureBodies: 'errors'
123
+ * captureBodies: { mode: 'all', redactKeys: ['dateOfBirth'], maxSize: 4096 }
124
+ */
125
+ captureBodies?: CaptureBodies;
126
+ /**
127
+ * Request and response headers on fetch/XHR spans (`http.request.header.*`,
128
+ * `http.response.header.*`), so a failed request shows what was sent and what came back.
129
+ * Default **on**. Secret headers (`authorization`, `cookie`, API keys, tokens…) are recorded as
130
+ * `[Filtered]`. The browser only lets a page read the response headers the server exposes
131
+ * (CORS). `false` turns it off; `{ redact: ['x-tenant'] }` filters more names.
132
+ */
133
+ captureHeaders?: boolean | {
134
+ redact?: Array<string | RegExp>;
135
+ };
136
+ /** URLs never traced (no span, no headers), e.g. analytics beacons. */
137
+ ignoreUrls?: Array<string | RegExp>;
138
+ /** Minutes without activity before a new session starts. Default 30. */
139
+ sessionTimeoutMinutes?: number;
140
+ }
141
+
142
+ type ReplayMode = 'off' | 'session' | 'buffer';
143
+ interface SessionState {
144
+ id: string;
145
+ started: number;
146
+ lastActive: number;
147
+ /** The replay decision, made once per session. Absent until replay has decided. */
148
+ replay?: ReplayMode;
149
+ /** Next replay batch number. Persisted so a reload does not reuse numbers the server already has. */
150
+ seq?: number;
151
+ user?: ZharpUser | null;
152
+ }
153
+ /** Where the session is kept: the tab's sessionStorage on the web, the device on mobile. */
154
+ interface SessionStore {
155
+ get(key: string): string | null;
156
+ set(key: string, value: string): void;
157
+ }
158
+ declare class Session {
159
+ private readonly timeoutMs;
160
+ private readonly store;
161
+ private state;
162
+ private lastWrite;
163
+ private readonly listeners;
164
+ constructor(timeoutMs: number, store?: SessionStore);
165
+ /** The current session, after starting a new one if this one has expired. */
166
+ get current(): SessionState;
167
+ get id(): string;
168
+ /** Something happened: the session is still going. */
169
+ touch(): void;
170
+ /** Start a new session now. The user carries over unless `user` is given. */
171
+ renew(user?: ZharpUser | null): void;
172
+ update(patch: Partial<SessionState>): void;
173
+ /** Called with the new state whenever a session ends and another begins. */
174
+ onRenew(listener: (state: SessionState) => void): void;
175
+ private read;
176
+ private write;
177
+ }
178
+
179
+ declare const SEVERITY: {
180
+ readonly trace: 1;
181
+ readonly debug: 5;
182
+ readonly info: 9;
183
+ readonly warn: 13;
184
+ readonly error: 17;
185
+ readonly fatal: 21;
186
+ };
187
+ type Level = keyof typeof SEVERITY;
188
+ type LogFn = (message: unknown, attributes?: Attributes) => void;
189
+ /** A manual span, as `Zharp.startSpan` hands it to its callback. */
190
+ interface ZharpSpan {
191
+ readonly traceId: string;
192
+ readonly spanId: string;
193
+ setAttribute(key: string, value: unknown): ZharpSpan;
194
+ setAttributes(attributes: Attributes): ZharpSpan;
195
+ }
196
+ /**
197
+ * @internal What a host around the page provides in place of the page's own: @zharp/electron's
198
+ * renderer sends through the main process and shares the main process's session.
199
+ */
200
+ interface BrowserHost {
201
+ /** Used in place of fetch to send each batch. */
202
+ fetch: typeof fetch;
203
+ /** The session, kept elsewhere. */
204
+ session: Session;
205
+ /** More resource attributes (the Electron version, the process). */
206
+ resource?: Record<string, unknown>;
207
+ /** The scope the records are sent under. */
208
+ scope?: {
209
+ name: string;
210
+ version: string;
211
+ };
212
+ }
213
+ declare class ZharpBrowser {
214
+ private readonly host?;
215
+ private running;
216
+ private user;
217
+ constructor(host?: BrowserHost | undefined);
218
+ private readonly tags;
219
+ /** Errors already reported, so one caught by the app and then rethrown is sent once. */
220
+ private readonly reported;
221
+ readonly log: Record<Level, LogFn>;
222
+ get isActive(): boolean;
223
+ /** The current session's ID, e.g. to show on a support page. */
224
+ get sessionId(): string | undefined;
225
+ init(options: BrowserOptions): void;
226
+ private start;
227
+ /** The page load span: from navigation start until the load event, its requests, and a quiet second. */
228
+ private startPageLoad;
229
+ /**
230
+ * Who is using the page: `enduser.id` (and `enduser.email`, `enduser.name`) on everything sent
231
+ * from now on, and in the `baggage` header so the back end's spans and logs carry it too.
232
+ * Call it after login and on every page load while logged in.
233
+ */
234
+ setUser(user: ZharpUser | null): void;
235
+ /** Forget the user and start a new session — call it on logout. */
236
+ clearUser(): void;
237
+ /** An attribute on every span and log from now on. `null` removes it. */
238
+ setTag(key: string, value: string | number | boolean | null | undefined): void;
239
+ /** Report an error you caught. Sent as handled, and grouped into an issue with its other occurrences. */
240
+ captureError(error: unknown, attributes?: Attributes): void;
241
+ /**
242
+ * React 19: the handler for createRoot's (or hydrateRoot's) error options. Each error a render
243
+ * throws is reported once, as a crash, with the component stack — which components were
244
+ * rendering — next to its own stack:
245
+ *
246
+ * createRoot(el, {
247
+ * onUncaughtError: Zharp.reactErrorHandler(),
248
+ * onCaughtError: Zharp.reactErrorHandler(),
249
+ * });
250
+ *
251
+ * React's own reporting (the console) carries on as before; `callback` runs after, for an app
252
+ * that had its own handler there. For React 18, use ZharpErrorBoundary from @zharp/browser/react.
253
+ */
254
+ reactErrorHandler(callback?: (error: unknown, errorInfo: {
255
+ componentStack?: string | null;
256
+ }) => void): (error: unknown, errorInfo?: {
257
+ componentStack?: string | null;
258
+ }) => void;
259
+ /** @internal An error React caught, with the stack of components that were rendering. */
260
+ reportReactError(error: unknown, componentStack?: string | null): void;
261
+ /**
262
+ * Run `fn` in a span named `name`. Requests and logs from its synchronous part belong to it;
263
+ * a promise it returns ends the span when it settles. Errors pass through unchanged.
264
+ */
265
+ startSpan<T>(name: string, fn: (span: ZharpSpan) => T, attributes?: Attributes): T;
266
+ /** Send everything waiting now. */
267
+ flush(): Promise<void>;
268
+ /** Flush and stop: every patch is undone and nothing more is recorded. */
269
+ close(): Promise<void>;
270
+ /** Session, user and tags: on every span and log, as they are when it is sent. */
271
+ private contextAttributes;
272
+ /** The `baggage` header value: session and user, for the back end to copy onto its spans. */
273
+ private baggage;
274
+ private emit;
275
+ private report;
276
+ }
277
+
278
+ /** Sent as `telemetry.sdk.version` and the scope's version. Bumped with package.json. */
279
+ declare const VERSION = "0.1.0";
280
+
281
+ /**
282
+ * @zharp/electron/renderer: errors, logs and traces from a window, sent through the main process.
283
+ *
284
+ * import { Zharp } from '@zharp/electron/renderer';
285
+ * Zharp.init();
286
+ *
287
+ * It is @zharp/browser — uncaught errors and rejections, page loads, fetch and XHR spans with
288
+ * their headers, `traceparent` to your own APIs, the console when asked — with three differences:
289
+ *
290
+ * - Batches go to the main process over IPC and main sends them: no request from the page, so a
291
+ * strict Content-Security-Policy (`connect-src 'self'`) needs no exception, and batches wait in
292
+ * main's queue on disk while the computer is offline.
293
+ * - Every window is in the main process's session, with its user and device ID.
294
+ * - The key, service, release and environment come from `Zharp.init()` in main: nothing to pass
295
+ * here unless a window should differ (`Zharp.init({ captureBodies: 'errors' })`).
296
+ *
297
+ * Needs the preload bridge (added by main's `Zharp.init()`, or `import '@zharp/electron/preload'`
298
+ * in your preload). Without it, it says so once and sends nothing.
299
+ */
300
+
301
+ /** What a window can set for itself; the rest comes from the main process. */
302
+ type RendererOptions = Omit<BrowserOptions, 'key' | 'endpoint' | 'replay' | 'sessionTimeoutMinutes'>;
303
+ declare class ZharpElectronRenderer extends ZharpBrowser {
304
+ private readonly bridged;
305
+ private readonly session;
306
+ private readonly startContext;
307
+ constructor();
308
+ /** Starts the SDK in this window, with the main process's key, service, release and session. */
309
+ init(options?: RendererOptions): void;
310
+ /** The device ID main keeps for this installation. */
311
+ get deviceId(): string | undefined;
312
+ }
313
+ declare const Zharp: ZharpElectronRenderer;
314
+
315
+ export { type Attributes, type CaptureBodies, type CaptureBodiesOptions, type RendererOptions, VERSION, Zharp, ZharpElectronRenderer, type ZharpSpan, type ZharpUser, Zharp as default };