@prisma/compute-sdk 0.44.0 → 0.45.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.
Files changed (127) hide show
  1. package/README.md +196 -0
  2. package/dist/archive.d.ts +2 -1
  3. package/dist/archive.d.ts.map +1 -1
  4. package/dist/archive.js +8 -4
  5. package/dist/archive.js.map +1 -1
  6. package/dist/build-strategy.d.ts +7 -0
  7. package/dist/build-strategy.d.ts.map +1 -1
  8. package/dist/build-strategy.js +3 -0
  9. package/dist/build-strategy.js.map +1 -1
  10. package/dist/compute-client.d.ts.map +1 -1
  11. package/dist/compute-client.js +1 -1
  12. package/dist/compute-client.js.map +1 -1
  13. package/dist/config/frameworks.d.ts +1 -1
  14. package/dist/errors.d.ts +14 -0
  15. package/dist/errors.d.ts.map +1 -1
  16. package/dist/errors.js +3 -0
  17. package/dist/errors.js.map +1 -1
  18. package/dist/package-manager.d.ts +6 -0
  19. package/dist/package-manager.d.ts.map +1 -0
  20. package/dist/package-manager.js +21 -0
  21. package/dist/package-manager.js.map +1 -0
  22. package/dist/service/artifact/exclude.d.ts +6 -0
  23. package/dist/service/artifact/exclude.d.ts.map +1 -0
  24. package/dist/service/artifact/exclude.js +8 -0
  25. package/dist/service/artifact/exclude.js.map +1 -0
  26. package/dist/service/artifact/launcher-file.d.ts +3 -0
  27. package/dist/service/artifact/launcher-file.d.ts.map +1 -0
  28. package/dist/service/artifact/launcher-file.js +13 -0
  29. package/dist/service/artifact/launcher-file.js.map +1 -0
  30. package/dist/service/artifact/write-artifact.d.ts +16 -0
  31. package/dist/service/artifact/write-artifact.d.ts.map +1 -0
  32. package/dist/service/artifact/write-artifact.js +24 -0
  33. package/dist/service/artifact/write-artifact.js.map +1 -0
  34. package/dist/service/build/build-output.d.ts +15 -0
  35. package/dist/service/build/build-output.d.ts.map +1 -0
  36. package/dist/service/build/build-output.js +63 -0
  37. package/dist/service/build/build-output.js.map +1 -0
  38. package/dist/service/build/build-service.d.ts +30 -0
  39. package/dist/service/build/build-service.d.ts.map +1 -0
  40. package/dist/service/build/build-service.js +95 -0
  41. package/dist/service/build/build-service.js.map +1 -0
  42. package/dist/service/build/run-step.d.ts +32 -0
  43. package/dist/service/build/run-step.d.ts.map +1 -0
  44. package/dist/service/build/run-step.js +29 -0
  45. package/dist/service/build/run-step.js.map +1 -0
  46. package/dist/service/index.d.ts +7 -0
  47. package/dist/service/index.d.ts.map +1 -0
  48. package/dist/service/index.js +7 -0
  49. package/dist/service/index.js.map +1 -0
  50. package/dist/service/launcher-contract/events.d.ts +22 -0
  51. package/dist/service/launcher-contract/events.d.ts.map +1 -0
  52. package/dist/service/launcher-contract/events.js +39 -0
  53. package/dist/service/launcher-contract/events.js.map +1 -0
  54. package/dist/service/launcher-contract/start-plan.d.ts +20 -0
  55. package/dist/service/launcher-contract/start-plan.d.ts.map +1 -0
  56. package/dist/service/launcher-contract/start-plan.js +10 -0
  57. package/dist/service/launcher-contract/start-plan.js.map +1 -0
  58. package/dist/service/launcher.mjs +482 -0
  59. package/dist/service/settings/dev-command.d.ts +6 -0
  60. package/dist/service/settings/dev-command.d.ts.map +1 -0
  61. package/dist/service/settings/dev-command.js +46 -0
  62. package/dist/service/settings/dev-command.js.map +1 -0
  63. package/dist/service/settings/index.d.ts +5 -0
  64. package/dist/service/settings/index.d.ts.map +1 -0
  65. package/dist/service/settings/index.js +3 -0
  66. package/dist/service/settings/index.js.map +1 -0
  67. package/dist/service/settings/install.d.ts +15 -0
  68. package/dist/service/settings/install.d.ts.map +1 -0
  69. package/dist/service/settings/install.js +58 -0
  70. package/dist/service/settings/install.js.map +1 -0
  71. package/dist/service/settings/node-version.d.ts +9 -0
  72. package/dist/service/settings/node-version.d.ts.map +1 -0
  73. package/dist/service/settings/node-version.js +18 -0
  74. package/dist/service/settings/node-version.js.map +1 -0
  75. package/dist/service/settings/package-json.d.ts +14 -0
  76. package/dist/service/settings/package-json.d.ts.map +1 -0
  77. package/dist/service/settings/package-json.js +51 -0
  78. package/dist/service/settings/package-json.js.map +1 -0
  79. package/dist/service/settings/resolve.d.ts +9 -0
  80. package/dist/service/settings/resolve.d.ts.map +1 -0
  81. package/dist/service/settings/resolve.js +49 -0
  82. package/dist/service/settings/resolve.js.map +1 -0
  83. package/dist/service/settings/start-order.d.ts +21 -0
  84. package/dist/service/settings/start-order.d.ts.map +1 -0
  85. package/dist/service/settings/start-order.js +138 -0
  86. package/dist/service/settings/start-order.js.map +1 -0
  87. package/dist/service/settings/types.d.ts +66 -0
  88. package/dist/service/settings/types.d.ts.map +1 -0
  89. package/dist/service/settings/types.js +2 -0
  90. package/dist/service/settings/types.js.map +1 -0
  91. package/dist/workspace.d.ts +4 -1
  92. package/dist/workspace.d.ts.map +1 -1
  93. package/dist/workspace.js +12 -23
  94. package/dist/workspace.js.map +1 -1
  95. package/package.json +16 -2
  96. package/src/archive.ts +9 -2
  97. package/src/build-strategy.ts +15 -1
  98. package/src/compute-client.ts +1 -0
  99. package/src/errors.ts +13 -0
  100. package/src/package-manager.ts +27 -0
  101. package/src/service/artifact/exclude.ts +7 -0
  102. package/src/service/artifact/launcher-file.ts +18 -0
  103. package/src/service/artifact/write-artifact.ts +50 -0
  104. package/src/service/build/build-output.ts +95 -0
  105. package/src/service/build/build-service.ts +171 -0
  106. package/src/service/build/run-step.ts +65 -0
  107. package/src/service/index.ts +24 -0
  108. package/src/service/launcher/bin-targets.ts +143 -0
  109. package/src/service/launcher/bin-wrappers.ts +48 -0
  110. package/src/service/launcher/bun-shell.ts +17 -0
  111. package/src/service/launcher/listening-ports.ts +112 -0
  112. package/src/service/launcher/main.ts +54 -0
  113. package/src/service/launcher/package-manager-shims.ts +147 -0
  114. package/src/service/launcher/proc.ts +112 -0
  115. package/src/service/launcher/run-command.ts +82 -0
  116. package/src/service/launcher/serve-static.ts +102 -0
  117. package/src/service/launcher-contract/events.ts +53 -0
  118. package/src/service/launcher-contract/start-plan.ts +18 -0
  119. package/src/service/settings/dev-command.ts +65 -0
  120. package/src/service/settings/index.ts +17 -0
  121. package/src/service/settings/install.ts +105 -0
  122. package/src/service/settings/node-version.ts +26 -0
  123. package/src/service/settings/package-json.ts +71 -0
  124. package/src/service/settings/resolve.ts +80 -0
  125. package/src/service/settings/start-order.ts +213 -0
  126. package/src/service/settings/types.ts +73 -0
  127. package/src/workspace.ts +20 -35
@@ -0,0 +1,143 @@
1
+ // Finds the file that each command in node_modules/.bin runs.
2
+ import { existsSync, readdirSync, readFileSync, realpathSync } from "node:fs";
3
+ import { dirname, join } from "node:path";
4
+
5
+ /** The two fields the Launcher reads. A package can hold any value in them, so they are checked before use. */
6
+ interface PackageManifest {
7
+ name?: unknown;
8
+ bin?: unknown;
9
+ }
10
+
11
+ /**
12
+ * The file each command name runs, for every node_modules/.bin from the Service's folder up to the file system root.
13
+ * The nearest node_modules wins for a name, as it does for `import`.
14
+ */
15
+ export function findBinTargets(serviceDir: string): Map<string, string> {
16
+ const targets = new Map<string, string>();
17
+
18
+ for (const dir of dirAndItsParents(serviceDir)) {
19
+ for (const [name, target] of binTargetsIn(join(dir, "node_modules"))) {
20
+ if (!targets.has(name)) {
21
+ targets.set(name, target);
22
+ }
23
+ }
24
+ }
25
+
26
+ return targets;
27
+ }
28
+
29
+ function dirAndItsParents(dir: string): string[] {
30
+ const parent = dirname(dir);
31
+
32
+ return parent === dir ? [dir] : [dir, ...dirAndItsParents(parent)];
33
+ }
34
+
35
+ /** The commands in `<nodeModules>/.bin` that a package in the same folder declares, each with its real file. */
36
+ function binTargetsIn(nodeModules: string): Map<string, string> {
37
+ const targets = new Map<string, string>();
38
+ const binDir = join(nodeModules, ".bin");
39
+
40
+ if (!existsSync(binDir)) {
41
+ return targets;
42
+ }
43
+
44
+ const declared = declaredBins(nodeModules);
45
+
46
+ for (const name of readdirSync(binDir)) {
47
+ const target = declared.get(name);
48
+
49
+ if (target !== undefined) {
50
+ targets.set(name, target);
51
+ }
52
+ }
53
+
54
+ return targets;
55
+ }
56
+
57
+ /** Every bin that the `bin` field of a package in `nodeModules` names, with the real path of its file. */
58
+ function declaredBins(nodeModules: string): Map<string, string> {
59
+ const bins = new Map<string, string>();
60
+
61
+ for (const packageDir of packageDirs(nodeModules)) {
62
+ for (const [name, path] of binFilesOf(packageDir)) {
63
+ bins.set(name, path);
64
+ }
65
+ }
66
+
67
+ return bins;
68
+ }
69
+
70
+ /** The bins one package declares, each with the real path of its file. */
71
+ function binFilesOf(packageDir: string): [name: string, path: string][] {
72
+ try {
73
+ return (
74
+ Object.entries(readBinField(packageDir))
75
+ .map(([name, file]): [string, string] => [name, join(packageDir, file)])
76
+ // A package can name a bin file that it does not ship.
77
+ .filter(([, path]) => existsSync(path))
78
+ .map(([name, path]) => [name, realpathSync(path)])
79
+ );
80
+ } catch {
81
+ // node_modules can hold anything. A package that cannot be read gets no wrapper, and the Service still starts.
82
+ return [];
83
+ }
84
+ }
85
+
86
+ /** The package folders in `nodeModules`. A scoped package is one level deeper, under `@scope/`. */
87
+ function packageDirs(nodeModules: string): string[] {
88
+ return entriesOf(nodeModules).flatMap((entry) => {
89
+ if (entry.startsWith(".")) {
90
+ return [];
91
+ }
92
+
93
+ if (entry.startsWith("@")) {
94
+ return entriesOf(join(nodeModules, entry)).map((name) =>
95
+ join(nodeModules, entry, name),
96
+ );
97
+ }
98
+
99
+ return [join(nodeModules, entry)];
100
+ });
101
+ }
102
+
103
+ function entriesOf(dir: string): string[] {
104
+ try {
105
+ return readdirSync(dir);
106
+ } catch {
107
+ // An entry that is not a readable folder holds no packages.
108
+ return [];
109
+ }
110
+ }
111
+
112
+ /** The `bin` field of a package as a map from command name to file. A string names one bin, called like the package. */
113
+ function readBinField(packageDir: string): Record<string, string> {
114
+ const { name, bin } = readManifest(packageDir);
115
+
116
+ if (typeof bin === "string") {
117
+ const unscopedName = typeof name === "string" ? name.split("/").pop() : "";
118
+
119
+ return unscopedName ? { [unscopedName]: bin } : {};
120
+ }
121
+
122
+ if (typeof bin !== "object" || bin === null) {
123
+ return {};
124
+ }
125
+
126
+ // A `bin` entry that does not name a file gets no wrapper. The Service may never call it.
127
+ return Object.fromEntries(
128
+ Object.entries(bin).filter(
129
+ (entry): entry is [string, string] => typeof entry[1] === "string",
130
+ ),
131
+ );
132
+ }
133
+
134
+ function readManifest(packageDir: string): PackageManifest {
135
+ const file = join(packageDir, "package.json");
136
+
137
+ // Not every folder in node_modules is a package.
138
+ if (!existsSync(file)) {
139
+ return {};
140
+ }
141
+
142
+ return JSON.parse(readFileSync(file, "utf8")) ?? {};
143
+ }
@@ -0,0 +1,48 @@
1
+ // Wrappers for the commands in node_modules/.bin.
2
+ // A bin file starts with `#!/usr/bin/env node`, which cannot run on the Runtime. A wrapper is a script that Bun runs.
3
+ import {
4
+ chmodSync,
5
+ mkdirSync,
6
+ rmSync,
7
+ symlinkSync,
8
+ writeFileSync,
9
+ } from "node:fs";
10
+ import { join } from "node:path";
11
+ import { findBinTargets } from "./bin-targets.ts";
12
+
13
+ /** The folder that holds every wrapper. It is the first entry of the Service's PATH. */
14
+ export const WRAPPER_DIR = "/tmp/prisma-bin";
15
+
16
+ /** The Bun binary that runs the Launcher. It also runs every wrapper and the Service. */
17
+ export const BUN_BINARY = process.execPath;
18
+
19
+ /** Writes one wrapper for each command in node_modules/.bin. */
20
+ export function writeBinWrappers(serviceDir: string, wrapperDir: string): void {
21
+ mkdirSync(wrapperDir, { recursive: true });
22
+
23
+ for (const [name, target] of findBinTargets(serviceDir)) {
24
+ writeBunScript(join(wrapperDir, name), binWrapperSource(target));
25
+ }
26
+ }
27
+
28
+ /** `node` is a link to Bun, because the Runtime has no Node.js. */
29
+ export function linkNodeToBun(wrapperDir: string): void {
30
+ const link = join(wrapperDir, "node");
31
+
32
+ // A package can declare a bin named `node`. The link replaces its wrapper.
33
+ rmSync(link, { force: true });
34
+ symlinkSync(BUN_BINARY, link);
35
+ }
36
+
37
+ /** Writes an executable script that Bun runs. */
38
+ export function writeBunScript(file: string, source: string): void {
39
+ writeFileSync(file, `#!${BUN_BINARY}\n${source}`);
40
+ chmodSync(file, 0o755);
41
+ }
42
+
43
+ /** The bin file must see its own path as the script name, as it does under Node.js. */
44
+ function binWrapperSource(target: string): string {
45
+ const path = JSON.stringify(target);
46
+
47
+ return `process.argv.splice(1, 1, ${path});\nawait import(${path});\n`;
48
+ }
@@ -0,0 +1,17 @@
1
+ // Runs a command line through Bun's shell, because the Runtime has no /bin/sh.
2
+ import { BUN_BINARY } from "./bin-wrappers.ts";
3
+
4
+ /**
5
+ * Runs `command` in a new Bun process and returns its exit code.
6
+ * The command's output goes straight to the Launcher's output. `Bun.$` in this process would keep
7
+ * all of that output in memory until the command ends, and a Service never ends.
8
+ */
9
+ export function runInBunShell(
10
+ command: string,
11
+ options: { cwd?: string; env?: Record<string, string | undefined> } = {},
12
+ ): Promise<number> {
13
+ return Bun.spawn([BUN_BINARY, "exec", command], {
14
+ ...options,
15
+ stdio: ["inherit", "inherit", "inherit"],
16
+ }).exited;
17
+ }
@@ -0,0 +1,112 @@
1
+ // Finds the port the Service listens on.
2
+ // Compute opens the routed port before the Service starts and hands that socket over, so a new socket alone proves nothing.
3
+ // "The Service listens" means: a process the Launcher started holds a listening socket.
4
+ import {
5
+ readListeningSockets,
6
+ readParentPid,
7
+ readProcessIds,
8
+ readSocketInodes,
9
+ } from "./proc.ts";
10
+
11
+ /** How often the Launcher looks for the Service's port. */
12
+ const POLL_INTERVAL_MS = 200;
13
+
14
+ /** The longest parent chain the Launcher follows. No real chain is this long, and the limit bounds the work of one poll. */
15
+ const MAX_PARENT_STEPS = 64;
16
+
17
+ /**
18
+ * Looks for the Service's port at every poll and calls `onListening` once, with the port to report.
19
+ * Returns the function that stops the search.
20
+ */
21
+ export function watchForListeningPort(
22
+ routedPort: number,
23
+ onListening: (port: number) => void,
24
+ ): () => void {
25
+ let failureLogged = false;
26
+ const timer = setInterval(() => {
27
+ let ports: number[];
28
+ try {
29
+ ports = portsOfProcessesStartedBy(process.pid);
30
+ } catch (error) {
31
+ // A look that fails must not end the Launcher, because that would stop the Service. The next poll looks again.
32
+ if (!failureLogged) {
33
+ failureLogged = true;
34
+ console.error("[prisma] cannot read the Service's ports:", error);
35
+ }
36
+ return;
37
+ }
38
+
39
+ const port = portToReport(ports, routedPort);
40
+
41
+ if (port !== null) {
42
+ clearInterval(timer);
43
+ onListening(port);
44
+ }
45
+ }, POLL_INTERVAL_MS);
46
+
47
+ return () => clearInterval(timer);
48
+ }
49
+
50
+ /**
51
+ * The routed port when the Service listens on it. Else the first port found, so the log shows where the Service listens.
52
+ * Null when the Service listens on no port yet.
53
+ */
54
+ export function portToReport(
55
+ ports: number[],
56
+ routedPort: number,
57
+ ): number | null {
58
+ if (ports.includes(routedPort)) {
59
+ return routedPort;
60
+ }
61
+
62
+ return ports[0] ?? null;
63
+ }
64
+
65
+ /**
66
+ * The ports that processes started by `launcherPid` listen on.
67
+ * The Launcher itself does not count: it can hold the socket that Compute handed over.
68
+ */
69
+ export function portsOfProcessesStartedBy(launcherPid: number): number[] {
70
+ const portByInode = readListeningSockets();
71
+ const ports = new Set<number>();
72
+
73
+ for (const pid of readProcessIds()) {
74
+ if (pid === launcherPid || !isStartedBy(pid, launcherPid, readParentPid)) {
75
+ continue;
76
+ }
77
+
78
+ for (const inode of readSocketInodes(pid)) {
79
+ const port = portByInode.get(inode);
80
+
81
+ if (port !== undefined) {
82
+ ports.add(port);
83
+ }
84
+ }
85
+ }
86
+
87
+ return [...ports];
88
+ }
89
+
90
+ /** True when `ancestorPid` started `pid`, directly or through other processes. */
91
+ export function isStartedBy(
92
+ pid: number,
93
+ ancestorPid: number,
94
+ parentOf: (pid: number) => number | null,
95
+ ): boolean {
96
+ let current: number | null = pid;
97
+
98
+ // Process 1 is the top of every chain.
99
+ for (
100
+ let step = 0;
101
+ step < MAX_PARENT_STEPS && current !== null && current > 1;
102
+ step++
103
+ ) {
104
+ if (current === ancestorPid) {
105
+ return true;
106
+ }
107
+
108
+ current = parentOf(current);
109
+ }
110
+
111
+ return false;
112
+ }
@@ -0,0 +1,54 @@
1
+ // The Launcher: the file Compute starts from an Artifact. It starts the Service.
2
+ // It exists because the Runtime has no /bin/sh and no /usr/bin/env, so `bun run start` cannot work there.
3
+ import { readFileSync } from "node:fs";
4
+ import { dirname, join, resolve } from "node:path";
5
+ import { fileURLToPath } from "node:url";
6
+ import { formatLauncherEvent } from "../launcher-contract/events.ts";
7
+ import {
8
+ DEFAULT_PORT,
9
+ START_PLAN_FILE,
10
+ type StartPlan,
11
+ } from "../launcher-contract/start-plan.ts";
12
+ import {
13
+ actAsPackageManager,
14
+ takeShimRequest,
15
+ } from "./package-manager-shims.ts";
16
+ import { runCommand } from "./run-command.ts";
17
+ import { serveStatic } from "./serve-static.ts";
18
+
19
+ const launcherFile = fileURLToPath(import.meta.url);
20
+
21
+ const shim = takeShimRequest(process.env);
22
+
23
+ if (shim === null) {
24
+ await startService();
25
+ } else {
26
+ process.exit(await actAsPackageManager(shim, process.argv.slice(2)));
27
+ }
28
+
29
+ /** Reads the Start plan, then serves the static folder or runs the start command. Exits with the command's exit code when it ends. */
30
+ async function startService(): Promise<void> {
31
+ // The Launcher is at .prisma/launcher.mjs in the Artifact, so the Service's folder is one level up.
32
+ const serviceDir = resolve(dirname(launcherFile), "..");
33
+ const plan = readStartPlan(serviceDir);
34
+ const port = routedPort(plan);
35
+
36
+ if (plan.kind === "static") {
37
+ serveStatic(resolve(serviceDir, plan.dir), port);
38
+ console.log(formatLauncherEvent({ event: "listening", port }));
39
+ return;
40
+ }
41
+
42
+ process.exit(
43
+ await runCommand({ command: plan.command, serviceDir, port, launcherFile }),
44
+ );
45
+ }
46
+
47
+ function readStartPlan(serviceDir: string): StartPlan {
48
+ return JSON.parse(readFileSync(join(serviceDir, START_PLAN_FILE), "utf8"));
49
+ }
50
+
51
+ /** The port Compute routes to: `PORT` from Compute, else the port in the Start plan, else the default. */
52
+ function routedPort(plan: StartPlan): number {
53
+ return Number(process.env["PORT"] ?? plan.port ?? DEFAULT_PORT);
54
+ }
@@ -0,0 +1,147 @@
1
+ // Shims for the package manager commands that a start command or a package.json script can call.
2
+ // `npm run x`, `yarn x`, `bun run x` and `npx x` cannot run on the Runtime, because `bun run` needs /bin/sh.
3
+ // A shim sets one environment variable and starts the Launcher file again. The Launcher then runs the script or the command itself.
4
+ import { existsSync, readFileSync } from "node:fs";
5
+ import { join } from "node:path";
6
+ import { BUN_BINARY, writeBunScript } from "./bin-wrappers.ts";
7
+ import { runInBunShell } from "./bun-shell.ts";
8
+
9
+ /** What a shim does with its arguments. */
10
+ type ShimBehaviour =
11
+ /** Runs the package.json script the arguments name. */
12
+ | "run script"
13
+ /** Runs the script when package.json has one with that name. Else gives the arguments to Bun. */
14
+ | "run script or Bun"
15
+ /** Runs the arguments as a command, the way `npx <command>` does. */
16
+ | "run command";
17
+
18
+ const SHIM_BEHAVIOURS = {
19
+ npm: "run script",
20
+ pnpm: "run script",
21
+ yarn: "run script",
22
+ bun: "run script or Bun",
23
+ npx: "run command",
24
+ pnpx: "run command",
25
+ bunx: "run command",
26
+ } as const satisfies Record<string, ShimBehaviour>;
27
+
28
+ /** A command name that has a shim. */
29
+ export type ShimName = keyof typeof SHIM_BEHAVIOURS;
30
+
31
+ /** A shim puts its own name in this variable, so the Launcher knows which package manager to act as. */
32
+ const SHIM_VARIABLE = "PRISMA_SHIM";
33
+
34
+ /** The words that can stand before the script name, as in `npm run build`. `yarn build` has none. */
35
+ const RUN_WORDS = ["run", "run-script"];
36
+
37
+ /** The flags that tell `npx` not to ask before a download. The Launcher downloads nothing, so they mean nothing here. */
38
+ const YES_FLAGS = ["-y", "--yes"];
39
+
40
+ interface ScriptRequest {
41
+ /** The script name, or undefined when the arguments name none. */
42
+ script: string | undefined;
43
+ /** The arguments for the script. */
44
+ args: string[];
45
+ }
46
+
47
+ /** Writes one shim for each package manager name into the wrapper folder. */
48
+ export function writePackageManagerShims(
49
+ wrapperDir: string,
50
+ launcherFile: string,
51
+ ): void {
52
+ for (const name of Object.keys(SHIM_BEHAVIOURS)) {
53
+ writeBunScript(join(wrapperDir, name), shimSource(name, launcherFile));
54
+ }
55
+ }
56
+
57
+ function shimSource(name: string, launcherFile: string): string {
58
+ return `process.env.${SHIM_VARIABLE} = ${JSON.stringify(name)};\nawait import(${JSON.stringify(launcherFile)});\n`;
59
+ }
60
+
61
+ /**
62
+ * The name of the shim that started the Launcher, or null when Compute started it.
63
+ * Removes the variable, so the commands this process starts do not get it.
64
+ */
65
+ export function takeShimRequest(env: NodeJS.ProcessEnv): ShimName | null {
66
+ const name = env[SHIM_VARIABLE];
67
+ delete env[SHIM_VARIABLE];
68
+
69
+ return isShimName(name) ? name : null;
70
+ }
71
+
72
+ /** Does what `<shim> <args>` asks for, in the current folder. Returns the exit code. */
73
+ export async function actAsPackageManager(
74
+ shim: ShimName,
75
+ args: string[],
76
+ ): Promise<number> {
77
+ const behaviour = SHIM_BEHAVIOURS[shim];
78
+
79
+ if (behaviour === "run command") {
80
+ return runProgram(withoutYesFlags(args));
81
+ }
82
+
83
+ const request = parseScriptRequest(args);
84
+ const script = readScript(process.cwd(), request.script);
85
+
86
+ if (script !== null) {
87
+ return runScript(script, request.args);
88
+ }
89
+
90
+ if (behaviour === "run script or Bun") {
91
+ return runProgram([BUN_BINARY, ...args]);
92
+ }
93
+
94
+ console.error(`${shim}: no script named "${request.script}" in package.json`);
95
+ return 1;
96
+ }
97
+
98
+ /** Reads `run build --watch`, `run-script build --watch` and `build --watch` as the script `build` with `--watch`. */
99
+ export function parseScriptRequest(args: string[]): ScriptRequest {
100
+ const nameIndex = RUN_WORDS.includes(args[0] ?? "") ? 1 : 0;
101
+
102
+ return { script: args[nameIndex], args: args.slice(nameIndex + 1) };
103
+ }
104
+
105
+ export function withoutYesFlags(args: string[]): string[] {
106
+ return args.filter((arg) => !YES_FLAGS.includes(arg));
107
+ }
108
+
109
+ /** One argument in single quotes, so the shell passes it on unchanged. */
110
+ export function quoteForShell(arg: string): string {
111
+ return `'${arg.replaceAll("'", "'\\''")}'`;
112
+ }
113
+
114
+ function isShimName(name: string | undefined): name is ShimName {
115
+ return name !== undefined && Object.hasOwn(SHIM_BEHAVIOURS, name);
116
+ }
117
+
118
+ /** The command of the script `name` in the package.json of `dir`, or null when there is no such script. */
119
+ function readScript(dir: string, name: string | undefined): string | null {
120
+ const file = join(dir, "package.json");
121
+
122
+ if (name === undefined || !existsSync(file)) {
123
+ return null;
124
+ }
125
+
126
+ const script = readScripts(file)[name];
127
+
128
+ return typeof script === "string" ? script : null;
129
+ }
130
+
131
+ function readScripts(file: string): Record<string, unknown> {
132
+ try {
133
+ return JSON.parse(readFileSync(file, "utf8"))?.scripts ?? {};
134
+ } catch {
135
+ // A package.json that does not parse has no scripts to run. The shim then says that it found no such script.
136
+ return {};
137
+ }
138
+ }
139
+
140
+ /** Runs a package.json script with its arguments. */
141
+ function runScript(script: string, args: string[]): Promise<number> {
142
+ return runInBunShell([script, ...args.map(quoteForShell)].join(" "));
143
+ }
144
+
145
+ async function runProgram(argv: string[]): Promise<number> {
146
+ return Bun.spawn(argv, { stdio: ["inherit", "inherit", "inherit"] }).exited;
147
+ }
@@ -0,0 +1,112 @@
1
+ // Reads from /proc what Linux knows about processes and their sockets.
2
+ // Each `parse` function turns the text of one /proc file into values. Each `read` function reads the file.
3
+ import { readdirSync, readFileSync, readlinkSync } from "node:fs";
4
+
5
+ interface ListeningSocket {
6
+ /** The number that names this socket among the open files of a process. */
7
+ inode: string;
8
+ port: number;
9
+ }
10
+
11
+ /** The state of a listening socket in /proc/net/tcp. */
12
+ const TCP_LISTEN_STATE = "0A";
13
+
14
+ /** The listening sockets in the text of /proc/net/tcp or /proc/net/tcp6. */
15
+ export function parseListeningSockets(text: string): ListeningSocket[] {
16
+ const sockets: ListeningSocket[] = [];
17
+
18
+ for (const line of text.split("\n").slice(1)) {
19
+ // The columns are: slot, local address, remote address, state, five more, inode.
20
+ const columns = line.trim().split(/\s+/);
21
+ const [, localAddress, , state] = columns;
22
+ const inode = columns[9];
23
+
24
+ if (state === TCP_LISTEN_STATE && localAddress && inode) {
25
+ const hexPort = localAddress.slice(localAddress.lastIndexOf(":") + 1);
26
+ sockets.push({ inode, port: Number.parseInt(hexPort, 16) });
27
+ }
28
+ }
29
+
30
+ return sockets;
31
+ }
32
+
33
+ /** The parent process id in the text of /proc/<pid>/stat. */
34
+ export function parseParentPid(stat: string): number {
35
+ // The second field is the command name in parentheses. It can contain spaces and parentheses, so read from the last ")".
36
+ const [, parentPid] = stat.slice(stat.lastIndexOf(")") + 2).split(" ");
37
+
38
+ return Number(parentPid);
39
+ }
40
+
41
+ /** The inode of a socket from the link text of /proc/<pid>/fd/<n>, or null when the open file is not a socket. */
42
+ export function parseSocketInode(link: string): string | null {
43
+ return /^socket:\[(\d+)\]$/.exec(link)?.[1] ?? null;
44
+ }
45
+
46
+ /** The port of every listening socket on the machine, by the socket's inode. */
47
+ export function readListeningSockets(): Map<string, number> {
48
+ const portByInode = new Map<string, number>();
49
+
50
+ for (const file of ["/proc/net/tcp", "/proc/net/tcp6"]) {
51
+ for (const socket of parseListeningSockets(readProcFile(file) ?? "")) {
52
+ portByInode.set(socket.inode, socket.port);
53
+ }
54
+ }
55
+
56
+ return portByInode;
57
+ }
58
+
59
+ export function readProcessIds(): number[] {
60
+ return readdirSync("/proc")
61
+ .filter((name) => /^\d+$/.test(name))
62
+ .map(Number);
63
+ }
64
+
65
+ /** The parent of a process, or null when the process ended. */
66
+ export function readParentPid(pid: number): number | null {
67
+ const stat = readProcFile(`/proc/${pid}/stat`);
68
+
69
+ return stat === null ? null : parseParentPid(stat);
70
+ }
71
+
72
+ /** The inodes of the sockets a process holds open. */
73
+ export function readSocketInodes(pid: number): string[] {
74
+ try {
75
+ return readdirSync(`/proc/${pid}/fd`)
76
+ .map((fd) => parseSocketInode(readlinkSync(`/proc/${pid}/fd/${fd}`)))
77
+ .filter((inode) => inode !== null);
78
+ } catch (error) {
79
+ if (isGoneOrForbidden(error)) {
80
+ // The process ended, or closed a file, after /proc listed it. The next poll sees the new state.
81
+ return [];
82
+ }
83
+
84
+ throw error;
85
+ }
86
+ }
87
+
88
+ /** The text of a file in /proc, or null when the file is not there or may not be read. */
89
+ function readProcFile(file: string): string | null {
90
+ try {
91
+ return readFileSync(file, "utf8");
92
+ } catch (error) {
93
+ if (isGoneOrForbidden(error)) {
94
+ // A process can end between two reads, and a machine without IPv6 has no /proc/net/tcp6.
95
+ return null;
96
+ }
97
+
98
+ throw error;
99
+ }
100
+ }
101
+
102
+ /** The error codes /proc gives for a process that ended (ENOENT, ESRCH) or that belongs to another user (EACCES, EPERM). */
103
+ function isGoneOrForbidden(error: unknown): boolean {
104
+ const code = (error as NodeJS.ErrnoException).code;
105
+
106
+ return (
107
+ code === "ENOENT" ||
108
+ code === "ESRCH" ||
109
+ code === "EACCES" ||
110
+ code === "EPERM"
111
+ );
112
+ }