@moonbase.sh/electron 0.0.0 → 0.2.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/README.md CHANGED
@@ -38,8 +38,27 @@ moonbase.start()
38
38
 
39
39
  The license is kept in `license.mb` in the app's user data folder, and the app's own version (`app.getVersion()`)
40
40
  is the version reported to Moonbase and the one a [license that covers some versions](https://www.npmjs.com/package/@moonbase.sh/licensing#licenses-that-cover-some-versions)
41
- has to cover. The module loads its UI from beside itself in `node_modules`, so leave it out of
42
- a bundle of the main process, as Electron Forge, electron-vite and electron-builder do for dependencies by default.
41
+ has to cover.
42
+
43
+ ### Bundling the main process
44
+
45
+ The module loads its activation UI from the folder it runs from. Left out of the main process's bundle, it finds
46
+ the UI in `node_modules`. Bundled, as Electron Forge's Vite template does with every dependency, it needs the UI
47
+ copied beside the bundle, which the module's Vite plugin does. Add it to the main process's Vite config:
48
+
49
+ ```ts
50
+ // vite.main.config.ts
51
+ import { moonbase } from '@moonbase.sh/electron/vite'
52
+ import { defineConfig } from 'vite'
53
+
54
+ export default defineConfig({
55
+ plugins: [moonbase()],
56
+ })
57
+ ```
58
+
59
+ With another bundler, leave the module out of the bundle, or copy the package's `dist/ui` folder and
60
+ `dist/ui-preload.cjs` to the folder the bundled module runs from. If they are not there, `start()` throws and names
61
+ the folder it looked in.
43
62
 
44
63
  ## The activation UI
45
64
 
@@ -84,7 +103,10 @@ float over the app's content, which is blurred behind them and takes no clicks o
84
103
  the overlay cannot be dismissed; once it has one it gets a close button and closes on Escape.
85
104
 
86
105
  The overlay is a view of the module's own laid over the window, so it works whatever the app's page does, and it
87
- survives the page reloading. Keep gating in the main process either way: the overlay is a lock on the interface.
106
+ survives the page reloading. It locks one window: the one `ui.window` names, or the app's first. When that window
107
+ closes while the app is locked, the overlay moves to the next window the app opens, such as the one a macOS app opens
108
+ again from the dock. The app's other windows stay usable, so keep gating in the main process either way: the overlay
109
+ is a lock on the interface.
88
110
 
89
111
  ## Gating
90
112
 
@@ -118,11 +140,26 @@ exposeMoonbase()
118
140
 
119
141
  ```ts
120
142
  // renderer
143
+ import type { ActivationState } from '@moonbase.sh/electron/renderer'
144
+
145
+ function render(state: ActivationState) {
146
+ document.querySelector('#license')!.textContent = state.licensed ? `Licensed to ${state.license?.issuedTo.name}` : 'Not activated'
147
+ }
148
+
121
149
  window.moonbase.onStateChanged(render)
122
150
  render(await window.moonbase.state())
123
151
  await window.moonbase.activate()
124
152
  ```
125
153
 
154
+ `@moonbase.sh/electron/renderer` has the types for renderer code, and importing from it types `window.moonbase`. To
155
+ type `window.moonbase` without importing anything, reference it once from a declaration file:
156
+
157
+ ```ts
158
+ /// <reference types="@moonbase.sh/electron/renderer" />
159
+ ```
160
+
161
+ Leave it out if you expose the API under another name with `exposeMoonbase(key)`.
162
+
126
163
  A sandboxed preload can require nothing but Electron, so bundle it, as Electron Forge and electron-vite do. The API
127
164
  has the same calls as tauri-plugin-moonbase's: `state`, `activate`, `cancelActivation`, `refresh`, `deactivate`,
128
165
  `forget`, `deviceToken`, `activateOffline`, `dismissError`, `device`, `checkUpdate`, `updateDownloadUrl`, `present`,
package/dist/index.cjs ADDED
@@ -0,0 +1,617 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/index.ts
31
+ var src_exports = {};
32
+ __export(src_exports, {
33
+ MoonbaseElectron: () => MoonbaseElectron,
34
+ createMoonbase: () => createMoonbase
35
+ });
36
+ module.exports = __toCommonJS(src_exports);
37
+ var import_node_buffer = require("buffer");
38
+ var import_node_fs = __toESM(require("fs"), 1);
39
+ var import_promises = __toESM(require("fs/promises"), 1);
40
+ var import_node_path = __toESM(require("path"), 1);
41
+ var import_node_process = __toESM(require("process"), 1);
42
+ var import_licensing = require("@moonbase.sh/licensing");
43
+ var import_electron = require("electron");
44
+
45
+ // package.json
46
+ var version = "0.2.0";
47
+
48
+ // src/download.ts
49
+ function downloadState(phase, rest = {}) {
50
+ return { phase, progress: null, path: null, error: null, releaseAccess: null, upgradeUrl: null, ...rest };
51
+ }
52
+ function fileSafe(name) {
53
+ const cleaned = name.replace(/[\u0000-\u001F\u007F\\/:*?"<>|]/g, "-").trim().replace(/^\.+|\.+$/g, "");
54
+ return cleaned || "license";
55
+ }
56
+
57
+ // src/index.ts
58
+ var WIDTH = 660;
59
+ var MOONBASE_SITE = "https://moonbase.sh";
60
+ var READ_ONLY = /* @__PURE__ */ new Set(["state", "device", "checkUpdate", "present"]);
61
+ function errorOutcome(err) {
62
+ if (err instanceof import_licensing.ActivationError)
63
+ return { ok: false, error: { kind: err.kind, message: err.message } };
64
+ const kind = err?.type;
65
+ return { ok: false, error: { kind: typeof kind === "string" ? kind : "internal", message: err instanceof Error ? err.message : String(err) } };
66
+ }
67
+ function uiFolder() {
68
+ return __dirname;
69
+ }
70
+ var UI_FILES = ["ui-preload.cjs", import_node_path.default.join("ui", "index.html"), import_node_path.default.join("ui", "overlay.html")];
71
+ function platformOs() {
72
+ switch (import_node_process.default.platform) {
73
+ case "darwin":
74
+ return "macos";
75
+ case "win32":
76
+ return "windows";
77
+ default:
78
+ return import_node_process.default.platform;
79
+ }
80
+ }
81
+ var MoonbaseElectron = class extends import_licensing.ActivationController {
82
+ constructor(options) {
83
+ const ui = options.ui === false ? null : options.ui ?? {};
84
+ const productName = ui?.productName ?? import_electron.app.getName();
85
+ super({
86
+ ...options,
87
+ appVersion: options.appVersion ?? import_electron.app.getVersion(),
88
+ licenseFile: options.licenseFile ?? import_node_path.default.join(import_electron.app.getPath("userData"), "license.mb"),
89
+ openUrl: options.openUrl ?? ((url) => import_electron.shell.openExternal(url)),
90
+ // Ahead of the SDK's own token, so Moonbase knows the product uses this module.
91
+ clientInfo: [options.clientInfo, `@moonbase.sh/electron/${version}`].filter(Boolean).join(" "),
92
+ productName,
93
+ accountName: ui?.manufacturerName
94
+ });
95
+ this.subscribers = /* @__PURE__ */ new Set();
96
+ this.folder = uiFolder();
97
+ this.window = null;
98
+ this.overlay = null;
99
+ /** Waiting for a window to lay the overlay over, when the app has none. */
100
+ this.waitingForWindow = null;
101
+ this.pendingScreen = null;
102
+ this.lastLicensed = null;
103
+ this.download = downloadState("idle");
104
+ this.downloaded = null;
105
+ this.running = false;
106
+ this.onSubscribe = (event) => {
107
+ const contents = event.sender;
108
+ if (this.accessOf(contents) === "none" || this.subscribers.has(contents))
109
+ return;
110
+ this.subscribers.add(contents);
111
+ contents.once("destroyed", () => this.subscribers.delete(contents));
112
+ };
113
+ this.onWindowFocus = () => this.onFocusChanged(true);
114
+ this.onWindowBlur = () => this.onFocusChanged(false);
115
+ this.ui = ui;
116
+ this.rendererAccess = options.rendererAccess;
117
+ this.endpoint = options.endpoint;
118
+ this.subscribe((state) => this.afterStateChange(state));
119
+ }
120
+ /**
121
+ * Validate the stored license, start watching it, and answer the app's
122
+ * renderers. Call once, before or after the app is ready.
123
+ */
124
+ start() {
125
+ if (this.running)
126
+ return;
127
+ if (this.ui)
128
+ this.checkUiFiles();
129
+ this.running = true;
130
+ import_electron.ipcMain.handle("moonbase:invoke", (event, command, args) => this.handleRenderer(event, command, args ?? {}));
131
+ import_electron.ipcMain.handle("moonbase:ui", (event, command, args) => this.handleUi(event, command, args ?? {}));
132
+ import_electron.ipcMain.on("moonbase:subscribe", this.onSubscribe);
133
+ import_electron.app.on("browser-window-focus", this.onWindowFocus);
134
+ import_electron.app.on("browser-window-blur", this.onWindowBlur);
135
+ super.start();
136
+ }
137
+ /** Stop watching, close the UI and stop answering renderers. */
138
+ dispose() {
139
+ if (this.running) {
140
+ import_electron.ipcMain.removeHandler("moonbase:invoke");
141
+ import_electron.ipcMain.removeHandler("moonbase:ui");
142
+ import_electron.ipcMain.off("moonbase:subscribe", this.onSubscribe);
143
+ import_electron.app.off("browser-window-focus", this.onWindowFocus);
144
+ import_electron.app.off("browser-window-blur", this.onWindowBlur);
145
+ this.running = false;
146
+ }
147
+ this.closeUi();
148
+ super.dispose();
149
+ }
150
+ /**
151
+ * Stop here, where the developer sees it, rather than open a blank window or
152
+ * lock the app behind an overlay that never loads. The files go missing when
153
+ * the module is bundled into the main process without them.
154
+ */
155
+ checkUiFiles() {
156
+ const missing = UI_FILES.filter((file) => !import_node_fs.default.existsSync(import_node_path.default.join(this.folder, file)));
157
+ if (missing.length === 0)
158
+ return;
159
+ throw new import_licensing.ActivationError("internal", `@moonbase.sh/electron can't find its activation UI in ${this.folder} (missing ${missing.join(", ")}). This happens when the module is bundled into the main process: add moonbase() from '@moonbase.sh/electron/vite' to the plugins of the main process's Vite config, which copies the UI beside the bundle, or leave the module out of the bundle. Pass ui: false to use a UI of your own instead.`);
160
+ }
161
+ isOwnUi(contents) {
162
+ return !!this.window && !this.window.isDestroyed() && this.window.webContents === contents || !!this.overlay && this.overlay.view.webContents === contents;
163
+ }
164
+ accessOf(contents) {
165
+ const access = this.rendererAccess ?? "full";
166
+ return typeof access === "function" ? access(contents) : access;
167
+ }
168
+ // -- Renderers ----------------------------------------------------------------
169
+ async handleRenderer(event, command, args) {
170
+ const access = this.isOwnUi(event.sender) ? "full" : this.accessOf(event.sender);
171
+ if (access === "none" || access === "read-only" && !READ_ONLY.has(command))
172
+ return { ok: false, error: { kind: "forbidden", message: `This window may not call ${command}` } };
173
+ try {
174
+ return { ok: true, value: await this.run(command, args) };
175
+ } catch (err) {
176
+ return errorOutcome(err);
177
+ }
178
+ }
179
+ async run(command, args) {
180
+ const id = String(args.id ?? "");
181
+ switch (command) {
182
+ case "state":
183
+ return this.state();
184
+ case "activate":
185
+ return await this.activate();
186
+ case "cancelActivation":
187
+ return this.cancelActivation();
188
+ case "refresh":
189
+ return await this.refresh({ force: args.force !== false });
190
+ case "deactivate":
191
+ return await this.deactivate();
192
+ case "forget":
193
+ return await this.forget();
194
+ case "deviceToken":
195
+ return await this.deviceToken();
196
+ case "activateOffline":
197
+ return await this.activateOffline(String(args.licenseFile ?? ""));
198
+ case "dismissError":
199
+ return this.dismissError();
200
+ case "device":
201
+ return await this.device();
202
+ case "checkUpdate":
203
+ return await this.checkUpdate();
204
+ case "updateDownloadUrl":
205
+ return await this.updateDownloadUrl();
206
+ case "present":
207
+ return await this.present(args.screen ?? void 0);
208
+ case "closeUi":
209
+ return this.closeUi();
210
+ case "upgradeLicense":
211
+ return await this.upgradeLicense();
212
+ case "loadAddOns":
213
+ return await this.loadAddOns();
214
+ case "refreshAddOns":
215
+ return await this.refreshAddOns();
216
+ case "activateSubProduct":
217
+ return await this.activateSubProduct(id);
218
+ case "requestSubProductTrial":
219
+ return await this.requestSubProductTrial(id);
220
+ case "buySubProduct":
221
+ return await this.buySubProduct(id);
222
+ default:
223
+ throw new import_licensing.ActivationError("internal", `Unknown command ${command}`);
224
+ }
225
+ }
226
+ /** The built-in UI's own commands, which only its window or overlay may call. */
227
+ async handleUi(event, command, args) {
228
+ if (!this.isOwnUi(event.sender))
229
+ return { ok: false, error: { kind: "forbidden", message: "Only the activation UI may call this" } };
230
+ try {
231
+ return { ok: true, value: await this.runUi(event.sender, command, args) };
232
+ } catch (err) {
233
+ return errorOutcome(err);
234
+ }
235
+ }
236
+ async runUi(sender, command, args) {
237
+ switch (command) {
238
+ case "ui_config":
239
+ return this.pageConfig();
240
+ case "ui_ready":
241
+ return this.uiReady(Number(args.height) || 0);
242
+ case "ui_resize":
243
+ return this.uiResize(Number(args.height) || 0);
244
+ case "close_ui":
245
+ return this.closeUi();
246
+ case "open_link":
247
+ return await this.openLink(String(args.url ?? ""));
248
+ case "copy_text":
249
+ return import_electron.clipboard.writeText(String(args.text ?? ""));
250
+ case "save_machine_file":
251
+ return await this.saveMachineFile(import_electron.BrowserWindow.fromWebContents(sender) ?? this.overlay?.target ?? null);
252
+ case "download_update":
253
+ return await this.downloadUpdate();
254
+ case "reveal_update":
255
+ return this.revealUpdate();
256
+ case "skip_update":
257
+ return await this.skipUpdate(String(args.version ?? ""));
258
+ case "cancel_activation":
259
+ return this.cancelActivation();
260
+ case "activate_offline":
261
+ return await this.activateOffline(String(args.licenseFile ?? ""));
262
+ case "upgrade_license":
263
+ return await this.upgradeLicense();
264
+ case "check_update":
265
+ return await this.checkUpdate();
266
+ case "load_add_ons":
267
+ return await this.loadAddOns();
268
+ case "refresh_add_ons":
269
+ return await this.refreshAddOns();
270
+ case "activate_sub_product":
271
+ return await this.activateSubProduct(String(args.id ?? ""));
272
+ case "request_sub_product_trial":
273
+ return await this.requestSubProductTrial(String(args.id ?? ""));
274
+ case "buy_sub_product":
275
+ return await this.buySubProduct(String(args.id ?? ""));
276
+ default:
277
+ return await this.run(command, args);
278
+ }
279
+ }
280
+ // -- The built-in UI ------------------------------------------------------------
281
+ pageConfig() {
282
+ const ui = this.ui ?? {};
283
+ const productName = ui.productName ?? import_electron.app.getName();
284
+ let logo = null;
285
+ if (ui.logoPng) {
286
+ const png = typeof ui.logoPng === "string" ? import_node_fs.default.readFileSync(ui.logoPng) : ui.logoPng;
287
+ logo = `data:image/png;base64,${import_node_buffer.Buffer.from(png).toString("base64")}`;
288
+ }
289
+ let activationHost = this.endpoint;
290
+ try {
291
+ activationHost = new URL(this.endpoint).host;
292
+ } catch {
293
+ }
294
+ return {
295
+ productName,
296
+ manufacturerName: ui.manufacturerName ?? null,
297
+ accent: ui.accent ?? "#186cdc",
298
+ logo,
299
+ logoSvg: ui.logoSvg ?? null,
300
+ trialFeatures: ui.trialFeatures ?? [],
301
+ trialLengthDays: Math.max(1, ui.trialLengthDays ?? 14),
302
+ showBadge: ui.showMoonbaseBadge ?? true,
303
+ strings: ui.strings ?? {},
304
+ showAddOns: ui.showAddOns ?? false,
305
+ reduceMotion: ui.reduceMotion ?? false,
306
+ activationHost,
307
+ requestFileName: `${fileSafe(productName)}.dt`,
308
+ os: platformOs(),
309
+ windowTitle: ui.windowTitle ?? productName
310
+ };
311
+ }
312
+ /** The window `ui.window` names, if it is open. */
313
+ chosenWindow() {
314
+ const chosen = typeof this.ui?.window === "function" ? this.ui.window() : this.ui?.window;
315
+ return chosen && !chosen.isDestroyed() ? chosen : null;
316
+ }
317
+ /** The app's window the overlay locks, and the activation window's parent. */
318
+ targetWindow() {
319
+ return this.chosenWindow() ?? import_electron.BrowserWindow.getAllWindows().filter((candidate) => !candidate.isDestroyed() && candidate !== this.window).sort((a, b) => a.id - b.id)[0] ?? null;
320
+ }
321
+ /** Hand the UI something new, wherever it is showing. */
322
+ push(name, payload) {
323
+ const contents = this.overlay?.view.webContents ?? (this.window && !this.window.isDestroyed() ? this.window.webContents : null);
324
+ if (contents && !contents.isDestroyed())
325
+ contents.send("moonbase:push", name, payload);
326
+ }
327
+ afterStateChange(state) {
328
+ for (const contents of [...this.subscribers]) {
329
+ if (contents.isDestroyed() || this.accessOf(contents) === "none")
330
+ this.subscribers.delete(contents);
331
+ else
332
+ contents.send("moonbase:state-changed", state);
333
+ }
334
+ if (!this.ui)
335
+ return;
336
+ this.push("update", state);
337
+ if (state.status === "loading")
338
+ return;
339
+ const previous = this.lastLicensed;
340
+ this.lastLicensed = state.licensed;
341
+ if (!state.licensed && previous !== false && (this.ui.autoPresentOnLock ?? true)) {
342
+ this.presentQuietly();
343
+ } else if (previous === null && state.licensed && (this.ui.autoPresentUpdate ?? true) && state.update) {
344
+ const latest = state.update.latestVersion;
345
+ void this.isUpdateSkipped(latest).then((skipped) => {
346
+ if (!skipped)
347
+ this.presentQuietly("update");
348
+ });
349
+ }
350
+ }
351
+ presentQuietly(screen) {
352
+ this.present(screen).catch((err) => console.warn(`moonbase: couldn't present the activation UI: ${err instanceof Error ? err.message : err}`));
353
+ }
354
+ /**
355
+ * Show the activation UI and bring it to the front, creating it when needed:
356
+ * its own window, or the overlay over the app's window. `screen` opens it on a
357
+ * particular screen; without one it shows whatever the license state calls for.
358
+ */
359
+ async present(screen) {
360
+ if (!this.ui)
361
+ throw new import_licensing.ActivationError("internal", "The built-in activation UI is turned off");
362
+ await import_electron.app.whenReady();
363
+ if (this.ui.presentation === "overlay")
364
+ return this.mountOverlay(screen ?? null);
365
+ if (this.window && !this.window.isDestroyed()) {
366
+ if (screen)
367
+ this.push("show", screen);
368
+ if (this.window.isMinimized())
369
+ this.window.restore();
370
+ this.window.show();
371
+ this.window.focus();
372
+ return;
373
+ }
374
+ this.pendingScreen = screen ?? null;
375
+ this.window = this.createWindow();
376
+ }
377
+ webPreferences() {
378
+ return {
379
+ preload: import_node_path.default.join(this.folder, "ui-preload.cjs"),
380
+ contextIsolation: true,
381
+ sandbox: true,
382
+ nodeIntegration: false,
383
+ spellcheck: false
384
+ };
385
+ }
386
+ /** The UI's pages load nothing but their own files, and open nothing themselves. */
387
+ lockDown(contents) {
388
+ contents.on("will-navigate", (event) => event.preventDefault());
389
+ contents.setWindowOpenHandler(() => ({ action: "deny" }));
390
+ }
391
+ createWindow() {
392
+ const ui = this.ui ?? {};
393
+ const parent = this.targetWindow();
394
+ const window = new import_electron.BrowserWindow({
395
+ width: WIDTH,
396
+ height: 560,
397
+ useContentSize: true,
398
+ show: false,
399
+ resizable: false,
400
+ maximizable: false,
401
+ fullscreenable: false,
402
+ title: ui.windowTitle ?? ui.productName ?? import_electron.app.getName(),
403
+ backgroundColor: "#080b13",
404
+ titleBarStyle: import_node_process.default.platform === "darwin" ? "hidden" : "default",
405
+ autoHideMenuBar: true,
406
+ ...parent && { parent },
407
+ webPreferences: this.webPreferences()
408
+ });
409
+ window.setMenuBarVisibility(false);
410
+ this.lockDown(window.webContents);
411
+ window.on("closed", () => {
412
+ if (this.window === window)
413
+ this.window = null;
414
+ });
415
+ void window.loadFile(import_node_path.default.join(this.folder, "ui", "index.html"));
416
+ setTimeout(() => {
417
+ if (!window.isDestroyed() && !window.isVisible())
418
+ window.show();
419
+ }, 1500).unref?.();
420
+ return window;
421
+ }
422
+ uiReady(height) {
423
+ if (this.window && !this.window.isDestroyed()) {
424
+ this.uiResize(height);
425
+ this.window.center();
426
+ this.window.show();
427
+ this.window.focus();
428
+ }
429
+ const screen = this.pendingScreen;
430
+ this.pendingScreen = null;
431
+ return { screen };
432
+ }
433
+ uiResize(height) {
434
+ if (this.window && !this.window.isDestroyed() && height > 0)
435
+ this.window.setContentSize(WIDTH, Math.round(Math.min(900, Math.max(240, height))));
436
+ }
437
+ /** Lay the overlay over the app's window, or bring it to `screen` if it is up. */
438
+ mountOverlay(screen, target = this.targetWindow()) {
439
+ if (this.overlay && !this.overlay.target.isDestroyed()) {
440
+ if (screen)
441
+ this.push("show", screen);
442
+ this.overlay.target.show();
443
+ this.overlay.view.webContents.focus();
444
+ return;
445
+ }
446
+ if (!target) {
447
+ this.lockNextWindow(screen);
448
+ return;
449
+ }
450
+ if (typeof import_electron.WebContentsView !== "function")
451
+ throw new import_licensing.ActivationError("internal", "The overlay needs Electron 30 or later");
452
+ this.pendingScreen = screen;
453
+ const view = new import_electron.WebContentsView({ webPreferences: this.webPreferences() });
454
+ view.setBackgroundColor("#00000000");
455
+ this.lockDown(view.webContents);
456
+ target.contentView.addChildView(view);
457
+ const overlay = {
458
+ view,
459
+ target,
460
+ css: null,
461
+ fit: () => {
462
+ const [width = 0, height = 0] = target.getContentSize();
463
+ view.setBounds({ x: 0, y: 0, width, height });
464
+ },
465
+ reinsert: () => {
466
+ void target.webContents.insertCSS("html { filter: blur(10px) saturate(0.8) brightness(0.85); pointer-events: none; }").then((key) => {
467
+ if (this.overlay === overlay)
468
+ overlay.css = key;
469
+ else
470
+ void target.webContents.removeInsertedCSS(key);
471
+ }).catch(() => {
472
+ });
473
+ }
474
+ };
475
+ this.overlay = overlay;
476
+ overlay.fit();
477
+ overlay.reinsert();
478
+ target.on("resize", overlay.fit);
479
+ target.webContents.on("did-finish-load", overlay.reinsert);
480
+ target.once("closed", () => {
481
+ if (this.overlay !== overlay)
482
+ return;
483
+ this.overlay = null;
484
+ if (!view.webContents.isDestroyed())
485
+ view.webContents.close();
486
+ if (!this.state().licensed && (this.ui?.autoPresentOnLock ?? true))
487
+ this.lockNextWindow(null);
488
+ });
489
+ void view.webContents.loadFile(import_node_path.default.join(this.folder, "ui", "overlay.html"));
490
+ view.webContents.once("did-finish-load", () => view.webContents.focus());
491
+ target.show();
492
+ }
493
+ /**
494
+ * Lay the overlay over the next window the app opens, or over the one
495
+ * `ui.window` names by then. Waits for one window at a time.
496
+ */
497
+ lockNextWindow(screen) {
498
+ this.pendingScreen = screen;
499
+ if (this.waitingForWindow)
500
+ return;
501
+ const listener = (_event, created) => {
502
+ this.waitingForWindow = null;
503
+ setImmediate(() => this.mountOverlay(this.pendingScreen, this.chosenWindow() ?? (created.isDestroyed() ? null : created)));
504
+ };
505
+ this.waitingForWindow = listener;
506
+ import_electron.app.once("browser-window-created", listener);
507
+ }
508
+ /** Close the activation window, or take the overlay down, if it is showing. */
509
+ closeUi() {
510
+ if (this.waitingForWindow) {
511
+ import_electron.app.off("browser-window-created", this.waitingForWindow);
512
+ this.waitingForWindow = null;
513
+ }
514
+ if (this.window && !this.window.isDestroyed())
515
+ this.window.close();
516
+ this.window = null;
517
+ const overlay = this.overlay;
518
+ if (!overlay)
519
+ return;
520
+ this.overlay = null;
521
+ if (overlay.target.isDestroyed())
522
+ return;
523
+ overlay.target.off("resize", overlay.fit);
524
+ overlay.target.webContents.off("did-finish-load", overlay.reinsert);
525
+ overlay.target.contentView.removeChildView(overlay.view);
526
+ overlay.view.webContents.close();
527
+ if (overlay.css)
528
+ void overlay.target.webContents.removeInsertedCSS(overlay.css);
529
+ overlay.target.webContents.focus();
530
+ }
531
+ /**
532
+ * Open a link from the UI in the browser: the pending activation, the store, or
533
+ * Moonbase's site from the footer. Nothing else, so the UI cannot be used to
534
+ * open arbitrary links.
535
+ */
536
+ async openLink(url) {
537
+ let parsed;
538
+ try {
539
+ parsed = new URL(url);
540
+ } catch {
541
+ throw new import_licensing.ActivationError("internal", "Not a link");
542
+ }
543
+ let sameOrigin = false;
544
+ try {
545
+ sameOrigin = new URL(this.endpoint).origin === parsed.origin;
546
+ } catch {
547
+ }
548
+ const pending = this.state().activation?.browserUrl === url;
549
+ const moonbase = url === MOONBASE_SITE && (this.ui?.showMoonbaseBadge ?? true);
550
+ if (!sameOrigin && !pending && !moonbase)
551
+ throw new import_licensing.ActivationError("internal", "That link can't be opened from here");
552
+ await import_electron.shell.openExternal(url);
553
+ }
554
+ /**
555
+ * Save the machine file for offline activation through a save dialog. Null when
556
+ * the customer cancels.
557
+ */
558
+ async saveMachineFile(parent = null) {
559
+ const token = await this.deviceToken();
560
+ const name = `${fileSafe(this.ui?.productName ?? import_electron.app.getName())}.dt`;
561
+ const options = {
562
+ title: "Save machine file",
563
+ defaultPath: import_node_path.default.join(import_electron.app.getPath("downloads"), name),
564
+ filters: [{ name: "Moonbase machine file", extensions: ["dt"] }]
565
+ };
566
+ const picked = parent ? await import_electron.dialog.showSaveDialog(parent, options) : await import_electron.dialog.showSaveDialog(options);
567
+ if (picked.canceled || !picked.filePath)
568
+ return null;
569
+ await import_promises.default.writeFile(picked.filePath, token);
570
+ return picked.filePath;
571
+ }
572
+ setDownload(next) {
573
+ this.download = next;
574
+ this.push("download", next);
575
+ }
576
+ /**
577
+ * Download the latest installer for this platform into Downloads, reporting
578
+ * progress to the UI, then show it in the file manager.
579
+ */
580
+ async downloadUpdate() {
581
+ if (this.download.phase === "downloading")
582
+ return;
583
+ this.setDownload(downloadState("downloading"));
584
+ try {
585
+ const file = await this.downloadInstaller({
586
+ directory: import_electron.app.getPath("downloads"),
587
+ onProgress: (progress) => this.setDownload(downloadState("downloading", { progress })),
588
+ // Through Chromium's network stack, which knows the system's proxy.
589
+ fetch: (url) => import_electron.net.fetch(url)
590
+ });
591
+ this.downloaded = file;
592
+ import_electron.shell.showItemInFolder(file);
593
+ this.setDownload(downloadState("done", { progress: 1, path: file }));
594
+ } catch (err) {
595
+ if (err instanceof import_licensing.ReleaseNotCoveredError) {
596
+ this.setDownload(downloadState("notCovered", { releaseAccess: err.releaseAccess ?? null, upgradeUrl: err.upgradeUrl ?? null }));
597
+ throw err;
598
+ }
599
+ this.setDownload(downloadState("failed", { error: `The download failed: ${err instanceof Error ? err.message : err}` }));
600
+ throw err;
601
+ }
602
+ }
603
+ /** Show the downloaded installer in the file manager again. */
604
+ revealUpdate() {
605
+ if (!this.downloaded)
606
+ throw new import_licensing.ActivationError("internal", "Nothing has been downloaded");
607
+ import_electron.shell.showItemInFolder(this.downloaded);
608
+ }
609
+ };
610
+ function createMoonbase(options) {
611
+ return new MoonbaseElectron(options);
612
+ }
613
+ // Annotate the CommonJS export names for ESM import in node:
614
+ 0 && (module.exports = {
615
+ MoonbaseElectron,
616
+ createMoonbase
617
+ });