dsh-plugin-wsl-env 0.25.0 → 0.26.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.
Files changed (70) hide show
  1. package/CHANGELOG.md +142 -0
  2. package/CODE_OF_CONDUCT.md +85 -0
  3. package/CODE_OF_CONDUCT.zh.md +85 -0
  4. package/CONTRIBUTING.md +19 -3
  5. package/CONTRIBUTING.zh.md +200 -0
  6. package/README.md +55 -149
  7. package/SECURITY.md +2 -0
  8. package/SECURITY.zh.md +108 -0
  9. package/SUPPORT.md +4 -2
  10. package/SUPPORT.zh.md +99 -0
  11. package/client.js +409 -8
  12. package/cordis.patch.yml +13 -0
  13. package/docs/AGENT-PROTOCOL-V7.md +2 -2
  14. package/docs/API.md +2 -0
  15. package/docs/API.zh.md +38 -0
  16. package/docs/ARCHITECTURE.md +15 -4
  17. package/docs/ARCHITECTURE.zh.md +518 -0
  18. package/docs/COMPATIBILITY.md +2 -0
  19. package/docs/COMPATIBILITY.zh.md +117 -0
  20. package/docs/CONFIGURATION.md +7 -10
  21. package/docs/CONFIGURATION.zh.md +7 -9
  22. package/docs/DIAGNOSTICS.md +24 -0
  23. package/docs/DIAGNOSTICS.zh.md +13 -0
  24. package/docs/LIMITATIONS.md +43 -5
  25. package/docs/LIMITATIONS.zh.md +34 -6
  26. package/docs/MIGRATION.md +10 -4
  27. package/docs/MIGRATION.zh.md +94 -0
  28. package/docs/PEER-PARITY.md +75 -47
  29. package/docs/PERFORMANCE.md +2 -0
  30. package/docs/PERFORMANCE.zh.md +59 -0
  31. package/docs/QUICKSTART.md +29 -15
  32. package/docs/QUICKSTART.zh.md +25 -17
  33. package/docs/README.zh.md +69 -150
  34. package/docs/RELEASING.md +4 -3
  35. package/docs/REQUIREMENTS.zh.md +4 -2
  36. package/docs/ROADMAP-1.0.md +2 -2
  37. package/docs/UPSTREAM-FILE-REFERENCE-SEAM.md +1 -1
  38. package/docs/UPSTREAM-OPEN-IN-APP.md +33 -11
  39. package/docs/UPSTREAM-SESSION-NOTICE.md +7 -0
  40. package/docs/VALUE.md +173 -0
  41. package/docs/VALUE.zh.md +42 -13
  42. package/docs/screenshots/with-plugin.png +0 -0
  43. package/docs/screenshots/with-plugin.svg +59 -0
  44. package/docs/screenshots/with-plugin.zh.png +0 -0
  45. package/docs/screenshots/with-plugin.zh.svg +56 -0
  46. package/docs/screenshots/without-plugin.png +0 -0
  47. package/docs/screenshots/without-plugin.svg +50 -0
  48. package/docs/screenshots/without-plugin.zh.png +0 -0
  49. package/docs/screenshots/without-plugin.zh.svg +45 -0
  50. package/lib/auto-preset-seam.d.ts +45 -0
  51. package/lib/auto-preset-seam.js +47 -0
  52. package/lib/auto-preset.d.ts +33 -10
  53. package/lib/auto-preset.js +148 -44
  54. package/lib/doctor-live.d.ts +30 -0
  55. package/lib/doctor-live.js +37 -0
  56. package/lib/doctor-report.js +10 -3
  57. package/lib/messages.d.ts +19 -0
  58. package/lib/messages.js +28 -0
  59. package/lib/open-in-app.d.ts +206 -0
  60. package/lib/open-in-app.js +300 -0
  61. package/lib/peer-versions.d.ts +53 -0
  62. package/lib/peer-versions.js +137 -0
  63. package/lib/preset-choice.d.ts +13 -0
  64. package/lib/preset-choice.js +18 -1
  65. package/lib/status.js +2 -1
  66. package/lib/update-check.d.ts +2 -2
  67. package/lib/update-check.js +2 -2
  68. package/lib/wsl-doctor-command.js +4 -2
  69. package/package.json +55 -25
  70. package/scripts/doctor.mjs +127 -9
@@ -0,0 +1,206 @@
1
+ /**
2
+ * Durable replacement for the local `app.asar` patch this repository used to
3
+ * carry around the host's "Open in app" launcher.
4
+ *
5
+ * Two independent defects made that patch necessary. The first is scrubbed from
6
+ * this route's editor child only; the shipped launcher still inherits it. The
7
+ * second is fixed here without touching the installed archive:
8
+ *
9
+ * 1. The Desktop Host runs with `ELECTRON_RUN_AS_NODE=1`; the host
10
+ * launcher (`@deepseek-ai/dsh-host-open-in-app`) copies the parent
11
+ * environment through `scrubbedParentEnv()`, which does not drop that
12
+ * name. An Electron editor therefore starts as plain Node, exits 1 and
13
+ * the route answers `launch-failed`. The row scrubs the name from the
14
+ * **editor child's** environment only. Editing the Host environment would
15
+ * do the same for every later child, including Node-mode helpers such as
16
+ * the Windows Job runner, which legitimately inherit it and then fail to
17
+ * start.
18
+ * 2. An Electron editor launched with a WSL UNC workspace opens the folder
19
+ * through the 9p share (Windows terminal, Windows extensions). The
20
+ * earlier patch rewrote the argument to `--folder-uri` and landed in
21
+ * Remote-WSL. The same conversion is offered here as an authenticated
22
+ * `POST /api/wsl-env/open-in-app` route; the browser's session-header
23
+ * menu calls it. The route refuses anything that is not a WSL UNC path,
24
+ * so it cannot launch an editor for an arbitrary path.
25
+ *
26
+ * The route is registered on the Host connection's authenticated exact-Fetch
27
+ * channel (the same channel as this plugin's status route), so only the owner
28
+ * browser reaches it. A composition without `connection` leaves the route
29
+ * unregistered; the child environment is only built when a launch happens.
30
+ *
31
+ * This is a TypeScript source built to `lib/open-in-app.js`; edit THIS file and
32
+ * run `pnpm run build` — the artifact under `lib/` is generated, and
33
+ * `pnpm test` fails when it drifts.
34
+ *
35
+ * @module dsh-plugin-wsl-env/open-in-app
36
+ */
37
+ import { spawn } from "node:child_process";
38
+ import z from "@deepseek-ai/schemastery";
39
+ /** The composition row's plugin name. */
40
+ export declare const name = "wsl-open-in-app";
41
+ /** The authenticated route the session-header menu posts to. */
42
+ export declare const OPEN_IN_APP_PATH = "/api/wsl-env/open-in-app";
43
+ export declare const Config: z<Schemastery.ObjectS<NoInfer<{
44
+ /**
45
+ * Editor executable to launch. Empty resolves VS Code from its usual
46
+ * Windows install locations, then falls back to `Code.exe` on PATH.
47
+ */
48
+ executable: z<string, string, "defined">;
49
+ /** Early-failure watch window per launch, in milliseconds. */
50
+ watchMs: z<number, number, "defined">;
51
+ }>>, Schemastery.ObjectT<NoInfer<{
52
+ /**
53
+ * Editor executable to launch. Empty resolves VS Code from its usual
54
+ * Windows install locations, then falls back to `Code.exe` on PATH.
55
+ */
56
+ executable: z<string, string, "defined">;
57
+ /** Early-failure watch window per launch, in milliseconds. */
58
+ watchMs: z<number, number, "defined">;
59
+ }>>, "plain">;
60
+ /** The config schema's validated output. */
61
+ export interface OpenInAppConfig {
62
+ /** Editor executable, or empty for the normal Windows lookup. */
63
+ executable?: string;
64
+ /** Early-failure watch window per launch, in milliseconds. */
65
+ watchMs?: number;
66
+ }
67
+ /** How one detached launch ended. */
68
+ export type LaunchOutcome = "launched" | "missing" | "failed";
69
+ /** The environment shape the pure helpers read. */
70
+ type Environment = Readonly<Record<string, string | undefined>>;
71
+ /** Options for one detached launch. */
72
+ export interface LaunchOptions {
73
+ /** Early-failure watch window, in milliseconds. */
74
+ watchMs: number;
75
+ /** Complete child environment; already scrubbed by the caller. */
76
+ env: NodeJS.ProcessEnv;
77
+ }
78
+ /**
79
+ * Convert a WSL UNC workspace to the `vscode-remote` URI Remote-WSL expects.
80
+ *
81
+ * Both share spellings (`\\wsl.localhost\<distro>\...` and
82
+ * `\\wsl$\<distro>\...`) are accepted; every other path is refused rather
83
+ * than guessed at.
84
+ *
85
+ * @param uncPath - candidate workspace path.
86
+ * @returns the editor URI, or undefined when the path is not WSL UNC or
87
+ * cannot be encoded (a path with malformed UTF-16 is not a workspace).
88
+ */
89
+ export declare function editorUri(uncPath: string): string | undefined;
90
+ /**
91
+ * The editor executables this machine is likely to carry, in preference order.
92
+ *
93
+ * @param env - environment carrying the Windows install roots.
94
+ * @returns absolute candidate paths; empty when no root is named.
95
+ */
96
+ export declare function editorCandidates(env: Environment): string[];
97
+ /**
98
+ * Resolve the editor executable: an explicit config value wins; otherwise the
99
+ * first existing install candidate; otherwise the PATH name `Code.exe`.
100
+ *
101
+ * @param config - this row's config.
102
+ * @param env - environment carrying the install roots.
103
+ * @param exists - existence check, injected for tests.
104
+ * @returns the command to spawn.
105
+ */
106
+ export declare function resolveEditor(config: OpenInAppConfig, env: Environment, exists?: (path: string) => boolean): string;
107
+ /**
108
+ * Remove `ELECTRON_RUN_AS_NODE` from an environment object, in place.
109
+ *
110
+ * Callers pass the editor child's environment copy, never the Host process
111
+ * environment: a Host-wide deletion breaks Node-mode helpers that inherit it.
112
+ *
113
+ * @param env - environment to clean, in place.
114
+ * @returns true when the name was present.
115
+ */
116
+ export declare function dropElectronRunAsNode(env: NodeJS.ProcessEnv): boolean;
117
+ /**
118
+ * The child environment for one editor launch: the Host environment with
119
+ * `ELECTRON_RUN_AS_NODE` removed. The deletion is scoped to this child;
120
+ * editing the Host's own environment would break Node-mode helpers (the
121
+ * Windows Job runner, for one) that legitimately inherit the flag.
122
+ *
123
+ * @param env - source environment; defaults to the current process environment.
124
+ * @returns a fresh environment safe to hand to an Electron editor.
125
+ */
126
+ export declare function launchEnvironment(env?: NodeJS.ProcessEnv): NodeJS.ProcessEnv;
127
+ /**
128
+ * Launch one detached editor through a `--folder-uri` argument and classify
129
+ * an early failure.
130
+ *
131
+ * Success is decoupled from process lifetime, mirroring the host launcher: a
132
+ * child still running when the watch window closes counts as launched (an
133
+ * existing editor window may keep the process in the foreground), exit code 0
134
+ * inside the window counts as launched, and a nonzero exit, a spawn error or
135
+ * a synchronous spawn throw is a failure.
136
+ *
137
+ * @param command - executable path or PATH name.
138
+ * @param args - argv, never a shell string.
139
+ * @param options - watch window and complete child environment.
140
+ * @param spawnChild - spawn seam, injected for tests.
141
+ * @returns the classified outcome.
142
+ */
143
+ export declare function launchDetached(command: string, args: readonly string[], options: LaunchOptions, spawnChild?: typeof spawn): Promise<LaunchOutcome>;
144
+ /** The launch seam the handler calls. */
145
+ export interface OpenInAppDeps {
146
+ /** Launch one editor URI and report how the attempt ended. */
147
+ launch: (uri: string) => Promise<LaunchOutcome>;
148
+ }
149
+ /**
150
+ * The route handler: validate one POST body and launch the editor for its WSL
151
+ * workspace. Only a `\\wsl...` UNC path is accepted; the route never launches
152
+ * for a Windows or POSIX path.
153
+ *
154
+ * @param deps - the launch seam.
155
+ * @returns the exact-Fetch handler.
156
+ */
157
+ export declare function createOpenInAppHandler(deps: OpenInAppDeps): (request: Request) => Promise<Response>;
158
+ /** One exact route's registration shape. */
159
+ interface ConnectionRoute {
160
+ readonly path: string;
161
+ readonly methods: readonly string[];
162
+ readonly requestBody: "buffered" | "streaming";
163
+ readonly fetch: (request: Request) => Promise<Response>;
164
+ }
165
+ /** The connection slice this row registers into. */
166
+ interface ConnectionFace {
167
+ /** The exact-Fetch route registry. */
168
+ readonly fetch: {
169
+ /** Register one exact route; the returned disposer withdraws it. */
170
+ register: (route: ConnectionRoute) => () => Promise<void> | void;
171
+ };
172
+ }
173
+ /** The context slice this row consumes; the seams keep it boot-free in tests. */
174
+ interface OpenInAppContext {
175
+ /** Optional cordis-style lookup: how production resolves the connection. */
176
+ get?: (name: string) => unknown;
177
+ /** Wait for a service, then run the callback in its scope. */
178
+ inject?: (deps: readonly string[], callback: (scope: OpenInAppContext) => void) => unknown;
179
+ /** Own one disposer on the calling fiber. */
180
+ effect?: (callback: () => () => void, label?: string) => unknown;
181
+ /** The Host connection whose `/api` channel carries the route. */
182
+ connection?: ConnectionFace;
183
+ }
184
+ /**
185
+ * Build the launch seam for one row: resolve the editor once, scrub the child
186
+ * environment once, and hand every call to {@link launchDetached}.
187
+ *
188
+ * The factory exists so a test can observe the exact argv, the detachment
189
+ * flags and the child environment the row produces without starting an editor.
190
+ *
191
+ * @param config - this row's config.
192
+ * @param env - source environment; defaults to the current process environment.
193
+ * @param spawnChild - spawn seam, injected for tests.
194
+ * @returns the launch seam {@link createOpenInAppHandler} calls.
195
+ */
196
+ export declare function createLauncher(config: OpenInAppConfig, env?: NodeJS.ProcessEnv, spawnChild?: typeof spawn): (uri: string) => Promise<LaunchOutcome>;
197
+ /**
198
+ * Mount the row: register the route once the Host connection is available.
199
+ * The route scrubs `ELECTRON_RUN_AS_NODE` from each editor child's environment
200
+ * without touching the Host process environment.
201
+ *
202
+ * @param ctx - the cordis context.
203
+ * @param config - the schema-validated config.
204
+ */
205
+ export declare function apply(ctx: OpenInAppContext, config?: OpenInAppConfig): void;
206
+ export {};
@@ -0,0 +1,300 @@
1
+ /**
2
+ * Durable replacement for the local `app.asar` patch this repository used to
3
+ * carry around the host's "Open in app" launcher.
4
+ *
5
+ * Two independent defects made that patch necessary. The first is scrubbed from
6
+ * this route's editor child only; the shipped launcher still inherits it. The
7
+ * second is fixed here without touching the installed archive:
8
+ *
9
+ * 1. The Desktop Host runs with `ELECTRON_RUN_AS_NODE=1`; the host
10
+ * launcher (`@deepseek-ai/dsh-host-open-in-app`) copies the parent
11
+ * environment through `scrubbedParentEnv()`, which does not drop that
12
+ * name. An Electron editor therefore starts as plain Node, exits 1 and
13
+ * the route answers `launch-failed`. The row scrubs the name from the
14
+ * **editor child's** environment only. Editing the Host environment would
15
+ * do the same for every later child, including Node-mode helpers such as
16
+ * the Windows Job runner, which legitimately inherit it and then fail to
17
+ * start.
18
+ * 2. An Electron editor launched with a WSL UNC workspace opens the folder
19
+ * through the 9p share (Windows terminal, Windows extensions). The
20
+ * earlier patch rewrote the argument to `--folder-uri` and landed in
21
+ * Remote-WSL. The same conversion is offered here as an authenticated
22
+ * `POST /api/wsl-env/open-in-app` route; the browser's session-header
23
+ * menu calls it. The route refuses anything that is not a WSL UNC path,
24
+ * so it cannot launch an editor for an arbitrary path.
25
+ *
26
+ * The route is registered on the Host connection's authenticated exact-Fetch
27
+ * channel (the same channel as this plugin's status route), so only the owner
28
+ * browser reaches it. A composition without `connection` leaves the route
29
+ * unregistered; the child environment is only built when a launch happens.
30
+ *
31
+ * This is a TypeScript source built to `lib/open-in-app.js`; edit THIS file and
32
+ * run `pnpm run build` — the artifact under `lib/` is generated, and
33
+ * `pnpm test` fails when it drifts.
34
+ *
35
+ * @module dsh-plugin-wsl-env/open-in-app
36
+ */
37
+ import { spawn } from "node:child_process";
38
+ import { existsSync } from "node:fs";
39
+ import { join } from "node:path";
40
+ import z from "@deepseek-ai/schemastery";
41
+ import { uncToPosix } from "./paths.js";
42
+ /** The composition row's plugin name. */
43
+ export const name = "wsl-open-in-app";
44
+ /** The authenticated route the session-header menu posts to. */
45
+ export const OPEN_IN_APP_PATH = "/api/wsl-env/open-in-app";
46
+ export const Config = z.object({
47
+ /**
48
+ * Editor executable to launch. Empty resolves VS Code from its usual
49
+ * Windows install locations, then falls back to `Code.exe` on PATH.
50
+ */
51
+ executable: z.string().default(""),
52
+ /** Early-failure watch window per launch, in milliseconds. */
53
+ watchMs: z.natural().min(1).default(1_500),
54
+ });
55
+ /**
56
+ * Convert a WSL UNC workspace to the `vscode-remote` URI Remote-WSL expects.
57
+ *
58
+ * Both share spellings (`\\wsl.localhost\<distro>\...` and
59
+ * `\\wsl$\<distro>\...`) are accepted; every other path is refused rather
60
+ * than guessed at.
61
+ *
62
+ * @param uncPath - candidate workspace path.
63
+ * @returns the editor URI, or undefined when the path is not WSL UNC or
64
+ * cannot be encoded (a path with malformed UTF-16 is not a workspace).
65
+ */
66
+ export function editorUri(uncPath) {
67
+ const target = uncToPosix(uncPath);
68
+ if (target === undefined)
69
+ return undefined;
70
+ try {
71
+ const encodedPath = target.linuxPath
72
+ .split("/")
73
+ .map((segment) => encodeURIComponent(segment))
74
+ .join("/");
75
+ const path = encodedPath.startsWith("/") ? encodedPath : `/${encodedPath}`;
76
+ return `vscode-remote://wsl%2B${encodeURIComponent(target.distro)}${path}`;
77
+ }
78
+ catch {
79
+ // `encodeURIComponent` throws URIError on a lone surrogate. The route must
80
+ // answer a classified 400, not reject the request, for such a body.
81
+ return undefined;
82
+ }
83
+ }
84
+ /**
85
+ * The editor executables this machine is likely to carry, in preference order.
86
+ *
87
+ * @param env - environment carrying the Windows install roots.
88
+ * @returns absolute candidate paths; empty when no root is named.
89
+ */
90
+ export function editorCandidates(env) {
91
+ const candidates = [];
92
+ const local = env.LOCALAPPDATA;
93
+ const programFiles = env.ProgramFiles;
94
+ const programFilesX86 = env["ProgramFiles(x86)"];
95
+ if (local !== undefined && local.length > 0) {
96
+ candidates.push(join(local, "Programs", "Microsoft VS Code", "Code.exe"));
97
+ candidates.push(join(local, "Programs", "Microsoft VS Code Insiders", "Code - Insiders.exe"));
98
+ candidates.push(join(local, "Programs", "cursor", "Cursor.exe"));
99
+ }
100
+ if (programFiles !== undefined && programFiles.length > 0) {
101
+ candidates.push(join(programFiles, "Microsoft VS Code", "Code.exe"));
102
+ }
103
+ if (programFilesX86 !== undefined && programFilesX86.length > 0) {
104
+ candidates.push(join(programFilesX86, "Microsoft VS Code", "Code.exe"));
105
+ }
106
+ return candidates;
107
+ }
108
+ /**
109
+ * Resolve the editor executable: an explicit config value wins; otherwise the
110
+ * first existing install candidate; otherwise the PATH name `Code.exe`.
111
+ *
112
+ * @param config - this row's config.
113
+ * @param env - environment carrying the install roots.
114
+ * @param exists - existence check, injected for tests.
115
+ * @returns the command to spawn.
116
+ */
117
+ export function resolveEditor(config, env, exists = existsSync) {
118
+ const configured = (config.executable ?? "").trim();
119
+ if (configured.length > 0)
120
+ return configured;
121
+ for (const candidate of editorCandidates(env)) {
122
+ if (exists(candidate))
123
+ return candidate;
124
+ }
125
+ return "Code.exe";
126
+ }
127
+ /**
128
+ * Remove `ELECTRON_RUN_AS_NODE` from an environment object, in place.
129
+ *
130
+ * Callers pass the editor child's environment copy, never the Host process
131
+ * environment: a Host-wide deletion breaks Node-mode helpers that inherit it.
132
+ *
133
+ * @param env - environment to clean, in place.
134
+ * @returns true when the name was present.
135
+ */
136
+ export function dropElectronRunAsNode(env) {
137
+ if (env.ELECTRON_RUN_AS_NODE === undefined)
138
+ return false;
139
+ delete env.ELECTRON_RUN_AS_NODE;
140
+ return true;
141
+ }
142
+ /**
143
+ * The child environment for one editor launch: the Host environment with
144
+ * `ELECTRON_RUN_AS_NODE` removed. The deletion is scoped to this child;
145
+ * editing the Host's own environment would break Node-mode helpers (the
146
+ * Windows Job runner, for one) that legitimately inherit the flag.
147
+ *
148
+ * @param env - source environment; defaults to the current process environment.
149
+ * @returns a fresh environment safe to hand to an Electron editor.
150
+ */
151
+ export function launchEnvironment(env = process.env) {
152
+ const copy = { ...env };
153
+ dropElectronRunAsNode(copy);
154
+ return copy;
155
+ }
156
+ /**
157
+ * Launch one detached editor through a `--folder-uri` argument and classify
158
+ * an early failure.
159
+ *
160
+ * Success is decoupled from process lifetime, mirroring the host launcher: a
161
+ * child still running when the watch window closes counts as launched (an
162
+ * existing editor window may keep the process in the foreground), exit code 0
163
+ * inside the window counts as launched, and a nonzero exit, a spawn error or
164
+ * a synchronous spawn throw is a failure.
165
+ *
166
+ * @param command - executable path or PATH name.
167
+ * @param args - argv, never a shell string.
168
+ * @param options - watch window and complete child environment.
169
+ * @param spawnChild - spawn seam, injected for tests.
170
+ * @returns the classified outcome.
171
+ */
172
+ export function launchDetached(command, args, options, spawnChild = spawn) {
173
+ return new Promise((resolve) => {
174
+ let child;
175
+ try {
176
+ child = spawnChild(command, [...args], {
177
+ detached: true,
178
+ stdio: "ignore",
179
+ windowsHide: false,
180
+ env: options.env,
181
+ });
182
+ }
183
+ catch {
184
+ resolve("failed");
185
+ return;
186
+ }
187
+ let settled = false;
188
+ const settle = (outcome) => {
189
+ if (settled)
190
+ return;
191
+ settled = true;
192
+ clearTimeout(watch);
193
+ child.unref();
194
+ resolve(outcome);
195
+ };
196
+ const watch = setTimeout(() => { settle("launched"); }, options.watchMs);
197
+ child.once("error", (error) => {
198
+ settle(error.code === "ENOENT" ? "missing" : "failed");
199
+ });
200
+ child.once("exit", (code) => { settle(code === 0 ? "launched" : "failed"); });
201
+ });
202
+ }
203
+ /** JSON response with no-store caching. */
204
+ function json(payload, status = 200) {
205
+ return new Response(JSON.stringify(payload), {
206
+ status,
207
+ headers: { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" },
208
+ });
209
+ }
210
+ /**
211
+ * The route handler: validate one POST body and launch the editor for its WSL
212
+ * workspace. Only a `\\wsl...` UNC path is accepted; the route never launches
213
+ * for a Windows or POSIX path.
214
+ *
215
+ * @param deps - the launch seam.
216
+ * @returns the exact-Fetch handler.
217
+ */
218
+ export function createOpenInAppHandler(deps) {
219
+ return async (request) => {
220
+ if (request.method !== "POST")
221
+ return json({ error: "只支持 POST" }, 405);
222
+ const essence = request.headers.get("content-type")?.split(";", 1)[0]?.trim().toLowerCase();
223
+ if (essence !== "application/json")
224
+ return json({ error: "content-type 必须是 application/json" }, 415);
225
+ let body;
226
+ try {
227
+ body = await request.json();
228
+ }
229
+ catch {
230
+ return json({ error: "请求体不是合法 JSON" }, 400);
231
+ }
232
+ if (typeof body !== "object" || body === null)
233
+ return json({ error: "请求体必须是对象" }, 400);
234
+ const path = body.path;
235
+ if (typeof path !== "string")
236
+ return json({ error: "path 必须是字符串" }, 400);
237
+ const uri = editorUri(path);
238
+ if (uri === undefined)
239
+ return json({ error: "不是 WSL 工作区路径" }, 400);
240
+ let outcome;
241
+ try {
242
+ outcome = await deps.launch(uri);
243
+ }
244
+ catch {
245
+ // The launcher is a seam: a rejected promise must become a classified
246
+ // failure, not an unhandled rejection inside the route.
247
+ return json({ error: "VS Code 启动失败" }, 502);
248
+ }
249
+ if (outcome === "launched")
250
+ return json({ ok: true, uri });
251
+ return json({
252
+ error: outcome === "missing"
253
+ ? "找不到 VS Code;可在 wsl-open-in-app 行配置 executable"
254
+ : "VS Code 启动失败",
255
+ }, 502);
256
+ };
257
+ }
258
+ /**
259
+ * Build the launch seam for one row: resolve the editor once, scrub the child
260
+ * environment once, and hand every call to {@link launchDetached}.
261
+ *
262
+ * The factory exists so a test can observe the exact argv, the detachment
263
+ * flags and the child environment the row produces without starting an editor.
264
+ *
265
+ * @param config - this row's config.
266
+ * @param env - source environment; defaults to the current process environment.
267
+ * @param spawnChild - spawn seam, injected for tests.
268
+ * @returns the launch seam {@link createOpenInAppHandler} calls.
269
+ */
270
+ export function createLauncher(config, env = process.env, spawnChild = spawn) {
271
+ const childEnvironment = launchEnvironment(env);
272
+ const executable = resolveEditor(config, childEnvironment);
273
+ const watchMs = config.watchMs ?? 1_500;
274
+ return (uri) => launchDetached(executable, ["--folder-uri", uri], { watchMs, env: childEnvironment }, spawnChild);
275
+ }
276
+ /**
277
+ * Mount the row: register the route once the Host connection is available.
278
+ * The route scrubs `ELECTRON_RUN_AS_NODE` from each editor child's environment
279
+ * without touching the Host process environment.
280
+ *
281
+ * @param ctx - the cordis context.
282
+ * @param config - the schema-validated config.
283
+ */
284
+ export function apply(ctx, config = {}) {
285
+ if (typeof ctx.inject !== "function")
286
+ return;
287
+ ctx.inject(["connection"], (scope) => {
288
+ const connection = scope.connection ?? scope.get?.("connection");
289
+ if (connection === undefined)
290
+ return;
291
+ const handler = createOpenInAppHandler({ launch: createLauncher(config) });
292
+ const dispose = connection.fetch.register({
293
+ path: OPEN_IN_APP_PATH,
294
+ methods: ["POST"],
295
+ requestBody: "buffered",
296
+ fetch: handler,
297
+ });
298
+ scope.effect?.(() => () => { void dispose(); }, `wsl-open-in-app: ${OPEN_IN_APP_PATH}`);
299
+ });
300
+ }
@@ -0,0 +1,53 @@
1
+ /** The private env contract between an in-app spawner and `scripts/doctor.mjs`. */
2
+ export declare const DOCTOR_PEERS_ENV = "DSH_WSL_DOCTOR_PEERS";
3
+ /**
4
+ * The version declared by the nearest `package.json` above a resolved file.
5
+ *
6
+ * Exported for the coverage suite: the walk's two failure arms (a malformed
7
+ * manifest, and the filesystem root) are not reachable with real peers.
8
+ * @param file - one resolved module file.
9
+ * @returns the version, or undefined when no readable manifest declares one.
10
+ */
11
+ export declare function versionAbove(file: string): string | undefined;
12
+ /**
13
+ * Resolve one peer's version the way this process loads it.
14
+ *
15
+ * Exported for the coverage suite: a peer that does not export
16
+ * `./package.json` exercises the entry-file fallback.
17
+ *
18
+ * `require.resolve` runs through the host's profile resolution when there is
19
+ * one, so a linked plugin sees the installation's copies and a plain process
20
+ * sees whatever `node_modules` it would actually import. The package's
21
+ * `./package.json` export is preferred because it names the version directly;
22
+ * a package that does not export it still resolves by its entry file.
23
+ *
24
+ * @param require - the anchored resolver.
25
+ * @param name - the peer package.
26
+ * @returns the resolved version, or undefined when the peer is absent.
27
+ */
28
+ export declare function resolvedPeerVersion(require: NodeJS.Require, name: string): string | undefined;
29
+ /**
30
+ * The peer versions this process resolves.
31
+ *
32
+ * Deliberately uncached: a harness upgrade or a plugin-manager reload changes
33
+ * the answer, and one doctor spawn costs one small resolve per peer.
34
+ *
35
+ * @returns a name → version map; empty when the manifest or the peers are
36
+ * unreadable.
37
+ */
38
+ export declare function resolvedPeerVersions(): Record<string, string>;
39
+ /**
40
+ * Overlay the resolved peer set on one doctor child environment.
41
+ *
42
+ * The variable is set even when the map is empty: its **presence** is what
43
+ * tells the doctor that an in-app process already attempted resolution, so a
44
+ * peer missing from the map means "the host could not resolve it" and must be
45
+ * reported as unchecked — not looked up again in the plugin's physical tree,
46
+ * which may hold a stale copy. Absent means the standalone CLI, which has no
47
+ * host resolution and keeps its own lookup.
48
+ *
49
+ * @param env - the base environment (normally a copy of `process.env`).
50
+ * @param versions - the map; defaults to {@link resolvedPeerVersions}.
51
+ * @returns the child environment to spawn with.
52
+ */
53
+ export declare function withHostPeerVersions(env: NodeJS.ProcessEnv, versions?: Record<string, string>): NodeJS.ProcessEnv;