@acryldev/launcher-desktop 0.1.7 → 0.1.9

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/lib/index.js CHANGED
@@ -1,194 +1,8 @@
1
- import { existsSync, mkdirSync, readFileSync } from "node:fs";
2
- import { basename, dirname, join } from "node:path";
3
- import { APP_MARKER, APP_NAME, STARTERS, addApp, appNameProblem, blendOf, blendVersionOf, clearGithub, githubClientId, githubEnv, githubOf, inspectApp, maskKey, modelEnv, pollGithubSignIn, prepareTools, readApps, readGithub, readModelKey, removeApp, setBlendVisibility, startGithubSignIn, toolsEnv, whereProblem } from "@acryldev/launcher";
1
+ import { A as LAUNCHER_UPDATE_PATH, C as LAUNCHER_PUBLISH_PLAN_PATH, D as LAUNCHER_START_PATH, E as LAUNCHER_SHARE_PLAN_PATH, F as WEBBOXES_NEW_BOX, I as webboxesDeployBlendUrl, L as webboxesDeployUrl, M as MAKEABLE_SURFACES, N as PLUGIN_NAME, O as LAUNCHER_STATE_PATH, P as SURFACES, S as LAUNCHER_PUBLISH_PATH, T as LAUNCHER_SHARE_PATH, _ as LAUNCHER_GITHUB_START_PATH, b as LAUNCHER_PLUGINS_PATH, c as BLEND_SOURCE, d as LAUNCHER_API_PREFIX, f as LAUNCHER_ASSISTANT_FOLDER_PATH, g as LAUNCHER_GITHUB_POLL_PATH, h as LAUNCHER_GITHUB_PATH, i as RegistryUnavailable, j as LICENSE_ID, k as LAUNCHER_STOP_PATH, l as LAUNCHER_ADD_PATH, m as LAUNCHER_GITHUB_DISCONNECT_PATH, n as LauncherRefusal, o as ACCOUNT_NAME, p as LAUNCHER_BLENDS_PATH, r as LauncherService, s as BLEND_ID, t as createNodeLauncher, u as LAUNCHER_ADE_PATH, v as LAUNCHER_HEALTH_PATH, w as LAUNCHER_REMOVE_PATH, x as LAUNCHER_PLUGIN_PULL_PATH, y as LAUNCHER_NEW_PATH } from "./node-DxDbk2F0.js";
4
2
  import { defineAcrylTool } from "@acryldev/control";
5
3
  import { Acryl } from "@acryldev/blends";
6
4
  import { error } from "@acryldev/loopback-http";
7
5
  import { INVALID_JSON, jsonBody, jsonContent, ownPage, privateApi, readJson } from "@acryldev/loopback-http/router";
8
- import { spawn, spawnSync } from "node:child_process";
9
- //#region src/contract.ts
10
- /** The wire contract of the ACRYL screen's routes (the desktop face of the launcher, spec 050 T012). The screen is the client of these routes. */
11
- /** Every launcher route lives under this prefix, the one the Host's Web adapter mounts for this plugin. */
12
- const LAUNCHER_API_PREFIX = "/api/acryl-launcher";
13
- const LAUNCHER_STATE_PATH = `${LAUNCHER_API_PREFIX}/state`;
14
- const LAUNCHER_HEALTH_PATH = `${LAUNCHER_API_PREFIX}/health`;
15
- const LAUNCHER_ADD_PATH = `${LAUNCHER_API_PREFIX}/add`;
16
- const LAUNCHER_REMOVE_PATH = `${LAUNCHER_API_PREFIX}/remove`;
17
- const LAUNCHER_NEW_PATH = `${LAUNCHER_API_PREFIX}/new`;
18
- const LAUNCHER_START_PATH = `${LAUNCHER_API_PREFIX}/start`;
19
- const LAUNCHER_STOP_PATH = `${LAUNCHER_API_PREFIX}/stop`;
20
- const LAUNCHER_UPDATE_PATH = `${LAUNCHER_API_PREFIX}/update`;
21
- /** Open ACRYL ADE (the Blend `acryl.ade` in `<home>/ade`, the folder `acryl ade` uses), made on first use, in a window or the browser. */
22
- const LAUNCHER_ADE_PATH = `${LAUNCHER_API_PREFIX}/ade`;
23
- const LAUNCHER_BLENDS_PATH = `${LAUNCHER_API_PREFIX}/blends`;
24
- const LAUNCHER_ASSISTANT_FOLDER_PATH = `${LAUNCHER_API_PREFIX}/assistant-folder`;
25
- const LAUNCHER_PLUGINS_PATH = `${LAUNCHER_API_PREFIX}/plugins`;
26
- const LAUNCHER_PLUGIN_PULL_PATH = `${LAUNCHER_API_PREFIX}/plugin-pull`;
27
- const LAUNCHER_PUBLISH_PLAN_PATH = `${LAUNCHER_API_PREFIX}/publish-plan`;
28
- const LAUNCHER_PUBLISH_PATH = `${LAUNCHER_API_PREFIX}/publish`;
29
- const LAUNCHER_SHARE_PLAN_PATH = `${LAUNCHER_API_PREFIX}/share-plan`;
30
- const LAUNCHER_SHARE_PATH = `${LAUNCHER_API_PREFIX}/share`;
31
- const LAUNCHER_GITHUB_PATH = `${LAUNCHER_API_PREFIX}/github`;
32
- const LAUNCHER_GITHUB_START_PATH = `${LAUNCHER_API_PREFIX}/github-start`;
33
- const LAUNCHER_GITHUB_POLL_PATH = `${LAUNCHER_API_PREFIX}/github-poll`;
34
- const LAUNCHER_GITHUB_DISCONNECT_PATH = `${LAUNCHER_API_PREFIX}/github-disconnect`;
35
- const SURFACES = [
36
- "web",
37
- "desktop",
38
- "tui"
39
- ];
40
- /** Surfaces a person can choose for a new app today. */
41
- const MAKEABLE_SURFACES = ["web", "desktop"];
42
- /** WebBoxes.ai's New WebBox form, opened with the app's repository filled in (the person signs in and presses Create there). */
43
- function webboxesDeployUrl(github, name) {
44
- const url = new URL(WEBBOXES_NEW_BOX);
45
- url.searchParams.set("github", github);
46
- url.searchParams.set("name", name.toLowerCase().replace(/[^a-z0-9-]+/gu, "-").replace(/^-+|-+$/gu, "").slice(0, 40));
47
- return url.href;
48
- }
49
- /** A Blend id as `acryl new --from` takes it: it starts with a letter or digit, so it can never read as an option. */
50
- /** WebBoxes.ai's WebBoxes page: with `github` (a public https://github.com/owner/repo) and `name` it opens the New WebBox form filled in. */
51
- const WEBBOXES_NEW_BOX = "https://webboxes.ai/dashboard/webboxes";
52
- const BLEND_ID = /^[a-z0-9][a-z0-9._-]{0,127}$/u;
53
- /** A Blend released on GitHub, as `--from` takes it (create-acrylblends `github:owner/repo#ref`): what a community Blend is made from. */
54
- const BLEND_SOURCE = /^github:[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})\/[A-Za-z0-9._-]{1,100}(?:#[A-Za-z0-9._/-]{1,100})?$/u;
55
- /** A plugin name, a GitHub account and a license id as the door takes them: nothing that could read as an option or a path. */
56
- const PLUGIN_NAME = /^[a-z0-9][a-z0-9._-]{0,127}$/u;
57
- const ACCOUNT_NAME = /^[A-Za-z0-9][A-Za-z0-9-]{0,38}$/u;
58
- const LICENSE_ID = /^[A-Za-z0-9][A-Za-z0-9.+-]{0,39}$/u;
59
- //#endregion
60
- //#region src/door.ts
61
- /**
62
- * The running app's door, reached the way the app's own `acryl` command reaches it: `<app>/.acryl/door.json` names the loopback address and the secret of the
63
- * app that is running now. The screen is a person's surface, so it may do what the terminal's prompt does: send a publish the person confirmed. Only
64
- * loopback addresses are used, and a missing or stale file means the app is not running.
65
- */
66
- var DoorUnavailable = class extends Error {};
67
- const TIMEOUT_MS$1 = 6e4;
68
- const LOOPBACK = /* @__PURE__ */ new Set([
69
- "127.0.0.1",
70
- "localhost",
71
- "[::1]"
72
- ]);
73
- const NOT_RUNNING = "the app is not running: start it from this screen, then try again";
74
- function readDoorFile(folder, read) {
75
- let parsed;
76
- try {
77
- parsed = JSON.parse(read(join(folder, ".acryl", "door.json")));
78
- } catch {
79
- throw new DoorUnavailable(NOT_RUNNING);
80
- }
81
- const file = parsed;
82
- if (typeof file?.url !== "string" || typeof file.secret !== "string") throw new DoorUnavailable(NOT_RUNNING);
83
- let url;
84
- try {
85
- url = new URL(file.url);
86
- } catch {
87
- throw new DoorUnavailable(NOT_RUNNING);
88
- }
89
- if (url.protocol !== "http:" || !LOOPBACK.has(url.hostname)) throw new DoorUnavailable(NOT_RUNNING);
90
- return {
91
- url: url.origin,
92
- secret: file.secret
93
- };
94
- }
95
- function fileDoor(fetchImpl = (input, init) => fetch(input, init), read = (path) => readFileSync(path, "utf8")) {
96
- const post = async (folder, path, body) => {
97
- const file = readDoorFile(folder, read);
98
- try {
99
- const answer = await (await fetchImpl(`${file.url}${path}`, {
100
- method: "POST",
101
- headers: {
102
- authorization: `Bearer ${file.secret}`,
103
- "content-type": "application/json"
104
- },
105
- body: JSON.stringify(body),
106
- signal: AbortSignal.timeout(TIMEOUT_MS$1)
107
- })).json();
108
- if (answer === null || typeof answer !== "object") throw new DoorUnavailable("the app answered with nothing readable");
109
- return answer;
110
- } catch (cause) {
111
- if (cause instanceof DoorUnavailable) throw cause;
112
- throw new DoorUnavailable(NOT_RUNNING);
113
- }
114
- };
115
- return {
116
- call: (folder, verb, args) => post(folder, "/api/acryl-door/call", {
117
- verb,
118
- args
119
- }),
120
- confirmPublish: (folder, body) => post(folder, "/api/acryl-door/publish-confirmed", body)
121
- };
122
- }
123
- //#endregion
124
- //#region src/registry.ts
125
- /** The public Blend registry as the screen's store lists it: only reads (the same index `acryl new --from` and the terminal's "Install a Blend" use). */
126
- const REGISTRY_INDEX = "https://acrylblends.github.io/registry/index.json";
127
- /** Blends released by people outside the ACRYL project and found on GitHub by the registry's hourly sync (origin `community`, each with its `source`). */
128
- const REGISTRY_DISCOVERED = "https://acrylblends.github.io/registry/discovered.json";
129
- const TIMEOUT_MS = 1e4;
130
- var RegistryUnavailable = class extends Error {};
131
- const record$1 = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
132
- const text$2 = (value) => typeof value === "string" ? value : "";
133
- /** The `entries` of one registry list; `RegistryUnavailable` in words a person can act on. */
134
- async function entriesOf(fetchImpl, url) {
135
- let body;
136
- try {
137
- const response = await fetchImpl(url, { signal: AbortSignal.timeout(TIMEOUT_MS) });
138
- if (!response.ok) throw new RegistryUnavailable(`The registry answered HTTP ${String(response.status)}.`);
139
- body = await response.json();
140
- } catch (cause) {
141
- if (cause instanceof RegistryUnavailable) throw cause;
142
- throw new RegistryUnavailable("The registry could not be read. Check the network and try again.");
143
- }
144
- const entries = record$1(body)?.entries;
145
- if (!Array.isArray(entries)) throw new RegistryUnavailable("The registry answered, but its list could not be read.");
146
- return entries;
147
- }
148
- /**
149
- * The Blends an ACRYL app can be made from (registry entries whose runtime is `acrylblends`), by name: the public registry's, and the community ones
150
- * the registry found on GitHub (made from their `source`). The community list is optional: when it cannot be read, the store still lists the rest.
151
- */
152
- async function readBlends(fetchImpl = (input, init) => fetch(input, init), url = REGISTRY_INDEX, discovered = REGISTRY_DISCOVERED) {
153
- const blends = [];
154
- const ids = /* @__PURE__ */ new Set();
155
- for (const raw of await entriesOf(fetchImpl, url)) {
156
- const entry = record$1(raw);
157
- if (entry === void 0 || entry.runtime !== "acrylblends" || typeof entry.id !== "string" || entry.id === "") continue;
158
- ids.add(entry.id);
159
- blends.push({
160
- id: entry.id,
161
- name: text$2(entry.name) || entry.id,
162
- version: text$2(entry.version),
163
- category: text$2(entry.category),
164
- description: text$2(entry.description),
165
- origin: entry.origin === "official" ? "official" : "community"
166
- });
167
- }
168
- const community = discovered === void 0 ? [] : await entriesOf(fetchImpl, discovered).catch(() => []);
169
- for (const raw of community) {
170
- const entry = record$1(raw);
171
- if (entry === void 0 || entry.runtime !== "acrylblends" || typeof entry.id !== "string" || entry.id === "" || ids.has(entry.id)) continue;
172
- const source = text$2(entry.source);
173
- if (!BLEND_SOURCE.test(source)) continue;
174
- ids.add(entry.id);
175
- const placement = record$1(entry.placement);
176
- const category = text$2(placement?.category) === "" ? text$2(entry.category) : [text$2(placement?.category), text$2(placement?.subcategory)].filter(Boolean).join(" › ");
177
- const publisher = text$2(entry.publisher);
178
- blends.push({
179
- id: entry.id,
180
- name: text$2(entry.name) || entry.id,
181
- version: text$2(entry.version),
182
- category,
183
- description: text$2(entry.description),
184
- origin: "community",
185
- source,
186
- ...publisher === "" ? {} : { publisher }
187
- });
188
- }
189
- return blends.sort((a, b) => a.name.localeCompare(b.name));
190
- }
191
- //#endregion
192
6
  //#region src/tools.ts
193
7
  const LAUNCHER_HELP = `The ACRYL launcher is the first screen of ACRYL (Web and Desktop). Where things are:
194
8
  - My apps (left nav): every app made with ACRYL on this machine, as cards with a state (running, stopped), a surface (Web = served at an address, Desktop = a window of its own) and a Blend name. Select a card for its panel: Start or Stop, Open, Remove from list, its folder, and, while it runs, its Plugins.
@@ -434,794 +248,6 @@ function registerLauncherTools(ctx, service) {
434
248
  };
435
249
  }
436
250
  //#endregion
437
- //#region src/runner.ts
438
- /**
439
- * The one place this plugin starts processes. A `Runner` hands back a `Run` the service watches; the real one spawns the command through the
440
- * machine's own Node and npm (the desktop app carries no Node of its own yet, spec 050 T005) and stops a whole tree, not only its first process
441
- * (`npm run dev` starts a server below npm).
442
- */
443
- /** Keys the desktop app set for itself; a started app must choose its own (a shared one would put the new app in this app's home and port). */
444
- const OWN_KEYS = /^(ACRYL_|ACRYLBLENDS_|DSH_|ELECTRON_|npm_|PORT$|WATCH_REPORT_DEPENDENCIES$)/u;
445
- /** The environment a started app gets: this process's, without the keys above, plus the places Node usually lives (a Dock launch has a short PATH). */
446
- function appEnvironment(base, platform = process.platform) {
447
- const env = {};
448
- for (const [key, value] of Object.entries(base)) if (!OWN_KEYS.test(key)) env[key] = value;
449
- if (platform !== "win32") {
450
- const extra = ["/opt/homebrew/bin", "/usr/local/bin"];
451
- const have = (env.PATH ?? "").split(":");
452
- env.PATH = [...have, ...extra.filter((dir) => !have.includes(dir))].filter((dir) => dir !== "").join(":");
453
- }
454
- return env;
455
- }
456
- /**
457
- * What a child of the Electron main process inherits. On Linux Chromium opens its DevTools port (`--remote-debugging-port`), its sockets and its files without
458
- * close-on-exec and Node's spawn passes every one on, so an app started from here kept the port bound after this app quit. macOS closes all but the standard streams
459
- * when it starts a process, and Windows does not inherit a socket, so only Linux needs it. bash's `exec 12>&-` closes a descriptor of any number (dash takes one
460
- * digit); the command then replaces bash, so the process id and group stay the child's. The same text is in plugins/desktop-shell/inherited.ts; keep them equal.
461
- */
462
- const CLOSE_AND_RUN = "for f in /proc/self/fd/*; do n=${f##*/}; if [ \"$n\" -gt 2 ]; then eval \"exec $n>&-\"; fi; done; exec \"$@\"";
463
- const BASH = "/bin/bash";
464
- /** The program and arguments to spawn so the child holds no descriptor above 2: the command itself where that is already so, or where bash is not there. */
465
- function withoutInheritedDescriptors(program, args, platform = process.platform, hasBash = existsSync(BASH)) {
466
- if (platform !== "linux" || !hasBash) return {
467
- program,
468
- args
469
- };
470
- return {
471
- program: BASH,
472
- args: [
473
- "-c",
474
- CLOSE_AND_RUN,
475
- "acryl-spawn",
476
- program,
477
- ...args
478
- ]
479
- };
480
- }
481
- /** Stop a command and everything it started: a process group on Unix, `taskkill /t` on Windows. */
482
- function stopTree(pid, platform) {
483
- try {
484
- if (platform === "win32") spawnSync("taskkill", [
485
- "/pid",
486
- String(pid),
487
- "/t",
488
- "/f"
489
- ], { windowsHide: true });
490
- else process.kill(-pid, "SIGTERM");
491
- } catch {}
492
- }
493
- const spawnRunner = (command) => {
494
- const win = process.platform === "win32";
495
- const start = win ? {
496
- program: command.program,
497
- args: command.args
498
- } : withoutInheritedDescriptors(command.program, command.args);
499
- const child = spawn(start.program, [...start.args], {
500
- cwd: command.cwd,
501
- env: command.env,
502
- shell: win,
503
- detached: !win,
504
- windowsHide: true,
505
- stdio: [
506
- "ignore",
507
- "pipe",
508
- "pipe"
509
- ]
510
- });
511
- const outputs = [];
512
- const ends = [];
513
- let ended = false;
514
- const finish = (end) => {
515
- if (ended) return;
516
- ended = true;
517
- for (const listener of ends) listener(end);
518
- };
519
- for (const stream of [child.stdout, child.stderr]) stream.on("data", (chunk) => {
520
- for (const listener of outputs) listener(chunk.toString("utf8"));
521
- });
522
- child.on("error", (cause) => {
523
- finish({
524
- code: null,
525
- notFound: cause.code === "ENOENT",
526
- error: cause.message
527
- });
528
- });
529
- child.on("close", (code) => {
530
- finish({
531
- code,
532
- notFound: code === 127
533
- });
534
- });
535
- return {
536
- onOutput: (listener) => {
537
- outputs.push(listener);
538
- },
539
- onEnd: (listener) => {
540
- ends.push(listener);
541
- },
542
- stop: () => {
543
- if (!ended && child.pid !== void 0) stopTree(child.pid, process.platform);
544
- }
545
- };
546
- };
547
- //#endregion
548
- //#region src/service.ts
549
- /**
550
- * What the ACRYL screen does, as one service with ports (Clean Architecture: the routes and the Cordis plugin are the edge; this holds the rules).
551
- * The list is the registry `<home>/apps.json` (`acryl-launcher`, the same file `acryl apps` and the terminal read); what runs is held here, in
552
- * memory, because the launcher records no port: an app is "running" when this service started it and it has not ended.
553
- */
554
- /** A request the service cannot honour, in a sentence a person can act on. The route answers it as 409. */
555
- var LauncherRefusal = class extends Error {};
556
- /** The address an app prints, with the token it needs: `http://127.0.0.1:3999/?token=...`. */
557
- const ADDRESS = /https?:\/\/(?:127\.0\.0\.1|localhost|\[::1\]):\d+[^\s'")\]]*/u;
558
- const BLENDS_FRESH_MS = 6e4;
559
- /** The package `acryl new` runs (`distribution/acryl-npm-launcher/forward.js` CREATE_SPEC). */
560
- const CREATE_SPEC = "create-acrylblends@latest";
561
- /** The command that updates an app from its Blend's newer release (`acrylblends update`, in the acrylblends package). */
562
- const UPDATE_SPEC = "acrylblends@latest";
563
- /** The app's own share command, from its folder (the `save` plugin of acrylblends). */
564
- const SHARE_COMMAND = join("plugins", "save", "share-cli.ts");
565
- /** ACRYL ADE: the Blend and the folder in the home that `acryl ade` makes and opens (`distribution/acryl-npm-launcher/managed.js` MANAGED.ade). */
566
- const ADE_BLEND = "acryl.ade";
567
- const ADE_FOLDER = "ade";
568
- const ANSI = /\u001b\[[0-9;?]*[ -/]*[@-~]/gu;
569
- const tail = (text) => {
570
- const lines = text.replace(ANSI, "").split(/\r?\n/u).map((line) => line.trim()).filter((line) => line !== "").slice(-12).join("\n");
571
- return lines !== "" && /\n\s*$/u.test(text) ? `${lines}\n` : lines;
572
- };
573
- var LauncherService = class {
574
- #ports;
575
- #started = /* @__PURE__ */ new Map();
576
- /** Why an app last ended without being stopped, until it is started again. */
577
- #failures = /* @__PURE__ */ new Map();
578
- #job;
579
- #blends;
580
- #signIn;
581
- /** Apps just made whose `npm install` is running (`#install`), by id. */
582
- #installing = /* @__PURE__ */ new Map();
583
- /** The tools apps need: being fetched (the first start on a computer without them), ready, or not had (apps then try the computer's own). */
584
- #tools = { state: "ready" };
585
- constructor(ports) {
586
- this.#ports = ports;
587
- }
588
- /** Start fetching what this computer lacks of Node.js and gh; apps wait for it (`#toolsReady`). Called once, when the launcher starts. */
589
- prepareTools() {
590
- const prepare = this.#ports.prepareTools;
591
- if (prepare === void 0) return Promise.resolve();
592
- this.#tools = { state: "preparing" };
593
- return prepare().then(() => {
594
- this.#tools = { state: "ready" };
595
- }, (cause) => {
596
- this.#tools = {
597
- state: "failed",
598
- reason: cause instanceof Error ? cause.message : String(cause)
599
- };
600
- });
601
- }
602
- /** Refuse, in words, to start anything while the tools are still being fetched; a failed fetch lets apps try the computer's own tools. */
603
- #toolsReady() {
604
- if (this.#tools.state === "preparing") throw new LauncherRefusal("Getting Node.js and GitHub's tool ready for your apps (only on the first start on this computer, about a minute). Try again in a moment.");
605
- }
606
- state() {
607
- if (this.#blends === void 0 || Date.now() - this.#blends.at >= BLENDS_FRESH_MS) this.blends().catch(() => void 0);
608
- const apps = readApps(this.#ports.home).map((entry) => this.#view(entry));
609
- const at = this.#job;
610
- const job = at === void 0 ? null : {
611
- name: at.name,
612
- kind: at.kind,
613
- line: at.line,
614
- status: at.status,
615
- step: at.step,
616
- since: at.since,
617
- output: at.output.trimEnd(),
618
- ...at.message === void 0 ? {} : { message: at.message }
619
- };
620
- return {
621
- apps,
622
- appsFolder: this.#ports.appsFolder,
623
- starters: STARTERS,
624
- job
625
- };
626
- }
627
- #view(entry) {
628
- const started = this.#started.get(entry.id);
629
- const missing = inspectApp(entry).state === "missing";
630
- const installing = this.#installing.get(entry.id);
631
- const state = missing ? "missing" : started === void 0 ? installing !== void 0 ? "starting" : "stopped" : started.address === void 0 ? "starting" : "running";
632
- const failure = this.#failures.get(entry.id);
633
- const blend = entry.blend === "" ? blendOf(entry.path) : entry.blend;
634
- const version = missing ? "" : blendVersionOf(entry.path);
635
- const latest = this.#blends?.list.find((listed) => listed.id === blend)?.version;
636
- const github = missing ? void 0 : githubOf(entry.path);
637
- return {
638
- id: entry.id,
639
- name: basename(entry.path),
640
- path: entry.path,
641
- blend,
642
- madeBy: entry.madeBy,
643
- surface: entry.surface,
644
- state,
645
- ...version === "" ? {} : { version },
646
- ...version !== "" && latest !== void 0 && newerVersion(latest, version) ? { update: latest } : {},
647
- ...started?.address === void 0 ? {} : { address: started.address },
648
- ...started === void 0 || started.address !== void 0 || started.output === "" ? {} : { output: started.output.trimEnd() },
649
- ...started === void 0 && installing !== void 0 && installing.output !== "" ? { output: installing.output.trimEnd() } : {},
650
- ...failure === void 0 || state !== "stopped" ? {} : { failure },
651
- ...github === void 0 ? {} : { github }
652
- };
653
- }
654
- add(path) {
655
- try {
656
- return this.#view(addApp(this.#ports.home, { path }).entry);
657
- } catch (cause) {
658
- throw new LauncherRefusal(cause instanceof Error ? cause.message : String(cause));
659
- }
660
- }
661
- remove(id) {
662
- this.stop(id);
663
- if (!removeApp(this.#ports.home, id)) throw new LauncherRefusal(`there is no app "${id}" in the list`);
664
- }
665
- /**
666
- * Start an app the way the terminal's "Open an app" does, with the saved model key: a Web app with `npm run dev` in its folder (its address opens in the
667
- * browser), a Desktop app with `npm run desktop`, which starts the same app and opens it in its own window (Electron is fetched the first time).
668
- */
669
- start(id, surface) {
670
- this.#toolsReady();
671
- const entry = readApps(this.#ports.home).find((app) => app.id === id);
672
- if (entry === void 0) throw new LauncherRefusal(`there is no app "${id}" in the list`);
673
- if (inspectApp(entry).state === "missing") throw new LauncherRefusal(`the folder ${entry.path} is gone: remove it from the list, or put it back`);
674
- if (this.#started.has(id)) return;
675
- this.#failures.delete(id);
676
- if (!this.#ports.exists(join(entry.path, "node_modules"))) {
677
- this.#installThenStart(id, entry.path, surface);
678
- return;
679
- }
680
- const run = this.#ports.runner({
681
- program: "npm",
682
- args: ["run", (surface ?? entry.surface) === "desktop" ? "desktop" : "dev"],
683
- cwd: entry.path,
684
- env: this.#environment()
685
- });
686
- this.#watch(id, run, void 0);
687
- }
688
- #installThenStart(id, folder, surface) {
689
- const run = this.#ports.runner({
690
- program: "npm",
691
- args: [
692
- "install",
693
- "--loglevel",
694
- "http"
695
- ],
696
- cwd: folder,
697
- env: this.#environment()
698
- });
699
- const started = {
700
- run,
701
- address: void 0,
702
- output: ""
703
- };
704
- this.#started.set(id, started);
705
- run.onOutput((text) => {
706
- started.output = tail(`${started.output}${text}`);
707
- });
708
- run.onEnd((end) => {
709
- if (this.#started.get(id) !== started) return;
710
- this.#started.delete(id);
711
- if (end.notFound) this.#failures.set(id, "Node.js and npm were not found on this machine. Install Node.js 22.19 or later from nodejs.org, then try again.");
712
- else if (end.code === 0) try {
713
- this.start(id, surface);
714
- } catch (cause) {
715
- this.#failures.set(id, cause instanceof Error ? cause.message : String(cause));
716
- }
717
- else if (end.code !== null) this.#failures.set(id, started.output === "" ? end.error ?? "npm install ended before the app could run." : started.output.trimEnd());
718
- });
719
- }
720
- /**
721
- * ACRYL ADE, the way `acryl ade` (`--gui`) opens it: the Blend `acryl.ade` in `<home>/ade`, made from the registry the first time (listed, installed and
722
- * started as any app made here is), then started in a window or the browser. Already running, it is left as it is.
723
- */
724
- openAde(surface) {
725
- const folder = join(this.#ports.home, ADE_FOLDER);
726
- if (!this.#ports.exists(join(folder, APP_MARKER))) {
727
- this.create({
728
- name: ADE_FOLDER,
729
- where: this.#ports.home,
730
- blend: ADE_BLEND,
731
- surface
732
- });
733
- return;
734
- }
735
- this.start(addApp(this.#ports.home, {
736
- path: folder,
737
- surface
738
- }).entry.id, surface);
739
- }
740
- stop(id) {
741
- this.#started.get(id)?.run.stop();
742
- }
743
- /**
744
- * Bring the newer registry release of the app's Blend into it: `acrylblends update` in its folder (a git merge that keeps the person's changes, then npm
745
- * install). A running app is stopped first and started again after.
746
- */
747
- update(id) {
748
- this.#toolsReady();
749
- if (this.#job?.status === "running") throw new LauncherRefusal(`${this.#job.name} is still being worked on: wait for it to finish`);
750
- const entry = readApps(this.#ports.home).find((app) => app.id === id);
751
- if (entry === void 0) throw new LauncherRefusal(`there is no app "${id}" in the list`);
752
- const view = this.#view(entry);
753
- if (view.update === void 0) throw new LauncherRefusal(`${view.name} is on the latest release of ${view.blend}`);
754
- const restart = this.#started.has(id);
755
- this.stop(id);
756
- const run = this.#ports.runner({
757
- program: "npm",
758
- args: [
759
- "exec",
760
- "--yes",
761
- UPDATE_SPEC,
762
- "--",
763
- "update"
764
- ],
765
- cwd: entry.path,
766
- env: this.#environment()
767
- });
768
- const job = {
769
- name: view.name,
770
- kind: "update",
771
- line: `cd ${entry.path} && npx ${UPDATE_SPEC} update`,
772
- status: "running",
773
- run,
774
- since: Date.now(),
775
- output: "",
776
- step: `Updating ${view.name} from ${view.blend} ${view.version ?? ""} to ${view.update}: getting the release and merging it in, your changes are kept, then npm install. Next: ${restart ? "starting it again" : "done"}.`
777
- };
778
- this.#job = job;
779
- let output = "";
780
- run.onOutput((text) => {
781
- output = tail(`${output}${text}`);
782
- job.output = output;
783
- });
784
- run.onEnd((end) => {
785
- if (job.run !== run) return;
786
- if (end.notFound) {
787
- job.status = "failed";
788
- job.message = "Node.js and npm were not found on this machine. Install Node.js 22.19 or later from nodejs.org, then try again.";
789
- return;
790
- }
791
- if (end.code !== 0) {
792
- job.status = "failed";
793
- job.message = output === "" ? end.error ?? "The update ended before it was done; the app is unchanged." : output.trimEnd();
794
- return;
795
- }
796
- job.status = "done";
797
- job.step = `Updated ${view.name} to ${view.blend} ${view.update}.${restart ? " Starting it again: its progress shows on its card below." : ""}`;
798
- job.output = "";
799
- if (restart) try {
800
- this.start(id);
801
- } catch (cause) {
802
- this.#failures.set(id, cause instanceof Error ? cause.message : String(cause));
803
- }
804
- });
805
- }
806
- stopAll() {
807
- for (const started of this.#started.values()) started.run.stop();
808
- this.#job?.run.stop();
809
- }
810
- /**
811
- * Make an app: the same `acryl new <name> <starter>` the terminal runs, in the folder the person chose. `acryl new` goes on to install and start the app,
812
- * so the process it began is the app's running process: when its blend.yaml appears the app is listed and that process is adopted as the app's.
813
- */
814
- create(request) {
815
- this.#toolsReady();
816
- if (this.#job?.status === "running") throw new LauncherRefusal(`${this.#job.name} is still being made: wait for it to finish`);
817
- const problem = whereProblem(request.where) ?? (APP_NAME.test(request.name) ? void 0 : appNameProblem(request.name, this.#ports));
818
- if (problem !== void 0) throw new LauncherRefusal(problem);
819
- if (request.starter === void 0 === (request.blend === void 0)) throw new LauncherRefusal("choose a starter or a Blend, not both");
820
- if (request.starter !== void 0 && !STARTERS.some((starter) => starter.value === request.starter)) throw new LauncherRefusal(`there is no starter "${request.starter}"`);
821
- if (request.blend !== void 0 && !BLEND_ID.test(request.blend) && !BLEND_SOURCE.test(request.blend)) throw new LauncherRefusal(`"${request.blend}" is not a Blend id (for example acrylblends.notes) or a Blend on GitHub (github:owner/repo#tag)`);
822
- if (!MAKEABLE_SURFACES.includes(request.surface)) throw new LauncherRefusal("CLI (TUI) apps are coming: choose Web or Desktop");
823
- const folder = join(request.where, request.name);
824
- if (this.#ports.exists(folder)) throw new LauncherRefusal(`there is already a folder named ${request.name} in ${request.where}`);
825
- this.#ports.makeFolder(request.where);
826
- const source = request.blend === void 0 ? [request.starter ?? ""] : ["--from", request.blend];
827
- const args = [
828
- "exec",
829
- "--yes",
830
- CREATE_SPEC,
831
- "--",
832
- request.name,
833
- ...source
834
- ];
835
- const line = `cd ${request.where} && acryl new ${request.name} ${source.join(" ")}`;
836
- const run = this.#ports.runner({
837
- program: "npm",
838
- args,
839
- cwd: request.where,
840
- env: {
841
- ...this.#environment(),
842
- npm_config_loglevel: "http"
843
- }
844
- });
845
- const step = request.blend === void 0 ? `Step 1 of 2: getting ${request.name} and installing its dependencies (${CREATE_SPEC}, about a minute). Next: starting it.` : `Step 1 of 3: getting ${request.name} (${CREATE_SPEC}). Next: installing its dependencies, then starting it.`;
846
- const job = {
847
- name: request.name,
848
- kind: "make",
849
- line,
850
- status: "running",
851
- run,
852
- step,
853
- since: Date.now(),
854
- output: ""
855
- };
856
- this.#job = job;
857
- this.#watch(void 0, run, {
858
- folder,
859
- surface: request.surface,
860
- job
861
- });
862
- }
863
- /** The registry's Blends, read again at most once a minute: the store is opened and closed often, and the registry is a public file. */
864
- async blends() {
865
- if (this.#blends !== void 0 && Date.now() - this.#blends.at < BLENDS_FRESH_MS) return this.#blends.list;
866
- const list = await this.#ports.blends();
867
- this.#blends = {
868
- at: Date.now(),
869
- list
870
- };
871
- return list;
872
- }
873
- /** The apps folder, made when it is not there yet: the assistant's agent works in it, and a folder that does not exist cannot be worked in. */
874
- assistantFolder() {
875
- this.#ports.makeFolder(this.#ports.appsFolder);
876
- return this.#ports.appsFolder;
877
- }
878
- #entry(id) {
879
- const entry = readApps(this.#ports.home).find((app) => app.id === id);
880
- if (entry === void 0) throw new LauncherRefusal(`there is no app "${id}" in the list`);
881
- return entry;
882
- }
883
- /** A door call, with "the app is not running" and a refusal as the sentence a person can act on. */
884
- async #door(id, run) {
885
- const entry = this.#entry(id);
886
- let answer;
887
- try {
888
- answer = await run(this.#ports.door, entry.path);
889
- } catch (cause) {
890
- if (cause instanceof DoorUnavailable) throw new LauncherRefusal(cause.message);
891
- throw cause;
892
- }
893
- if (!answer.ok) throw new LauncherRefusal(answer.message ?? "the app refused");
894
- return answer;
895
- }
896
- /** The plugins of a running app: the ones its people made (shareable) and the ones pulled from a registry. */
897
- async plugins(id) {
898
- let answer;
899
- try {
900
- answer = await this.#door(id, (door, folder) => door.call(folder, "plugin-list", {}));
901
- } catch (cause) {
902
- if (cause instanceof LauncherRefusal && /no extensions plugin to drive/u.test(cause.message)) throw new LauncherRefusal("This app keeps its plugins in its own page: open it, then Settings > Plugins. Pulling a plugin from here needs an app made with a newer Blueprint.");
903
- throw cause;
904
- }
905
- return (Array.isArray(answer.value) ? answer.value : []).filter((plugin) => typeof plugin.name === "string").map((plugin) => ({
906
- name: String(plugin.name),
907
- version: typeof plugin.version === "string" ? plugin.version : "",
908
- state: typeof plugin.state === "string" ? plugin.state : "",
909
- ...typeof plugin.pulledFrom === "string" ? { pulledFrom: plugin.pulledFrom } : {},
910
- ...typeof plugin.author === "string" ? { author: plugin.author } : {}
911
- }));
912
- }
913
- /** Pull a plugin into a running app from a registry source (`github:owner/repo@version`), the way `acryl plugin pull` does. */
914
- async pullPlugin(id, source) {
915
- if (source.trim() === "" || source.startsWith("-") || source.length > 1024) throw new LauncherRefusal("say where the plugin is, for example github:someone/pomodoro@0.1.0");
916
- return {
917
- text: (await this.#door(id, (door, folder) => door.call(folder, "plugin-pull", { source: source.trim() }))).text ?? "Pulled.",
918
- plugins: await this.plugins(id)
919
- };
920
- }
921
- #checkPublish(request) {
922
- if (!PLUGIN_NAME.test(request.plugin)) throw new LauncherRefusal(`"${request.plugin}" is not a plugin name`);
923
- if (request.owner !== void 0 && !ACCOUNT_NAME.test(request.owner)) throw new LauncherRefusal(`"${request.owner}" is not a GitHub account name`);
924
- if (request.license !== void 0 && !LICENSE_ID.test(request.license)) throw new LauncherRefusal(`"${request.license}" is not a license id`);
925
- }
926
- #options(request) {
927
- return {
928
- ...request.owner === void 0 ? {} : { owner: request.owner },
929
- ...request.license === void 0 ? {} : { license: request.license }
930
- };
931
- }
932
- /** What publishing a plugin would send (the account, repository, version, license and files). Sends nothing. */
933
- async publishPlan(request) {
934
- this.#checkPublish(request);
935
- const plan = (await this.#door(request.id, (door, folder) => door.call(folder, "plugin-publish", {
936
- name: request.plugin,
937
- ...this.#options(request)
938
- }))).value;
939
- if (plan === null || typeof plan !== "object" || typeof plan.owner !== "string" || typeof plan.repo !== "string" || typeof plan.version !== "string") throw new LauncherRefusal("the app did not give a publish plan");
940
- return {
941
- owner: plan.owner,
942
- repo: plan.repo,
943
- version: plan.version,
944
- visibility: String(plan.visibility ?? ""),
945
- license: String(plan.license ?? ""),
946
- createsRepository: plan.createsRepository === true,
947
- files: Array.isArray(plan.files) ? plan.files.map(String) : [],
948
- integrity: String(plan.integrity ?? ""),
949
- digest: String(plan.digest ?? ""),
950
- pullLine: String(plan.pullLine ?? "")
951
- };
952
- }
953
- /** The person's yes: publish exactly the plan they read. The app sends it only if the plugin still matches that plan. */
954
- async publish(request) {
955
- this.#checkPublish(request);
956
- const result = (await this.#door(request.id, (door, folder) => door.confirmPublish(folder, {
957
- name: request.plugin,
958
- ...this.#options(request),
959
- confirm: request.plan
960
- }))).value;
961
- if (result?.ok !== true) throw new LauncherRefusal(`Not published: ${result?.reason ?? "the app did not answer"}${result?.next === void 0 ? "" : `. ${result.next}`}`);
962
- return {
963
- releaseUrl: result.releaseUrl ?? "",
964
- pullLine: result.pullLine ?? ""
965
- };
966
- }
967
- /**
968
- * The app's own share command (`plugins/save/share-cli.ts`, acrylblends 1.5.5), run in its folder: it prints one JSON line, the plan or the result.
969
- * The app need not be running. An app made before that command has none, and is told how to get it.
970
- */
971
- async #shareCommand(request, confirm) {
972
- this.#toolsReady();
973
- const entry = this.#entry(request.id);
974
- if (request.owner !== void 0 && !ACCOUNT_NAME.test(request.owner)) throw new LauncherRefusal(`"${request.owner}" is not a GitHub account name`);
975
- if (!this.#ports.exists(join(entry.path, SHARE_COMMAND))) throw new LauncherRefusal(`This app was made before apps could share themselves. In ${entry.path} run "npx acrylblends@latest upgrade", then try again.`);
976
- if (request.visibility !== void 0 && confirm === void 0) try {
977
- setBlendVisibility(entry.path, request.visibility);
978
- } catch (cause) {
979
- throw new LauncherRefusal(`Could not set who may see it: ${cause instanceof Error ? cause.message : String(cause)}`);
980
- }
981
- const args = [
982
- SHARE_COMMAND,
983
- "--json",
984
- ...request.owner === void 0 ? [] : ["--owner", request.owner],
985
- ...confirm === void 0 ? [] : ["--confirm", Buffer.from(JSON.stringify(confirm), "utf8").toString("base64url")]
986
- ];
987
- const run = this.#ports.runner({
988
- program: "node",
989
- args,
990
- cwd: entry.path,
991
- env: this.#environment()
992
- });
993
- let output = "";
994
- run.onOutput((text) => {
995
- output += text;
996
- });
997
- if ((await new Promise((resolve) => {
998
- run.onEnd(resolve);
999
- })).notFound) throw new LauncherRefusal("Node.js was not found on this machine. Install Node.js 22.19 or later from nodejs.org, then try again.");
1000
- const line = output.split(/\r?\n/u).map((text) => text.trim()).findLast((text) => text.startsWith("{"));
1001
- let answer;
1002
- try {
1003
- answer = line === void 0 ? void 0 : JSON.parse(line);
1004
- } catch {
1005
- answer = void 0;
1006
- }
1007
- if (answer === null || typeof answer !== "object") throw new LauncherRefusal(tail(output) === "" ? "the app did not answer" : tail(output));
1008
- const value = answer;
1009
- if (value.ok === false) throw new LauncherRefusal(`Not shared: ${typeof value.reason === "string" ? value.reason : "the app refused"}`);
1010
- return value;
1011
- }
1012
- /** What sharing the app would send: the repository (a new one, or the remote it has), its visibility and how many changed files are saved first. Sends nothing. */
1013
- async sharePlan(request) {
1014
- const plan = await this.#shareCommand(request, void 0);
1015
- if (typeof plan.repository !== "string" || typeof plan.create !== "boolean" || plan.visibility !== "private" && plan.visibility !== "public" || typeof plan.changes !== "number") throw new LauncherRefusal("the app did not give a share plan");
1016
- return {
1017
- repository: plan.repository,
1018
- create: plan.create,
1019
- visibility: plan.visibility,
1020
- changes: plan.changes
1021
- };
1022
- }
1023
- /** The person's yes: share exactly the plan they read. The app sends it only if it still matches that plan. */
1024
- async share(request) {
1025
- const result = await this.#shareCommand(request, request.plan);
1026
- if (result.ok !== true || typeof result.remote !== "string") throw new LauncherRefusal("Not shared: the app did not answer");
1027
- return {
1028
- remote: result.remote,
1029
- created: result.created === true
1030
- };
1031
- }
1032
- async health(probe = this.#ports.runner) {
1033
- const version = (program) => new Promise((resolve) => {
1034
- const run = probe({
1035
- program,
1036
- args: ["--version"],
1037
- cwd: this.#ports.home,
1038
- env: this.#environment()
1039
- });
1040
- let text = "";
1041
- run.onOutput((chunk) => {
1042
- text += chunk;
1043
- });
1044
- run.onEnd((end) => {
1045
- resolve(end.code === 0 && !end.notFound ? text.trim().split(/\s+/u)[0]?.replace(/^v/u, "") : void 0);
1046
- });
1047
- });
1048
- const [node, npm] = await Promise.all([version("node"), version("npm")]);
1049
- return {
1050
- ...node === void 0 ? {} : { node },
1051
- ...npm === void 0 ? {} : { npm },
1052
- modelKey: readModelKey(this.#ports.home) !== void 0,
1053
- home: this.#ports.home
1054
- };
1055
- }
1056
- /** The saved key, masked, for the screen's Settings and Health; never the key itself. */
1057
- maskedModelKey() {
1058
- const key = readModelKey(this.#ports.home);
1059
- return key === void 0 ? void 0 : maskKey(key);
1060
- }
1061
- #environment() {
1062
- const inherited = this.#ports.environment();
1063
- return appEnvironment(toolsEnv(this.#ports.home, {
1064
- ...inherited,
1065
- ...modelEnv(this.#ports.home, inherited),
1066
- ...githubEnv(this.#ports.home, inherited)
1067
- }));
1068
- }
1069
- /** Who is signed in to GitHub here (the token apps get as GH_TOKEN), never the token. */
1070
- github() {
1071
- return {
1072
- available: githubClientId(this.#ports.environment()) !== void 0,
1073
- login: readGithub(this.#ports.home)?.login ?? null
1074
- };
1075
- }
1076
- /** Start GitHub's device sign-in: the code for the person; the device code stays here until it is approved, refused or expires. */
1077
- async githubStart() {
1078
- const clientId = githubClientId(this.#ports.environment());
1079
- if (clientId === void 0) throw new LauncherRefusal("this build of Control Center has no GitHub app to sign in with");
1080
- try {
1081
- const started = await startGithubSignIn(clientId);
1082
- this.#signIn = {
1083
- clientId,
1084
- deviceCode: started.deviceCode,
1085
- until: Date.now() + started.expiresIn * 1e3
1086
- };
1087
- return {
1088
- userCode: started.userCode,
1089
- verificationUri: started.verificationUri,
1090
- interval: started.interval
1091
- };
1092
- } catch (cause) {
1093
- throw new LauncherRefusal(`GitHub sign-in could not start: ${cause instanceof Error ? cause.message : String(cause)}. Check the network and try again.`);
1094
- }
1095
- }
1096
- /** One poll of the sign-in under way: pending, connected (the token is saved and every app started from now on gets it), or failed. */
1097
- async githubPoll() {
1098
- const signIn = this.#signIn;
1099
- if (signIn === void 0) return {
1100
- state: "failed",
1101
- reason: "no GitHub sign-in is under way: start it again"
1102
- };
1103
- if (Date.now() > signIn.until) {
1104
- this.#signIn = void 0;
1105
- return {
1106
- state: "failed",
1107
- reason: "the code expired: start the sign-in again"
1108
- };
1109
- }
1110
- try {
1111
- const answer = await pollGithubSignIn(this.#ports.home, signIn.clientId, signIn.deviceCode);
1112
- if (answer.state !== "pending") this.#signIn = void 0;
1113
- return answer;
1114
- } catch {
1115
- return { state: "pending" };
1116
- }
1117
- }
1118
- /** Forget the GitHub connection on this machine. Apps started from now on no longer get the token. */
1119
- githubDisconnect() {
1120
- this.#signIn = void 0;
1121
- clearGithub(this.#ports.home);
1122
- return this.github();
1123
- }
1124
- /**
1125
- * Follow one process. For an app being started, `id` is known; for one being made it is not until the folder has its blend.yaml, which is when the app
1126
- * is listed and the process becomes that app's.
1127
- */
1128
- #watch(id, run, making) {
1129
- const started = {
1130
- run,
1131
- address: void 0,
1132
- output: ""
1133
- };
1134
- let appId = id;
1135
- if (appId !== void 0) this.#started.set(appId, started);
1136
- run.onOutput((text) => {
1137
- started.output = tail(`${started.output}${text}`);
1138
- if (making !== void 0 && making.job.run === run) making.job.output = started.output;
1139
- started.address ??= ADDRESS.exec(text)?.[0];
1140
- if (making !== void 0 && appId === void 0 && this.#ports.exists(join(making.folder, APP_MARKER))) {
1141
- appId = addApp(this.#ports.home, {
1142
- path: making.folder,
1143
- surface: making.surface
1144
- }).entry.id;
1145
- this.#started.set(appId, started);
1146
- }
1147
- if (making !== void 0 && started.address !== void 0 && making.job.status === "running") making.job.status = "done";
1148
- });
1149
- run.onEnd((end) => {
1150
- if (appId !== void 0 && this.#started.get(appId) === started) {
1151
- this.#started.delete(appId);
1152
- const closed = started.address !== void 0 && readApps(this.#ports.home).find((entry) => entry.id === appId)?.surface === "desktop";
1153
- if (end.code !== 0 && end.code !== null && !end.notFound && !closed) this.#failures.set(appId, started.output.trimEnd());
1154
- }
1155
- if (end.notFound) this.#note(making, "failed", "Node.js and npm were not found on this machine. Install Node.js 22.19 or later from nodejs.org, then try again.", id);
1156
- else if (making !== void 0 && making.job.status === "running") if (end.code === 0 && appId !== void 0) if (this.#ports.exists(join(making.folder, "node_modules"))) this.#finish(appId, making.job);
1157
- else this.#install(appId, making.folder, making.job);
1158
- else making.job.status = "failed";
1159
- if (making !== void 0 && making.job.status === "failed" && making.job.message === void 0) making.job.message = started.output === "" ? end.error ?? "The command ended before the app was made." : started.output.trimEnd();
1160
- });
1161
- }
1162
- /** The job's last step: the app is made, so it is started (a Desktop app opens its window). */
1163
- #finish(appId, job) {
1164
- job.status = "done";
1165
- job.step = `Made. Starting ${job.name} now: its progress shows on its card below.`;
1166
- job.output = "";
1167
- delete job.message;
1168
- try {
1169
- this.start(appId);
1170
- } catch (cause) {
1171
- this.#failures.set(appId, cause instanceof Error ? cause.message : String(cause));
1172
- }
1173
- }
1174
- /** `npm install` in the new app's folder, as the job's second step; the job is still running while it does, and says so. */
1175
- #install(appId, folder, job) {
1176
- this.#installing.set(appId, job);
1177
- job.step = "Step 2 of 3: installing its dependencies (npm install, about a minute). Next: starting it.";
1178
- job.output = "";
1179
- const run = this.#ports.runner({
1180
- program: "npm",
1181
- args: [
1182
- "install",
1183
- "--loglevel",
1184
- "http"
1185
- ],
1186
- cwd: folder,
1187
- env: this.#environment()
1188
- });
1189
- job.run = run;
1190
- let output = "";
1191
- run.onOutput((text) => {
1192
- output = tail(`${output}${text}`);
1193
- job.output = output;
1194
- });
1195
- run.onEnd((end) => {
1196
- this.#installing.delete(appId);
1197
- if (job.run !== run) return;
1198
- if (end.notFound) {
1199
- job.status = "failed";
1200
- job.message = "Node.js and npm were not found on this machine. Install Node.js 22.19 or later from nodejs.org, then try again.";
1201
- } else if (end.code === 0) this.#finish(appId, job);
1202
- else {
1203
- job.status = "failed";
1204
- job.message = output === "" ? end.error ?? "npm install ended before the app could run." : output.trimEnd();
1205
- }
1206
- });
1207
- }
1208
- #note(making, status, message, id) {
1209
- if (making !== void 0) {
1210
- making.job.status = status;
1211
- making.job.message = message;
1212
- } else if (id !== void 0) this.#failures.set(id, message);
1213
- }
1214
- };
1215
- /** `0.2.0` is newer than `0.1.9`; anything that is not three numbers is never newer. */
1216
- function newerVersion(candidate, current) {
1217
- const parse = (text) => /^(\d+)\.(\d+)\.(\d+)$/u.exec(text)?.slice(1).map(Number);
1218
- const a = parse(candidate);
1219
- const b = parse(current);
1220
- if (a === void 0 || b === void 0) return false;
1221
- for (let index = 0; index < 3; index += 1) if (a[index] !== b[index]) return (a[index] ?? 0) > (b[index] ?? 0);
1222
- return false;
1223
- }
1224
- //#endregion
1225
251
  //#region src/route.ts
1226
252
  /** Strict same-origin loopback routes for the ACRYL screen. Reads need the app's own page; a change needs the exact `Origin` and a small JSON body. */
1227
253
  const MAX_FIELD = 1024;
@@ -1451,11 +477,6 @@ function launcherRoutes(service, report = () => {}) {
1451
477
  }
1452
478
  //#endregion
1453
479
  //#region src/index.ts
1454
- /**
1455
- * Cordis Host plugin: the routes behind the ACRYL screen, the first screen of the desktop app (spec 050 T012). It lists the apps in the ACRYL home's
1456
- * `apps.json`, adds, removes, makes, starts and stops them, and stops everything it started when it unloads.
1457
- * Capability boundary: the list and what runs on this machine (one service, `LauncherService`); the drawing is the Client half.
1458
- */
1459
480
  const name = "acryl-launcher-desktop";
1460
481
  const inject = [
1461
482
  "router",
@@ -1463,26 +484,14 @@ const inject = [
1463
484
  "appInstance"
1464
485
  ];
1465
486
  function apply(ctx) {
1466
- const home = ctx.appInstance.home;
1467
- const service = new LauncherService({
1468
- home,
1469
- appsFolder: join(dirname(home), "ACRYL"),
1470
- runner: spawnRunner,
1471
- environment: () => process.env,
1472
- exists: (path) => existsSync(path),
1473
- makeFolder: (path) => {
1474
- mkdirSync(path, { recursive: true });
1475
- },
1476
- blends: () => readBlends(),
1477
- door: fileDoor(),
1478
- prepareTools: () => prepareTools(home, process.env)
1479
- });
487
+ const service = createNodeLauncher(ctx.appInstance.home);
1480
488
  service.prepareTools();
1481
489
  const report = (operation, cause) => {
1482
490
  ctx.logger.error(`@acryldev/launcher-desktop: failed to ${operation}: ${cause instanceof Error ? cause.message : String(cause)}`);
1483
491
  };
1484
492
  ctx.effect(() => () => {
1485
- service.stopAll();
493
+ const kept = service.stopAll();
494
+ if (kept.length > 0) ctx.logger.info(`left open (a Desktop app with its window up; closing the window stops it): ${kept.join(", ")}`);
1486
495
  }, "@acryldev/launcher-desktop: apps it started");
1487
496
  ctx.inject(["acrylTools"], (child) => {
1488
497
  child.effect(() => registerLauncherTools(child, service), "@acryldev/launcher-desktop: launcher tools");
@@ -1491,6 +500,6 @@ function apply(ctx) {
1491
500
  ctx.routerHttp.mount(LAUNCHER_API_PREFIX);
1492
501
  }
1493
502
  //#endregion
1494
- export { ACCOUNT_NAME, BLEND_ID, BLEND_SOURCE, LAUNCHER_ADD_PATH, LAUNCHER_ADE_PATH, LAUNCHER_API_PREFIX, LAUNCHER_ASSISTANT_FOLDER_PATH, LAUNCHER_BLENDS_PATH, LAUNCHER_GITHUB_DISCONNECT_PATH, LAUNCHER_GITHUB_PATH, LAUNCHER_GITHUB_POLL_PATH, LAUNCHER_GITHUB_START_PATH, LAUNCHER_HEALTH_PATH, LAUNCHER_NEW_PATH, LAUNCHER_PLUGINS_PATH, LAUNCHER_PLUGIN_PULL_PATH, LAUNCHER_PUBLISH_PATH, LAUNCHER_PUBLISH_PLAN_PATH, LAUNCHER_REMOVE_PATH, LAUNCHER_SHARE_PATH, LAUNCHER_SHARE_PLAN_PATH, LAUNCHER_START_PATH, LAUNCHER_STATE_PATH, LAUNCHER_STOP_PATH, LAUNCHER_UPDATE_PATH, LICENSE_ID, LauncherRefusal, LauncherService, MAKEABLE_SURFACES, PLUGIN_NAME, SURFACES, WEBBOXES_NEW_BOX, apply, inject, name, webboxesDeployUrl };
503
+ export { ACCOUNT_NAME, BLEND_ID, BLEND_SOURCE, LAUNCHER_ADD_PATH, LAUNCHER_ADE_PATH, LAUNCHER_API_PREFIX, LAUNCHER_ASSISTANT_FOLDER_PATH, LAUNCHER_BLENDS_PATH, LAUNCHER_GITHUB_DISCONNECT_PATH, LAUNCHER_GITHUB_PATH, LAUNCHER_GITHUB_POLL_PATH, LAUNCHER_GITHUB_START_PATH, LAUNCHER_HEALTH_PATH, LAUNCHER_NEW_PATH, LAUNCHER_PLUGINS_PATH, LAUNCHER_PLUGIN_PULL_PATH, LAUNCHER_PUBLISH_PATH, LAUNCHER_PUBLISH_PLAN_PATH, LAUNCHER_REMOVE_PATH, LAUNCHER_SHARE_PATH, LAUNCHER_SHARE_PLAN_PATH, LAUNCHER_START_PATH, LAUNCHER_STATE_PATH, LAUNCHER_STOP_PATH, LAUNCHER_UPDATE_PATH, LICENSE_ID, LauncherRefusal, LauncherService, MAKEABLE_SURFACES, PLUGIN_NAME, SURFACES, WEBBOXES_NEW_BOX, apply, inject, name, webboxesDeployBlendUrl, webboxesDeployUrl };
1495
504
 
1496
505
  //# sourceMappingURL=index.js.map