@effected/engine 0.3.0 → 0.4.0

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,145 @@
1
+ //#region src/ProcessGuard.ts
2
+ const isInjectedKind = (kind) => kind === "uncaughtException" || kind === "unhandledRejection";
3
+ const INJECT_AT = ["load", "connected"];
4
+ const INJECT_KIND = ["uncaughtException", "unhandledRejection"];
5
+ /** Emit one injected crash through the host, to the listeners the guard installed there. */
6
+ const emitInjected = (host, kind) => {
7
+ const error = /* @__PURE__ */ new Error(`[injected] ${kind}`);
8
+ if (kind === "uncaughtException") {
9
+ host.emit("uncaughtException", error, "uncaughtException");
10
+ return;
11
+ }
12
+ const promise = Promise.reject(error);
13
+ promise.catch(() => void 0);
14
+ host.emit("unhandledRejection", error, promise);
15
+ };
16
+ const fallbackFormat = (error) => error instanceof Error ? error.stack ?? error.message : String(error);
17
+ /**
18
+ * Transport-neutral crash guards for a server process, installed before the
19
+ * server's module graph loads. Imported from `@effected/engine/guard`.
20
+ *
21
+ * @remarks
22
+ * {@link ProcessGuard.run} registers `uncaughtException` and
23
+ * `unhandledRejection` listeners on `host`, then awaits `load`. It launches
24
+ * nothing itself: `load` starts the server, over whatever transport, and
25
+ * calls `markConnected` once it is serving. `@effected/mcp/guard`'s
26
+ * `McpGuard.run` is this guard with an MCP stdio launch in its `load`.
27
+ *
28
+ * - This entrypoint has no runtime import at all, so a throw while the
29
+ * server graph evaluates is still reported on stderr.
30
+ * - A `load` that rejects is reported as `startup failed` and exits 1
31
+ * whatever the policy. Left to a log-only rejection listener, it would let
32
+ * the event loop drain and exit 0 with no server.
33
+ * - Installing an `unhandledRejection` listener switches off Node's default
34
+ * of throwing on one, so `"log"` really does keep the process running.
35
+ * - An exit from a guard skips every finalizer the server registered.
36
+ * - Every report is one line: `<label>: uncaughtException (<origin>): …`,
37
+ * `<label>: unhandledRejection: …` or `<label>: startup failed: …`.
38
+ *
39
+ * @example
40
+ * ```ts
41
+ * import { ProcessGuard } from "@effected/engine/guard";
42
+ *
43
+ * await ProcessGuard.run({
44
+ * label: "my-lsp",
45
+ * host: process,
46
+ * policy: { onUncaught: "exitBeforeConnect", onRejection: "log" },
47
+ * load: async (guard) => {
48
+ * const { startServer } = await import("./server.js");
49
+ * await startServer();
50
+ * guard.markConnected();
51
+ * },
52
+ * });
53
+ * ```
54
+ *
55
+ * @public
56
+ */
57
+ var ProcessGuard = class {
58
+ constructor() {}
59
+ /**
60
+ * Parse a test-only crash-injection setting into {@link ProcessGuardOptions.injectCrash}: `<at>:<kind>`, where `at`
61
+ * is `"load"` or `"connected"` and `kind` is `"uncaughtException"` or `"unhandledRejection"`. Anything else, or no
62
+ * value, is `undefined` (no injection), so a launcher can pass an environment variable straight through and every
63
+ * launcher shares one grammar.
64
+ *
65
+ * @example
66
+ * ```ts
67
+ * ProcessGuard.parseInjectCrash("connected:unhandledRejection"); // => { at: "connected", kind: "unhandledRejection" }
68
+ * ProcessGuard.parseInjectCrash("later:boom"); // => undefined
69
+ * ```
70
+ */
71
+ static parseInjectCrash = (value) => {
72
+ if (value === void 0) return void 0;
73
+ const [at, kind, ...rest] = value.split(":");
74
+ if (rest.length > 0) return void 0;
75
+ const validAt = INJECT_AT.find((candidate) => candidate === at);
76
+ const validKind = INJECT_KIND.find((candidate) => candidate === kind);
77
+ return validAt === void 0 || validKind === void 0 ? void 0 : {
78
+ at: validAt,
79
+ kind: validKind
80
+ };
81
+ };
82
+ /** Install the guards, then run `load`. Resolves once `load` has resolved. */
83
+ static run = async (options) => {
84
+ const { host, label } = options;
85
+ const onUncaught = options.policy?.onUncaught ?? "exit";
86
+ const onRejection = options.policy?.onRejection ?? "exit";
87
+ let connected = false;
88
+ let format = fallbackFormat;
89
+ const describe = (error) => {
90
+ try {
91
+ return format(error);
92
+ } catch {
93
+ try {
94
+ return fallbackFormat(error);
95
+ } catch {
96
+ return "<unformattable error value>";
97
+ }
98
+ }
99
+ };
100
+ const exits = (mode) => mode === "exit" || mode === "exitBeforeConnect" && !connected;
101
+ host.on("uncaughtException", (error, origin) => {
102
+ host.stderr.write(`${label}: uncaughtException (${origin}): ${describe(error)}\n`);
103
+ if (exits(onUncaught)) host.exit(1);
104
+ });
105
+ host.on("unhandledRejection", (reason) => {
106
+ host.stderr.write(`${label}: unhandledRejection: ${describe(reason)}\n`);
107
+ if (exits(onRejection)) host.exit(1);
108
+ });
109
+ const inject = options.injectCrash;
110
+ const injectKind = isInjectedKind(inject?.kind) ? inject.kind : void 0;
111
+ if (inject?.at === "load" && injectKind !== void 0) await new Promise((resolve, reject) => {
112
+ setTimeout(() => {
113
+ try {
114
+ emitInjected(host, injectKind);
115
+ resolve();
116
+ } catch (error) {
117
+ reject(error);
118
+ }
119
+ }, 0);
120
+ });
121
+ const control = {
122
+ markConnected: () => {
123
+ if (connected) return;
124
+ connected = true;
125
+ if (inject?.at === "connected" && injectKind !== void 0) setTimeout(() => {
126
+ try {
127
+ emitInjected(host, injectKind);
128
+ } catch {}
129
+ }, 0);
130
+ },
131
+ useFormat: (next) => {
132
+ format = next;
133
+ }
134
+ };
135
+ try {
136
+ await options.load(control);
137
+ } catch (error) {
138
+ host.stderr.write(`${label}: startup failed: ${describe(error)}\n`);
139
+ host.exit(1);
140
+ }
141
+ };
142
+ };
143
+
144
+ //#endregion
145
+ export { ProcessGuard };
package/guard.d.ts ADDED
@@ -0,0 +1,207 @@
1
+ //#region src/ProcessGuard.d.ts
2
+ /**
3
+ * The slice of the host process {@link ProcessGuard.run} uses. Node's
4
+ * `process` satisfies it.
5
+ *
6
+ * @remarks
7
+ * Structural on purpose: the guard never reads a global, so a test passes a
8
+ * double and a front end passes `process` from its own `main`.
9
+ *
10
+ * @public
11
+ */
12
+ interface ProcessGuardHost {
13
+ /** Register the `uncaughtException` listener. */
14
+ on(event: "uncaughtException", listener: (error: Error, origin: string) => void): unknown;
15
+ /** Register the `unhandledRejection` listener. */
16
+ on(event: "unhandledRejection", listener: (reason: unknown) => void): unknown;
17
+ /** Raise an `uncaughtException` to the registered listeners. Used only by {@link ProcessGuardOptions.injectCrash}. */
18
+ emit(event: "uncaughtException", error: Error, origin: "uncaughtException" | "unhandledRejection"): unknown;
19
+ /** Raise an `unhandledRejection` to the registered listeners. Used only by {@link ProcessGuardOptions.injectCrash}. */
20
+ emit(event: "unhandledRejection", reason: unknown, promise: Promise<unknown>): unknown;
21
+ /** Where every guard report is written. For a stdio server, never stdout: that is the protocol wire. */
22
+ readonly stderr: {
23
+ write(chunk: string): unknown;
24
+ };
25
+ /** End the process at once. */
26
+ exit(code?: number): never;
27
+ }
28
+ /**
29
+ * When a stray exception or rejection ends the process.
30
+ *
31
+ * @remarks
32
+ * `"exit"` exits 1 whenever it happens. `"exitBeforeConnect"` exits 1 until
33
+ * the caller reports the server connected with
34
+ * {@link ProcessGuardControl.markConnected}, then logs and keeps serving: a
35
+ * server that dies mid-session drops every client attached to it. `"log"`
36
+ * never exits.
37
+ *
38
+ * @public
39
+ */
40
+ interface ProcessGuardPolicy {
41
+ /** For `uncaughtException`. */
42
+ readonly onUncaught: "exit" | "exitBeforeConnect";
43
+ /** For `unhandledRejection`. Defaults to `"exit"`. */
44
+ readonly onRejection?: "exit" | "exitBeforeConnect" | "log" | undefined;
45
+ }
46
+ /**
47
+ * One crash {@link ProcessGuardOptions.injectCrash} raises: which event, and
48
+ * when.
49
+ *
50
+ * @public
51
+ */
52
+ interface ProcessGuardInjection {
53
+ /** `"load"`: before `load` is called. `"connected"`: after the first {@link ProcessGuardControl.markConnected}. */
54
+ readonly at: "load" | "connected";
55
+ /** Which event to raise. */
56
+ readonly kind: "uncaughtException" | "unhandledRejection";
57
+ }
58
+ /**
59
+ * What {@link ProcessGuardOptions.load} is handed: the two moments only the
60
+ * caller can see.
61
+ *
62
+ * @remarks
63
+ * Plain callbacks, so a caller with no Effect runtime (a
64
+ * `vscode-languageserver` server, a hand-written socket loop) uses them the
65
+ * same way an Effect launcher does: an MCP launcher passes `markConnected`
66
+ * to `McpStdio.launch`'s `onReady`; an LSP calls it once its connection is
67
+ * listening.
68
+ *
69
+ * @public
70
+ */
71
+ interface ProcessGuardControl {
72
+ /**
73
+ * Report the server connected: from here on `"exitBeforeConnect"` logs and
74
+ * keeps going. Call it once the server is serving. Later calls do nothing.
75
+ * Safe to call after `load` has resolved, which is the usual case.
76
+ *
77
+ * @remarks
78
+ * For a server framed over stdio (MCP, LSP), "serving" is the moment its
79
+ * transport is built and reading stdin, before the first request arrives:
80
+ * from then on a client is attached, and a stray error should be logged,
81
+ * not end the session.
82
+ */
83
+ readonly markConnected: () => void;
84
+ /**
85
+ * Format every report from here on with `format`, in place of the guard's
86
+ * own dependency-free formatter. A `format` that throws falls back to the
87
+ * guard's own, so a broken formatter never hides a crash.
88
+ */
89
+ readonly useFormat: (format: (error: unknown) => string) => void;
90
+ }
91
+ /**
92
+ * Options for {@link ProcessGuard.run}.
93
+ *
94
+ * @public
95
+ */
96
+ interface ProcessGuardOptions {
97
+ /** Prefixes every report the guard writes, as in `my-server: uncaughtException (…): …`. */
98
+ readonly label: string;
99
+ /** The process: pass `process`. */
100
+ readonly host: ProcessGuardHost;
101
+ /** Defaults to `{ onUncaught: "exit", onRejection: "exit" }`. */
102
+ readonly policy?: ProcessGuardPolicy | undefined;
103
+ /**
104
+ * Import, assemble and start the server. Everything that can throw while
105
+ * loading belongs here, behind a dynamic `import()`, so the guards are
106
+ * already listening when it runs. A rejection is reported as
107
+ * `startup failed` and exits 1, whatever the policy.
108
+ */
109
+ readonly load: (guard: ProcessGuardControl) => Promise<unknown>;
110
+ /**
111
+ * For a test of the guards themselves: raise one stray `kind` at `at`, so
112
+ * both halves of a policy can be driven end to end in a real process.
113
+ *
114
+ * @remarks
115
+ * - `"load"` raises it once both listeners are installed and before
116
+ * `load` is called, then waits for the guard to handle it: `load` is
117
+ * not called until the listener has run. If a test double's `exit`
118
+ * throws instead of ending the process, `run` rejects with what it
119
+ * threw and never calls `load`. The pre-connect half of the policy
120
+ * applies, so `"exitBeforeConnect"` exits 1 here, and only an
121
+ * `onRejection` of `"log"` lets the process go on to load and serve.
122
+ * The report uses the guard's own formatter, since no `useFormat` has
123
+ * run yet.
124
+ * - `"connected"` raises it after the first `markConnected`, where
125
+ * `"exitBeforeConnect"` logs and keeps serving. It is never raised if
126
+ * `markConnected` is never called. A throw from a test double's `exit`
127
+ * there is dropped.
128
+ *
129
+ * **The `"connected"` report is asynchronous.** It is raised on a later
130
+ * tick, a `setTimeout(0)` after `markConnected`, so it can land after the
131
+ * first responses the server sends: a test that reads stderr once, right
132
+ * after its first response, can see nothing. Wait for the report (with
133
+ * `McpProcess.stderrUntil` from `@effected/mcp/testing`, for an MCP
134
+ * server) rather than reading it once.
135
+ *
136
+ * Either is raised only through `host.emit`, on a `setTimeout(0)` tick,
137
+ * never as a real throw or rejection, so the guard's listeners handle it
138
+ * the same way under the real `process` and under a test double. Under
139
+ * `process`, every listener registered for the event sees it, not only
140
+ * the guard's. It carries an `[injected]` message; a rejection is emitted
141
+ * with an already-handled rejected promise. `undefined`, or an `at` or
142
+ * `kind` outside these values, does nothing at all. Wire it to an
143
+ * environment variable only a test sets.
144
+ */
145
+ readonly injectCrash?: ProcessGuardInjection | undefined;
146
+ }
147
+ /**
148
+ * Transport-neutral crash guards for a server process, installed before the
149
+ * server's module graph loads. Imported from `@effected/engine/guard`.
150
+ *
151
+ * @remarks
152
+ * {@link ProcessGuard.run} registers `uncaughtException` and
153
+ * `unhandledRejection` listeners on `host`, then awaits `load`. It launches
154
+ * nothing itself: `load` starts the server, over whatever transport, and
155
+ * calls `markConnected` once it is serving. `@effected/mcp/guard`'s
156
+ * `McpGuard.run` is this guard with an MCP stdio launch in its `load`.
157
+ *
158
+ * - This entrypoint has no runtime import at all, so a throw while the
159
+ * server graph evaluates is still reported on stderr.
160
+ * - A `load` that rejects is reported as `startup failed` and exits 1
161
+ * whatever the policy. Left to a log-only rejection listener, it would let
162
+ * the event loop drain and exit 0 with no server.
163
+ * - Installing an `unhandledRejection` listener switches off Node's default
164
+ * of throwing on one, so `"log"` really does keep the process running.
165
+ * - An exit from a guard skips every finalizer the server registered.
166
+ * - Every report is one line: `<label>: uncaughtException (<origin>): …`,
167
+ * `<label>: unhandledRejection: …` or `<label>: startup failed: …`.
168
+ *
169
+ * @example
170
+ * ```ts
171
+ * import { ProcessGuard } from "@effected/engine/guard";
172
+ *
173
+ * await ProcessGuard.run({
174
+ * label: "my-lsp",
175
+ * host: process,
176
+ * policy: { onUncaught: "exitBeforeConnect", onRejection: "log" },
177
+ * load: async (guard) => {
178
+ * const { startServer } = await import("./server.js");
179
+ * await startServer();
180
+ * guard.markConnected();
181
+ * },
182
+ * });
183
+ * ```
184
+ *
185
+ * @public
186
+ */
187
+ export declare class ProcessGuard {
188
+ private constructor();
189
+ /**
190
+ * Parse a test-only crash-injection setting into {@link ProcessGuardOptions.injectCrash}: `<at>:<kind>`, where `at`
191
+ * is `"load"` or `"connected"` and `kind` is `"uncaughtException"` or `"unhandledRejection"`. Anything else, or no
192
+ * value, is `undefined` (no injection), so a launcher can pass an environment variable straight through and every
193
+ * launcher shares one grammar.
194
+ *
195
+ * @example
196
+ * ```ts
197
+ * ProcessGuard.parseInjectCrash("connected:unhandledRejection"); // => { at: "connected", kind: "unhandledRejection" }
198
+ * ProcessGuard.parseInjectCrash("later:boom"); // => undefined
199
+ * ```
200
+ */
201
+ static readonly parseInjectCrash: (value: string | undefined) => ProcessGuardInjection | undefined;
202
+ /** Install the guards, then run `load`. Resolves once `load` has resolved. */
203
+ static readonly run: (options: ProcessGuardOptions) => Promise<void>;
204
+ }
205
+ //#endregion
206
+ export type { ProcessGuardControl, ProcessGuardHost, ProcessGuardInjection, ProcessGuardOptions, ProcessGuardPolicy };
207
+ //# sourceMappingURL=guard.d.ts.map
package/guard.js ADDED
@@ -0,0 +1,3 @@
1
+ import { ProcessGuard } from "./ProcessGuard.js";
2
+
3
+ export { ProcessGuard };
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "@effected/engine",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
4
  "private": false,
5
- "description": "Platform-free primitives shared by every front end of an Effect v4 tool: distribution identity, remediation, and launch context",
5
+ "description": "Platform-free primitives shared by every front end of an Effect v4 tool: distribution identity, remediation, launch context, and transport-neutral process crash guards",
6
6
  "keywords": [
7
7
  "effect",
8
8
  "cli",
@@ -34,6 +34,11 @@
34
34
  "import": "./index.js",
35
35
  "default": "./index.js"
36
36
  },
37
+ "./guard": {
38
+ "types": "./guard.d.ts",
39
+ "import": "./guard.js",
40
+ "default": "./guard.js"
41
+ },
37
42
  "./package.json": "./package.json"
38
43
  },
39
44
  "peerDependencies": {