@twinsearth/core-dsh-plugin 1.0.0 → 1.0.1

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.
@@ -1,330 +0,0 @@
1
- import { PROFILE_PATCH_FILENAME, PluginPackages, boot, createRuntimeResolution, initProfile, installFailLoud, loadOverlayPatches, loadProfile, readProfilePatches, reportSkippedBundles, resolveProfileDir } from "@twinsearth/dsh-app-boot";
2
- import { resolveDshHome } from "@twinsearth/dsh-home-paths";
3
- import { dirname, join, resolve } from "node:path";
4
- import { existsSync, mkdirSync, mkdtempSync, renameSync, rmSync, writeFileSync } from "node:fs";
5
- import { fileURLToPath } from "node:url";
6
- import { PROFILE_TEMPLATES } from "@twinsearth/dsh-official-bundles";
7
- import { installProxyFromEnvironment } from "@twinsearth/dsh-http-proxy";
8
- import { DSH_LAUNCH_ENVIRONMENT_KEY } from "@twinsearth/dsh-launch-environment";
9
- import { provideCmdline } from "@twinsearth/dsh-cmdline";
10
- //#region lib/types/process-shutdown.js
11
- /** Bounded, escalating process shutdown for the long-lived CLI surfaces. */
12
- /** Maximum grace allowed for the application tree to dispose before process exit. */
13
- const PROCESS_SHUTDOWN_TIMEOUT_MS = 5e3;
14
- /**
15
- * Create one process-exit controller around an application disposer.
16
- * @param dispose - Whole-application teardown that resolves at quiescence.
17
- * @param forceExit - Function that exits the process immediately, replaceable by tests.
18
- * @param complete - Function that records the natural completion code, replaceable by tests.
19
- * @param timeoutMs - Grace before forced exit, replaceable by tests.
20
- * @returns A controller whose normal calls coalesce and whose repeated signal call escalates.
21
- */
22
- function createProcessShutdown(dispose, forceExit = (code) => {
23
- process.exit(code);
24
- }, complete = (code) => {
25
- process.exitCode = code;
26
- }, timeoutMs = PROCESS_SHUTDOWN_TIMEOUT_MS) {
27
- let pending;
28
- let timeout;
29
- let completed = false;
30
- let forceExited = false;
31
- const clearExitTimeout = () => {
32
- /* v8 ignore else -- shutdown() arms the timer before any asynchronous exit path can run. */
33
- if (timeout !== void 0) clearTimeout(timeout);
34
- };
35
- const forceExitOnce = (code) => {
36
- if (forceExited) return;
37
- forceExited = true;
38
- clearExitTimeout();
39
- forceExit(code);
40
- };
41
- const completeOnce = (code) => {
42
- if (completed || forceExited) return;
43
- completed = true;
44
- clearExitTimeout();
45
- complete(code);
46
- };
47
- const start = (code, forceAfterDispose) => {
48
- if (pending !== void 0) return pending;
49
- timeout = setTimeout(() => {
50
- forceExitOnce(code);
51
- }, timeoutMs);
52
- pending = Promise.resolve().then(dispose).then(() => {
53
- if (forceAfterDispose) forceExitOnce(code);
54
- else completeOnce(code);
55
- }, () => {
56
- forceExitOnce(code);
57
- });
58
- return pending;
59
- };
60
- return {
61
- shutdown(code) {
62
- return start(code, false);
63
- },
64
- interrupt(code) {
65
- if (pending !== void 0) {
66
- forceExitOnce(code);
67
- return;
68
- }
69
- start(code, true);
70
- }
71
- };
72
- }
73
- //#endregion
74
- //#region lib/types/profile-boot.js
75
- /**
76
- * Shared profile boot for every `dsh` surface: resolve the profile, stack its
77
- * patch layers (bundle layers in `dsh.profile.bundles` order, the profile's
78
- * own `cordis.patch.yml`, `--patch` overlays, the telemetry switch), mount the
79
- * tree over the profile's empty root config, and wire fail-loud plus bounded shutdown.
80
- *
81
- * App flags are not the launcher's business: the invocation's inner arguments
82
- * are provided to the tree through `ctx.cmdlineArgs`, where any injected app
83
- * plugin may read the same immutable snapshot.
84
- * @module @twinsearth/dsh/profile-boot
85
- */
86
- const NAME = "dsh";
87
- /** Launcher-owned readiness signal committed only after boot and host setup succeed. */
88
- function createAppReady() {
89
- let ready = false;
90
- const listeners = /* @__PURE__ */ new Set();
91
- return {
92
- service: { onReady(listener) {
93
- if (ready) {
94
- listener();
95
- return () => {};
96
- }
97
- listeners.add(listener);
98
- return () => {
99
- listeners.delete(listener);
100
- };
101
- } },
102
- commit() {
103
- if (ready) return;
104
- ready = true;
105
- for (const listener of [...listeners]) listener();
106
- listeners.clear();
107
- }
108
- };
109
- }
110
- /**
111
- * The home-level user patch layer (`$DSH_HOME/cordis.patch.yml`), applied
112
- * over every profile's own layer. Resolved per call, not at module load:
113
- * `$DSH_HOME` may be set by the test or launcher after import.
114
- * @returns the absolute patch-file path.
115
- */
116
- function homePatchPath() {
117
- return join(resolveDshHome(), PROFILE_PATCH_FILENAME);
118
- }
119
- /** Absolute path of this dsh installation's package.json (both anchors: src/ and lib/ sit one level under apps/cli). */
120
- const INSTALL_ANCHOR = fileURLToPath(new URL("../package.json", import.meta.url));
121
- /** The empty root entry list every profile tree patches over. */
122
- const PROFILE_ROOT_CONFIG = `# dsh profile root — an empty entry list. The tree is composed as patches:
123
- # each bundle in package.json's dsh.profile.bundles, then cordis.patch.yml, then any
124
- # --patch overlays. Edit cordis.patch.yml, not this file.
125
- []
126
- `;
127
- /** Root config filename inside a profile directory. */
128
- const PROFILE_ROOT_FILENAME = "cordis.yml";
129
- /**
130
- * Replace the named custom profile with a fresh copy of one shipped template.
131
- * This copies only the template's bundle list; local state from the
132
- * same-named shipped profile is not read, and no inheritance metadata is
133
- * persisted. The new profile is assembled in a `.<name>.staging-*` directory
134
- * under the profiles directory and moved into place; only then is any previous
135
- * target directory, including its dependencies and user patch, deleted. A
136
- * failed move restores the previous directory; when restoring also fails, it
137
- * stays in the staging directory. Shipped profile names, compared without
138
- * case, are reserved. Concurrent replacements leave one complete copy; each
139
- * one either succeeds or reports the concurrent recreation.
140
- * @param name - the profile name to create or replace.
141
- * @param fromDefaultProfile - shipped profile template to copy.
142
- * @param home - Harness home containing the profile directory.
143
- * @throws when the template is unknown, the target name is shipped, another process recreates the target
144
- * between the two renames, or a file-system operation fails; a restore failure is an `AggregateError`
145
- * that names the staging path holding the previous profile.
146
- */
147
- function initializeProfileFromDefault(name, fromDefaultProfile, home = resolveDshHome()) {
148
- const dir = resolveProfileDir(name, home);
149
- const template = Object.hasOwn(PROFILE_TEMPLATES, fromDefaultProfile) ? PROFILE_TEMPLATES[fromDefaultProfile] : void 0;
150
- if (template === void 0) {
151
- const expected = Object.keys(PROFILE_TEMPLATES).sort().map((value) => JSON.stringify(value)).join(", ");
152
- throw new Error(`${NAME}: unknown default profile ${JSON.stringify(fromDefaultProfile)}; expected one of ${expected}`);
153
- }
154
- const shipped = Object.keys(PROFILE_TEMPLATES).find((shippedName) => shippedName.toLowerCase() === name.toLowerCase());
155
- if (shipped !== void 0) throw new Error(`${NAME}: profile ${JSON.stringify(name)} names shipped profile ${JSON.stringify(shipped)} and cannot be a custom profile target; omit --from-default-profile to use it`);
156
- mkdirSync(dirname(dir), { recursive: true });
157
- const staging = mkdtempSync(join(dirname(dir), `.${name}.staging-`));
158
- const previous = join(staging, "previous");
159
- try {
160
- const fresh = join(staging, "new", name);
161
- initProfile(fresh, template.bundles);
162
- let moved = false;
163
- try {
164
- renameSync(dir, previous);
165
- moved = true;
166
- } catch (error) {
167
- if (error.code !== "ENOENT") throw error;
168
- }
169
- try {
170
- renameSync(fresh, dir);
171
- } catch (error) {
172
- if (existsSync(dir)) {
173
- rmSync(previous, {
174
- recursive: true,
175
- force: true
176
- });
177
- throw new Error(`${NAME}: profile ${JSON.stringify(name)} was recreated concurrently at ${dir}`, { cause: error });
178
- }
179
- if (moved) try {
180
- renameSync(previous, dir);
181
- } catch (restoreError) {
182
- throw new AggregateError([error, restoreError], `${NAME}: profile replacement failed and ${dir} could not be restored from ${previous}`);
183
- }
184
- throw error;
185
- }
186
- } catch (error) {
187
- if (!existsSync(previous)) rmSync(staging, {
188
- recursive: true,
189
- force: true
190
- });
191
- throw error;
192
- }
193
- try {
194
- rmSync(staging, {
195
- recursive: true,
196
- force: true
197
- });
198
- } catch (error) {
199
- process.stderr.write(`${NAME}: replaced profile ${JSON.stringify(name)} but could not remove ${staging}: ${String(error)}\n`);
200
- }
201
- }
202
- /**
203
- * Load a resolved profile for `name` and (re)write the empty root config. The
204
- * root is always rewritten: the whole composition is patch layers, and the
205
- * vendored Loader's tree write-back (a plugin self-disposing persists the
206
- * current tree) can bake composed rows into this file — which would duplicate
207
- * every bundle insert on the next boot. The file exists on disk only because
208
- * the Loader needs a real include root to anchor `baseUrl` at the profile
209
- * directory (the config dump anchors on the same file, so both compose over
210
- * the identical base).
211
- * @param name - the profile name.
212
- * @param userLayer - `false` skips parsing `cordis.patch.yml` (the default dump).
213
- * @param fromDefaultProfile - shipped template that replaces the profile before loading it.
214
- * @returns the loaded profile.
215
- * @throws when explicit initialization names an unknown template or a shipped target.
216
- */
217
- function prepareProfile(name, userLayer = true, fromDefaultProfile) {
218
- if (fromDefaultProfile !== void 0) initializeProfileFromDefault(name, fromDefaultProfile);
219
- const profile = loadProfile(NAME, name, INSTALL_ANCHOR, void 0, { userLayer });
220
- reportSkippedBundles(NAME, profile);
221
- writeFileSync(join(profile.dir, PROFILE_ROOT_FILENAME), PROFILE_ROOT_CONFIG);
222
- return profile;
223
- }
224
- /**
225
- * Load `name` and compose its effective patch stack: bundle layers in
226
- * `dsh.profile.bundles` order (a base-backed profile gets the base bundle's
227
- * platform-gated shell rows), the profile's user layer, the home-level user
228
- * layer (`$DSH_HOME/cordis.patch.yml` — machine-local preferences that apply
229
- * to every profile, so it outranks the per-profile layer), `--patch` overlays,
230
- * then the telemetry switch.
231
- * @param name - the profile name.
232
- * @param patchFiles - `--patch` overlay paths, in argv order.
233
- * @param fromDefaultProfile - shipped template that replaces the named profile.
234
- * @param resolvedProfile - application-owned profile and installation.
235
- * @returns the profile and its patch layers.
236
- */
237
- async function composeProfile(name, patchFiles, fromDefaultProfile, resolvedProfile) {
238
- const profile = resolvedProfile?.profile ?? prepareProfile(name, true, fromDefaultProfile);
239
- if (resolvedProfile !== void 0) writeFileSync(join(profile.dir, PROFILE_ROOT_FILENAME), PROFILE_ROOT_CONFIG);
240
- return {
241
- profile,
242
- resolution: await createRuntimeResolution({
243
- installAnchor: resolvedProfile?.installAnchor ?? INSTALL_ANCHOR,
244
- profile
245
- }),
246
- overlays: patchFiles.flatMap((file) => loadOverlayPatches(NAME, resolve(file)))
247
- };
248
- }
249
- /**
250
- * Boot one profile invocation end to end and leave process lifetime to the
251
- * mounted plugins (or to a one-shot runner the composition mounts).
252
- * @param options - environment snapshot, profile name, overlays, and the booted app's own arguments.
253
- * @returns the settled root context and the shutdown controller.
254
- * @throws after disposing startup resources; cleanup failures retain the original error.
255
- */
256
- async function runProfile(options) {
257
- const disposeProxy = await installProxyFromEnvironment(options.environment, (message) => {
258
- process.stderr.write(`${NAME}: ${message}\n`);
259
- });
260
- const app = {};
261
- let disposal;
262
- const dispose = () => disposal ??= (async () => {
263
- const failures = [];
264
- for (const release of [() => app.current?.fiber.dispose(), disposeProxy]) try {
265
- await release();
266
- } catch (error) {
267
- failures.push(error);
268
- }
269
- if (failures.length === 1) throw failures[0];
270
- if (failures.length > 1) throw new AggregateError(failures, "dsh: profile cleanup failed");
271
- })();
272
- try {
273
- const composed = await composeProfile(options.profile, options.patchFiles, options.fromDefaultProfile, options.resolvedProfile);
274
- const appReady = createAppReady();
275
- const shutdown = createProcessShutdown(dispose);
276
- const signalShutdown = new AbortController();
277
- const interrupt = (code) => {
278
- signalShutdown.abort();
279
- shutdown.interrupt(code);
280
- };
281
- process.on("SIGTERM", () => {
282
- interrupt(0);
283
- });
284
- process.on("SIGINT", () => {
285
- interrupt(130);
286
- });
287
- installFailLoud(NAME, process, async () => {
288
- await app.current?.fiber.dispose();
289
- });
290
- const rootConfig = join(composed.profile.dir, PROFILE_ROOT_FILENAME);
291
- const profileContext = {
292
- name: options.profile,
293
- ...options.packageManager === void 0 ? {} : { packageManager: options.packageManager },
294
- dir: composed.profile.dir,
295
- patchPath: composed.profile.patchPath,
296
- installAnchor: options.resolvedProfile?.installAnchor ?? INSTALL_ANCHOR,
297
- startedBundles: composed.profile.layers.map((layer) => layer.packageName),
298
- cwd: process.cwd(),
299
- home: resolveDshHome(),
300
- overlays: composed.overlays,
301
- telemetryDisabledEnv: process.env.DSH_TELEMETRY_DISABLED
302
- };
303
- const ctx = await boot(NAME, rootConfig, readProfilePatches(NAME, profileContext, composed.profile), async (hostCtx) => {
304
- app.current = hostCtx;
305
- hostCtx.provide("profileContext", profileContext);
306
- hostCtx.provide(DSH_LAUNCH_ENVIRONMENT_KEY, options.environment);
307
- await hostCtx.plugin(PluginPackages, { resolution: composed.resolution });
308
- provideCmdline(hostCtx, {
309
- args: options.args,
310
- exit: (code) => void shutdown.shutdown(code),
311
- ready: appReady.service
312
- });
313
- });
314
- app.current = ctx;
315
- if (!signalShutdown.signal.aborted && ctx.fiber.state === 2 && ctx.get("loader") !== void 0) appReady.commit();
316
- return {
317
- ctx,
318
- shutdown
319
- };
320
- } catch (error) {
321
- try {
322
- await dispose();
323
- } catch (cleanupError) {
324
- throw new AggregateError([error, cleanupError], "dsh: profile startup and cleanup failed");
325
- }
326
- throw error;
327
- }
328
- }
329
- //#endregion
330
- export { prepareProfile as a, initializeProfileFromDefault as i, PROFILE_ROOT_FILENAME as n, runProfile as o, homePatchPath as r, INSTALL_ANCHOR as t };
@@ -1,2 +0,0 @@
1
- import { a as prepareProfile, i as initializeProfileFromDefault, n as PROFILE_ROOT_FILENAME, o as runProfile, r as homePatchPath, t as INSTALL_ANCHOR } from "./profile-boot-e2mS45fC.js";
2
- export { INSTALL_ANCHOR, PROFILE_ROOT_FILENAME, homePatchPath, initializeProfileFromDefault, prepareProfile, runProfile };
@@ -1,65 +0,0 @@
1
- /**
2
- * Commander adapter for the `dsh` command line.
3
- *
4
- * The launcher parses only what it owns — which profile to boot, which extra
5
- * patch overlays to apply, and the config dumps — and hands **everything after
6
- * its own flags** to the booted tree verbatim, where injected app plugins parse
7
- * their own flag families and print their own `--help` (see
8
- * `@twinsearth/dsh-cmdline`). Launcher flags therefore come first: the first
9
- * token this parser does not recognize starts the inner arguments, so
10
- * `dsh --profile tui --resume abc` boots the tui profile with `--resume abc`,
11
- * and `dsh --profile web -h` prints the web app's help, not this one's.
12
- *
13
- * `dsh <name>` abbreviates `dsh --profile <name>`; `plugin` manages a profile's
14
- * plugin dependencies by forwarding to pnpm.
15
- * @module @twinsearth/dsh/args
16
- */
17
- /** Boot a named profile and hand it the invocation's inner arguments. */
18
- interface ProfileInvocation {
19
- mode: 'profile';
20
- profile: string;
21
- /** Shipped template that replaces the named profile. */
22
- fromDefaultProfile?: string | undefined;
23
- /** Extra patch-list overlays applied after the profile's own layer, in argv order. */
24
- patches: string[];
25
- /** Everything after the launcher's own flags, verbatim, for injected app plugins. */
26
- args: string[];
27
- }
28
- /** Print a composed profile tree and exit without booting. */
29
- interface DumpConfigInvocation {
30
- mode: 'dump-config';
31
- profile: string;
32
- /** Shipped template that replaces the named profile. */
33
- fromDefaultProfile?: string | undefined;
34
- /** Omit the profile's user layer and --patch overlays; print bundle layers only. */
35
- defaultOnly: boolean;
36
- patches: string[];
37
- }
38
- /** Print declared plugin schemas without mounting the profile. */
39
- interface DumpConfigSchemaInvocation {
40
- mode: 'dump-config-schema';
41
- profile: string;
42
- /** Shipped template that replaces the named profile. */
43
- fromDefaultProfile?: string | undefined;
44
- patches: string[];
45
- }
46
- /** Manage a profile's plugins: forward `args` to pnpm inside the profile directory. */
47
- interface PluginInvocation {
48
- mode: 'plugin';
49
- profile: string;
50
- /** Raw pnpm arguments, verbatim. */
51
- args: string[];
52
- }
53
- /** The resolved `dsh` invocation. Help, version, and errors exit inside {@link parseDshArgs}. */
54
- export type DshInvocation = ProfileInvocation | DumpConfigInvocation | DumpConfigSchemaInvocation | PluginInvocation;
55
- /**
56
- * Resolve argv into one invocation, or print and exit for help, version, or an
57
- * error.
58
- * @param argv - arguments after the Node binary and script.
59
- * @param version - version string printed by `--version`.
60
- * @param manageDesktopProfile - permit Desktop's installed carrier to manage its reserved profile's plugins.
61
- * @returns the resolved invocation.
62
- */
63
- export declare function parseDshArgs(argv: readonly string[], version: string, manageDesktopProfile?: boolean): DshInvocation;
64
- export {};
65
- //# sourceMappingURL=args.d.ts.map
@@ -1,18 +0,0 @@
1
- #!/usr/bin/env node
2
- /**
3
- * Command-line entry for dsh.
4
- * @module @twinsearth/dsh/bin
5
- */
6
- import type { RunProfileOptions } from './profile-boot.ts';
7
- /** Installation-owned dependencies supplied by a packaged CLI launcher. */
8
- export type RunCliOptions = Pick<RunProfileOptions, 'packageManager'> & {
9
- /** Permit plugin commands for Desktop's existing profile; reserved for its installed carrier. */
10
- manageDesktopProfile?: boolean;
11
- };
12
- /**
13
- * Run the public dsh command-line interface.
14
- * @param options - Package runtime and Desktop profile access supplied by the installation.
15
- * @returns a promise that settles when the selected command mode finishes.
16
- */
17
- export declare function runCli(options?: RunCliOptions): Promise<void>;
18
- //# sourceMappingURL=bin.d.ts.map
@@ -1,17 +0,0 @@
1
- /**
2
- * Schema-dump entry: inspect the composed profile without applying its plugins.
3
- * Imports and lazy schema builders execute trusted module code.
4
- * @module @twinsearth/dsh/dump-config-schema
5
- */
6
- /**
7
- * Print one JSON Schema document; incomplete collection or projection sets exitCode to 1.
8
- * Profile initialization writes match the YAML dump. Plugin imports may execute
9
- * top-level code, but collection never applies plugins or evaluates `!!js`.
10
- * During schema generation, ordinary stdout writes are redirected to stderr.
11
- * @param profile - the profile name.
12
- * @param patches - overlay paths, in argv order.
13
- * @param fromDefaultProfile - shipped template that replaces the profile before loading it.
14
- * @returns after collection and output, with diagnostics also written to stderr.
15
- */
16
- export declare function runDumpConfigSchema(profile: string, patches: readonly string[], fromDefaultProfile?: string): Promise<void>;
17
- //# sourceMappingURL=dump-config-schema.d.ts.map
@@ -1,27 +0,0 @@
1
- /**
2
- * Config-dump entry for `dsh --profile <name> --dump-config`: compose the
3
- * profile's patch layers through the include plugin's patch algorithm without
4
- * booting or evaluating `!!js`, with one source layer per bundle, the
5
- * profile's own patch file, and each `--patch` overlay.
6
- * @module @twinsearth/dsh/dump-config
7
- */
8
- import { type ConfigDumpLayer, type Profile } from '@twinsearth/dsh-app-boot';
9
- /**
10
- * Print a profile composition with comments naming each source file and patch layer.
11
- * @param profile - the profile name.
12
- * @param defaultOnly - omit the profile's user layer and `--patch` overlays
13
- * (the recovery diagnostic for a broken `cordis.patch.yml`, which is then
14
- * never parsed).
15
- * @param patches - `--patch` overlay paths, in argv order.
16
- * @param fromDefaultProfile - shipped template that replaces the profile before loading it.
17
- */
18
- export declare function runDumpConfig(profile: string, defaultOnly: boolean, patches: readonly string[], fromDefaultProfile?: string): void;
19
- /**
20
- * Read dump layers in bundle, profile, home, then argv order without composing them.
21
- * @param loaded - prepared profile and parsed bundle and profile patches.
22
- * @param defaultOnly - omit profile, home, and argv layers without reading their files.
23
- * @param patches - overlay paths relative to the invoking directory, in argv order.
24
- * @returns the labeled layers shared by YAML and schema dumps.
25
- */
26
- export declare function collectConfigDumpLayers(loaded: Profile, defaultOnly: boolean, patches: readonly string[]): ConfigDumpLayer[];
27
- //# sourceMappingURL=dump-config.d.ts.map
@@ -1,9 +0,0 @@
1
- import { type ProfileContext } from '@twinsearth/dsh-app-boot';
2
- /** Run package management for a profile.
3
- * @param profile Profile name; Desktop's reserved profile must already be initialized by the application.
4
- * @param args DSH exemption command or pnpm arguments relative to the invoking directory.
5
- * @param packageManager Installation-owned executable and environment for pnpm operations.
6
- * @returns Zero on success; nonzero on invalid approval or package-manager failure.
7
- */
8
- export declare function runPlugin(profile: string, args: readonly string[], packageManager?: ProfileContext['packageManager']): Promise<number>;
9
- //# sourceMappingURL=plugin.d.ts.map
@@ -1,20 +0,0 @@
1
- /** Bounded, escalating process shutdown for the long-lived CLI surfaces. */
2
- /** Maximum grace allowed for the application tree to dispose before process exit. */
3
- export declare const PROCESS_SHUTDOWN_TIMEOUT_MS = 5000;
4
- /** Process-exit controller shared by normal completion and Unix signal handlers. */
5
- export interface ProcessShutdown {
6
- /** Start or join graceful disposal before allowing natural completion with `code`. */
7
- shutdown(code: number): Promise<void>;
8
- /** Start graceful disposal followed by exit, or force exit when shutdown is already running. */
9
- interrupt(code: number): void;
10
- }
11
- /**
12
- * Create one process-exit controller around an application disposer.
13
- * @param dispose - Whole-application teardown that resolves at quiescence.
14
- * @param forceExit - Function that exits the process immediately, replaceable by tests.
15
- * @param complete - Function that records the natural completion code, replaceable by tests.
16
- * @param timeoutMs - Grace before forced exit, replaceable by tests.
17
- * @returns A controller whose normal calls coalesce and whose repeated signal call escalates.
18
- */
19
- export declare function createProcessShutdown(dispose: () => Promise<void>, forceExit?: (code: number) => void, complete?: (code: number) => void, timeoutMs?: number): ProcessShutdown;
20
- //# sourceMappingURL=process-shutdown.d.ts.map
@@ -1,97 +0,0 @@
1
- /**
2
- * Shared profile boot for every `dsh` surface: resolve the profile, stack its
3
- * patch layers (bundle layers in `dsh.profile.bundles` order, the profile's
4
- * own `cordis.patch.yml`, `--patch` overlays, the telemetry switch), mount the
5
- * tree over the profile's empty root config, and wire fail-loud plus bounded shutdown.
6
- *
7
- * App flags are not the launcher's business: the invocation's inner arguments
8
- * are provided to the tree through `ctx.cmdlineArgs`, where any injected app
9
- * plugin may read the same immutable snapshot.
10
- * @module @twinsearth/dsh/profile-boot
11
- */
12
- import { type Context } from '@deepseek-ai/cordis';
13
- import { type ProfileContext, type Profile } from '@twinsearth/dsh-app-boot';
14
- import { type LaunchEnvironmentSnapshot } from '@twinsearth/dsh-launch-environment';
15
- import { type ProcessShutdown } from './process-shutdown.ts';
16
- /**
17
- * The home-level user patch layer (`$DSH_HOME/cordis.patch.yml`), applied
18
- * over every profile's own layer. Resolved per call, not at module load:
19
- * `$DSH_HOME` may be set by the test or launcher after import.
20
- * @returns the absolute patch-file path.
21
- */
22
- export declare function homePatchPath(): string;
23
- /** Absolute path of this dsh installation's package.json (both anchors: src/ and lib/ sit one level under apps/cli). */
24
- export declare const INSTALL_ANCHOR: string;
25
- /** Root config filename inside a profile directory. */
26
- export declare const PROFILE_ROOT_FILENAME = "cordis.yml";
27
- /**
28
- * Replace the named custom profile with a fresh copy of one shipped template.
29
- * This copies only the template's bundle list; local state from the
30
- * same-named shipped profile is not read, and no inheritance metadata is
31
- * persisted. The new profile is assembled in a `.<name>.staging-*` directory
32
- * under the profiles directory and moved into place; only then is any previous
33
- * target directory, including its dependencies and user patch, deleted. A
34
- * failed move restores the previous directory; when restoring also fails, it
35
- * stays in the staging directory. Shipped profile names, compared without
36
- * case, are reserved. Concurrent replacements leave one complete copy; each
37
- * one either succeeds or reports the concurrent recreation.
38
- * @param name - the profile name to create or replace.
39
- * @param fromDefaultProfile - shipped profile template to copy.
40
- * @param home - Harness home containing the profile directory.
41
- * @throws when the template is unknown, the target name is shipped, another process recreates the target
42
- * between the two renames, or a file-system operation fails; a restore failure is an `AggregateError`
43
- * that names the staging path holding the previous profile.
44
- */
45
- export declare function initializeProfileFromDefault(name: string, fromDefaultProfile: string, home?: string): void;
46
- /**
47
- * Load a resolved profile for `name` and (re)write the empty root config. The
48
- * root is always rewritten: the whole composition is patch layers, and the
49
- * vendored Loader's tree write-back (a plugin self-disposing persists the
50
- * current tree) can bake composed rows into this file — which would duplicate
51
- * every bundle insert on the next boot. The file exists on disk only because
52
- * the Loader needs a real include root to anchor `baseUrl` at the profile
53
- * directory (the config dump anchors on the same file, so both compose over
54
- * the identical base).
55
- * @param name - the profile name.
56
- * @param userLayer - `false` skips parsing `cordis.patch.yml` (the default dump).
57
- * @param fromDefaultProfile - shipped template that replaces the profile before loading it.
58
- * @returns the loaded profile.
59
- * @throws when explicit initialization names an unknown template or a shipped target.
60
- */
61
- export declare function prepareProfile(name: string, userLayer?: boolean, fromDefaultProfile?: string): Profile;
62
- /** An application-owned profile and its independent installation fallback. */
63
- export interface ResolvedProfileRuntime {
64
- /** Profile already loaded from the application's own directory. */
65
- profile: Profile;
66
- /** Absolute package.json path of the application's dsh installation. */
67
- installAnchor: string;
68
- }
69
- /** Options for {@link runProfile}. */
70
- export interface RunProfileOptions {
71
- /** This run's frozen environment snapshot, provided before any entry mounts. */
72
- environment: LaunchEnvironmentSnapshot;
73
- /** The profile name to boot. */
74
- profile: string;
75
- /** Loaded application profile; bypasses named profile initialization when supplied. */
76
- resolvedProfile?: ResolvedProfileRuntime | undefined;
77
- /** Shipped template that replaces the named profile before boot. */
78
- fromDefaultProfile?: string | undefined;
79
- /** `--patch` overlay paths, in argv order. */
80
- patchFiles: readonly string[];
81
- /** The invocation's inner arguments, handed to the tree through `ctx.cmdlineArgs`. */
82
- args: readonly string[];
83
- /** Application-owned package runtime, scoped to plugin package operations. */
84
- packageManager?: ProfileContext['packageManager'];
85
- }
86
- /**
87
- * Boot one profile invocation end to end and leave process lifetime to the
88
- * mounted plugins (or to a one-shot runner the composition mounts).
89
- * @param options - environment snapshot, profile name, overlays, and the booted app's own arguments.
90
- * @returns the settled root context and the shutdown controller.
91
- * @throws after disposing startup resources; cleanup failures retain the original error.
92
- */
93
- export declare function runProfile(options: RunProfileOptions): Promise<{
94
- ctx: Context;
95
- shutdown: ProcessShutdown;
96
- }>;
97
- //# sourceMappingURL=profile-boot.d.ts.map
@@ -1,19 +0,0 @@
1
- /** Save original startup diagnostics while keeping the terminal report concise. */
2
- import type { StartupError } from '@twinsearth/dsh-app-boot';
3
- /** Launcher-owned context; no environment values or plugin configurations are collected. */
4
- interface StartupDiagnosticContext {
5
- home: string;
6
- version: string;
7
- profile: string;
8
- }
9
- /**
10
- * Print the startup summary and save a private, uniquely named report under DSH_HOME/logs.
11
- * Failed writes print the complete report to stderr instead of claiming a saved path.
12
- * @param error - startup audit failure retaining plugin metadata and original errors.
13
- * @param context - resolved Harness home, application version, and selected profile.
14
- * @param write - terminal output sink; awaited before returning, defaults to stderr.
15
- * @returns after saving or printing the report and completing terminal writes.
16
- */
17
- export declare function reportStartupFailure(error: StartupError, context: StartupDiagnosticContext, write?: (text: string) => void | Promise<void>): Promise<void>;
18
- export {};
19
- //# sourceMappingURL=startup-diagnostics.d.ts.map