mirinjs 0.0.1-alpha.10 → 0.0.1-alpha.11

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mirinjs",
3
- "version": "0.0.1-alpha.10",
3
+ "version": "0.0.1-alpha.11",
4
4
  "description": "Build desktop apps with Bun, TypeScript, and Chromium (CEF). The Bun-native Electron alternative.",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/src/app.ts CHANGED
@@ -6,6 +6,8 @@
6
6
  import { runtime, onNativeEvent, resolveUrl, type NativeEvent } from "./runtime.ts";
7
7
  import type { Router, EventProc } from "./rpc.ts";
8
8
  import type { WindowConfig, WindowMaterial, WindowMaterialOptions } from "./config.ts";
9
+ import { updater } from "./updater.ts";
10
+ import type { Updater } from "./updater.ts";
9
11
 
10
12
  /** Which native backend a window's `material` resolved to. */
11
13
  export type WindowMaterialInfo = {
@@ -279,6 +281,9 @@ export interface Dock {
279
281
  class MirinApp extends Emitter<AppEvents> {
280
282
  readonly windows = new Windows();
281
283
 
284
+ /** Auto-updater (macOS). Inert unless the app was built with `release` set. */
285
+ readonly updater: Updater = updater;
286
+
282
287
  /** macOS Dock-icon controls. Hiding suits resident, hotkey-summoned apps. */
283
288
  readonly dock: Dock = {
284
289
  hide: () => this.#setDock(false),
package/src/config.ts CHANGED
@@ -86,9 +86,24 @@ export interface MirinConfig {
86
86
  * into an `.icns`. Embedded in the bundle for the Dock and Finder.
87
87
  */
88
88
  icon?: string;
89
+ /**
90
+ * Auto-update configuration (macOS). Omit to disable updates entirely.
91
+ * `baseUrl` is a flat directory of release artifacts (a GitHub Releases
92
+ * `…/releases/latest/download` URL, an S3/R2 bucket, or any static host).
93
+ * `channel` (default "stable") is baked into artifact filenames + the app's
94
+ * support folder, so multiple channels can coexist at the same `baseUrl`.
95
+ */
96
+ release?: ReleaseConfig;
89
97
  windows: Record<string, WindowConfig>;
90
98
  }
91
99
 
100
+ export interface ReleaseConfig {
101
+ /** Flat directory URL hosting `{channel}-{platform}-{arch}-*` update files. */
102
+ baseUrl: string;
103
+ /** Update channel; baked into artifact names + support dir. Default "stable". */
104
+ channel?: string;
105
+ }
106
+
92
107
  /** Identity function for typing/intellisense. `const` generic preserves window names as literal keys. */
93
108
  export function defineConfig<const T extends MirinConfig>(config: T): T {
94
109
  return config;
package/src/host.ts CHANGED
@@ -48,7 +48,7 @@ const coreConfig = JSON.parse(
48
48
  const core = new Core(corePath);
49
49
 
50
50
  const worker = new Worker(workerPath, {
51
- workerData: { corePath, manifest, devUrl: process.env.MIRIN_DEV_URL },
51
+ workerData: { corePath, manifest, devUrl: process.env.MIRIN_DEV_URL, resourcesDir },
52
52
  });
53
53
  worker.on("error", (err) => console.error("[mirin worker]", err));
54
54
 
package/src/index.ts CHANGED
@@ -23,6 +23,7 @@ export { dialog } from "./dialog.ts";
23
23
  export { clipboard } from "./clipboard.ts";
24
24
  export { globalShortcut } from "./shortcut.ts";
25
25
  export { logger, setLogLevel, getLogLevel, Logger } from "./logger.ts";
26
+ export { updater, Updater } from "./updater.ts";
26
27
  export { NotAttachedError } from "./runtime.ts";
27
28
 
28
29
  export type {
@@ -38,6 +39,7 @@ export type {
38
39
  } from "./app.ts";
39
40
  export type { MenuItemTemplate, MenuRole } from "./menu.ts";
40
41
  export type { LogLevel } from "./logger.ts";
42
+ export type { UpdaterStatus, UpdateInfo, UpdateProgress, UpdaterEvents } from "./updater.ts";
41
43
  export type { TrayOptions } from "./tray.ts";
42
44
  export type { OpenDialogOptions, SaveDialogOptions, MessageDialogOptions } from "./dialog.ts";
43
45
  export type {
package/src/runtime.ts CHANGED
@@ -18,6 +18,8 @@ export interface Runtime {
18
18
  rpc: RpcServer;
19
19
  manifestWindows: ManifestWindowConfig[];
20
20
  devUrl?: string;
21
+ /** Contents/Resources of the running .app (for the updater). Absent in dev. */
22
+ resourcesDir?: string;
21
23
  }
22
24
 
23
25
  export class NotAttachedError extends Error {
@@ -79,6 +81,7 @@ export function boot(): void {
79
81
  corePath?: string;
80
82
  manifest?: { windows?: Record<string, WindowConfig> };
81
83
  devUrl?: string;
84
+ resourcesDir?: string;
82
85
  };
83
86
  const corePath = data.corePath ?? process.env.MIRIN_CORE;
84
87
  if (!corePath) return; // not under the host; the API stays detached
@@ -92,6 +95,6 @@ export function boot(): void {
92
95
  data.manifest?.windows ?? {},
93
96
  ).map(([name, cfg]) => ({ name, ...cfg }));
94
97
 
95
- current = { core, rpc, manifestWindows, devUrl: data.devUrl };
98
+ current = { core, rpc, manifestWindows, devUrl: data.devUrl, resourcesDir: data.resourcesDir };
96
99
  core.onEvent(dispatch);
97
100
  }
package/src/updater.ts ADDED
@@ -0,0 +1,314 @@
1
+ /**
2
+ * mirin/updater — the `app.updater` API (runs in the Bun Worker).
3
+ *
4
+ * Reads the app's own `Resources/version.json` (embedded by `mirin build` when
5
+ * `release` is configured), polls the manifest at `{baseUrl}/{prefix}-update.json`,
6
+ * downloads the full `.app` bundle when a different version is published, verifies
7
+ * its SHA-256, then swaps the whole `.app` and relaunches.
8
+ *
9
+ * A signed/notarized `.app` cannot be modified in place without breaking its
10
+ * signature, so every update replaces the entire bundle. Updates run only in a
11
+ * packaged app with `release` set; in `mirin dev` (no version.json) the updater
12
+ * stays idle and `checkForUpdate()` resolves `null`.
13
+ *
14
+ * import { app } from "mirinjs";
15
+ * const info = await app.updater.checkForUpdate();
16
+ * if (info) { await app.updater.download(p => …); await app.updater.applyAndRelaunch(); }
17
+ */
18
+
19
+ import { homedir } from "node:os";
20
+ import { dirname, join } from "node:path";
21
+ import { existsSync, mkdirSync, readFileSync, rmSync } from "node:fs";
22
+ import { $ } from "bun";
23
+ import { runtime } from "./runtime.ts";
24
+
25
+ export type UpdaterStatus =
26
+ | "idle"
27
+ | "checking"
28
+ | "update-available"
29
+ | "downloading"
30
+ | "applying"
31
+ | "complete"
32
+ | "error";
33
+
34
+ /** The running app's embedded identity (Resources/version.json). */
35
+ interface VersionInfo {
36
+ version: string;
37
+ channel: string;
38
+ baseUrl: string;
39
+ name: string;
40
+ identifier: string;
41
+ }
42
+
43
+ /** A published release the running app can update to. */
44
+ export interface UpdateInfo {
45
+ /** Version being offered. */
46
+ version: string;
47
+ /** The currently-running version. */
48
+ currentVersion: string;
49
+ channel: string;
50
+ /** Artifact filename, relative to baseUrl. */
51
+ url: string;
52
+ sha256: string;
53
+ size?: number;
54
+ }
55
+
56
+ export interface UpdateProgress {
57
+ received: number;
58
+ total: number;
59
+ /** 0..1 (0 when total is unknown). */
60
+ fraction: number;
61
+ }
62
+
63
+ export type UpdaterEvents = {
64
+ status: { status: UpdaterStatus };
65
+ progress: UpdateProgress;
66
+ "update-available": UpdateInfo;
67
+ error: { message: string };
68
+ };
69
+
70
+ type Listener<P> = (payload: P) => void;
71
+
72
+ export class Updater {
73
+ #listeners = new Map<keyof UpdaterEvents, Set<Listener<unknown>>>();
74
+ #status: UpdaterStatus = "idle";
75
+ #info: VersionInfo | null | undefined; // undefined = not yet read
76
+ #pending: UpdateInfo | null = null;
77
+ #staged: string | null = null; // path to the extracted, verified .app
78
+ #autoCheck: ReturnType<typeof setInterval> | undefined;
79
+
80
+ /** Subscribe to an updater event. Returns an unsubscribe function. */
81
+ on<K extends keyof UpdaterEvents>(type: K, listener: Listener<UpdaterEvents[K]>): () => void {
82
+ let set = this.#listeners.get(type);
83
+ if (!set) this.#listeners.set(type, (set = new Set()));
84
+ set.add(listener as Listener<unknown>);
85
+ return () => set!.delete(listener as Listener<unknown>);
86
+ }
87
+
88
+ get status(): UpdaterStatus {
89
+ return this.#status;
90
+ }
91
+ get currentVersion(): string {
92
+ return this.#version()?.version ?? "0.0.0";
93
+ }
94
+ get channel(): string {
95
+ return this.#version()?.channel ?? "stable";
96
+ }
97
+ /** Whether this build has updates configured (packaged + `release` set). */
98
+ get enabled(): boolean {
99
+ return this.#version() != null;
100
+ }
101
+
102
+ /**
103
+ * Fetch the channel manifest and report an available update, or `null` if the
104
+ * app is up to date / updates aren't configured. Never throws.
105
+ */
106
+ async checkForUpdate(): Promise<UpdateInfo | null> {
107
+ const v = this.#version();
108
+ if (!v) return null;
109
+ this.#setStatus("checking");
110
+ try {
111
+ const url = `${v.baseUrl.replace(/\/$/, "")}/${this.#prefix()}-update.json?t=${Date.now()}`;
112
+ const res = await fetch(url, { redirect: "follow" });
113
+ if (!res.ok) throw new Error(`manifest ${res.status}`);
114
+ const m = (await res.json()) as {
115
+ version: string;
116
+ url: string;
117
+ sha256: string;
118
+ size?: number;
119
+ };
120
+ if (!m.version || m.version === v.version) {
121
+ this.#setStatus("idle");
122
+ return null;
123
+ }
124
+ const info: UpdateInfo = {
125
+ version: m.version,
126
+ currentVersion: v.version,
127
+ channel: v.channel,
128
+ url: m.url,
129
+ sha256: m.sha256,
130
+ size: m.size,
131
+ };
132
+ this.#pending = info;
133
+ this.#setStatus("update-available");
134
+ this.#emit("update-available", info);
135
+ return info;
136
+ } catch (err) {
137
+ this.#fail(err);
138
+ return null;
139
+ }
140
+ }
141
+
142
+ /**
143
+ * Download (and verify) the pending update's bundle into the app's support
144
+ * dir. Emits `progress`. Call `checkForUpdate()` first.
145
+ */
146
+ async download(onProgress?: (p: UpdateProgress) => void): Promise<void> {
147
+ const v = this.#version();
148
+ if (!v || !this.#pending) throw new Error("no update to download — call checkForUpdate() first");
149
+ const info = this.#pending;
150
+ this.#setStatus("downloading");
151
+ try {
152
+ const dir = this.#updatesDir(v);
153
+ rmSync(dir, { recursive: true, force: true });
154
+ mkdirSync(dir, { recursive: true });
155
+
156
+ const url = `${v.baseUrl.replace(/\/$/, "")}/${info.url}`;
157
+ const res = await fetch(url, { redirect: "follow" });
158
+ if (!res.ok || !res.body) throw new Error(`download ${res.status}`);
159
+ const total = Number(res.headers.get("content-length") ?? info.size ?? 0);
160
+
161
+ const reader = res.body.getReader();
162
+ const chunks: Uint8Array[] = [];
163
+ let received = 0;
164
+ for (;;) {
165
+ const { done, value } = await reader.read();
166
+ if (done) break;
167
+ chunks.push(value);
168
+ received += value.byteLength;
169
+ const p: UpdateProgress = { received, total, fraction: total ? received / total : 0 };
170
+ this.#emit("progress", p);
171
+ onProgress?.(p);
172
+ }
173
+ const buf = Buffer.concat(chunks);
174
+
175
+ // Integrity: the manifest's sha256 must match the downloaded artifact.
176
+ const got = new Bun.CryptoHasher("sha256").update(buf).digest("hex");
177
+ if (got !== info.sha256) {
178
+ throw new Error(`hash mismatch (expected ${info.sha256.slice(0, 12)}…, got ${got.slice(0, 12)}…)`);
179
+ }
180
+
181
+ const tarPath = join(dir, "update.tar.gz");
182
+ await Bun.write(tarPath, buf);
183
+ await $`tar -xzf ${tarPath} -C ${dir}`.quiet();
184
+ const staged = join(dir, `${v.name}.app`);
185
+ if (!existsSync(staged)) throw new Error(`extracted bundle not found at ${staged}`);
186
+
187
+ // Refuse a tampered/corrupt bundle (works for ad-hoc + Developer ID).
188
+ const verify = await $`codesign --verify --deep --strict ${staged}`.quiet().nothrow();
189
+ if (verify.exitCode !== 0) throw new Error("codesign verification failed on the downloaded update");
190
+
191
+ this.#staged = staged;
192
+ this.#setStatus("update-available");
193
+ } catch (err) {
194
+ this.#fail(err);
195
+ throw err;
196
+ }
197
+ }
198
+
199
+ /**
200
+ * Swap the running `.app` with the downloaded bundle and relaunch. Spawns a
201
+ * detached helper that waits for this process to exit, replaces the bundle,
202
+ * strips quarantine, and reopens the app — then quits.
203
+ */
204
+ async applyAndRelaunch(): Promise<void> {
205
+ const v = this.#version();
206
+ if (!v || !this.#staged) throw new Error("no staged update — call download() first");
207
+ this.#setStatus("applying");
208
+ try {
209
+ const runningApp = join(this.#resourcesDir()!, "..", "..");
210
+ const script = [
211
+ `APP=${sh(runningApp)}`,
212
+ `NEW=${sh(this.#staged)}`,
213
+ `PID=${process.pid}`,
214
+ // Wait for the running app to fully exit before swapping.
215
+ `while kill -0 "$PID" 2>/dev/null; do sleep 0.2; done`,
216
+ `sleep 0.3`,
217
+ `rm -rf "$APP"`,
218
+ `mv "$NEW" "$APP"`,
219
+ `xattr -r -d com.apple.quarantine "$APP" 2>/dev/null || true`,
220
+ `open "$APP"`,
221
+ ].join("\n");
222
+
223
+ Bun.spawn(["/bin/sh", "-c", script], {
224
+ stdin: "ignore",
225
+ stdout: "ignore",
226
+ stderr: "ignore",
227
+ }).unref();
228
+
229
+ this.#setStatus("complete");
230
+ // Quit; the detached helper does the swap + relaunch after we exit.
231
+ runtime().core.quit();
232
+ } catch (err) {
233
+ this.#fail(err);
234
+ throw err;
235
+ }
236
+ }
237
+
238
+ /** Poll for updates every `intervalMs`. Returns a stop function. */
239
+ startAutoCheck(intervalMs = 6 * 60 * 60 * 1000): () => void {
240
+ this.stopAutoCheck();
241
+ void this.checkForUpdate();
242
+ this.#autoCheck = setInterval(() => void this.checkForUpdate(), intervalMs);
243
+ return () => this.stopAutoCheck();
244
+ }
245
+
246
+ stopAutoCheck(): void {
247
+ if (this.#autoCheck) clearInterval(this.#autoCheck);
248
+ this.#autoCheck = undefined;
249
+ }
250
+
251
+ // ---- internals ----
252
+
253
+ #version(): VersionInfo | null {
254
+ if (this.#info !== undefined) return this.#info;
255
+ const dir = this.#resourcesDir();
256
+ const path = dir ? join(dir, "version.json") : undefined;
257
+ if (path && existsSync(path)) {
258
+ try {
259
+ this.#info = JSON.parse(readFileSync(path, "utf8")) as VersionInfo;
260
+ } catch {
261
+ this.#info = null;
262
+ }
263
+ } else {
264
+ this.#info = null;
265
+ }
266
+ return this.#info;
267
+ }
268
+
269
+ #resourcesDir(): string | undefined {
270
+ try {
271
+ return runtime().resourcesDir;
272
+ } catch {
273
+ return undefined; // detached (not under the host)
274
+ }
275
+ }
276
+
277
+ #prefix(): string {
278
+ const v = this.#version()!;
279
+ return `${v.channel}-darwin-${process.arch}`;
280
+ }
281
+
282
+ #updatesDir(v: VersionInfo): string {
283
+ return join(homedir(), "Library", "Application Support", v.identifier, v.channel, "updates");
284
+ }
285
+
286
+ #setStatus(status: UpdaterStatus): void {
287
+ this.#status = status;
288
+ this.#emit("status", { status });
289
+ }
290
+
291
+ #fail(err: unknown): void {
292
+ const message = err instanceof Error ? err.message : String(err);
293
+ this.#status = "error";
294
+ this.#emit("status", { status: "error" });
295
+ this.#emit("error", { message });
296
+ }
297
+
298
+ #emit<K extends keyof UpdaterEvents>(type: K, payload: UpdaterEvents[K]): void {
299
+ this.#listeners.get(type)?.forEach((fn) => fn(payload));
300
+ // Bridge to webviews so frontends can react without polling.
301
+ try {
302
+ runtime().rpc.broadcast(`mirin:updater:${type}`, payload);
303
+ } catch {
304
+ // detached / rpc not up — ignore
305
+ }
306
+ }
307
+ }
308
+
309
+ /** Single-quote a path for safe interpolation into a /bin/sh script. */
310
+ function sh(p: string): string {
311
+ return `'${p.replace(/'/g, `'\\''`)}'`;
312
+ }
313
+
314
+ export const updater = new Updater();