@monotykamary/dsh 0.1.0-rc.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,129 @@
1
+ import { t as INSTALL_ANCHOR } from "./profile-boot-CCBe1Ijy.js";
2
+ import { existsSync } from "node:fs";
3
+ import { DEFAULT_PROFILE_BUNDLES, PROFILE_TEMPLATES, initProfile, readProfileManifest, resolveBundleDir, resolveProfileDir, writeProfileManifest } from "@monotykamary/dsh-app-boot";
4
+ import { join, resolve } from "node:path";
5
+ import { spawnSync } from "node:child_process";
6
+ //#region lib/types/plugin.js
7
+ /**
8
+ * `dsh plugin --profile <name> <args...>` — profile plugin management as a
9
+ * thin pnpm forwarder: initialize the profile on first use, run
10
+ * `pnpm <args...>` in the profile directory, then reconcile the
11
+ * `dsh.profile.bundles` layer list against the installed state (a dependency
12
+ * resolving to a package that declares `dsh.bundle` joins the layer stack; a
13
+ * removed or bundle-less dependency leaves it). Reconciling by installed
14
+ * state, not by dependency diff, means `update` activates a package that
15
+ * gained its `dsh.bundle` declaration in a newer version.
16
+ * @module @monotykamary/dsh/plugin
17
+ */
18
+ const NAME = "dsh";
19
+ /**
20
+ * Whether a resolved dependency exports a profile patch, i.e. is a bundle.
21
+ * @param packageName - the dependency's package name.
22
+ * @param profileDir - the profile directory (resolution anchor).
23
+ * @returns true when the package manifest declares `dsh.bundle`.
24
+ */
25
+ function exportsPatch(packageName, profileDir) {
26
+ let dir;
27
+ try {
28
+ dir = resolveBundleDir(NAME, packageName, INSTALL_ANCHOR, profileDir);
29
+ } catch {
30
+ return false;
31
+ }
32
+ return readProfileManifest(NAME, dir).dsh?.bundle?.patch !== void 0;
33
+ }
34
+ /**
35
+ * Reconcile `dsh.profile.bundles` against the installed state: pnpm has
36
+ * already written the real installed names (so a git/path/tarball/alias spec
37
+ * on the command line reconciles by its true package name) and materialized
38
+ * the packages. A dependency that resolves to a `dsh.bundle`-declaring
39
+ * package joins the layer stack (appended in dependency order); a
40
+ * dependency-listed name that no longer does — removed, or the installed
41
+ * version dropped the declaration — leaves it. In-box bundles from the
42
+ * profile template are not dependencies and are never touched. Warns once
43
+ * per newly-added bundle-less dependency (a plain library is fine; the
44
+ * warning is orientation).
45
+ */
46
+ function reconcilePlugins(before, profileDir) {
47
+ const after = readProfileManifest(NAME, profileDir);
48
+ const beforeDeps = new Set(Object.keys(before.dependencies ?? {}));
49
+ const dependencies = Object.keys(after.dependencies ?? {});
50
+ const plugins = after.dsh?.profile?.bundles ?? [];
51
+ let changed = false;
52
+ for (const packageName of dependencies) {
53
+ const isBundle = exportsPatch(packageName, profileDir);
54
+ if (isBundle && !plugins.includes(packageName)) {
55
+ plugins.push(packageName);
56
+ changed = true;
57
+ } else if (!isBundle && !beforeDeps.has(packageName)) process.stderr.write(`${NAME}: warning: ${packageName} declares no dsh.bundle — installed as a plain dependency, not a profile layer (a later update that gains one activates it automatically)
58
+ `);
59
+ }
60
+ const dependencySet = new Set(dependencies);
61
+ for (const packageName of [...plugins]) {
62
+ const wasDependency = beforeDeps.has(packageName) || dependencySet.has(packageName);
63
+ const stillBundle = dependencySet.has(packageName) && exportsPatch(packageName, profileDir);
64
+ if (wasDependency && !stillBundle) {
65
+ plugins.splice(plugins.indexOf(packageName), 1);
66
+ changed = true;
67
+ }
68
+ }
69
+ if (!changed) return;
70
+ after.dsh = {
71
+ ...after.dsh,
72
+ profile: {
73
+ ...after.dsh?.profile,
74
+ bundles: plugins
75
+ }
76
+ };
77
+ writeProfileManifest(profileDir, after);
78
+ }
79
+ /**
80
+ * Rewrite relative filesystem specs against the user's invoking directory.
81
+ * pnpm runs with cwd = the profile directory, so a bare `.` or `../plugin`
82
+ * (or their `file:`/`link:` forms) would silently resolve inside the profile
83
+ * — `add .` from a plugin checkout would self-link the profile. Absolute
84
+ * specs, registry names, and every other pnpm argument pass through
85
+ * untouched.
86
+ * @param argument - one pnpm argument, verbatim from argv.
87
+ * @param cwd - the directory `dsh` was invoked from.
88
+ * @returns the argument with a relative path spec anchored to `cwd`.
89
+ */
90
+ function anchorPathSpec(argument, cwd) {
91
+ const match = /^(?<prefix>(?:file|link):)?(?<path>\.{1,2}(?:[/\\].*)?)$/.exec(argument);
92
+ if (match?.groups?.path === void 0) return argument;
93
+ return `${match.groups.prefix ?? ""}${resolve(cwd, match.groups.path)}`;
94
+ }
95
+ /**
96
+ * Run one `dsh plugin` invocation: init if needed, forward to pnpm, reconcile.
97
+ * @param profile - the profile name.
98
+ * @param args - pnpm arguments with relative path specs anchored to the invoking directory.
99
+ * @returns the pnpm exit code.
100
+ */
101
+ function runPlugin(profile, args) {
102
+ const dir = resolveProfileDir(profile);
103
+ if (!existsSync(join(dir, "package.json"))) {
104
+ initProfile(dir, PROFILE_TEMPLATES[profile] ?? DEFAULT_PROFILE_BUNDLES);
105
+ process.stderr.write(`${NAME}: initialized profile ${profile} at ${dir}\n`);
106
+ }
107
+ const before = readProfileManifest(NAME, dir);
108
+ const result = spawnSync("pnpm", args.map((argument) => anchorPathSpec(argument, process.cwd())), {
109
+ cwd: dir,
110
+ stdio: "inherit",
111
+ shell: process.platform === "win32"
112
+ });
113
+ if (result.error !== void 0) {
114
+ if (result.error.code === "ENOENT") {
115
+ process.stderr.write(`${NAME}: pnpm not found on PATH — install pnpm to manage profile plugins\n`);
116
+ return 127;
117
+ }
118
+ throw result.error;
119
+ }
120
+ const exitCode = result.status ?? 1;
121
+ if (exitCode === 0) reconcilePlugins(before, dir);
122
+ else {
123
+ process.stderr.write(`${NAME}: pnpm failed in profile directory ${dir}\n`);
124
+ if (args.some((argument) => /^git\+|^github:|\.git(?:#|$)/.test(argument))) process.stderr.write(`${NAME}: git-hosted plugins build on install via their prepare script, which pnpm blocks until allowed — add the exact key pnpm printed above under allowBuilds in ${join(dir, "pnpm-workspace.yaml")}, then re-run\n`);
125
+ }
126
+ return exitCode;
127
+ }
128
+ //#endregion
129
+ export { runPlugin };
@@ -0,0 +1,129 @@
1
+ import { t as INSTALL_ANCHOR } from "./profile-boot-hvAsNaX6.js";
2
+ import { existsSync } from "node:fs";
3
+ import { DEFAULT_PROFILE_BUNDLES, PROFILE_TEMPLATES, initProfile, readProfileManifest, resolveBundleDir, resolveProfileDir, writeProfileManifest } from "@monotykamary/dsh-app-boot";
4
+ import { join, resolve } from "node:path";
5
+ import { spawnSync } from "node:child_process";
6
+ //#region lib/types/plugin.js
7
+ /**
8
+ * `dsh plugin --profile <name> <args...>` — profile plugin management as a
9
+ * thin pnpm forwarder: initialize the profile on first use, run
10
+ * `pnpm <args...>` in the profile directory, then reconcile the
11
+ * `dsh.profile.bundles` layer list against the installed state (a dependency
12
+ * resolving to a package that declares `dsh.bundle` joins the layer stack; a
13
+ * removed or bundle-less dependency leaves it). Reconciling by installed
14
+ * state, not by dependency diff, means `update` activates a package that
15
+ * gained its `dsh.bundle` declaration in a newer version.
16
+ * @module @monotykamary/dsh/plugin
17
+ */
18
+ const NAME = "dsh";
19
+ /**
20
+ * Whether a resolved dependency exports a profile patch, i.e. is a bundle.
21
+ * @param packageName - the dependency's package name.
22
+ * @param profileDir - the profile directory (resolution anchor).
23
+ * @returns true when the package manifest declares `dsh.bundle`.
24
+ */
25
+ function exportsPatch(packageName, profileDir) {
26
+ let dir;
27
+ try {
28
+ dir = resolveBundleDir(NAME, packageName, INSTALL_ANCHOR, profileDir);
29
+ } catch {
30
+ return false;
31
+ }
32
+ return readProfileManifest(NAME, dir).dsh?.bundle?.patch !== void 0;
33
+ }
34
+ /**
35
+ * Reconcile `dsh.profile.bundles` against the installed state: pnpm has
36
+ * already written the real installed names (so a git/path/tarball/alias spec
37
+ * on the command line reconciles by its true package name) and materialized
38
+ * the packages. A dependency that resolves to a `dsh.bundle`-declaring
39
+ * package joins the layer stack (appended in dependency order); a
40
+ * dependency-listed name that no longer does — removed, or the installed
41
+ * version dropped the declaration — leaves it. In-box bundles from the
42
+ * profile template are not dependencies and are never touched. Warns once
43
+ * per newly-added bundle-less dependency (a plain library is fine; the
44
+ * warning is orientation).
45
+ */
46
+ function reconcilePlugins(before, profileDir) {
47
+ const after = readProfileManifest(NAME, profileDir);
48
+ const beforeDeps = new Set(Object.keys(before.dependencies ?? {}));
49
+ const dependencies = Object.keys(after.dependencies ?? {});
50
+ const plugins = after.dsh?.profile?.bundles ?? [];
51
+ let changed = false;
52
+ for (const packageName of dependencies) {
53
+ const isBundle = exportsPatch(packageName, profileDir);
54
+ if (isBundle && !plugins.includes(packageName)) {
55
+ plugins.push(packageName);
56
+ changed = true;
57
+ } else if (!isBundle && !beforeDeps.has(packageName)) process.stderr.write(`${NAME}: warning: ${packageName} declares no dsh.bundle — installed as a plain dependency, not a profile layer (a later update that gains one activates it automatically)
58
+ `);
59
+ }
60
+ const dependencySet = new Set(dependencies);
61
+ for (const packageName of [...plugins]) {
62
+ const wasDependency = beforeDeps.has(packageName) || dependencySet.has(packageName);
63
+ const stillBundle = dependencySet.has(packageName) && exportsPatch(packageName, profileDir);
64
+ if (wasDependency && !stillBundle) {
65
+ plugins.splice(plugins.indexOf(packageName), 1);
66
+ changed = true;
67
+ }
68
+ }
69
+ if (!changed) return;
70
+ after.dsh = {
71
+ ...after.dsh,
72
+ profile: {
73
+ ...after.dsh?.profile,
74
+ bundles: plugins
75
+ }
76
+ };
77
+ writeProfileManifest(profileDir, after);
78
+ }
79
+ /**
80
+ * Rewrite relative filesystem specs against the user's invoking directory.
81
+ * pnpm runs with cwd = the profile directory, so a bare `.` or `../plugin`
82
+ * (or their `file:`/`link:` forms) would silently resolve inside the profile
83
+ * — `add .` from a plugin checkout would self-link the profile. Absolute
84
+ * specs, registry names, and every other pnpm argument pass through
85
+ * untouched.
86
+ * @param argument - one pnpm argument, verbatim from argv.
87
+ * @param cwd - the directory `dsh` was invoked from.
88
+ * @returns the argument with a relative path spec anchored to `cwd`.
89
+ */
90
+ function anchorPathSpec(argument, cwd) {
91
+ const match = /^(?<prefix>(?:file|link):)?(?<path>\.{1,2}(?:[/\\].*)?)$/.exec(argument);
92
+ if (match?.groups?.path === void 0) return argument;
93
+ return `${match.groups.prefix ?? ""}${resolve(cwd, match.groups.path)}`;
94
+ }
95
+ /**
96
+ * Run one `dsh plugin` invocation: init if needed, forward to pnpm, reconcile.
97
+ * @param profile - the profile name.
98
+ * @param args - pnpm arguments with relative path specs anchored to the invoking directory.
99
+ * @returns the pnpm exit code.
100
+ */
101
+ function runPlugin(profile, args) {
102
+ const dir = resolveProfileDir(profile);
103
+ if (!existsSync(join(dir, "package.json"))) {
104
+ initProfile(dir, PROFILE_TEMPLATES[profile] ?? DEFAULT_PROFILE_BUNDLES);
105
+ process.stderr.write(`${NAME}: initialized profile ${profile} at ${dir}\n`);
106
+ }
107
+ const before = readProfileManifest(NAME, dir);
108
+ const result = spawnSync("pnpm", args.map((argument) => anchorPathSpec(argument, process.cwd())), {
109
+ cwd: dir,
110
+ stdio: "inherit",
111
+ shell: process.platform === "win32"
112
+ });
113
+ if (result.error !== void 0) {
114
+ if (result.error.code === "ENOENT") {
115
+ process.stderr.write(`${NAME}: pnpm not found on PATH — install pnpm to manage profile plugins\n`);
116
+ return 127;
117
+ }
118
+ throw result.error;
119
+ }
120
+ const exitCode = result.status ?? 1;
121
+ if (exitCode === 0) reconcilePlugins(before, dir);
122
+ else {
123
+ process.stderr.write(`${NAME}: pnpm failed in profile directory ${dir}\n`);
124
+ if (args.some((argument) => /^git\+|^github:|\.git(?:#|$)/.test(argument))) process.stderr.write(`${NAME}: git-hosted plugins build on install via their prepare script, which pnpm blocks until allowed — add the exact key pnpm printed above under allowBuilds in ${join(dir, "pnpm-workspace.yaml")}, then re-run\n`);
125
+ }
126
+ return exitCode;
127
+ }
128
+ //#endregion
129
+ export { runPlugin };
@@ -0,0 +1,129 @@
1
+ import { t as INSTALL_ANCHOR } from "./profile-boot-CXPZgDex.js";
2
+ import { existsSync } from "node:fs";
3
+ import { DEFAULT_PROFILE_BUNDLES, PROFILE_TEMPLATES, initProfile, readProfileManifest, resolveBundleDir, resolveProfileDir, writeProfileManifest } from "@monotykamary/dsh-app-boot";
4
+ import { join, resolve } from "node:path";
5
+ import { spawnSync } from "node:child_process";
6
+ //#region lib/types/plugin.js
7
+ /**
8
+ * `dsh plugin --profile <name> <args...>` — profile plugin management as a
9
+ * thin pnpm forwarder: initialize the profile on first use, run
10
+ * `pnpm <args...>` in the profile directory, then reconcile the
11
+ * `dsh.profile.bundles` layer list against the installed state (a dependency
12
+ * resolving to a package that declares `dsh.bundle` joins the layer stack; a
13
+ * removed or bundle-less dependency leaves it). Reconciling by installed
14
+ * state, not by dependency diff, means `update` activates a package that
15
+ * gained its `dsh.bundle` declaration in a newer version.
16
+ * @module @monotykamary/dsh/plugin
17
+ */
18
+ const NAME = "dsh";
19
+ /**
20
+ * Whether a resolved dependency exports a profile patch, i.e. is a bundle.
21
+ * @param packageName - the dependency's package name.
22
+ * @param profileDir - the profile directory (resolution anchor).
23
+ * @returns true when the package manifest declares `dsh.bundle`.
24
+ */
25
+ function exportsPatch(packageName, profileDir) {
26
+ let dir;
27
+ try {
28
+ dir = resolveBundleDir(NAME, packageName, INSTALL_ANCHOR, profileDir);
29
+ } catch {
30
+ return false;
31
+ }
32
+ return readProfileManifest(NAME, dir).dsh?.bundle?.patch !== void 0;
33
+ }
34
+ /**
35
+ * Reconcile `dsh.profile.bundles` against the installed state: pnpm has
36
+ * already written the real installed names (so a git/path/tarball/alias spec
37
+ * on the command line reconciles by its true package name) and materialized
38
+ * the packages. A dependency that resolves to a `dsh.bundle`-declaring
39
+ * package joins the layer stack (appended in dependency order); a
40
+ * dependency-listed name that no longer does — removed, or the installed
41
+ * version dropped the declaration — leaves it. In-box bundles from the
42
+ * profile template are not dependencies and are never touched. Warns once
43
+ * per newly-added bundle-less dependency (a plain library is fine; the
44
+ * warning is orientation).
45
+ */
46
+ function reconcilePlugins(before, profileDir) {
47
+ const after = readProfileManifest(NAME, profileDir);
48
+ const beforeDeps = new Set(Object.keys(before.dependencies ?? {}));
49
+ const dependencies = Object.keys(after.dependencies ?? {});
50
+ const plugins = after.dsh?.profile?.bundles ?? [];
51
+ let changed = false;
52
+ for (const packageName of dependencies) {
53
+ const isBundle = exportsPatch(packageName, profileDir);
54
+ if (isBundle && !plugins.includes(packageName)) {
55
+ plugins.push(packageName);
56
+ changed = true;
57
+ } else if (!isBundle && !beforeDeps.has(packageName)) process.stderr.write(`${NAME}: warning: ${packageName} declares no dsh.bundle — installed as a plain dependency, not a profile layer (a later update that gains one activates it automatically)
58
+ `);
59
+ }
60
+ const dependencySet = new Set(dependencies);
61
+ for (const packageName of [...plugins]) {
62
+ const wasDependency = beforeDeps.has(packageName) || dependencySet.has(packageName);
63
+ const stillBundle = dependencySet.has(packageName) && exportsPatch(packageName, profileDir);
64
+ if (wasDependency && !stillBundle) {
65
+ plugins.splice(plugins.indexOf(packageName), 1);
66
+ changed = true;
67
+ }
68
+ }
69
+ if (!changed) return;
70
+ after.dsh = {
71
+ ...after.dsh,
72
+ profile: {
73
+ ...after.dsh?.profile,
74
+ bundles: plugins
75
+ }
76
+ };
77
+ writeProfileManifest(profileDir, after);
78
+ }
79
+ /**
80
+ * Rewrite relative filesystem specs against the user's invoking directory.
81
+ * pnpm runs with cwd = the profile directory, so a bare `.` or `../plugin`
82
+ * (or their `file:`/`link:` forms) would silently resolve inside the profile
83
+ * — `add .` from a plugin checkout would self-link the profile. Absolute
84
+ * specs, registry names, and every other pnpm argument pass through
85
+ * untouched.
86
+ * @param argument - one pnpm argument, verbatim from argv.
87
+ * @param cwd - the directory `dsh` was invoked from.
88
+ * @returns the argument with a relative path spec anchored to `cwd`.
89
+ */
90
+ function anchorPathSpec(argument, cwd) {
91
+ const match = /^(?<prefix>(?:file|link):)?(?<path>\.{1,2}(?:[/\\].*)?)$/.exec(argument);
92
+ if (match?.groups?.path === void 0) return argument;
93
+ return `${match.groups.prefix ?? ""}${resolve(cwd, match.groups.path)}`;
94
+ }
95
+ /**
96
+ * Run one `dsh plugin` invocation: init if needed, forward to pnpm, reconcile.
97
+ * @param profile - the profile name.
98
+ * @param args - pnpm arguments with relative path specs anchored to the invoking directory.
99
+ * @returns the pnpm exit code.
100
+ */
101
+ function runPlugin(profile, args) {
102
+ const dir = resolveProfileDir(profile);
103
+ if (!existsSync(join(dir, "package.json"))) {
104
+ initProfile(dir, PROFILE_TEMPLATES[profile] ?? DEFAULT_PROFILE_BUNDLES);
105
+ process.stderr.write(`${NAME}: initialized profile ${profile} at ${dir}\n`);
106
+ }
107
+ const before = readProfileManifest(NAME, dir);
108
+ const result = spawnSync("pnpm", args.map((argument) => anchorPathSpec(argument, process.cwd())), {
109
+ cwd: dir,
110
+ stdio: "inherit",
111
+ shell: process.platform === "win32"
112
+ });
113
+ if (result.error !== void 0) {
114
+ if (result.error.code === "ENOENT") {
115
+ process.stderr.write(`${NAME}: pnpm not found on PATH — install pnpm to manage profile plugins\n`);
116
+ return 127;
117
+ }
118
+ throw result.error;
119
+ }
120
+ const exitCode = result.status ?? 1;
121
+ if (exitCode === 0) reconcilePlugins(before, dir);
122
+ else {
123
+ process.stderr.write(`${NAME}: pnpm failed in profile directory ${dir}\n`);
124
+ if (args.some((argument) => /^git\+|^github:|\.git(?:#|$)/.test(argument))) process.stderr.write(`${NAME}: git-hosted plugins build on install via their prepare script, which pnpm blocks until allowed — add the exact key pnpm printed above under allowBuilds in ${join(dir, "pnpm-workspace.yaml")}, then re-run\n`);
125
+ }
126
+ return exitCode;
127
+ }
128
+ //#endregion
129
+ export { runPlugin };
@@ -0,0 +1,2 @@
1
+ import { a as runProfile } from "./profile-boot-CCBe1Ijy.js";
2
+ export { runProfile };
@@ -0,0 +1,2 @@
1
+ import { a as runProfile } from "./profile-boot-CXPZgDex.js";
2
+ export { runProfile };
@@ -0,0 +1,261 @@
1
+ import { writeFileSync } from "node:fs";
2
+ import { fileURLToPath } from "node:url";
3
+ import { PROFILE_PATCH_FILENAME, boot, composeEntries, healProfilesModuleFallback, installFailLoud, loadOptionalPatches, loadOverlayPatches, loadProfile, watchUserPatches } from "@monotykamary/dsh-app-boot";
4
+ import { join, resolve } from "node:path";
5
+ import { resolveDshHome } from "@monotykamary/dsh-home-paths";
6
+ import { DSH_LAUNCH_ENVIRONMENT_KEY } from "@monotykamary/dsh-launch-environment";
7
+ import { provideCmdline } from "@monotykamary/dsh-cmdline";
8
+ //#region lib/types/process-shutdown.js
9
+ /** Bounded, escalating process shutdown for the long-lived CLI surfaces. */
10
+ /** Maximum grace allowed for the application tree to dispose before process exit. */
11
+ const PROCESS_SHUTDOWN_TIMEOUT_MS = 5e3;
12
+ /**
13
+ * Create one process-exit controller around an application disposer.
14
+ * @param dispose - Whole-application teardown that resolves at quiescence.
15
+ * @param forceExit - Function that exits the process immediately, replaceable by tests.
16
+ * @param complete - Function that records the natural completion code, replaceable by tests.
17
+ * @param timeoutMs - Grace before forced exit, replaceable by tests.
18
+ * @returns A controller whose normal calls coalesce and whose repeated signal call escalates.
19
+ */
20
+ function createProcessShutdown(dispose, forceExit = (code) => {
21
+ process.exit(code);
22
+ }, complete = (code) => {
23
+ process.exitCode = code;
24
+ }, timeoutMs = PROCESS_SHUTDOWN_TIMEOUT_MS) {
25
+ let pending;
26
+ let timeout;
27
+ let completed = false;
28
+ let forceExited = false;
29
+ const clearExitTimeout = () => {
30
+ /* v8 ignore else -- shutdown() arms the timer before any asynchronous exit path can run. */
31
+ if (timeout !== void 0) clearTimeout(timeout);
32
+ };
33
+ const forceExitOnce = (code) => {
34
+ if (forceExited) return;
35
+ forceExited = true;
36
+ clearExitTimeout();
37
+ forceExit(code);
38
+ };
39
+ const completeOnce = (code) => {
40
+ if (completed || forceExited) return;
41
+ completed = true;
42
+ clearExitTimeout();
43
+ complete(code);
44
+ };
45
+ const start = (code, forceAfterDispose) => {
46
+ if (pending !== void 0) return pending;
47
+ timeout = setTimeout(() => {
48
+ forceExitOnce(code);
49
+ }, timeoutMs);
50
+ pending = Promise.resolve().then(dispose).then(() => {
51
+ if (forceAfterDispose) forceExitOnce(code);
52
+ else completeOnce(code);
53
+ }, () => {
54
+ forceExitOnce(code);
55
+ });
56
+ return pending;
57
+ };
58
+ return {
59
+ shutdown(code) {
60
+ return start(code, false);
61
+ },
62
+ interrupt(code) {
63
+ if (pending !== void 0) {
64
+ forceExitOnce(code);
65
+ return;
66
+ }
67
+ start(code, true);
68
+ }
69
+ };
70
+ }
71
+ //#endregion
72
+ //#region lib/types/profile-boot.js
73
+ /**
74
+ * Shared profile boot for every `dsh` surface: resolve the profile, stack its
75
+ * patch layers (bundle layers in `dsh.profile.bundles` order, the profile's
76
+ * own `cordis.patch.yml`, `--patch` overlays), mount the
77
+ * tree over the profile's empty root config, keep the profile patch layer
78
+ * live, and wire fail-loud plus bounded shutdown.
79
+ *
80
+ * App flags are not the launcher's business: the invocation's inner arguments
81
+ * are provided to the tree through `ctx.cmdlineArgs`, where any injected app
82
+ * plugin may read the same immutable snapshot.
83
+ * @module @monotykamary/dsh/profile-boot
84
+ */
85
+ /** Shipped agent-preset root: beside this app's own config, in both source and built layouts. */
86
+ const SHIPPED_PRESET_ROOT = fileURLToPath(new URL("../config/agent-presets/", import.meta.url));
87
+ const NAME = "dsh";
88
+ /**
89
+ * The home-level user patch layer (`$DSH_HOME/cordis.patch.yml`), applied
90
+ * over every profile's own layer. Resolved per call, not at module load:
91
+ * `$DSH_HOME` may be set by the test or launcher after import.
92
+ * @returns the absolute patch-file path.
93
+ */
94
+ function homePatchPath() {
95
+ return join(resolveDshHome(), PROFILE_PATCH_FILENAME);
96
+ }
97
+ /** Absolute path of this dsh installation's package.json (both anchors: src/ and lib/ sit one level under apps/cli). */
98
+ const INSTALL_ANCHOR = fileURLToPath(new URL("../package.json", import.meta.url));
99
+ /** The empty root entry list every profile tree patches over. */
100
+ const PROFILE_ROOT_CONFIG = `# dsh profile root — an empty entry list. The tree is composed as patches:
101
+ # each bundle in package.json's dsh.profile.bundles, then cordis.patch.yml, then any
102
+ # --patch overlays. Edit cordis.patch.yml, not this file.
103
+ []
104
+ `;
105
+ /** Root config filename inside a profile directory. */
106
+ const PROFILE_ROOT_FILENAME = "cordis.yml";
107
+ /**
108
+ * Load a resolved profile for `name`: heal the shared module fallback, then
109
+ * (re)write the empty root config. The root is always rewritten: the whole
110
+ * composition is patch layers, and the vendored Loader's tree write-back (a
111
+ * plugin self-disposing persists the current tree) can bake composed rows
112
+ * into this file — which would duplicate every bundle insert on the next
113
+ * boot. The file exists on disk only because the Loader needs a real include
114
+ * root to anchor `baseUrl` at the profile directory (the config dump anchors
115
+ * on the same file, so both compose over the identical base).
116
+ * @param name - the profile name.
117
+ * @param userLayer - `false` skips parsing `cordis.patch.yml` (the default dump).
118
+ * @returns the loaded profile.
119
+ */
120
+ function prepareProfile(name, userLayer = true) {
121
+ healProfilesModuleFallback(INSTALL_ANCHOR);
122
+ const profile = loadProfile(NAME, name, INSTALL_ANCHOR, void 0, { userLayer });
123
+ writeFileSync(join(profile.dir, PROFILE_ROOT_FILENAME), PROFILE_ROOT_CONFIG);
124
+ return profile;
125
+ }
126
+ /** The full patch stack of one composed profile, in application order. */
127
+ function allPatches(composed) {
128
+ return [
129
+ ...composed.bundlePatches,
130
+ ...composed.profile.patches,
131
+ ...composed.homePatches,
132
+ ...composed.overlays
133
+ ];
134
+ }
135
+ /**
136
+ * Load `name` and compose its effective patch stack: bundle layers in
137
+ * `dsh.profile.bundles` order (the base bundle gates the shell stacks by
138
+ * platform on its own rows), the profile's user layer, the home-level user
139
+ * layer (`$DSH_HOME/cordis.patch.yml` — machine-local preferences that apply
140
+ * to every profile, so it outranks the per-profile layer), and `--patch`
141
+ * overlays.
142
+ * @param name - the profile name.
143
+ * @param patchFiles - `--patch` overlay paths, in argv order.
144
+ * @returns the profile, its patch layers, and the composed row index.
145
+ */
146
+ function composeProfile(name, patchFiles) {
147
+ const profile = prepareProfile(name);
148
+ const homePatches = loadOptionalPatches(NAME, homePatchPath()) ?? [];
149
+ const overlays = patchFiles.flatMap((file) => loadOverlayPatches(NAME, resolve(file)));
150
+ const bundlePatches = profile.layers.flatMap((layer) => layer.patches);
151
+ const rows = /* @__PURE__ */ new Map();
152
+ for (const row of composeEntries([
153
+ bundlePatches,
154
+ profile.patches,
155
+ homePatches,
156
+ overlays
157
+ ])) if (typeof row.id === "string") rows.set(row.id, row);
158
+ const composedOverlays = [...overlays];
159
+ if (rows.has("agent-presets")) composedOverlays.push({
160
+ id: "agent-presets",
161
+ config: {
162
+ ...rows.get("agent-presets")?.config ?? {},
163
+ roots: [{
164
+ path: SHIPPED_PRESET_ROOT,
165
+ trust: "system"
166
+ }]
167
+ }
168
+ });
169
+ return {
170
+ profile,
171
+ bundlePatches,
172
+ homePatches,
173
+ overlays: composedOverlays,
174
+ rows
175
+ };
176
+ }
177
+ /**
178
+ * Re-throw a watcher-setup failure unless a shutdown already owns the tree:
179
+ * a signal aborted this invocation, or an app requested exit (`ctx.appExit`
180
+ * from a fast one-shot) and the root's disposal rejected the in-flight setup
181
+ * await. Either way the failure describes a tree that is exiting as asked,
182
+ * not a broken watch.
183
+ * @param ctx - the booted root context.
184
+ * @param signal - this invocation's signal-shutdown fact.
185
+ * @param error - the setup failure.
186
+ */
187
+ function suppressShutdownError(ctx, signal, error) {
188
+ if (signal.aborted) return;
189
+ if (ctx.fiber.state !== 2 || ctx.get("loader") === void 0) return;
190
+ throw error;
191
+ }
192
+ /**
193
+ * Boot one profile invocation end to end and leave process lifetime to the
194
+ * mounted plugins (or to a one-shot runner the composition mounts).
195
+ * @param options - environment snapshot, profile name, overlays, and the booted app's own arguments.
196
+ * @returns the settled root context and the shutdown controller.
197
+ */
198
+ async function runProfile(options) {
199
+ const composed = composeProfile(options.profile, options.patchFiles);
200
+ const app = {};
201
+ const shutdown = createProcessShutdown(async () => {
202
+ await app.current?.fiber.dispose();
203
+ });
204
+ const signalShutdown = new AbortController();
205
+ const interrupt = (code) => {
206
+ signalShutdown.abort();
207
+ shutdown.interrupt(code);
208
+ };
209
+ process.on("SIGTERM", () => {
210
+ interrupt(0);
211
+ });
212
+ process.on("SIGINT", () => {
213
+ interrupt(130);
214
+ });
215
+ installFailLoud(NAME, process, async () => {
216
+ await app.current?.fiber.dispose();
217
+ });
218
+ const rootConfig = join(composed.profile.dir, PROFILE_ROOT_FILENAME);
219
+ const composeLive = () => structuredClone([
220
+ ...composed.bundlePatches,
221
+ ...loadOptionalPatches(NAME, composed.profile.patchPath) ?? [],
222
+ ...loadOptionalPatches(NAME, homePatchPath()) ?? [],
223
+ ...composed.overlays
224
+ ]);
225
+ const ctx = await boot(NAME, rootConfig, structuredClone(allPatches(composed)), (hostCtx) => {
226
+ app.current = hostCtx;
227
+ hostCtx.provide(DSH_LAUNCH_ENVIRONMENT_KEY, options.environment);
228
+ provideCmdline(hostCtx, {
229
+ args: options.args,
230
+ exit: (code) => void shutdown.shutdown(code)
231
+ });
232
+ });
233
+ app.current = ctx;
234
+ if (!signalShutdown.signal.aborted && ctx.fiber.state === 2 && ctx.get("loader") !== void 0) try {
235
+ if (ctx.get("hmr") === void 0) {
236
+ if (ctx.get("timer") === void 0) await ctx.loader.create({ name: "@monotykamary/cordis-plugin-timer" });
237
+ await ctx.loader.create({
238
+ name: "@monotykamary/cordis-plugin-hmr",
239
+ config: { root: [] }
240
+ });
241
+ }
242
+ await watchUserPatches(ctx, {
243
+ binName: NAME,
244
+ filename: composed.profile.patchPath,
245
+ compose: composeLive
246
+ });
247
+ await watchUserPatches(ctx, {
248
+ binName: NAME,
249
+ filename: homePatchPath(),
250
+ compose: composeLive
251
+ });
252
+ } catch (error) {
253
+ suppressShutdownError(ctx, signalShutdown.signal, error);
254
+ }
255
+ return {
256
+ ctx,
257
+ shutdown
258
+ };
259
+ }
260
+ //#endregion
261
+ export { runProfile as a, prepareProfile as i, PROFILE_ROOT_FILENAME as n, homePatchPath as r, INSTALL_ANCHOR as t };