akanjs 3.0.0-beta.28 → 3.0.0-beta.29

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.
Files changed (34) hide show
  1. package/package.json +1 -1
  2. package/server/akanApp.ts +5 -3
  3. package/server/akanServer.ts +16 -6
  4. package/server/contentEncoding.ts +11 -0
  5. package/server/ops/appInfo.ts +3 -1
  6. package/server/selfExec.ts +12 -4
  7. package/types/server/ops/appInfo.d.ts +1 -0
  8. package/types/vendor/@akanjs/native/packages/cli/src/api.d.ts +17 -1
  9. package/types/vendor/@akanjs/native/packages/cli/src/lib/publish.d.ts +8 -0
  10. package/types/vendor/@akanjs/native/packages/cli/src/lib/updates.d.ts +2 -0
  11. package/types/vendor/@akanjs/native/packages/cli/src/platforms/desktop-update.d.ts +7 -1
  12. package/types/vendor/@akanjs/native/packages/cli/src/platforms/windows-installer.d.ts +21 -6
  13. package/types/vendor/@akanjs/native/packages/desktop/src/plugin.d.ts +19 -5
  14. package/types/vendor/@akanjs/native/packages/desktop/src/relaunch.d.ts +20 -1
  15. package/types/vendor/@akanjs/native/packages/desktop/src/server.d.ts +18 -0
  16. package/types/vendor/@akanjs/native/plugins/app/src/index.d.ts +7 -0
  17. package/types/vendor/@akanjs/native/plugins/updates/src/desktop.d.ts +7 -1
  18. package/types/vendor/@akanjs/native/plugins/updates/src/index.d.ts +18 -6
  19. package/vendor/@akanjs/native/packages/cli/src/api.ts +32 -12
  20. package/vendor/@akanjs/native/packages/cli/src/commands/update.ts +9 -2
  21. package/vendor/@akanjs/native/packages/cli/src/lib/publish.ts +22 -5
  22. package/vendor/@akanjs/native/packages/cli/src/lib/updates.ts +2 -0
  23. package/vendor/@akanjs/native/packages/cli/src/platforms/desktop-update.ts +51 -26
  24. package/vendor/@akanjs/native/packages/cli/src/platforms/windows-installer.ts +198 -33
  25. package/vendor/@akanjs/native/packages/desktop/src/dispatcher.ts +9 -2
  26. package/vendor/@akanjs/native/packages/desktop/src/host.ts +21 -9
  27. package/vendor/@akanjs/native/packages/desktop/src/plugin.ts +20 -5
  28. package/vendor/@akanjs/native/packages/desktop/src/relaunch.ts +82 -5
  29. package/vendor/@akanjs/native/packages/desktop/src/server.ts +124 -7
  30. package/vendor/@akanjs/native/plugins/app/native-plugin.json +1 -1
  31. package/vendor/@akanjs/native/plugins/app/src/desktop.ts +5 -0
  32. package/vendor/@akanjs/native/plugins/app/src/index.ts +6 -1
  33. package/vendor/@akanjs/native/plugins/updates/src/desktop.ts +410 -111
  34. package/vendor/@akanjs/native/plugins/updates/src/index.ts +18 -6
@@ -15,7 +15,14 @@ import { createLifecycle } from "./lifecycle.ts";
15
15
  import { appDataDir, appLocalDataDir, reservedDirs, serverDataDir } from "./paths.ts";
16
16
  import { type DesktopPlugin, useShellOpenLimit } from "./plugin.ts";
17
17
  import { nextRelaunchDelay, relaunchAfterExit } from "./relaunch.ts";
18
- import { createDesktopServer, pathWithFirst, readServerManifest, type ServerManifest } from "./server.ts";
18
+ import {
19
+ createDesktopServer,
20
+ createServerStatus,
21
+ envValue,
22
+ pathWithFirst,
23
+ readServerManifest,
24
+ type ServerManifest,
25
+ } from "./server.ts";
19
26
 
20
27
  declare const self: Worker;
21
28
 
@@ -53,7 +60,12 @@ export function startHost(plugins: DesktopPlugin[]): void {
53
60
  const paths = resolvePaths();
54
61
 
55
62
  const binDir = existsSync(join(paths.resources, "bin")) ? join(paths.resources, "bin") : null;
56
- if (binDir) process.env.PATH = pathWithFirst(binDir, process.env.PATH);
63
+ if (binDir) {
64
+
65
+ const path = envValue(process.env, "PATH");
66
+ for (const name of Object.keys(process.env)) if (name.toUpperCase() === "PATH") delete process.env[name];
67
+ process.env.PATH = pathWithFirst(binDir, path);
68
+ }
57
69
  const lib = openNative(paths.lib);
58
70
  const native = lib.symbols;
59
71
 
@@ -137,9 +149,7 @@ export function startHost(plugins: DesktopPlugin[]): void {
137
149
  } catch (error) {
138
150
  manifestProblem = error;
139
151
  }
140
- const carriesServer = manifest !== null || manifestProblem !== undefined;
141
- let settleServer = (_ready: boolean) => {};
142
- const serverReady = new Promise<boolean>((resolve) => (settleServer = resolve));
152
+ const serverStatus = manifest !== null || manifestProblem !== undefined ? createServerStatus() : null;
143
153
  const dispatcher = createDispatcher(
144
154
  plugins,
145
155
  {
@@ -148,7 +158,7 @@ export function startHost(plugins: DesktopPlugin[]): void {
148
158
  appDataDir: appDataDir(boot.app.id),
149
159
  appLocalDataDir: appLocalDataDir(boot.app.id),
150
160
  binDir,
151
- server: carriesServer ? { ready: serverReady } : null,
161
+ server: serverStatus?.status ?? null,
152
162
  emit(window, message) {
153
163
  emitJs(window, `window.__AKAN_NATIVE__&&window.__AKAN_NATIVE__.receive(${JSON.stringify(message)})`);
154
164
  },
@@ -404,7 +414,7 @@ export function startHost(plugins: DesktopPlugin[]): void {
404
414
  };
405
415
 
406
416
  const startServer = async (): Promise<Record<string, string> | undefined> => {
407
- if (!carriesServer) return undefined;
417
+ if (!serverStatus) return undefined;
408
418
  const dataDir = serverDataDir(boot.app.id, boot.dev === true);
409
419
  try {
410
420
  if (!manifest) throw manifestProblem;
@@ -414,15 +424,17 @@ export function startHost(plugins: DesktopPlugin[]): void {
414
424
  manifest,
415
425
  binDir,
416
426
  onGiveUp: serverAlert,
427
+ onState: serverStatus.setState,
417
428
  });
418
- void server.ready.then(settleServer);
429
+ void server.ready.then(serverStatus.settle);
419
430
  lifecycle.onQuit(() => server.stop());
420
431
  const { url, ready } = await server.start();
421
432
  console.info(`[akan-native] server ${ready ? "ready" : "not ready"} on ${url}`);
422
433
  return { PUBLIC_AKAN_SERVER_URL: url };
423
434
  } catch (error) {
424
435
  console.error("[akan-native] the app's server could not start", error);
425
- settleServer(false);
436
+ serverStatus.settle(false);
437
+ serverStatus.setState("gaveUp");
426
438
  serverAlert(`The app's server cannot start: ${error instanceof Error ? error.message : String(error)}`);
427
439
  return { PUBLIC_AKAN_SERVER_URL: "http://127.0.0.1:0" };
428
440
  }
@@ -16,7 +16,10 @@ export type EmitTarget = { window: number } | "focused";
16
16
 
17
17
  export interface DesktopContext {
18
18
  app: AppInfo;
19
- /** A dev build (boot.json `dev`): its pages come from a dev server the shell did not start. */
19
+ /**
20
+ * A debug build (boot.json `dev`: `--debug`, and every dev build, whose pages come from a dev server the shell did not
21
+ * start). It has the release app's id, so what it keeps apart goes in folders of its own.
22
+ */
20
23
  readonly dev: boolean;
21
24
  /**
22
25
  * The window whose page made this call (SH-6; 1 = the window the app opened). Only in method
@@ -55,7 +58,7 @@ export interface DesktopContext {
55
58
  readonly binDir: string | null;
56
59
  /**
57
60
  * The server the app carries (desktop.server), or null. `ready` settles once per session: true when the server
58
- * first answered ready, false when it could not start or gave up before that.
61
+ * first answered ready, false when it could not start or gave up before that; `state` and `onState` follow it after.
59
62
  */
60
63
  readonly server: DesktopServerStatus | null;
61
64
  /** Pushes an event of this plugin to the pages that listen. Returns the windows reached. */
@@ -108,19 +111,31 @@ export interface DesktopContext {
108
111
  closeWindow(window?: number): void;
109
112
  /**
110
113
  * Launch phase: only while setup runs, before the window exists. The host waits for every
111
- * plugin's setup (async allowed, at most 3 s each) before it creates the window. Calls after
112
- * that are ignored with a warning.
114
+ * plugin's setup (async allowed, at most 3 s each) before it creates the window. setWindow after
115
+ * that is ignored with a warning.
113
116
  */
114
117
  readonly launch: {
115
118
  /** Creates the window at these bounds (logical points) instead of the configured size (window-state). */
116
119
  setWindow(bounds: LaunchWindow): void;
117
- /** Ends the app before a window is created; onQuit hooks do not run (single-instance). */
120
+ /**
121
+ * Ends the app before a window is created; onQuit hooks do not run (single-instance). A setup that ran past its
122
+ * time quits the app instead, since its window exists by then.
123
+ */
118
124
  exit(code?: number): void;
119
125
  };
120
126
  }
121
127
 
128
+ /**
129
+ * "starting" until the server answers ready (again after a crash before that), "up" while it answers, "restarting"
130
+ * after a crash once it had been up, "gaveUp" when it is not started again this session, "stopped" as the app quits.
131
+ */
132
+ export type DesktopServerState = "starting" | "up" | "restarting" | "gaveUp" | "stopped";
133
+
122
134
  export interface DesktopServerStatus {
123
135
  readonly ready: Promise<boolean>;
136
+ readonly state: DesktopServerState;
137
+ /** Every later change of `state`. Returns an unsubscribe function. */
138
+ onState(listener: (state: DesktopServerState) => void): () => void;
124
139
  }
125
140
 
126
141
  /** Which page load ended. `id` is "" for a page that sends no document id (v1 callers, tests). */
@@ -8,6 +8,41 @@ import { dirname } from "node:path";
8
8
  export interface RelaunchOptions {
9
9
  /** How long the helper waits after this process exited before it starts the app. */
10
10
  delayMs?: number;
11
+ /**
12
+ * Windows, a swap: while the helper moves the folders, a RunOnce value named `name` runs `script` (written here) at
13
+ * the next logon, which puts back what a shutdown or a killed helper left half moved and starts the app. The helper
14
+ * removes the value once the moves are done or undone.
15
+ */
16
+ recover?: { script: string; name: string };
17
+ }
18
+
19
+ const RUN_ONCE = "HKCU:\\Software\\Microsoft\\Windows\\CurrentVersion\\RunOnce";
20
+
21
+ /** A PowerShell single-quoted literal. */
22
+ const quoted = (value: string) => `'${value.replaceAll("'", "''")}'`;
23
+
24
+ /**
25
+ * The recovery `recover.script` holds: when `exe` is missing, every move whose source is gone and whose target is
26
+ * there goes back, newest first, and the app starts. An app that is there was never half moved: it is left alone.
27
+ */
28
+ export function recoveryScript(exe: string, moves: [string, string][]): string {
29
+ return `$ErrorActionPreference = 'SilentlyContinue'
30
+ $exe = ${quoted(exe)}
31
+ if (Test-Path -LiteralPath $exe) { exit }
32
+ $moves = ${quoted(JSON.stringify(moves))} | ConvertFrom-Json
33
+ [array]::Reverse($moves)
34
+ foreach ($m in $moves) { if (-not (Test-Path -LiteralPath $m[0]) -and (Test-Path -LiteralPath $m[1])) { Move-Item -LiteralPath $m[1] -Destination $m[0] } }
35
+ if (Test-Path -LiteralPath $exe) { Start-Process -WorkingDirectory $env:TEMP -FilePath $exe }
36
+ `;
37
+ }
38
+
39
+ /**
40
+ * The RunOnce command for a recovery script, or null past the 260 characters Windows runs from there. The script is
41
+ * read as text: an execution policy that refuses .ps1 files does not apply to it, as it does not to -EncodedCommand.
42
+ */
43
+ export function recoveryCommand(script: string): string | null {
44
+ const command = `powershell.exe -NoProfile -NonInteractive -WindowStyle Hidden -Command "iex ([IO.File]::ReadAllText(${quoted(script)}))"`;
45
+ return command.length <= 260 ? command : null;
11
46
  }
12
47
 
13
48
  let started: Promise<void> | null = null;
@@ -21,11 +56,11 @@ let started: Promise<void> | null = null;
21
56
  export function relaunchAfterExit(
22
57
  exe: string,
23
58
  moves: [string, string][] = [],
24
- { delayMs = 0 }: RelaunchOptions = {},
59
+ { delayMs = 0, recover }: RelaunchOptions = {},
25
60
  ): Promise<void> {
26
61
  if (started) return started;
27
62
  try {
28
- const helper = startHelper(exe, moves, Math.max(0, Math.round(delayMs)));
63
+ const helper = startHelper(exe, moves, Math.max(0, Math.round(delayMs)), recover);
29
64
  started = helper;
30
65
  return helper;
31
66
  } catch (error) {
@@ -33,17 +68,38 @@ export function relaunchAfterExit(
33
68
  }
34
69
  }
35
70
 
36
- function startHelper(exe: string, moves: [string, string][], delayMs: number): Promise<void> {
71
+ function startHelper(
72
+ exe: string,
73
+ moves: [string, string][],
74
+ delayMs: number,
75
+ recover: RelaunchOptions["recover"],
76
+ ): Promise<void> {
37
77
 
38
78
  const { AKAN_NATIVE_QUIT_ON_STDIN: _cli, ...inherited } = process.env;
39
79
  const delay = (delayMs / 1000).toFixed(3);
40
80
  if (process.platform !== "win32") {
41
- for (const [from, to] of moves) renameSync(from, to);
81
+ const done: [string, string][] = [];
82
+ try {
83
+ for (const [from, to] of moves) {
84
+ renameSync(from, to);
85
+ done.unshift([from, to]);
86
+ }
87
+ } catch (error) {
88
+ for (const [from, to] of done) {
89
+ try {
90
+ renameSync(to, from);
91
+ } catch (undo) {
92
+ console.error(`[akan-native] cannot put ${from} back`, undo);
93
+ }
94
+ }
95
+ throw error;
96
+ }
97
+
42
98
  const child = spawn(
43
99
  "/bin/sh",
44
100
  [
45
101
  "-c",
46
- 'while kill -0 "$AKAN_NATIVE_PARENT" 2>/dev/null; do sleep 0.2; done; sleep "$AKAN_NATIVE_DELAY"; exec "$AKAN_NATIVE_EXE"',
102
+ 'while kill -0 "$AKAN_NATIVE_PARENT" 2>/dev/null && [ "$(ps -o stat= -p "$AKAN_NATIVE_PARENT" 2>/dev/null | cut -c1)" != Z ]; do sleep 0.2; done; sleep "$AKAN_NATIVE_DELAY"; exec "$AKAN_NATIVE_EXE"',
47
103
  ],
48
104
  {
49
105
  detached: true,
@@ -66,6 +122,13 @@ $ErrorActionPreference = 'Stop'
66
122
  $ProgressPreference = 'SilentlyContinue'
67
123
  Wait-Process -Id $env:AKAN_NATIVE_PARENT -ErrorAction SilentlyContinue
68
124
  $moves = $env:AKAN_NATIVE_MOVES | ConvertFrom-Json
125
+ $runOnce = '${RUN_ONCE}'
126
+ if ($env:AKAN_NATIVE_RECOVER) {
127
+ try {
128
+ if (-not (Test-Path $runOnce)) { New-Item -Path $runOnce -Force | Out-Null }
129
+ Set-ItemProperty -Path $runOnce -Name $env:AKAN_NATIVE_RECOVER_NAME -Value $env:AKAN_NATIVE_RECOVER
130
+ } catch {}
131
+ }
69
132
  $done = @()
70
133
  try {
71
134
  foreach ($m in $moves) {
@@ -75,9 +138,22 @@ try {
75
138
  } catch {
76
139
  foreach ($m in $done) { try { Move-Item -LiteralPath $m[1] -Destination $m[0] } catch {} }
77
140
  }
141
+ if ($env:AKAN_NATIVE_RECOVER) { Remove-ItemProperty -Path $runOnce -Name $env:AKAN_NATIVE_RECOVER_NAME -ErrorAction SilentlyContinue }
78
142
  Start-Sleep -Milliseconds ([int]$env:AKAN_NATIVE_DELAY_MS)
79
143
  Start-Process -NoNewWindow -WorkingDirectory $env:AKAN_NATIVE_CWD -FilePath $env:AKAN_NATIVE_EXE
80
144
  `;
145
+ let recovery: Record<string, string> = {};
146
+ const command = recover && moves.length > 0 ? recoveryCommand(recover.script) : null;
147
+ if (recover && command) {
148
+ try {
149
+ mkdirSync(dirname(recover.script), { recursive: true });
150
+ writeFileSync(recover.script, `\uFEFF${recoveryScript(exe, moves)}`);
151
+ recovery = { AKAN_NATIVE_RECOVER: command, AKAN_NATIVE_RECOVER_NAME: recover.name };
152
+ } catch (error) {
153
+ console.warn("[akan-native] cannot write the swap's recovery script", error);
154
+ }
155
+ } else if (recover && moves.length > 0)
156
+ console.warn(`[akan-native] ${recover.script} is too long a path for RunOnce`);
81
157
 
82
158
  const encoded = Buffer.from(script, "utf16le").toString("base64");
83
159
 
@@ -89,6 +165,7 @@ Start-Process -NoNewWindow -WorkingDirectory $env:AKAN_NATIVE_CWD -FilePath $env
89
165
  AKAN_NATIVE_MOVES: JSON.stringify(moves),
90
166
  AKAN_NATIVE_DELAY_MS: String(delayMs),
91
167
  AKAN_NATIVE_CWD: cwd,
168
+ ...recovery,
92
169
  };
93
170
  const args = [
94
171
  "/d",
@@ -1,10 +1,20 @@
1
1
 
2
2
 
3
3
  import { randomBytes } from "node:crypto";
4
- import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
5
- import { createServer } from "node:net";
4
+ import {
5
+ appendFileSync,
6
+ chmodSync,
7
+ existsSync,
8
+ mkdirSync,
9
+ readFileSync,
10
+ renameSync,
11
+ statSync,
12
+ writeFileSync,
13
+ } from "node:fs";
14
+ import { connect, createServer } from "node:net";
6
15
  import { join } from "node:path";
7
16
  import { resolveGrant } from "./grants.ts";
17
+ import type { DesktopServerState, DesktopServerStatus } from "./plugin.ts";
8
18
 
9
19
  export interface ServerManifest {
10
20
  /** The file in resources/server that starts the server. */
@@ -90,6 +100,8 @@ export const MAX_FAILURES = 5;
90
100
  export const BOOT_RESTART_DELAY = 250;
91
101
  /** A run that stayed up this long was healthy: its crash starts the count again. */
92
102
  export const HEALTHY_RUN = 60_000;
103
+ /** server-output.log moves to server-output.log.1 past this size. */
104
+ export const OUTPUT_LOG_LIMIT = 1 << 20;
93
105
 
94
106
  export interface ServerProcess {
95
107
  readonly exited: Promise<number | null>;
@@ -120,6 +132,8 @@ export interface DesktopServerOptions {
120
132
  freePort?(preferred?: number): Promise<number>;
121
133
  /** The server gave up: MAX_FAILURES crashes in a row, or it could not start at all. */
122
134
  onGiveUp?(message: string): void;
135
+ /** Every change of `state`. */
136
+ onState?(state: DesktopServerState): void;
123
137
  readyTimeout?: number;
124
138
  stopGrace?: number;
125
139
  restartDelay?(failures: number, everReady: boolean): number;
@@ -134,9 +148,41 @@ export interface DesktopServer {
134
148
  start(): Promise<{ url: string; ready: boolean }>;
135
149
  /** Settles once: true at the first ready, false when the server gave up or stopped before that. */
136
150
  readonly ready: Promise<boolean>;
151
+ /** Where the server is now; `ready` only tells the first answer. */
152
+ readonly state: DesktopServerState;
137
153
  stop(): Promise<void>;
138
154
  }
139
155
 
156
+ /** What plugins see of the server (ctx.server) from their setup on: the plugin host starts it only after that. */
157
+ export function createServerStatus() {
158
+ let settle = (_ready: boolean) => {};
159
+ const ready = new Promise<boolean>((resolve) => (settle = resolve));
160
+ let state: DesktopServerState = "starting";
161
+ const listeners = new Set<(state: DesktopServerState) => void>();
162
+ const status: DesktopServerStatus = {
163
+ ready,
164
+ get state() {
165
+ return state;
166
+ },
167
+ onState(listener) {
168
+ listeners.add(listener);
169
+ return () => void listeners.delete(listener);
170
+ },
171
+ };
172
+ const setState = (next: DesktopServerState) => {
173
+ if (next === state) return;
174
+ state = next;
175
+ for (const listener of listeners) {
176
+ try {
177
+ listener(next);
178
+ } catch (error) {
179
+ console.error("[akan-native] a server state listener failed", error);
180
+ }
181
+ }
182
+ };
183
+ return { status, settle: (value: boolean) => settle(value), setState };
184
+ }
185
+
140
186
  export function readServerManifest(resources: string): ServerManifest | null {
141
187
  const file = join(resources, "server.json");
142
188
  if (!existsSync(file)) return null;
@@ -161,6 +207,20 @@ export function serverArgv(execPath: string, resources: string, entry: string):
161
207
  ];
162
208
  }
163
209
 
210
+ /**
211
+ * `key`'s value in `env`. Windows names a variable in any case (`Path`), and the plugin host's copy of process.env
212
+ * matches a name only in the case it has, where the process's own env ignores case.
213
+ */
214
+ export function envValue(
215
+ env: Record<string, string | undefined>,
216
+ key: string,
217
+ platform: NodeJS.Platform = process.platform,
218
+ ): string | undefined {
219
+ if (env[key] !== undefined || platform !== "win32") return env[key];
220
+ const name = Object.keys(env).find((candidate) => candidate.toUpperCase() === key.toUpperCase());
221
+ return name === undefined ? undefined : env[name];
222
+ }
223
+
164
224
  /** `dir` first on a PATH, once: a relaunched app inherits the PATH its predecessor already extended. */
165
225
  export function pathWithFirst(
166
226
  dir: string,
@@ -194,7 +254,7 @@ export function serverEnv(
194
254
  ): Record<string, string> {
195
255
  const system: Record<string, string> = {};
196
256
  for (const key of SYSTEM_ENV_KEYS) {
197
- const value = env[key];
257
+ const value = envValue(env, key, platform);
198
258
  if (value === undefined) continue;
199
259
 
200
260
  if (platform === "win32" && Object.keys(system).some((k) => k.toUpperCase() === key.toUpperCase())) continue;
@@ -254,7 +314,22 @@ const listenOn = (port: number) =>
254
314
  });
255
315
  });
256
316
 
257
- const loopbackPort = (preferred?: number) => (preferred ? listenOn(preferred).catch(() => listenOn(0)) : listenOn(0));
317
+ const answers = (port: number) =>
318
+ new Promise<boolean>((resolve) => {
319
+ const socket = connect({ host: "127.0.0.1", port });
320
+ const done = (answered: boolean) => {
321
+ socket.destroy();
322
+ resolve(answered);
323
+ };
324
+ socket.once("connect", () => done(true));
325
+ socket.once("error", () => done(false));
326
+ socket.setTimeout(500, () => done(false));
327
+ });
328
+
329
+ const loopbackPort = async (preferred?: number) => {
330
+ const kept = preferred && !(await answers(preferred)) ? await listenOn(preferred).catch(() => 0) : 0;
331
+ return kept || listenOn(0);
332
+ };
258
333
 
259
334
  const validPort = (port: number) => Number.isInteger(port) && port > 0 && port < 65536;
260
335
 
@@ -330,6 +405,8 @@ export function createDesktopServer(options: DesktopServerOptions): DesktopServe
330
405
  const argv = serverArgv(options.execPath ?? process.execPath, options.resources, options.manifest.entry);
331
406
  const grace = options.stopGrace ?? STOP_GRACE;
332
407
  const logs = join(dataDir, "runtime", "logs");
408
+ const outputLog = join(logs, "server-output.log");
409
+ let outputSize = -1;
333
410
  let env: Record<string, string> = {};
334
411
  let secret = "";
335
412
  let port = 0;
@@ -345,6 +422,33 @@ export function createDesktopServer(options: DesktopServerOptions): DesktopServe
345
422
  const crashedGroups = new Set<NonNullable<ServerProcess["killGroup"]>>();
346
423
  let settleReady = (_ready: boolean) => {};
347
424
  const ready = new Promise<boolean>((resolve) => (settleReady = resolve));
425
+ let state: DesktopServerState = "starting";
426
+ const setState = (next: DesktopServerState) => {
427
+ if (next === state || state === "stopped") return;
428
+ state = next;
429
+ try {
430
+ options.onState?.(next);
431
+ } catch (error) {
432
+ console.error("[akan-native] the server's state handler failed", error);
433
+ }
434
+ };
435
+
436
+ const record = (line: string) => {
437
+ try {
438
+ if (outputSize < 0) {
439
+ mkdirSync(logs, { recursive: true });
440
+ outputSize = existsSync(outputLog) ? statSync(outputLog).size : 0;
441
+ }
442
+ if (outputSize > OUTPUT_LOG_LIMIT) {
443
+ renameSync(outputLog, `${outputLog}.1`);
444
+ outputSize = 0;
445
+ }
446
+ const text = `${new Date().toISOString()} ${line}\n`;
447
+ appendFileSync(outputLog, text);
448
+ outputSize += Buffer.byteLength(text);
449
+ } catch {
450
+ }
451
+ };
348
452
 
349
453
  const configure = () => {
350
454
  env = serverEnv(options.manifest, {
@@ -359,6 +463,8 @@ export function createDesktopServer(options: DesktopServerOptions): DesktopServe
359
463
  const giveUp = (message: string) => {
360
464
  gaveUp = true;
361
465
  settleReady(false);
466
+ setState("gaveUp");
467
+ record(`[akan-native] ${message}`);
362
468
  try {
363
469
  options.onGiveUp?.(message);
364
470
  } catch (error) {
@@ -368,7 +474,10 @@ export function createDesktopServer(options: DesktopServerOptions): DesktopServe
368
474
 
369
475
  const failed = (why: string) => {
370
476
  failures++;
371
- console.error(`[akan-native] the server ${why} (${failures} of ${MAX_FAILURES} in a row)`);
477
+ const line = `[akan-native] the server ${why} (${failures} of ${MAX_FAILURES} in a row)`;
478
+ console.error(line);
479
+ record(line);
480
+ setState(everReady ? "restarting" : "starting");
372
481
  if (failures >= MAX_FAILURES)
373
482
  return giveUp(
374
483
  `The app's server stopped ${MAX_FAILURES} times in a row and is not restarted again. Its logs are in ${logs}.`,
@@ -386,6 +495,7 @@ export function createDesktopServer(options: DesktopServerOptions): DesktopServe
386
495
  if (type === "file.resolve") return answerGrant(child, message as { id?: unknown; grant?: unknown });
387
496
  if (type !== "ready" || readyAt !== null) return;
388
497
  readyAt = now();
498
+ setState("up");
389
499
  if (!everReady) {
390
500
  everReady = true;
391
501
  settleReady(true);
@@ -395,7 +505,10 @@ export function createDesktopServer(options: DesktopServerOptions): DesktopServe
395
505
  } catch {
396
506
  }
397
507
  },
398
- onLine: (line, stream) => (stream === "stderr" ? console.error : console.info)(`[server] ${line}`),
508
+ onLine: (line, stream) => {
509
+ (stream === "stderr" ? console.error : console.info)(`[server] ${line}`);
510
+ if (stream === "stderr" || readyAt === null) record(line);
511
+ },
399
512
  });
400
513
  proc = child;
401
514
  child.exited.then(
@@ -423,7 +536,7 @@ export function createDesktopServer(options: DesktopServerOptions): DesktopServe
423
536
  if (stopping || gaveUp) return;
424
537
  try {
425
538
  if (!everReady && !handedOut && failures > 0) {
426
- const fresh = await pickPort();
539
+ const fresh = await pickPort(port);
427
540
  if (stopping || gaveUp) return;
428
541
  if (!handedOut && fresh !== port) {
429
542
  port = fresh;
@@ -439,6 +552,9 @@ export function createDesktopServer(options: DesktopServerOptions): DesktopServe
439
552
 
440
553
  return {
441
554
  ready,
555
+ get state() {
556
+ return state;
557
+ },
442
558
  async start() {
443
559
  const kept = lastPort(dataDir);
444
560
  try {
@@ -474,6 +590,7 @@ export function createDesktopServer(options: DesktopServerOptions): DesktopServe
474
590
  stopping = true;
475
591
  clearTimeout(restartTimer);
476
592
  settleReady(false);
593
+ setState("stopped");
477
594
  for (const group of crashedGroups) group("SIGKILL");
478
595
  crashedGroups.clear();
479
596
  const child = proc;
@@ -2,7 +2,7 @@
2
2
  "id": "app",
3
3
  "apiVersion": 1,
4
4
  "methods": ["getInfo", "getLaunchUrl", "exit", "relaunch", "minimize", "answerBeforeQuit", "setBackEnabled"],
5
- "events": ["urlOpen", "backButton", "beforeQuit", "backProgress"],
5
+ "events": ["urlOpen", "backButton", "beforeQuit", "backProgress", "serverState"],
6
6
  "codegen": true,
7
7
  "web": "./src/web.ts",
8
8
  "desktop": "./src/desktop.ts",
@@ -68,5 +68,10 @@ export default defineDesktopPlugin<AppApi, AppEvents>({
68
68
 
69
69
  backButton: () => () => {},
70
70
  backProgress: () => () => {},
71
+ serverState(send, ctx) {
72
+ if (!ctx.server) return () => {};
73
+ send({ state: ctx.server.state });
74
+ return ctx.server.onState((state) => void send({ state }));
75
+ },
71
76
  },
72
77
  });
@@ -54,11 +54,16 @@ export interface AppEvents {
54
54
  * arrives as backButton, and one let go early as `cancelled`.
55
55
  */
56
56
  backProgress: { phase: BackProgressPhase; progress: number; swipeEdge: "left" | "right" };
57
+ /**
58
+ * Desktop, an app that carries a server (desktop.server): where it is, at every change and when the first page
59
+ * starts listening. "gaveUp" means it is not started again until the app is.
60
+ */
61
+ serverState: { state: "starting" | "up" | "restarting" | "gaveUp" | "stopped" };
57
62
  }
58
63
 
59
64
  export const app = definePlugin<AppApi, AppEvents>("app", {
60
65
  methods: ["getInfo", "getLaunchUrl", "exit", "relaunch", "minimize", "answerBeforeQuit", "setBackEnabled"],
61
- events: ["urlOpen", "backButton", "beforeQuit", "backProgress"],
66
+ events: ["urlOpen", "backButton", "beforeQuit", "backProgress", "serverState"],
62
67
  web,
63
68
  });
64
69