@mark1russell7/service 0.8.10 → 0.8.12

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,170 +0,0 @@
1
- // src/process.ts
2
- /** These are the signals that the runtime handles. */
3
- const EXIT_SIGNALS = [
4
- "SIGINT",
5
- "SIGTERM",
6
- "SIGQUIT"
7
- ];
8
- /** These are the process triggers that a declaration can opt in to. */
9
- const PROCESS_TRIGGERS = [
10
- "stdin-close",
11
- "ipc-close",
12
- "ipc-message"
13
- ];
14
- /** These are the origins of the errors that the option `uncaught` of `run()` receives. */
15
- const UNCAUGHT_ORIGINS = ["uncaughtException", "unhandledRejection"];
16
- /** This function tells if a number is an exit code of a process: a whole number from 0 to 255. */
17
- const isExitCode = (code) => Number.isInteger(code) && code >= 0 && code <= 255;
18
- /** This function tells if a trigger is an exit signal. A repeat signal obeys `onRepeatSignal`. */
19
- const isExitSignal = (trigger) => EXIT_SIGNALS.includes(trigger);
20
- /** This function tells if a value is a message shape: a value of JSON, with no function and no undefined. */
21
- const isMessageShape = (value) => {
22
- if (value === null || typeof value === "string" || typeof value === "boolean") return true;
23
- if (typeof value === "number") return Number.isFinite(value);
24
- if (Array.isArray(value)) return value.every(isMessageShape);
25
- if (typeof value !== "object") return false;
26
- const prototype = Object.getPrototypeOf(value);
27
- return (prototype === Object.prototype || prototype === null) && Object.values(value).every(isMessageShape);
28
- };
29
- /** This function tells if a message of the IPC channel matches a shape. */
30
- const matchesMessage = (shape, message) => {
31
- if (shape === null || typeof shape !== "object") return Object.is(shape, message);
32
- if (Array.isArray(shape)) {
33
- const items = shape;
34
- return Array.isArray(message) && message.length === items.length && items.every((item, at) => matchesMessage(item, message[at]));
35
- }
36
- if (message === null || typeof message !== "object" || Array.isArray(message)) return false;
37
- const fields = message;
38
- return Object.entries(shape).every(([field, value]) => Object.hasOwn(fields, field) && matchesMessage(value, fields[field]));
39
- };
40
- /** This time is the interval of the timer of a hold, the most that a timer of Node accepts. */
41
- const HOLD_INTERVAL = 2147483647;
42
- /** This function adds a handler to some events of an emitter. The handler operates one time at most. */
43
- const once = (emitter, events, handler) => {
44
- let called = false;
45
- const fire = () => {
46
- if (called) return;
47
- called = true;
48
- handler();
49
- };
50
- for (const event of events) emitter.on(event, fire);
51
- return () => {
52
- for (const event of events) emitter.off(event, fire);
53
- };
54
- };
55
- /** This function gives a promise that ends when the data before it in a stream is written. */
56
- const written = (stream) => new Promise((resolve) => {
57
- if (stream === void 0 || stream.destroyed === true || stream.writable === false) {
58
- resolve();
59
- return;
60
- }
61
- try {
62
- stream.write("", () => resolve());
63
- } catch {
64
- resolve();
65
- }
66
- });
67
- /**
68
- * This function makes a process port on a host. `find` gives the host at each use, or undefined
69
- * when the platform has no process. Then the use throws.
70
- */
71
- const processPortOf = (find) => {
72
- const hostProcess = () => {
73
- const host = find();
74
- if (host === void 0) throw new Error("no process: give the runtime a process port");
75
- return host;
76
- };
77
- return {
78
- on(trigger, handler) {
79
- const host = hostProcess();
80
- if (trigger === "stdin-close") {
81
- const input = host.stdin;
82
- if (input === void 0) return () => {};
83
- if (input.readableEnded === true) {
84
- let live = true;
85
- queueMicrotask(() => {
86
- if (live) handler();
87
- });
88
- return () => {
89
- live = false;
90
- };
91
- }
92
- return once(input, ["end", "close"], handler);
93
- }
94
- if (trigger === "ipc-close") return once(host, ["disconnect"], handler);
95
- if (trigger === "ipc-message") {
96
- const receive = (message) => handler(message);
97
- host.on("message", receive);
98
- return () => {
99
- host.off("message", receive);
100
- };
101
- }
102
- host.on(trigger, handler);
103
- return () => {
104
- host.off(trigger, handler);
105
- };
106
- },
107
- onUncaught(handler) {
108
- const host = hostProcess();
109
- const offs = UNCAUGHT_ORIGINS.map((origin) => {
110
- const receive = (error) => handler(error, origin);
111
- host.on(origin, receive);
112
- return () => {
113
- host.off(origin, receive);
114
- };
115
- });
116
- return () => {
117
- for (const off of offs) off();
118
- };
119
- },
120
- async flush() {
121
- const host = hostProcess();
122
- await Promise.all([written(host.stdout), written(host.stderr)]);
123
- },
124
- hold() {
125
- hostProcess();
126
- const timer = setInterval(() => {}, HOLD_INTERVAL);
127
- let held = true;
128
- return () => {
129
- if (!held) return;
130
- held = false;
131
- clearInterval(timer);
132
- };
133
- },
134
- exit(code) {
135
- hostProcess().exit(code);
136
- }
137
- };
138
- };
139
- /** This port is the process of Node. */
140
- const nodeProcess = processPortOf(() => globalThis.process);
141
- /**
142
- * This function gives a process port for a lifecycle in a process that another part owns. That
143
- * part is a script, a test of an application, or a library entry. The port adds no handler of a signal or of
144
- * a trigger, it does not hold the process, and its `exit` only records the code. The caller stops
145
- * the lifecycle with `life.shutdown()`. A process with a service of its own gives its parts to
146
- * that service, and does not use this port.
147
- */
148
- const embeddedProcess = () => {
149
- let code = null;
150
- let resolve = () => {};
151
- return {
152
- on() {
153
- return () => {};
154
- },
155
- exit(requested) {
156
- if (code !== null) return;
157
- code = requested;
158
- resolve(requested);
159
- },
160
- get exitCode() {
161
- return code;
162
- },
163
- exited: new Promise((done) => {
164
- resolve = done;
165
- })
166
- };
167
- };
168
- export { isExitCode as a, matchesMessage as c, embeddedProcess as i, nodeProcess as l, PROCESS_TRIGGERS as n, isExitSignal as o, UNCAUGHT_ORIGINS as r, isMessageShape as s, EXIT_SIGNALS as t, processPortOf as u };
169
-
170
- //# sourceMappingURL=process-Oe0Abbsm.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"process-Oe0Abbsm.js","names":[],"sources":["../src/process.ts"],"sourcesContent":["/** An exit signal is a signal that asks the process to stop: each one starts the shutdown. */\nexport type ExitSignal = \"SIGINT\" | \"SIGTERM\" | \"SIGQUIT\";\n\n/** These are the signals that the runtime handles. */\nexport const EXIT_SIGNALS: readonly ExitSignal[] = [\"SIGINT\", \"SIGTERM\", \"SIGQUIT\"];\n\n/**\n * A process trigger is an event of the process, other than a signal, that starts the shutdown. A\n * declaration opts in to each one (`svc.trigger`):\n * - `stdin-close`: the standard input ends or closes, as when the parent of a stdio child goes away.\n * The process must read its input, as a stdio transport does, or Node does not see the end.\n * - `ipc-close`: the IPC channel to the parent process closes.\n * - `ipc-message`: a message on the IPC channel matches a declared shape. Windows cannot give a\n * child a SIGTERM that the child can catch, thus a parent sends a message.\n */\nexport type ProcessTrigger = \"stdin-close\" | \"ipc-close\" | \"ipc-message\";\n\n/** These are the process triggers that a declaration can opt in to. */\nexport const PROCESS_TRIGGERS: readonly ProcessTrigger[] = [\"stdin-close\", \"ipc-close\", \"ipc-message\"];\n\n/** An exit trigger is an event that starts the shutdown: an exit signal, or a declared process trigger. */\nexport type ExitTrigger = ExitSignal | ProcessTrigger;\n\n/**\n * An uncaught origin tells how an error that no code caught came to the process. It is an exception\n * that no code caught, or a rejection of a promise that no code handled.\n */\nexport type UncaughtOrigin = \"uncaughtException\" | \"unhandledRejection\";\n\n/** These are the origins of the errors that the option `uncaught` of `run()` receives. */\nexport const UNCAUGHT_ORIGINS: readonly UncaughtOrigin[] = [\"uncaughtException\", \"unhandledRejection\"];\n\n/** This function tells if a number is an exit code of a process: a whole number from 0 to 255. */\nexport const isExitCode = (code: number): boolean => Number.isInteger(code) && code >= 0 && code <= 255;\n\n/** This function tells if a trigger is an exit signal. A repeat signal obeys `onRepeatSignal`. */\nexport const isExitSignal = (trigger: string): trigger is ExitSignal =>\n (EXIT_SIGNALS as readonly string[]).includes(trigger);\n\n/**\n * A message shape is a value of JSON that a message of the IPC channel can match. A string, a\n * number, a boolean or null matches an equal message. An object matches a message that has each of\n * its fields, and each value of the field matches. An array matches an array of the same length, item by item.\n */\nexport type MessageShape = string | number | boolean | null | readonly MessageShape[] | { readonly [field: string]: MessageShape };\n\n/** This function tells if a value is a message shape: a value of JSON, with no function and no undefined. */\nexport const isMessageShape = (value: unknown): value is MessageShape => {\n if (value === null || typeof value === \"string\" || typeof value === \"boolean\") return true;\n if (typeof value === \"number\") return Number.isFinite(value);\n if (Array.isArray(value)) return value.every(isMessageShape);\n if (typeof value !== \"object\") return false;\n const prototype = Object.getPrototypeOf(value) as unknown;\n return (prototype === Object.prototype || prototype === null) && Object.values(value).every(isMessageShape);\n};\n\n/** This function tells if a message of the IPC channel matches a shape. */\nexport const matchesMessage = (shape: MessageShape, message: unknown): boolean => {\n if (shape === null || typeof shape !== \"object\") return Object.is(shape, message);\n if (Array.isArray(shape)) {\n const items: readonly MessageShape[] = shape;\n return Array.isArray(message) && message.length === items.length && items.every((item, at) => matchesMessage(item, message[at]));\n }\n if (message === null || typeof message !== \"object\" || Array.isArray(message)) return false;\n const fields = message as Readonly<Record<string, unknown>>;\n return Object.entries(shape).every(([field, value]) => Object.hasOwn(fields, field) && matchesMessage(value, fields[field]));\n};\n\n/**\n * A process port is the part of the process that the runtime uses: its exit triggers, its output\n * and its exit. The runtime owns the handlers, because Node as PID 1 without a handler ignores\n * SIGTERM. Only the runtime ends the process, and library code does not. A test gives a fake port,\n * sends triggers, and reads the exit code.\n */\nexport interface ProcessPort {\n /**\n * This method adds a handler for a trigger, and gives the function that removes it. The runtime\n * asks for a process trigger only when the declaration opts in to it. For `ipc-message`, the\n * handler gets each message of the IPC channel, and the runtime matches it.\n */\n on(trigger: ExitTrigger, handler: (message?: unknown) => void): () => void;\n /**\n * This method adds a handler for each error that no code caught, and gives the function that\n * removes it. The runtime asks for it only when `run()` gets the option `uncaught`. A port without\n * this method gets no handler, as the embedded port.\n */\n onUncaught?(handler: (error: unknown, origin: UncaughtOrigin) => void): () => void;\n /**\n * This method writes each buffered line of the output, and its promise ends when the output is\n * written. The stage `flush the output` uses it, in the cap of that stage.\n */\n flush?(): Promise<void> | void;\n /**\n * This method keeps the process alive, and gives the function that releases it. The lifecycle\n * holds its process from its start to its exit, as a listening socket does. Thus a process whose\n * timers do not keep it alive does not end in the middle of its work. It keeps its teardown and its exit code.\n */\n hold?(): () => void;\n /** This method ends the process with a code: the code of the exit request, 1 after an error, or 0. */\n exit(code: number): void;\n}\n\n/** A host stream is the part of a stream of Node that the port uses. */\nexport interface HostStream {\n readonly writable?: boolean;\n readonly destroyed?: boolean;\n readonly readableEnded?: boolean;\n write(chunk: string, done: (error?: unknown) => void): boolean;\n on(event: string, handler: () => void): unknown;\n off(event: string, handler: () => void): unknown;\n}\n\n/** A process host is the part of the process of Node that the port uses. Its event `message` gives the message of the IPC channel. */\nexport interface ProcessHost {\n on(signal: string, handler: (message?: unknown) => void): unknown;\n off(signal: string, handler: (message?: unknown) => void): unknown;\n exit(code: number): unknown;\n readonly stdin?: HostStream | undefined;\n readonly stdout?: HostStream | undefined;\n readonly stderr?: HostStream | undefined;\n}\n\n/** This time is the interval of the timer of a hold, the most that a timer of Node accepts. */\nconst HOLD_INTERVAL = 0x7fffffff;\n\n/** This function adds a handler to some events of an emitter. The handler operates one time at most. */\nconst once = (emitter: HostStream | ProcessHost, events: readonly string[], handler: () => void): (() => void) => {\n let called = false;\n const fire = (): void => {\n if (called) return;\n called = true;\n handler();\n };\n for (const event of events) emitter.on(event, fire);\n return () => {\n for (const event of events) emitter.off(event, fire);\n };\n};\n\n/** This function gives a promise that ends when the data before it in a stream is written. */\nconst written = (stream: HostStream | undefined): Promise<void> =>\n new Promise<void>((resolve) => {\n if (stream === undefined || stream.destroyed === true || stream.writable === false) {\n resolve();\n return;\n }\n try {\n // the callback of an empty write comes after each write before it\n stream.write(\"\", () => resolve());\n } catch {\n resolve();\n }\n });\n\n/**\n * This function makes a process port on a host. `find` gives the host at each use, or undefined\n * when the platform has no process. Then the use throws.\n */\nexport const processPortOf = (find: () => ProcessHost | undefined): ProcessPort => {\n const hostProcess = (): ProcessHost => {\n const host = find();\n if (host === undefined) throw new Error(\"no process: give the runtime a process port\");\n return host;\n };\n return {\n on(trigger, handler) {\n const host = hostProcess();\n if (trigger === \"stdin-close\") {\n const input = host.stdin;\n if (input === undefined) return () => {};\n // an input that ended before the handler was added still starts the shutdown\n if (input.readableEnded === true) {\n let live = true;\n queueMicrotask(() => {\n if (live) handler();\n });\n return () => {\n live = false;\n };\n }\n return once(input, [\"end\", \"close\"], handler);\n }\n if (trigger === \"ipc-close\") return once(host, [\"disconnect\"], handler);\n if (trigger === \"ipc-message\") {\n // each message goes to the runtime, which matches it with the declared shapes\n const receive = (message?: unknown): void => handler(message);\n host.on(\"message\", receive);\n return () => {\n host.off(\"message\", receive);\n };\n }\n host.on(trigger, handler);\n return () => {\n host.off(trigger, handler);\n };\n },\n onUncaught(handler) {\n const host = hostProcess();\n // a handler of each origin: Node then does not end the process, and the runtime does the shutdown\n const offs = UNCAUGHT_ORIGINS.map((origin) => {\n const receive = (error?: unknown): void => handler(error, origin);\n host.on(origin, receive);\n return () => {\n host.off(origin, receive);\n };\n });\n return () => {\n for (const off of offs) off();\n };\n },\n async flush() {\n const host = hostProcess();\n await Promise.all([written(host.stdout), written(host.stderr)]);\n },\n hold() {\n hostProcess();\n // one interval that keeps the event loop alive: its timer does nothing, and the release stops it\n const timer = setInterval(() => {}, HOLD_INTERVAL);\n let held = true;\n return () => {\n if (!held) return;\n held = false;\n clearInterval(timer);\n };\n },\n exit(code) {\n hostProcess().exit(code);\n },\n };\n};\n\n/** This port is the process of Node. */\nexport const nodeProcess: ProcessPort = processPortOf(() => (globalThis as { process?: ProcessHost }).process);\n\n/** An embedded process port records the exit code of a lifecycle that does not own its process. */\nexport interface EmbeddedProcess extends ProcessPort {\n /** This code is the code of the exit request of the lifecycle, or null before that request. */\n readonly exitCode: number | null;\n /** This promise ends with the exit code when the lifecycle asks for its exit. */\n readonly exited: Promise<number>;\n}\n\n/**\n * This function gives a process port for a lifecycle in a process that another part owns. That\n * part is a script, a test of an application, or a library entry. The port adds no handler of a signal or of\n * a trigger, it does not hold the process, and its `exit` only records the code. The caller stops\n * the lifecycle with `life.shutdown()`. A process with a service of its own gives its parts to\n * that service, and does not use this port.\n */\nexport const embeddedProcess = (): EmbeddedProcess => {\n let code: number | null = null;\n let resolve: (code: number) => void = () => {};\n const exited = new Promise<number>((done) => {\n resolve = done;\n });\n return {\n on() {\n // the owner of the process keeps its signals and triggers\n return () => {};\n },\n exit(requested) {\n if (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