@smthrs/kernel 0.0.0-stage → 1.0.0-rc.3

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 (267) hide show
  1. package/CHANGELOG.md +206 -0
  2. package/LICENSE +21 -0
  3. package/README.md +154 -2
  4. package/dist/cjs/CapabilitySet.d.ts +6 -0
  5. package/dist/cjs/CapabilitySet.d.ts.map +1 -0
  6. package/dist/cjs/CapabilitySet.js +19 -0
  7. package/dist/cjs/CapabilitySet.js.map +7 -0
  8. package/dist/cjs/ChildProcessEnvironment.d.ts +60 -0
  9. package/dist/cjs/ChildProcessEnvironment.d.ts.map +1 -0
  10. package/dist/cjs/ChildProcessEnvironment.js +61 -0
  11. package/dist/cjs/ChildProcessEnvironment.js.map +7 -0
  12. package/dist/cjs/ChildProcessSpawner.d.ts +100 -0
  13. package/dist/cjs/ChildProcessSpawner.d.ts.map +1 -0
  14. package/dist/cjs/ChildProcessSpawner.js +291 -0
  15. package/dist/cjs/ChildProcessSpawner.js.map +7 -0
  16. package/dist/cjs/CommandLine.d.ts +173 -0
  17. package/dist/cjs/CommandLine.d.ts.map +1 -0
  18. package/dist/cjs/CommandLine.js +54 -0
  19. package/dist/cjs/CommandLine.js.map +7 -0
  20. package/dist/cjs/ContainedSpawner.d.ts +135 -0
  21. package/dist/cjs/ContainedSpawner.d.ts.map +1 -0
  22. package/dist/cjs/ContainedSpawner.js +141 -0
  23. package/dist/cjs/ContainedSpawner.js.map +7 -0
  24. package/dist/cjs/FileSystem.d.ts +452 -0
  25. package/dist/cjs/FileSystem.d.ts.map +1 -0
  26. package/dist/cjs/FileSystem.js +890 -0
  27. package/dist/cjs/FileSystem.js.map +7 -0
  28. package/dist/cjs/FileSystemBatch.d.ts +94 -0
  29. package/dist/cjs/FileSystemBatch.d.ts.map +1 -0
  30. package/dist/cjs/FileSystemBatch.js +31 -0
  31. package/dist/cjs/FileSystemBatch.js.map +7 -0
  32. package/dist/cjs/GrantEvent.d.ts +240 -0
  33. package/dist/cjs/GrantEvent.d.ts.map +1 -0
  34. package/dist/cjs/GrantEvent.js +115 -0
  35. package/dist/cjs/GrantEvent.js.map +7 -0
  36. package/dist/cjs/GrantStore.d.ts +270 -0
  37. package/dist/cjs/GrantStore.d.ts.map +1 -0
  38. package/dist/cjs/GrantStore.js +857 -0
  39. package/dist/cjs/GrantStore.js.map +7 -0
  40. package/dist/cjs/HostError.d.ts +36 -0
  41. package/dist/cjs/HostError.d.ts.map +1 -0
  42. package/dist/cjs/HostError.js +17 -0
  43. package/dist/cjs/HostError.js.map +7 -0
  44. package/dist/cjs/HostServices.d.ts +101 -0
  45. package/dist/cjs/HostServices.d.ts.map +1 -0
  46. package/dist/cjs/HostServices.js +66 -0
  47. package/dist/cjs/HostServices.js.map +7 -0
  48. package/dist/cjs/HttpClient.d.ts +177 -0
  49. package/dist/cjs/HttpClient.d.ts.map +1 -0
  50. package/dist/cjs/HttpClient.js +217 -0
  51. package/dist/cjs/HttpClient.js.map +7 -0
  52. package/dist/cjs/Jj.d.ts +67 -0
  53. package/dist/cjs/Jj.d.ts.map +1 -0
  54. package/dist/cjs/Jj.js +118 -0
  55. package/dist/cjs/Jj.js.map +7 -0
  56. package/dist/cjs/JournalGrantStore.d.ts +65 -0
  57. package/dist/cjs/JournalGrantStore.d.ts.map +1 -0
  58. package/dist/cjs/JournalGrantStore.js +354 -0
  59. package/dist/cjs/JournalGrantStore.js.map +7 -0
  60. package/dist/cjs/Path.d.ts +37 -0
  61. package/dist/cjs/Path.d.ts.map +1 -0
  62. package/dist/cjs/Path.js +46 -0
  63. package/dist/cjs/Path.js.map +7 -0
  64. package/dist/cjs/ProcessConfinement.d.ts +55 -0
  65. package/dist/cjs/ProcessConfinement.d.ts.map +1 -0
  66. package/dist/cjs/ProcessConfinement.js +94 -0
  67. package/dist/cjs/ProcessConfinement.js.map +7 -0
  68. package/dist/cjs/ProcessLedger.d.ts +260 -0
  69. package/dist/cjs/ProcessLedger.d.ts.map +1 -0
  70. package/dist/cjs/ProcessLedger.js +190 -0
  71. package/dist/cjs/ProcessLedger.js.map +7 -0
  72. package/dist/cjs/Rooted.d.ts +53 -0
  73. package/dist/cjs/Rooted.d.ts.map +1 -0
  74. package/dist/cjs/Rooted.js +101 -0
  75. package/dist/cjs/Rooted.js.map +7 -0
  76. package/dist/cjs/Unreachable.d.ts +27 -0
  77. package/dist/cjs/Unreachable.d.ts.map +1 -0
  78. package/dist/cjs/Unreachable.js +43 -0
  79. package/dist/cjs/Unreachable.js.map +7 -0
  80. package/dist/cjs/Workspace.d.ts +62 -0
  81. package/dist/cjs/Workspace.d.ts.map +1 -0
  82. package/dist/cjs/Workspace.js +35 -0
  83. package/dist/cjs/Workspace.js.map +7 -0
  84. package/dist/cjs/index.d.ts +161 -0
  85. package/dist/cjs/index.d.ts.map +1 -0
  86. package/dist/cjs/index.js +73 -0
  87. package/dist/cjs/index.js.map +7 -0
  88. package/dist/cjs/internal/Containment.d.ts +24 -0
  89. package/dist/cjs/internal/Containment.d.ts.map +1 -0
  90. package/dist/cjs/internal/Containment.js +30 -0
  91. package/dist/cjs/internal/Containment.js.map +7 -0
  92. package/dist/cjs/internal/Pipeline.d.ts +18 -0
  93. package/dist/cjs/internal/Pipeline.d.ts.map +1 -0
  94. package/dist/cjs/internal/Pipeline.js +90 -0
  95. package/dist/cjs/internal/Pipeline.js.map +7 -0
  96. package/dist/cjs/internal/makeCapability.d.ts +16 -0
  97. package/dist/cjs/internal/makeCapability.d.ts.map +1 -0
  98. package/dist/cjs/internal/makeCapability.js +44 -0
  99. package/dist/cjs/internal/makeCapability.js.map +7 -0
  100. package/dist/cjs/package.json +1 -0
  101. package/dist/cjs/test/FileSystemBatchContract.d.ts +15 -0
  102. package/dist/cjs/test/FileSystemBatchContract.d.ts.map +1 -0
  103. package/dist/cjs/test/FileSystemBatchContract.js +76 -0
  104. package/dist/cjs/test/FileSystemBatchContract.js.map +7 -0
  105. package/dist/cjs/test/HostContract.d.ts +225 -0
  106. package/dist/cjs/test/HostContract.d.ts.map +1 -0
  107. package/dist/cjs/test/HostContract.js +489 -0
  108. package/dist/cjs/test/HostContract.js.map +7 -0
  109. package/dist/cjs/test/TestGrantStore.d.ts +31 -0
  110. package/dist/cjs/test/TestGrantStore.d.ts.map +1 -0
  111. package/dist/cjs/test/TestGrantStore.js +65 -0
  112. package/dist/cjs/test/TestGrantStore.js.map +7 -0
  113. package/dist/esm/CapabilitySet.d.ts +6 -0
  114. package/dist/esm/CapabilitySet.d.ts.map +1 -0
  115. package/dist/esm/CapabilitySet.js +6 -0
  116. package/dist/esm/CapabilitySet.js.map +1 -0
  117. package/dist/esm/ChildProcessEnvironment.d.ts +60 -0
  118. package/dist/esm/ChildProcessEnvironment.d.ts.map +1 -0
  119. package/dist/esm/ChildProcessEnvironment.js +91 -0
  120. package/dist/esm/ChildProcessEnvironment.js.map +1 -0
  121. package/dist/esm/ChildProcessSpawner.d.ts +100 -0
  122. package/dist/esm/ChildProcessSpawner.d.ts.map +1 -0
  123. package/dist/esm/ChildProcessSpawner.js +342 -0
  124. package/dist/esm/ChildProcessSpawner.js.map +1 -0
  125. package/dist/esm/CommandLine.d.ts +173 -0
  126. package/dist/esm/CommandLine.d.ts.map +1 -0
  127. package/dist/esm/CommandLine.js +195 -0
  128. package/dist/esm/CommandLine.js.map +1 -0
  129. package/dist/esm/ContainedSpawner.d.ts +135 -0
  130. package/dist/esm/ContainedSpawner.d.ts.map +1 -0
  131. package/dist/esm/ContainedSpawner.js +180 -0
  132. package/dist/esm/ContainedSpawner.js.map +1 -0
  133. package/dist/esm/FileSystem.d.ts +452 -0
  134. package/dist/esm/FileSystem.d.ts.map +1 -0
  135. package/dist/esm/FileSystem.js +989 -0
  136. package/dist/esm/FileSystem.js.map +1 -0
  137. package/dist/esm/FileSystemBatch.d.ts +94 -0
  138. package/dist/esm/FileSystemBatch.d.ts.map +1 -0
  139. package/dist/esm/FileSystemBatch.js +26 -0
  140. package/dist/esm/FileSystemBatch.js.map +1 -0
  141. package/dist/esm/GrantEvent.d.ts +240 -0
  142. package/dist/esm/GrantEvent.d.ts.map +1 -0
  143. package/dist/esm/GrantEvent.js +155 -0
  144. package/dist/esm/GrantEvent.js.map +1 -0
  145. package/dist/esm/GrantStore.d.ts +270 -0
  146. package/dist/esm/GrantStore.d.ts.map +1 -0
  147. package/dist/esm/GrantStore.js +951 -0
  148. package/dist/esm/GrantStore.js.map +1 -0
  149. package/dist/esm/HostError.d.ts +36 -0
  150. package/dist/esm/HostError.d.ts.map +1 -0
  151. package/dist/esm/HostError.js +20 -0
  152. package/dist/esm/HostError.js.map +1 -0
  153. package/dist/esm/HostServices.d.ts +101 -0
  154. package/dist/esm/HostServices.d.ts.map +1 -0
  155. package/dist/esm/HostServices.js +76 -0
  156. package/dist/esm/HostServices.js.map +1 -0
  157. package/dist/esm/HttpClient.d.ts +177 -0
  158. package/dist/esm/HttpClient.d.ts.map +1 -0
  159. package/dist/esm/HttpClient.js +299 -0
  160. package/dist/esm/HttpClient.js.map +1 -0
  161. package/dist/esm/Jj.d.ts +67 -0
  162. package/dist/esm/Jj.d.ts.map +1 -0
  163. package/dist/esm/Jj.js +111 -0
  164. package/dist/esm/Jj.js.map +1 -0
  165. package/dist/esm/JournalGrantStore.d.ts +65 -0
  166. package/dist/esm/JournalGrantStore.d.ts.map +1 -0
  167. package/dist/esm/JournalGrantStore.js +350 -0
  168. package/dist/esm/JournalGrantStore.js.map +1 -0
  169. package/dist/esm/Path.d.ts +37 -0
  170. package/dist/esm/Path.d.ts.map +1 -0
  171. package/dist/esm/Path.js +34 -0
  172. package/dist/esm/Path.js.map +1 -0
  173. package/dist/esm/ProcessConfinement.d.ts +55 -0
  174. package/dist/esm/ProcessConfinement.d.ts.map +1 -0
  175. package/dist/esm/ProcessConfinement.js +106 -0
  176. package/dist/esm/ProcessConfinement.js.map +1 -0
  177. package/dist/esm/ProcessLedger.d.ts +260 -0
  178. package/dist/esm/ProcessLedger.d.ts.map +1 -0
  179. package/dist/esm/ProcessLedger.js +283 -0
  180. package/dist/esm/ProcessLedger.js.map +1 -0
  181. package/dist/esm/Rooted.d.ts +53 -0
  182. package/dist/esm/Rooted.d.ts.map +1 -0
  183. package/dist/esm/Rooted.js +104 -0
  184. package/dist/esm/Rooted.js.map +1 -0
  185. package/dist/esm/Unreachable.d.ts +27 -0
  186. package/dist/esm/Unreachable.d.ts.map +1 -0
  187. package/dist/esm/Unreachable.js +26 -0
  188. package/dist/esm/Unreachable.js.map +1 -0
  189. package/dist/esm/Workspace.d.ts +62 -0
  190. package/dist/esm/Workspace.d.ts.map +1 -0
  191. package/dist/esm/Workspace.js +51 -0
  192. package/dist/esm/Workspace.js.map +1 -0
  193. package/dist/esm/index.d.ts +161 -0
  194. package/dist/esm/index.d.ts.map +1 -0
  195. package/dist/esm/index.js +151 -0
  196. package/dist/esm/index.js.map +1 -0
  197. package/dist/esm/internal/Containment.d.ts +24 -0
  198. package/dist/esm/internal/Containment.d.ts.map +1 -0
  199. package/dist/esm/internal/Containment.js +27 -0
  200. package/dist/esm/internal/Containment.js.map +1 -0
  201. package/dist/esm/internal/Pipeline.d.ts +18 -0
  202. package/dist/esm/internal/Pipeline.d.ts.map +1 -0
  203. package/dist/esm/internal/Pipeline.js +68 -0
  204. package/dist/esm/internal/Pipeline.js.map +1 -0
  205. package/dist/esm/internal/makeCapability.d.ts +16 -0
  206. package/dist/esm/internal/makeCapability.d.ts.map +1 -0
  207. package/dist/esm/internal/makeCapability.js +22 -0
  208. package/dist/esm/internal/makeCapability.js.map +1 -0
  209. package/dist/esm/test/FileSystemBatchContract.d.ts +15 -0
  210. package/dist/esm/test/FileSystemBatchContract.d.ts.map +1 -0
  211. package/dist/esm/test/FileSystemBatchContract.js +57 -0
  212. package/dist/esm/test/FileSystemBatchContract.js.map +1 -0
  213. package/dist/esm/test/HostContract.d.ts +225 -0
  214. package/dist/esm/test/HostContract.d.ts.map +1 -0
  215. package/dist/esm/test/HostContract.js +460 -0
  216. package/dist/esm/test/HostContract.js.map +1 -0
  217. package/dist/esm/test/TestGrantStore.d.ts +31 -0
  218. package/dist/esm/test/TestGrantStore.d.ts.map +1 -0
  219. package/dist/esm/test/TestGrantStore.js +57 -0
  220. package/dist/esm/test/TestGrantStore.js.map +1 -0
  221. package/docs/README.md +162 -0
  222. package/docs/api.md +1532 -0
  223. package/docs/concepts/decoration-in-place.md +117 -0
  224. package/docs/concepts/filesystem-batches.md +58 -0
  225. package/docs/concepts/filesystem-confinement.md +168 -0
  226. package/docs/concepts/grant-decisions.md +181 -0
  227. package/docs/concepts/process-containment.md +155 -0
  228. package/docs/contract.md +14 -0
  229. package/docs/guides/adapt-a-new-host-platform.md +148 -0
  230. package/docs/guides/answer-permission-requests.md +151 -0
  231. package/docs/guides/authorize-network-and-model-calls.md +118 -0
  232. package/docs/guides/contain-spawned-processes.md +118 -0
  233. package/docs/guides/guard-a-host-bundle.md +109 -0
  234. package/docs/guides/persist-grants-across-restarts.md +135 -0
  235. package/docs/guides/write-a-capability-policy.md +159 -0
  236. package/docs/installation.md +115 -0
  237. package/docs/quickstart.md +182 -0
  238. package/docs/testing.md +108 -0
  239. package/docs/troubleshooting.md +281 -0
  240. package/package.json +344 -3
  241. package/src/CapabilitySet.ts +6 -0
  242. package/src/ChildProcessEnvironment.ts +98 -0
  243. package/src/ChildProcessSpawner.ts +414 -0
  244. package/src/CommandLine.ts +250 -0
  245. package/src/ContainedSpawner.ts +284 -0
  246. package/src/FileSystem.ts +1655 -0
  247. package/src/FileSystemBatch.ts +90 -0
  248. package/src/GrantEvent.ts +174 -0
  249. package/src/GrantStore.ts +1345 -0
  250. package/src/HostError.ts +37 -0
  251. package/src/HostServices.ts +133 -0
  252. package/src/HttpClient.ts +406 -0
  253. package/src/Jj.ts +159 -0
  254. package/src/JournalGrantStore.ts +461 -0
  255. package/src/Path.ts +47 -0
  256. package/src/ProcessConfinement.ts +156 -0
  257. package/src/ProcessLedger.ts +423 -0
  258. package/src/Rooted.ts +128 -0
  259. package/src/Unreachable.ts +30 -0
  260. package/src/Workspace.ts +65 -0
  261. package/src/index.ts +181 -0
  262. package/src/internal/Containment.ts +37 -0
  263. package/src/internal/Pipeline.ts +85 -0
  264. package/src/internal/makeCapability.ts +26 -0
  265. package/src/test/FileSystemBatchContract.ts +59 -0
  266. package/src/test/HostContract.ts +785 -0
  267. package/src/test/TestGrantStore.ts +73 -0
@@ -0,0 +1,54 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var CommandLine_exports = {};
20
+ __export(CommandLine_exports, {
21
+ cwd: () => cwd,
22
+ env: () => env,
23
+ executable: () => executable,
24
+ quote: () => quote,
25
+ render: () => render,
26
+ resource: () => resource,
27
+ stages: () => stages
28
+ });
29
+ module.exports = __toCommonJS(CommandLine_exports);
30
+ var import_ChildProcessEnvironment = require("./ChildProcessEnvironment.js");
31
+ const SAFE = /^[A-Za-z0-9_@%+=:,./-]+$/;
32
+ const quote = (token) => token !== "" && SAFE.test(token) ? token : `'${token.replaceAll("'", `'\\''`)}'`;
33
+ const render = (command) => command._tag === "StandardCommand" ? command.options.shell === void 0 || command.options.shell === false ? [command.command, ...command.args].map(quote).join(" ") : command.options.shell === true ? [command.command, ...command.args].join(" ") : `${quote(command.options.shell)} -c ${quote([command.command, ...command.args].join(" "))}` : `${render(command.left)} | ${render(command.right)}`;
34
+ const shellControl = /[;&|`$<>()\n\r]/;
35
+ const harmlessRedirect = /(^|\s)(?:\d*>&\d+|\d*>[ \t]*\/dev\/null)(?=\s|$)/g;
36
+ const overriddenNames = (command, ambient) => Object.entries(command.options.env ?? {}).filter(([name, value]) => value !== void 0 && (!(0, import_ChildProcessEnvironment.isInheritedName)(name) || ambient[name] !== value)).map(([name]) => name).sort();
37
+ const stages = (command) => command._tag === "StandardCommand" ? [command] : [...stages(command.left), ...stages(command.right)];
38
+ const resource = (command, context = {}) => {
39
+ const line = render(command);
40
+ const shown = command.options.shell === true && shellControl.test(line.replace(harmlessRedirect, "$1")) ? `sh -c ${quote(line)}` : line;
41
+ const names = overriddenNames(command, context.ambient ?? {});
42
+ const withEnv = names.length === 0 ? shown : `env ${names.map(quote).join(" ")} -- ${shown}`;
43
+ const directory = command.options.cwd === void 0 ? void 0 : context.resolvedCwd ?? command.options.cwd;
44
+ return directory === void 0 || context.contains?.(directory) === true ? withEnv : `cwd ${quote(directory)} -- ${withEnv}`;
45
+ };
46
+ const program = (line) => {
47
+ const trimmed = line.trimStart();
48
+ const end = trimmed.search(/\s/);
49
+ return end === -1 ? trimmed : trimmed.slice(0, end);
50
+ };
51
+ const executable = (command) => command._tag === "StandardCommand" ? command.options.shell === void 0 || command.options.shell === false ? command.command : program(command.command) : `${executable(command.left)} | ${executable(command.right)}`;
52
+ const cwd = (command) => command._tag === "StandardCommand" ? command.options.cwd : cwd(command.left);
53
+ const env = (command) => command._tag === "StandardCommand" ? command.options.env : env(command.left);
54
+ //# sourceMappingURL=CommandLine.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/CommandLine.ts"],
4
+ "sourcesContent": ["/**\n * @since 1.0.0-rc.0\n *\n * Rendering an `effect/unstable/process` `Command` back to a shell command\n * line.\n *\n * Two callers need the same string and must agree on it exactly:\n *\n * 1. `@smthrs/kernel/ChildProcessSpawner` uses it as the `proc:spawn`\n * capability resource, so a grant reads the way an operator wrote it; and\n * 2. `@smthrs/platform-browser/BrowserChildProcessSpawner` uses it as the line\n * it hands to the in-browser bash interpreter, which has no `argv` to spawn\n * with.\n *\n * A single renderer keeps a granted capability and the command a browser\n * actually runs from drifting apart.\n *\n * The module is pure string handling \u2014 no host access \u2014 so it stays on the\n * browser-safe side of the package.\n */\n\nimport type * as ChildProcess from \"effect/unstable/process/ChildProcess\"\nimport { isInheritedName } from \"./ChildProcessEnvironment.ts\"\n\n/** Tokens made only of these characters need no quoting in a POSIX shell. */\nconst SAFE = /^[A-Za-z0-9_@%+=:,./-]+$/\n\n/**\n * Quotes one token for a POSIX shell, leaving obviously safe tokens alone.\n *\n * @category rendering\n * @since 1.0.0-rc.0\n */\nexport const quote = (token: string): string =>\n token !== \"\" && SAFE.test(token) ? token : `'${token.replaceAll(\"'\", `'\\\\''`)}'`\n\n/**\n * Renders a `Command` as a single shell command line.\n *\n * A standard command with `shell: true` renders its tokens verbatim, matching\n * the line Node and the browser interpreter hand to the default shell. A\n * custom shell renders as an explicit `<shell> -c <line>` invocation so the\n * selected executable is part of the permission resource. Without `shell`,\n * every token is POSIX-quoted to preserve literal argv semantics. These\n * distinctions are security-sensitive: the rendered value is also the\n * `proc:spawn` capability resource, so it must describe what will execute.\n * The rendering is POSIX-only by contract: on Windows, Node invokes the shell\n * with `/d /s /c` rather than `-c`, so the rendered line describes the POSIX\n * invocation, not a cmd.exe one.\n *\n * The `proc:spawn` capability resource is {@link resource}, which starts from\n * this line and adds what the line alone cannot show.\n *\n * A `PipedCommand` renders with `|` between its sides. That is a faithful\n * rendering of what the pipeline does, and it is the only form an interpreter\n * that takes a command line rather than an `argv` can be given. `from`/`to`\n * pipe options are *not* expressible this way; rendering ignores them, so a\n * pipeline that redirects `stderr` renders like one that pipes `stdout`.\n * Capability checks therefore see the commands, never the plumbing.\n *\n * @category rendering\n * @since 1.0.0-rc.0\n */\nexport const render = (command: ChildProcess.Command): string =>\n command._tag === \"StandardCommand\"\n ? command.options.shell === undefined || command.options.shell === false\n ? [command.command, ...command.args].map(quote).join(\" \")\n : command.options.shell === true\n ? [command.command, ...command.args].join(\" \")\n : `${quote(command.options.shell)} -c ${quote([command.command, ...command.args].join(\" \"))}`\n : `${render(command.left)} | ${render(command.right)}`\n\n/**\n * Shell syntax that chains, substitutes, groups, or redirects: everything that\n * lets one shell line run or write more than a single simple command.\n */\nconst shellControl = /[;&|`$<>()\\n\\r]/\n\n/**\n * Redirections that neither run nor write anything a grant should see: an fd\n * duplication such as `2>&1` and a discard to `/dev/null`. They are removed\n * before {@link shellControl} is tested, so `git status 2>&1` keeps its\n * verbatim resource. Only a space or tab may sit between `>` and `/dev/null`:\n * `>` followed by a line break is not a discard, so it stays control syntax.\n */\nconst harmlessRedirect = /(^|\\s)(?:\\d*>&\\d+|\\d*>[ \\t]*\\/dev\\/null)(?=\\s|$)/g\n\n/**\n * What {@link resource} compares a stage against, supplied by the spawner that\n * checks it.\n *\n * @category models\n * @since 1.0.0-rc.1\n */\nexport interface ResourceContext {\n /**\n * The environment the spawning process itself holds. A bootstrap name\n * (`PATH`, `HOME`, ...) whose declared value equals the ambient value is the\n * inherited default and stays out of the resource; one set to anything else\n * is named. Omitted, every declared bootstrap name is named.\n */\n readonly ambient?: Readonly<Record<string, string | undefined>> | undefined\n /**\n * Whether a stage's working directory is inside the directory the flow\n * already governs. A `cwd` it rejects is named in the resource. Omitted,\n * every `cwd` a stage sets is named.\n */\n readonly contains?: ((directory: string) => boolean) | undefined\n /**\n * The stage `cwd` with every symlink resolved, when the host could resolve\n * it. It replaces the lexical `cwd` both for `contains` and in the\n * `cwd <path> -- ` prefix, so a symlink inside the governed directory that\n * leads out of it is judged, and shown, by where the command really runs.\n */\n readonly resolvedCwd?: string | undefined\n}\n\n/**\n * Names of the environment variables a stage sets that the child would not\n * otherwise inherit: every name outside the bootstrap set, and a bootstrap\n * name whose value differs from the ambient one.\n */\nconst overriddenNames = (\n command: ChildProcess.StandardCommand,\n ambient: Readonly<Record<string, string | undefined>>\n): ReadonlyArray<string> =>\n Object.entries(command.options.env ?? {})\n .filter(([name, value]) => value !== undefined && (!isInheritedName(name) || ambient[name] !== value))\n .map(([name]) => name)\n .sort()\n\n/**\n * The stages of a command in execution order: the command itself, or every\n * `StandardCommand` of a pipeline from left to right. The spawner checks each\n * stage as its own `proc:spawn` capability.\n *\n * @category rendering\n * @since 1.0.0-rc.1\n */\nexport const stages = (command: ChildProcess.Command): ReadonlyArray<ChildProcess.StandardCommand> =>\n command._tag === \"StandardCommand\" ? [command] : [...stages(command.left), ...stages(command.right)]\n\n/**\n * The `proc:spawn` capability resource for one stage: {@link render}, with\n * three additions that keep a prefix grant from authorizing code the stage\n * never named.\n *\n * - A `shell: true` stage whose line holds shell control syntax (`;`, `&`,\n * `|`, `` ` ``, `$`, `<`, `>`, `(`, `)`, or a line break) is marked as the\n * explicit `sh -c '<line>'` it is. A grant such as `git status *` then\n * cannot match `git status; curl x | sh`, while a simple shell line such as\n * `git status --short` keeps its verbatim resource. An fd duplication such\n * as `2>&1` and a discard to `/dev/null` do not count as control syntax.\n * - A stage that sets an environment variable the child would not otherwise\n * inherit is prefixed with `env <NAME>\u2026 -- `, sorted names only. That is\n * every name outside the bootstrap set `ChildProcessEnvironment` inherits\n * (`PATH`, `HOME`, `USER`, `LANG`, `TERM`, `TMPDIR`, `SHELL`, `LC_*`), and a\n * bootstrap name whose value differs from `context.ambient`. A grant for\n * `git status` covers neither `env GIT_SSH_COMMAND -- git status` nor\n * `env PATH -- git status`. Values never enter the resource because they\n * often carry credentials.\n * - A stage whose `cwd` `context.contains` rejects is prefixed with\n * `cwd <path> -- `, so a grant does not follow the command into a\n * directory whose configuration the flow does not govern. When\n * `context.resolvedCwd` is given, that real path is judged and named\n * instead of the lexical `cwd`.\n *\n * A pipeline has no single resource: the spawner checks every one of its\n * {@link stages}, so `git status | sh` needs a grant for `sh` too.\n *\n * The `env` and `cwd` prefixes share their spelling with a literal command:\n * `make(\"env\", [\"PATH\", \"--\", \"git\", \"status\"])` renders as\n * `env PATH -- git status`, the resource of `git status` with `PATH`\n * overridden. The alias grants nothing extra. The literal command runs a\n * program named `PATH` (or `cwd`) from the ambient `PATH`, not `git`. A grant\n * with `*` inside the prefix, such as `env * -- git status`, also matches\n * `env -C /x -- git status`, but it already admits any variable name,\n * including `GIT_SSH_COMMAND` and `LD_PRELOAD`, which run arbitrary code.\n * Grant a prefixed resource exactly as the request shows it.\n *\n * @category rendering\n * @since 1.0.0-rc.1\n */\nexport const resource = (command: ChildProcess.StandardCommand, context: ResourceContext = {}): string => {\n const line = render(command)\n const shown = command.options.shell === true && shellControl.test(line.replace(harmlessRedirect, \"$1\"))\n ? `sh -c ${quote(line)}`\n : line\n const names = overriddenNames(command, context.ambient ?? {})\n const withEnv = names.length === 0 ? shown : `env ${names.map(quote).join(\" \")} -- ${shown}`\n const directory = command.options.cwd === undefined ? undefined : context.resolvedCwd ?? command.options.cwd\n return directory === undefined || context.contains?.(directory) === true\n ? withEnv\n : `cwd ${quote(directory)} -- ${withEnv}`\n}\n\n/** The leading token of a shell line, which is the program the line runs. */\nconst program = (line: string): string => {\n const trimmed = line.trimStart()\n const end = trimmed.search(/\\s/)\n return end === -1 ? trimmed : trimmed.slice(0, end)\n}\n\n/**\n * The executable a command runs, without its arguments.\n *\n * A durable record of a spawned process names its program with this rather\n * than with {@link render}: arguments carry credentials (`curl -u user:pass`,\n * `mysql -phunter2`), and a journal that keeps them keeps them permanently.\n * Nothing that reads such a record needs more than the program name; a reaper\n * matches processes by pid and process group.\n *\n * Without `shell`, `command` is the executable itself, spaces and all. With a\n * shell, the line is what runs, so the program is its first token: both\n * `make(\"mysql -phunter2\", [], { shell: true })` and\n * `make(\"mysql\", [\"-phunter2\"])` yield `mysql`. A pipeline names one\n * executable per stage, joined the way {@link render} joins the stages.\n *\n * @category rendering\n * @since 1.0.0-rc.0\n */\nexport const executable = (command: ChildProcess.Command): string =>\n command._tag === \"StandardCommand\"\n ? command.options.shell === undefined || command.options.shell === false\n ? command.command\n : program(command.command)\n : `${executable(command.left)} | ${executable(command.right)}`\n\n/**\n * The working directory a command runs in, taking the leftmost stage of a\n * pipeline, which is the stage `setCwd` and the spawners agree to treat as the\n * pipeline's own directory.\n *\n * @category rendering\n * @since 1.0.0-rc.0\n */\nexport const cwd = (command: ChildProcess.Command): string | undefined =>\n command._tag === \"StandardCommand\" ? command.options.cwd : cwd(command.left)\n\n/**\n * The environment overrides a command runs with, taking the leftmost stage of\n * a pipeline for the same reason {@link cwd} does.\n *\n * @category rendering\n * @since 1.0.0-rc.0\n */\nexport const env = (\n command: ChildProcess.Command\n): Record<string, string | undefined> | undefined =>\n command._tag === \"StandardCommand\" ? command.options.env : env(command.left)\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAsBA,qCAAgC;AAGhC,MAAM,OAAO;AAQN,MAAM,QAAQ,CAAC,UACpB,UAAU,MAAM,KAAK,KAAK,KAAK,IAAI,QAAQ,IAAI,MAAM,WAAW,KAAK,OAAO,CAAC;AA6BxE,MAAM,SAAS,CAAC,YACrB,QAAQ,SAAS,oBACb,QAAQ,QAAQ,UAAU,UAAa,QAAQ,QAAQ,UAAU,QAC/D,CAAC,QAAQ,SAAS,GAAG,QAAQ,IAAI,EAAE,IAAI,KAAK,EAAE,KAAK,GAAG,IACtD,QAAQ,QAAQ,UAAU,OAC1B,CAAC,QAAQ,SAAS,GAAG,QAAQ,IAAI,EAAE,KAAK,GAAG,IAC3C,GAAG,MAAM,QAAQ,QAAQ,KAAK,CAAC,OAAO,MAAM,CAAC,QAAQ,SAAS,GAAG,QAAQ,IAAI,EAAE,KAAK,GAAG,CAAC,CAAC,KAC3F,GAAG,OAAO,QAAQ,IAAI,CAAC,MAAM,OAAO,QAAQ,KAAK,CAAC;AAMxD,MAAM,eAAe;AASrB,MAAM,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,QAAQ,QAAQ,OAAO,IACzB,GAAG,WAAW,QAAQ,IAAI,CAAC,MAAM,WAAW,QAAQ,KAAK,CAAC;AAUzD,MAAM,MAAM,CAAC,YAClB,QAAQ,SAAS,oBAAoB,QAAQ,QAAQ,MAAM,IAAI,QAAQ,IAAI;AAStE,MAAM,MAAM,CACjB,YAEA,QAAQ,SAAS,oBAAoB,QAAQ,QAAQ,MAAM,IAAI,QAAQ,IAAI;",
6
+ "names": []
7
+ }
@@ -0,0 +1,135 @@
1
+ /**
2
+ * Process containment: prepared ownership, bounded cleanup and durable records.
3
+ *
4
+ * A host supplies a {@link Lifecycle} that owns launch and cleanup independently
5
+ * of the command's exit status. The lifecycle first prepares a process identity;
6
+ * this decorator commits that identity to {@link ProcessLedger.ProcessLedger}
7
+ * before activating the caller's command. Failed or interrupted startup closes
8
+ * its child scope immediately, including any earlier legs of a partial pipeline.
9
+ *
10
+ * Each command receives default termination and escalation options. The host
11
+ * lifecycle validates that policy and verifies cleanup before the decorator
12
+ * retires its record. Unverifiable cleanup retains the record for recovery;
13
+ * a host that dies also leaves its committed records discoverable by the next
14
+ * incarnation's reaper (`ProcessReaper` in `@smthrs/platform-node`).
15
+ *
16
+ * Every pipeline leg is prepared and recorded separately, including legs whose
17
+ * pid the aggregate handle does not expose. The module remains platform-neutral.
18
+ * A layer without a lifecycle provides only deadline defaults and bookkeeping;
19
+ * it does not declare the verified-cleanup contract read by {@link isContained}.
20
+ *
21
+ * Governing design:
22
+ * `docs/specs/Concepts/Host Adapters.md`.
23
+ *
24
+ * @since 1.0.0-rc.0
25
+ */
26
+ import * as Effect from "effect/Effect";
27
+ import * as Layer from "effect/Layer";
28
+ import * as PlatformError from "effect/PlatformError";
29
+ import * as Scope from "effect/Scope";
30
+ import * as ChildProcess from "effect/unstable/process/ChildProcess";
31
+ import { type ChildProcessHandle, ChildProcessSpawner } from "effect/unstable/process/ChildProcessSpawner";
32
+ import * as ProcessLedger from "./ProcessLedger.ts";
33
+ /**
34
+ * How long a contained child may take to honour `SIGTERM`.
35
+ *
36
+ * @category models
37
+ * @since 1.0.0-rc.0
38
+ */
39
+ export declare const defaultGraceMs = 2000;
40
+ /**
41
+ * Containment configuration.
42
+ *
43
+ * @category models
44
+ * @since 1.0.0-rc.0
45
+ */
46
+ export interface Options {
47
+ /**
48
+ * Milliseconds between the `SIGTERM` that asks a child to stop and the
49
+ * `SIGKILL` that makes it. Default {@link defaultGraceMs}.
50
+ */
51
+ readonly graceMs?: number | undefined;
52
+ /**
53
+ * The platform the host spawner runs on, as `process.platform` spells it.
54
+ * Windows records no POSIX process group, including for detached children.
55
+ * On POSIX, detachment determines whether the child leads its own group.
56
+ * Default `"linux"`; host bundles pass their actual platform.
57
+ */
58
+ readonly platform?: string | undefined;
59
+ }
60
+ /**
61
+ * A platform's preparation, activation, and cleanup of a contained process.
62
+ *
63
+ * Preparation receives the underlying spawner and must own cleanup before it
64
+ * can fail or be interrupted. It returns the process identity to record and an
65
+ * idempotent `activate` effect. The decorator runs activation only after that
66
+ * identity commits to the ledger. A platform can therefore prepare an owner
67
+ * without executing the caller's command before it is durably discoverable.
68
+ *
69
+ * Failed startup closes its own scope immediately. A successful startup keeps
70
+ * that scope attached to the caller's scope. `settled` must stay false on failed
71
+ * or unverifiable cleanup; only verified cleanup permits ledger retirement.
72
+ * The wrapped handle applies the same policy to an explicit `kill`.
73
+ *
74
+ * @category models
75
+ * @since 1.0.0
76
+ */
77
+ export type Lifecycle = (command: ChildProcess.StandardCommand, spawn: (command: ChildProcess.StandardCommand) => Effect.Effect<ChildProcessHandle, PlatformError.PlatformError, Scope.Scope>) => Effect.Effect<{
78
+ readonly handle: ChildProcessHandle;
79
+ readonly activate: Effect.Effect<void, PlatformError.PlatformError, Scope.Scope>;
80
+ readonly settled: Effect.Effect<boolean>;
81
+ }, PlatformError.PlatformError, Scope.Scope>;
82
+ /**
83
+ * Whether a spawner declares the platform lifecycle required for containment.
84
+ *
85
+ * Only a layer with a {@link Lifecycle} declares this contract. A kill deadline
86
+ * alone does not verify cleanup. The permission decorator preserves the
87
+ * declaration when it wraps a contained service. The marker interoperates
88
+ * across the package's ESM and CommonJS projections.
89
+ *
90
+ * This is a trusted composition check: a caller-supplied lifecycle remains
91
+ * responsible for implementing its contract.
92
+ *
93
+ * @category predicates
94
+ * @since 1.0.0
95
+ */
96
+ export declare const isContained: (spawner: ChildProcessSpawner["Service"]) => boolean;
97
+ /**
98
+ * Supplies a command's default termination signal and escalation deadline.
99
+ *
100
+ * Both legs of a pipeline get the same policy — a pipeline is one action's
101
+ * process tree and a surviving leg is as much of a leak as a surviving
102
+ * child. Explicit `killSignal` and `forceKillAfter` values are preserved for
103
+ * the host lifecycle to validate.
104
+ *
105
+ * @category constructors
106
+ * @since 1.0.0-rc.0
107
+ */
108
+ export declare const withContainment: (command: ChildProcess.Command, options?: Options) => ChildProcess.Command;
109
+ /**
110
+ * The process group a started child leads, or `null` when it shares the
111
+ * host's or the platform has no POSIX process groups.
112
+ *
113
+ * A detached POSIX child leads a group whose id is its own pid. A child in
114
+ * the host's group must not record that group as its own cleanup target.
115
+ * Windows detachment creates an independent console, not a POSIX group;
116
+ * Windows records therefore always carry `null`.
117
+ *
118
+ * @category constructors
119
+ * @since 1.0.0-rc.0
120
+ */
121
+ export declare const groupOf: (command: ChildProcess.Command, pid: number, platform?: string) => number | null;
122
+ /**
123
+ * Decorates the process spawner in place with containment and bookkeeping.
124
+ *
125
+ * Compose it over a host spawner layer with `Layer.provide`. It provides the
126
+ * tag it also requires. Compose the permission decorator over this layer to
127
+ * authorize the caller's whole pipeline before its per-process expansion. A
128
+ * lifecycle may use different commands during preparation; a decorator below
129
+ * containment sees those platform commands instead of the caller's command.
130
+ *
131
+ * @category layers
132
+ * @since 1.0.0-rc.0
133
+ */
134
+ export declare const layer: (options?: Options, lifecycle?: Lifecycle) => Layer.Layer<ChildProcessSpawner, never, ChildProcessSpawner | ProcessLedger.ProcessLedger>;
135
+ //# sourceMappingURL=ContainedSpawner.d.ts.map
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C,CAAA;CACzC,EACD,aAAa,CAAC,aAAa,EAC3B,KAAK,CAAC,KAAK,CACZ,CAAA;AAED;;;;;;;;;;;;;GAaG;AACH,eAAO,MAAM,WAAW,GAAI,SAAS,mBAAmB,CAAC,SAAS,CAAC,KAAG,OAA2C,CAAA;AAEjH;;;;;;;;;;GAUG;AACH,eAAO,MAAM,eAAe,GAC1B,SAAS,YAAY,CAAC,OAAO,EAC7B,UAAU,OAAO,KAChB,YAAY,CAAC,OAcf,CAAA;AAED;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,OAAO,GAAI,SAAS,YAAY,CAAC,OAAO,EAAE,KAAK,MAAM,EAAE,WAAW,MAAM,KAAG,MAAM,GAAG,IAIhG,CAAA;AAKD;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,KAAK,GAChB,UAAU,OAAO,EACjB,YAAY,SAAS,KACpB,KAAK,CAAC,KAAK,CAAC,mBAAmB,EAAE,KAAK,EAAE,mBAAmB,GAAG,aAAa,CAAC,aAAa,CAmEzF,CAAA"}
@@ -0,0 +1,141 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+ var ContainedSpawner_exports = {};
30
+ __export(ContainedSpawner_exports, {
31
+ defaultGraceMs: () => defaultGraceMs,
32
+ groupOf: () => groupOf,
33
+ isContained: () => isContained,
34
+ layer: () => layer,
35
+ withContainment: () => withContainment
36
+ });
37
+ module.exports = __toCommonJS(ContainedSpawner_exports);
38
+ var Effect = __toESM(require("effect/Effect"), 1);
39
+ var Exit = __toESM(require("effect/Exit"), 1);
40
+ var Layer = __toESM(require("effect/Layer"), 1);
41
+ var PlatformError = __toESM(require("effect/PlatformError"), 1);
42
+ var Schedule = __toESM(require("effect/Schedule"), 1);
43
+ var Scope = __toESM(require("effect/Scope"), 1);
44
+ var ChildProcess = __toESM(require("effect/unstable/process/ChildProcess"), 1);
45
+ var import_ChildProcessSpawner = require("effect/unstable/process/ChildProcessSpawner");
46
+ var CommandLine = __toESM(require("./CommandLine.js"), 1);
47
+ var Containment = __toESM(require("./internal/Containment.js"), 1);
48
+ var Pipeline = __toESM(require("./internal/Pipeline.js"), 1);
49
+ var ProcessLedger = __toESM(require("./ProcessLedger.js"), 1);
50
+ const defaultGraceMs = 2e3;
51
+ const isContained = (spawner) => Containment.isContained(spawner);
52
+ const withContainment = (command, options) => {
53
+ const graceMs = options?.graceMs ?? defaultGraceMs;
54
+ if (command._tag === "PipedCommand") {
55
+ return ChildProcess.pipeTo(
56
+ withContainment(command.left, options),
57
+ withContainment(command.right, options),
58
+ command.options
59
+ );
60
+ }
61
+ return ChildProcess.make(command.command, [...command.args], {
62
+ ...command.options,
63
+ killSignal: command.options.killSignal ?? "SIGTERM",
64
+ forceKillAfter: command.options.forceKillAfter ?? graceMs
65
+ });
66
+ };
67
+ const groupOf = (command, pid, platform) => {
68
+ if (platform === "win32") return null;
69
+ const options = command._tag === "PipedCommand" ? rightmost(command).options : command.options;
70
+ return options.detached ?? true ? pid : null;
71
+ };
72
+ const rightmost = (command) => command._tag === "StandardCommand" ? command : rightmost(command.right);
73
+ const layer = (options, lifecycle) => Layer.effect(
74
+ import_ChildProcessSpawner.ChildProcessSpawner,
75
+ Effect.gen(function* () {
76
+ const spawner = yield* import_ChildProcessSpawner.ChildProcessSpawner;
77
+ const ledger = yield* ProcessLedger.ProcessLedger;
78
+ const service = (0, import_ChildProcessSpawner.make)(
79
+ (command) => Effect.uninterruptibleMask(
80
+ (restore) => Effect.gen(function* () {
81
+ const processScope = yield* Scope.fork(yield* Scope.Scope);
82
+ return yield* restore(
83
+ Pipeline.spawn(
84
+ command,
85
+ Effect.fn("ContainedSpawner.spawn")(function* (command2) {
86
+ const slot = {
87
+ settled: Effect.succeed(true)
88
+ };
89
+ yield* Effect.addFinalizer(
90
+ () => Effect.gen(function* () {
91
+ if (slot.current === void 0) return;
92
+ if (yield* slot.settled) return yield* releaseQuietly(ledger, slot.current);
93
+ yield* Effect.logWarning(
94
+ `process cleanup could not verify ${slot.current.pid}; retaining its ledger record`
95
+ );
96
+ })
97
+ );
98
+ const contained = withContainment(command2, options);
99
+ const watched = lifecycle === void 0 ? void 0 : yield* lifecycle(contained, spawner.spawn);
100
+ const handle = watched?.handle ?? (yield* spawner.spawn(contained));
101
+ slot.settled = watched?.settled ?? slot.settled;
102
+ const pid = handle.pid;
103
+ slot.current = yield* ledger.record({
104
+ pid,
105
+ pgid: groupOf(command2, pid, options?.platform),
106
+ commandDigest: CommandLine.executable(command2)
107
+ }).pipe(
108
+ // A spawn whose record did not commit is precisely the child this
109
+ // module exists to make discoverable, so it is not started: the
110
+ // process is signalled and the caller is told, rather than left
111
+ // running with nothing durable naming it.
112
+ Effect.tapCause(() => Effect.ignore(handle.kill())),
113
+ Effect.mapError(unrecorded)
114
+ );
115
+ if (watched !== void 0) yield* watched.activate;
116
+ return handle;
117
+ })
118
+ ).pipe(Scope.provide(processScope))
119
+ ).pipe(
120
+ Effect.onError((cause) => Scope.close(processScope, Exit.failCause(cause)))
121
+ );
122
+ })
123
+ )
124
+ );
125
+ return lifecycle === void 0 ? service : Containment.mark(service);
126
+ })
127
+ );
128
+ const unrecorded = (cause) => PlatformError.systemError({
129
+ _tag: "Unknown",
130
+ module: "ChildProcess",
131
+ method: "spawn",
132
+ description: "the process ledger could not record this spawn durably",
133
+ cause
134
+ });
135
+ const releaseQuietly = (ledger, record) => ledger.release(record).pipe(
136
+ Effect.retry(Schedule.recurs(2)),
137
+ Effect.catch(
138
+ (error) => Effect.logWarning(`process ledger could not retire ${record.pid}; leaving it for the reaper`, error)
139
+ )
140
+ );
141
+ //# sourceMappingURL=ContainedSpawner.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/ContainedSpawner.ts"],
4
+ "sourcesContent": ["/**\n * Process containment: prepared ownership, bounded cleanup and durable records.\n *\n * A host supplies a {@link Lifecycle} that owns launch and cleanup independently\n * of the command's exit status. The lifecycle first prepares a process identity;\n * this decorator commits that identity to {@link ProcessLedger.ProcessLedger}\n * before activating the caller's command. Failed or interrupted startup closes\n * its child scope immediately, including any earlier legs of a partial pipeline.\n *\n * Each command receives default termination and escalation options. The host\n * lifecycle validates that policy and verifies cleanup before the decorator\n * retires its record. Unverifiable cleanup retains the record for recovery;\n * a host that dies also leaves its committed records discoverable by the next\n * incarnation's reaper (`ProcessReaper` in `@smthrs/platform-node`).\n *\n * Every pipeline leg is prepared and recorded separately, including legs whose\n * pid the aggregate handle does not expose. The module remains platform-neutral.\n * A layer without a lifecycle provides only deadline defaults and bookkeeping;\n * it does not declare the verified-cleanup contract read by {@link isContained}.\n *\n * Governing design:\n * `docs/specs/Concepts/Host Adapters.md`.\n *\n * @since 1.0.0-rc.0\n */\n\nimport * as Effect from \"effect/Effect\"\nimport * as Exit from \"effect/Exit\"\nimport * as Layer from \"effect/Layer\"\nimport * as PlatformError from \"effect/PlatformError\"\nimport * as Schedule from \"effect/Schedule\"\nimport * as Scope from \"effect/Scope\"\nimport * as ChildProcess from \"effect/unstable/process/ChildProcess\"\nimport {\n type ChildProcessHandle,\n ChildProcessSpawner,\n make as makeSpawner\n} from \"effect/unstable/process/ChildProcessSpawner\"\nimport * as CommandLine from \"./CommandLine.ts\"\nimport * as Containment from \"./internal/Containment.ts\"\nimport * as Pipeline from \"./internal/Pipeline.ts\"\nimport * as ProcessLedger from \"./ProcessLedger.ts\"\n\n/**\n * How long a contained child may take to honour `SIGTERM`.\n *\n * @category models\n * @since 1.0.0-rc.0\n */\nexport const defaultGraceMs = 2000\n\n/**\n * Containment configuration.\n *\n * @category models\n * @since 1.0.0-rc.0\n */\nexport interface Options {\n /**\n * Milliseconds between the `SIGTERM` that asks a child to stop and the\n * `SIGKILL` that makes it. Default {@link defaultGraceMs}.\n */\n readonly graceMs?: number | undefined\n /**\n * The platform the host spawner runs on, as `process.platform` spells it.\n * Windows records no POSIX process group, including for detached children.\n * On POSIX, detachment determines whether the child leads its own group.\n * Default `\"linux\"`; host bundles pass their actual platform.\n */\n readonly platform?: string | undefined\n}\n\n/**\n * A platform's preparation, activation, and cleanup of a contained process.\n *\n * Preparation receives the underlying spawner and must own cleanup before it\n * can fail or be interrupted. It returns the process identity to record and an\n * idempotent `activate` effect. The decorator runs activation only after that\n * identity commits to the ledger. A platform can therefore prepare an owner\n * without executing the caller's command before it is durably discoverable.\n *\n * Failed startup closes its own scope immediately. A successful startup keeps\n * that scope attached to the caller's scope. `settled` must stay false on failed\n * or unverifiable cleanup; only verified cleanup permits ledger retirement.\n * The wrapped handle applies the same policy to an explicit `kill`.\n *\n * @category models\n * @since 1.0.0\n */\nexport type Lifecycle = (\n command: ChildProcess.StandardCommand,\n spawn: (\n command: ChildProcess.StandardCommand\n ) => Effect.Effect<ChildProcessHandle, PlatformError.PlatformError, Scope.Scope>\n) => Effect.Effect<\n {\n readonly handle: ChildProcessHandle\n readonly activate: Effect.Effect<void, PlatformError.PlatformError, Scope.Scope>\n readonly settled: Effect.Effect<boolean>\n },\n PlatformError.PlatformError,\n Scope.Scope\n>\n\n/**\n * Whether a spawner declares the platform lifecycle required for containment.\n *\n * Only a layer with a {@link Lifecycle} declares this contract. A kill deadline\n * alone does not verify cleanup. The permission decorator preserves the\n * declaration when it wraps a contained service. The marker interoperates\n * across the package's ESM and CommonJS projections.\n *\n * This is a trusted composition check: a caller-supplied lifecycle remains\n * responsible for implementing its contract.\n *\n * @category predicates\n * @since 1.0.0\n */\nexport const isContained = (spawner: ChildProcessSpawner[\"Service\"]): boolean => Containment.isContained(spawner)\n\n/**\n * Supplies a command's default termination signal and escalation deadline.\n *\n * Both legs of a pipeline get the same policy \u2014 a pipeline is one action's\n * process tree and a surviving leg is as much of a leak as a surviving\n * child. Explicit `killSignal` and `forceKillAfter` values are preserved for\n * the host lifecycle to validate.\n *\n * @category constructors\n * @since 1.0.0-rc.0\n */\nexport const withContainment = (\n command: ChildProcess.Command,\n options?: Options\n): ChildProcess.Command => {\n const graceMs = options?.graceMs ?? defaultGraceMs\n if (command._tag === \"PipedCommand\") {\n return ChildProcess.pipeTo(\n withContainment(command.left, options),\n withContainment(command.right, options),\n command.options\n )\n }\n return ChildProcess.make(command.command, [...command.args], {\n ...command.options,\n killSignal: command.options.killSignal ?? \"SIGTERM\",\n forceKillAfter: command.options.forceKillAfter ?? graceMs\n })\n}\n\n/**\n * The process group a started child leads, or `null` when it shares the\n * host's or the platform has no POSIX process groups.\n *\n * A detached POSIX child leads a group whose id is its own pid. A child in\n * the host's group must not record that group as its own cleanup target.\n * Windows detachment creates an independent console, not a POSIX group;\n * Windows records therefore always carry `null`.\n *\n * @category constructors\n * @since 1.0.0-rc.0\n */\nexport const groupOf = (command: ChildProcess.Command, pid: number, platform?: string): number | null => {\n if (platform === \"win32\") return null\n const options = command._tag === \"PipedCommand\" ? rightmost(command).options : command.options\n return (options.detached ?? true) ? pid : null\n}\n\nconst rightmost = (command: ChildProcess.Command): ChildProcess.StandardCommand =>\n command._tag === \"StandardCommand\" ? command : rightmost(command.right)\n\n/**\n * Decorates the process spawner in place with containment and bookkeeping.\n *\n * Compose it over a host spawner layer with `Layer.provide`. It provides the\n * tag it also requires. Compose the permission decorator over this layer to\n * authorize the caller's whole pipeline before its per-process expansion. A\n * lifecycle may use different commands during preparation; a decorator below\n * containment sees those platform commands instead of the caller's command.\n *\n * @category layers\n * @since 1.0.0-rc.0\n */\nexport const layer = (\n options?: Options,\n lifecycle?: Lifecycle\n): Layer.Layer<ChildProcessSpawner, never, ChildProcessSpawner | ProcessLedger.ProcessLedger> =>\n Layer.effect(\n ChildProcessSpawner,\n Effect.gen(function*() {\n const spawner = yield* ChildProcessSpawner\n const ledger = yield* ProcessLedger.ProcessLedger\n const service = makeSpawner(\n (command) =>\n Effect.uninterruptibleMask((restore) =>\n Effect.gen(function*() {\n // A failed startup must clean up even when its caller catches the\n // error and keeps the outer scope open. One child scope contains\n // the entire pipeline, so failure of a later leg also closes all\n // earlier legs. Successful spawns retain it until their caller closes.\n const processScope = yield* Scope.fork(yield* Scope.Scope)\n return yield* restore(\n Pipeline.spawn(\n command,\n Effect.fn(\"ContainedSpawner.spawn\")(function*(command) {\n // The release finalizer is registered BEFORE the spawn, so scope\n // closure runs it AFTER the spawn's own kill finalizer: finalizers\n // run last-registered-first, and a ledger that announced an exit\n // while the process was still being signalled would be telling the\n // next incarnation to stop looking for something still alive. The\n // slot is empty until the record exists, which is also what makes a\n // spawn that never got recorded a no-op to release.\n const slot: { current?: ProcessLedger.ProcessRecord; settled: Effect.Effect<boolean> } = {\n settled: Effect.succeed(true)\n }\n yield* Effect.addFinalizer(() =>\n Effect.gen(function*() {\n if (slot.current === undefined) return\n if (yield* slot.settled) return yield* releaseQuietly(ledger, slot.current)\n yield* Effect.logWarning(\n `process cleanup could not verify ${slot.current.pid}; retaining its ledger record`\n )\n })\n )\n const contained = withContainment(command, options) as ChildProcess.StandardCommand\n const watched = lifecycle === undefined ? undefined : yield* lifecycle(contained, spawner.spawn)\n const handle = watched?.handle ?? (yield* spawner.spawn(contained))\n slot.settled = watched?.settled ?? slot.settled\n const pid = handle.pid as number\n slot.current = yield* ledger.record({\n pid,\n pgid: groupOf(command, pid, options?.platform),\n commandDigest: CommandLine.executable(command)\n }).pipe(\n // A spawn whose record did not commit is precisely the child this\n // module exists to make discoverable, so it is not started: the\n // process is signalled and the caller is told, rather than left\n // running with nothing durable naming it.\n Effect.tapCause(() => Effect.ignore(handle.kill())),\n Effect.mapError(unrecorded)\n )\n if (watched !== undefined) yield* watched.activate\n return handle\n })\n ).pipe(Scope.provide(processScope))\n ).pipe(\n Effect.onError((cause) => Scope.close(processScope, Exit.failCause(cause)))\n )\n })\n )\n )\n return lifecycle === undefined ? service : Containment.mark(service)\n })\n )\n\n/** The spawn failure a caller sees when the ledger could not record a child. */\nconst unrecorded = (cause: unknown): PlatformError.PlatformError =>\n PlatformError.systemError({\n _tag: \"Unknown\",\n module: \"ChildProcess\",\n method: \"spawn\",\n description: \"the process ledger could not record this spawn durably\",\n cause\n })\n\n/**\n * Retires a record on scope close, retrying the durable write.\n *\n * A finalizer has nowhere to report a failure, so the retry is the report: an\n * exit that never commits leaves the record inherited, and the next\n * incarnation's reaper finds a pid that is already gone and retires it then.\n * That is the safe direction, and the reason this is the ONE place a ledger\n * failure is logged rather than propagated.\n */\nconst releaseQuietly = (\n ledger: ProcessLedger.Service,\n record: ProcessLedger.ProcessRecord\n): Effect.Effect<void> =>\n ledger.release(record).pipe(\n Effect.retry(Schedule.recurs(2)),\n Effect.catch((error) =>\n Effect.logWarning(`process ledger could not retire ${record.pid}; leaving it for the reaper`, error)\n )\n )\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA0B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