@prisma/compute-sdk 0.49.0 → 0.51.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 (60) hide show
  1. package/README.md +42 -5
  2. package/dist/errors.d.ts +1 -1
  3. package/dist/errors.d.ts.map +1 -1
  4. package/dist/errors.js.map +1 -1
  5. package/dist/nextjs-build.d.ts +14 -0
  6. package/dist/nextjs-build.d.ts.map +1 -1
  7. package/dist/nextjs-build.js +2 -2
  8. package/dist/nextjs-build.js.map +1 -1
  9. package/dist/service/build/build-service.d.ts +3 -2
  10. package/dist/service/build/build-service.d.ts.map +1 -1
  11. package/dist/service/build/build-service.js +68 -25
  12. package/dist/service/build/build-service.js.map +1 -1
  13. package/dist/service/frameworks/framework.d.ts +26 -0
  14. package/dist/service/frameworks/framework.d.ts.map +1 -0
  15. package/dist/service/frameworks/framework.js +2 -0
  16. package/dist/service/frameworks/framework.js.map +1 -0
  17. package/dist/service/frameworks/index.d.ts +7 -0
  18. package/dist/service/frameworks/index.d.ts.map +1 -0
  19. package/dist/service/frameworks/index.js +8 -0
  20. package/dist/service/frameworks/index.js.map +1 -0
  21. package/dist/service/frameworks/nextjs.d.ts +3 -0
  22. package/dist/service/frameworks/nextjs.d.ts.map +1 -0
  23. package/dist/service/frameworks/nextjs.js +77 -0
  24. package/dist/service/frameworks/nextjs.js.map +1 -0
  25. package/dist/service/output/build-output.d.ts +14 -3
  26. package/dist/service/output/build-output.d.ts.map +1 -1
  27. package/dist/service/output/build-output.js +22 -11
  28. package/dist/service/output/build-output.js.map +1 -1
  29. package/dist/service/output/entrypoint.d.ts.map +1 -1
  30. package/dist/service/output/entrypoint.js +4 -22
  31. package/dist/service/output/entrypoint.js.map +1 -1
  32. package/dist/service/output/trace/imports.d.ts +3 -0
  33. package/dist/service/output/trace/imports.d.ts.map +1 -1
  34. package/dist/service/output/trace/imports.js +6 -0
  35. package/dist/service/output/trace/imports.js.map +1 -1
  36. package/dist/service/output/trace/trace.d.ts +8 -3
  37. package/dist/service/output/trace/trace.d.ts.map +1 -1
  38. package/dist/service/output/trace/trace.js +13 -8
  39. package/dist/service/output/trace/trace.js.map +1 -1
  40. package/dist/service/settings/install.d.ts +8 -3
  41. package/dist/service/settings/install.d.ts.map +1 -1
  42. package/dist/service/settings/install.js +28 -11
  43. package/dist/service/settings/install.js.map +1 -1
  44. package/dist/service/settings/resolve.d.ts +4 -1
  45. package/dist/service/settings/resolve.d.ts.map +1 -1
  46. package/dist/service/settings/resolve.js +5 -2
  47. package/dist/service/settings/resolve.js.map +1 -1
  48. package/package.json +1 -1
  49. package/src/errors.ts +5 -1
  50. package/src/nextjs-build.ts +4 -2
  51. package/src/service/build/build-service.ts +86 -25
  52. package/src/service/frameworks/framework.ts +28 -0
  53. package/src/service/frameworks/index.ts +12 -0
  54. package/src/service/frameworks/nextjs.ts +98 -0
  55. package/src/service/output/build-output.ts +32 -13
  56. package/src/service/output/entrypoint.ts +4 -24
  57. package/src/service/output/trace/imports.ts +7 -0
  58. package/src/service/output/trace/trace.ts +25 -17
  59. package/src/service/settings/install.ts +32 -12
  60. package/src/service/settings/resolve.ts +5 -1
@@ -1,9 +1,11 @@
1
1
  // Builds one Service folder and writes its build output. Runs on the Build runner: it needs a shell,
2
2
  // the repository's package manager, and the checkout. It never starts the Service.
3
3
  import { existsSync, readFileSync } from "node:fs";
4
- import { join } from "node:path";
4
+ import { dirname, join, resolve } from "node:path";
5
5
  import { Result } from "better-result";
6
6
  import { ServiceBuildError } from "../../errors.ts";
7
+ import type { Framework } from "../frameworks/framework.ts";
8
+ import { findFramework } from "../frameworks/index.ts";
7
9
  import { type BuildOutput, writeBuildOutput } from "../output/build-output.ts";
8
10
  import { readPackageJson } from "../settings/package-json.ts";
9
11
  import {
@@ -65,9 +67,10 @@ const NO_START: Failure = {
65
67
 
66
68
  /**
67
69
  * Runs the Service's install and build commands, decides how the Service starts, and writes the build output.
70
+ * A framework's own build output comes before the one this package writes.
68
71
  *
69
- * A failed install, a failed build and a missing start are expected outcomes:
70
- * they come back as a `ServiceBuildError`, not as a thrown error.
72
+ * A failed install, a failed build, a missing start and a server that imports files from outside
73
+ * the Service folder are expected outcomes: they come back as a `ServiceBuildError`, not as a thrown error.
71
74
  */
72
75
  export async function buildService(
73
76
  options: BuildServiceOptions,
@@ -78,16 +81,51 @@ export async function buildService(
78
81
  read,
79
82
  options.config,
80
83
  options.signal,
84
+ foldersAboveInRepository(dir),
81
85
  );
86
+ const { packageJson } = await readPackageJson(read);
87
+ // A start the user states in the Service config is final, so no framework changes the build.
88
+ const startIsFromConfig =
89
+ settings.start !== "after build" && settings.start.from === "config";
90
+ const framework = startIsFromConfig ? null : findFramework(packageJson);
82
91
  const steps: BuildStep[] = [];
83
92
  const fail = (failure: Failure) =>
84
93
  Result.err(new ServiceBuildError({ ...failure, settings, steps }));
85
-
86
- const outputDirectories = await installAndBuild(settings, options, steps);
94
+ const done = (start: Resolved<Start>, output: BuildOutput) =>
95
+ Result.ok({
96
+ settings: {
97
+ ...settings,
98
+ start,
99
+ notes: [...settings.notes, ...buildOutputNotes(output)],
100
+ },
101
+ start,
102
+ steps,
103
+ output,
104
+ });
105
+
106
+ const outputDirectories = await installAndBuild(
107
+ settings,
108
+ framework,
109
+ options,
110
+ steps,
111
+ );
87
112
  if (outputDirectories.isErr()) {
88
113
  return fail(outputDirectories.error);
89
114
  }
90
115
 
116
+ const port = settings.port?.value ?? null;
117
+ const fromFramework = await framework?.buildOutput?.({
118
+ serviceDir: dir,
119
+ port,
120
+ signal: options.signal,
121
+ });
122
+ if (fromFramework) {
123
+ return done(
124
+ { value: fromFramework.start, from: "build output" },
125
+ fromFramework.output,
126
+ );
127
+ }
128
+
91
129
  const start =
92
130
  settings.start === "after build"
93
131
  ? await resolveStartAfterBuild(
@@ -103,30 +141,34 @@ export async function buildService(
103
141
  const output = await writeBuildOutput({
104
142
  serviceDir: dir,
105
143
  start: start.value,
106
- port: settings.port?.value ?? null,
107
- packageJson: (await readPackageJson(read)).packageJson,
144
+ port,
145
+ packageJson,
108
146
  outputDirectories: outputDirectories.value,
109
147
  signal: options.signal,
110
148
  });
111
- const notes =
112
- output.kind === "whole folder"
113
- ? [
114
- ...settings.notes,
115
- `The build output is the whole folder, with all of node_modules: ${output.reason}.`,
116
- ]
117
- : settings.notes;
118
-
119
- return Result.ok({
120
- settings: { ...settings, start, notes },
121
- start,
122
- steps,
123
- output,
124
- });
149
+ if (output.isErr()) {
150
+ return fail({
151
+ code: "files_outside_service",
152
+ message: `The server imports files from outside the Service folder, and workspaces are not supported yet. The first such file is ${output.error.outside}.`,
153
+ });
154
+ }
155
+
156
+ return done(start, output.value);
157
+ }
158
+
159
+ /** A note is for a build output the user may want to change. The whole Service folder is one: it is larger than a trace. */
160
+ function buildOutputNotes(output: BuildOutput): string[] {
161
+ if (output.kind === "whole folder") {
162
+ return [`The build output is the whole Service folder: ${output.reason}.`];
163
+ }
164
+
165
+ return [];
125
166
  }
126
167
 
127
168
  /** Runs the install, then the build. Returns what the build created, or the step that failed. */
128
169
  async function installAndBuild(
129
170
  settings: ServiceBuildSettings,
171
+ framework: Framework | null,
130
172
  options: BuildServiceOptions,
131
173
  steps: BuildStep[],
132
174
  ): Promise<Result<OutputDirectories, Failure>> {
@@ -140,7 +182,7 @@ async function installAndBuild(
140
182
  }
141
183
 
142
184
  const beforeBuild = snapshotFolders(dir);
143
- const build = buildStep(settings, env);
185
+ const build = buildStep(settings, framework, env);
144
186
  const built = await runStep(build, run);
145
187
  if (!built.ok) {
146
188
  return Result.err(stepFailed(build, built.output));
@@ -149,15 +191,22 @@ async function installAndBuild(
149
191
  return Result.ok(outputDirectoriesSince(dir, beforeBuild));
150
192
  }
151
193
 
152
- /** The build runs in production mode. The caller's variables win over these. */
194
+ /** The build runs in production mode, with the framework's variables. The caller's variables win over these. */
153
195
  function buildStep(
154
196
  settings: ServiceBuildSettings,
197
+ framework: Framework | null,
155
198
  extraEnv: Record<string, string> = {},
156
199
  ): StepToRun {
157
200
  return {
158
201
  name: "build",
159
202
  command: settings.build.value,
160
- env: { ...process.env, CI: "true", NODE_ENV: "production", ...extraEnv },
203
+ env: {
204
+ ...process.env,
205
+ CI: "true",
206
+ NODE_ENV: "production",
207
+ ...framework?.buildEnv,
208
+ ...extraEnv,
209
+ },
161
210
  };
162
211
  }
163
212
 
@@ -186,7 +235,19 @@ function stepFailed(step: StepToRun, commandOutput: string): Failure {
186
235
  };
187
236
  }
188
237
 
189
- /** Reads the files of the Service folder for the Build rules. */
238
+ /** How many folders above the Service folder belong to the repository: up to the folder that holds `.git`, or to the file system root. */
239
+ function foldersAboveInRepository(dir: string): number {
240
+ let count = 0;
241
+ let folder = resolve(dir);
242
+ while (!existsSync(join(folder, ".git")) && folder !== dirname(folder)) {
243
+ folder = dirname(folder);
244
+ count++;
245
+ }
246
+
247
+ return count;
248
+ }
249
+
250
+ /** Reads the files of the Service folder for the Build rules. A path that starts with `../` reads a folder above it. */
190
251
  function readFrom(dir: string): ReadFile {
191
252
  return (path) =>
192
253
  existsSync(join(dir, path)) ? readFileSync(join(dir, path), "utf8") : null;
@@ -0,0 +1,28 @@
1
+ // A framework definition: how the build of one Service detects a framework, and what the build does differently for it.
2
+ import type { BuildOutput } from "../output/build-output.ts";
3
+ import type { PackageJson, Start } from "../settings/types.ts";
4
+
5
+ export interface Framework {
6
+ /** The name the framework goes by, such as `Next.js`. The build output it produces carries the name. */
7
+ name: string;
8
+ /** True when the Service uses the framework. */
9
+ detect(packageJson: PackageJson): boolean;
10
+ /** Variables for the build command. */
11
+ buildEnv?: Record<string, string>;
12
+ /**
13
+ * Runs after the build. Returns the build output that the framework's build wrote,
14
+ * or null when it wrote none. The build then writes its own build output.
15
+ */
16
+ buildOutput?(service: {
17
+ serviceDir: string;
18
+ /** The port the user stated, or null. */
19
+ port: number | null;
20
+ signal?: AbortSignal;
21
+ }): Promise<FrameworkBuildOutput | null>;
22
+ }
23
+
24
+ /** The build output that a framework's build wrote, and how the Service starts from it. */
25
+ export interface FrameworkBuildOutput {
26
+ output: BuildOutput;
27
+ start: Start;
28
+ }
@@ -0,0 +1,12 @@
1
+ // The framework definitions that the build of one Service knows, in detection order.
2
+ import type { PackageJson } from "../settings/types.ts";
3
+ import type { Framework } from "./framework.ts";
4
+ import { nextjs } from "./nextjs.ts";
5
+
6
+ /** The first definition that detects the Service is its framework. */
7
+ export const FRAMEWORKS: Framework[] = [nextjs];
8
+
9
+ /** The framework the Service uses, or null when no definition detects it. */
10
+ export function findFramework(packageJson: PackageJson): Framework | null {
11
+ return FRAMEWORKS.find((framework) => framework.detect(packageJson)) ?? null;
12
+ }
@@ -0,0 +1,98 @@
1
+ // The Next.js framework definition: `next build` writes standalone output, and that becomes the build output.
2
+ import { statSync } from "node:fs";
3
+ import { rm } from "node:fs/promises";
4
+ import path from "node:path";
5
+ import { stageStandaloneArtifact } from "../../artifact-stage.ts";
6
+ import {
7
+ copyStaticAssets,
8
+ findStandaloneEntrypoint,
9
+ } from "../../nextjs-build.ts";
10
+ import { LAUNCHER_FILE } from "../launcher-contract/start-plan.ts";
11
+ import { BUILD_OUTPUT_FOLDER, writeLauncher } from "../output/build-output.ts";
12
+ import type { Framework } from "./framework.ts";
13
+
14
+ const NAME = "Next.js";
15
+
16
+ /** `next start` alone, with options at most. A command joined to it with `&&`, `;` or `|` is something else. */
17
+ const NEXT_START = /^\s*next\s+start(\s+[^&|;]*)?$/;
18
+
19
+ /**
20
+ * The standalone server replaces the start script. That is only right when the script does nothing
21
+ * but start Next.js: a migration in front of it, a `prestart` script or a custom server would not run.
22
+ */
23
+ function startsOnlyNext(scripts: Record<string, string>): boolean {
24
+ const { start, prestart, poststart } = scripts;
25
+
26
+ return (
27
+ (start === undefined || NEXT_START.test(start)) &&
28
+ prestart === undefined &&
29
+ poststart === undefined
30
+ );
31
+ }
32
+
33
+ /** The output directory of `next build`, relative to the Service folder. */
34
+ const OUTPUT_DIRECTORY = ".next";
35
+
36
+ /** The Launcher runs the start command in a shell, and the path of the server file comes from the file system. */
37
+ function shellWord(filePath: string): string {
38
+ return /^[\w./-]+$/.test(filePath)
39
+ ? filePath
40
+ : `'${filePath.replaceAll("'", "'\\''")}'`;
41
+ }
42
+
43
+ export const nextjs: Framework = {
44
+ name: NAME,
45
+
46
+ detect: ({ dependencies, devDependencies, scripts }) =>
47
+ "next" in { ...dependencies, ...devDependencies } &&
48
+ startsOnlyNext(scripts ?? {}),
49
+
50
+ // `next build` then writes standalone output, as it does for `output: "standalone"` in next.config.
51
+ buildEnv: { NEXT_PRIVATE_STANDALONE: "true" },
52
+
53
+ async buildOutput({ serviceDir, port, signal }) {
54
+ const standaloneDir = path.join(serviceDir, OUTPUT_DIRECTORY, "standalone");
55
+ // A Next.js version that does not read the variable writes no standalone output.
56
+ if (!statSync(standaloneDir, { throwIfNoEntry: false })?.isDirectory()) {
57
+ return null;
58
+ }
59
+
60
+ const dir = path.join(serviceDir, BUILD_OUTPUT_FOLDER);
61
+ await rm(dir, { recursive: true, force: true });
62
+ await stageStandaloneArtifact({
63
+ standaloneDir,
64
+ artifactDir: dir,
65
+ appPath: serviceDir,
66
+ signal,
67
+ });
68
+ // Standalone output with no server file cannot start. The build then writes its own build output.
69
+ const server = await findStandaloneEntrypoint(dir).catch(() => null);
70
+ if (server === null) {
71
+ await rm(dir, { recursive: true, force: true });
72
+
73
+ return null;
74
+ }
75
+
76
+ // Standalone output leaves out `public` and `.next/static`. The server serves them from its own folder.
77
+ await copyStaticAssets({
78
+ appPath: serviceDir,
79
+ artifactDir: dir,
80
+ outputRoot: OUTPUT_DIRECTORY,
81
+ entrypoint: server,
82
+ signal,
83
+ });
84
+
85
+ const command = `node ${shellWord(server)}`;
86
+ writeLauncher(dir, { kind: "command", command, port });
87
+
88
+ return {
89
+ start: { kind: "command", command },
90
+ output: {
91
+ dir,
92
+ entrypoint: LAUNCHER_FILE,
93
+ kind: "standalone output",
94
+ framework: NAME,
95
+ },
96
+ };
97
+ },
98
+ };
@@ -2,6 +2,7 @@
2
2
  import { copyFileSync, mkdirSync, realpathSync, writeFileSync } from "node:fs";
3
3
  import { rm } from "node:fs/promises";
4
4
  import path from "node:path";
5
+ import { Result } from "better-result";
5
6
  import {
6
7
  LAUNCHER_FILE,
7
8
  START_PLAN_FILE,
@@ -17,6 +18,7 @@ import { excludedFromBuildOutput } from "./exclude.ts";
17
18
  import { launcherFile } from "./launcher-file.ts";
18
19
  import { inOutputDirectory, sourceFiles } from "./source-files.ts";
19
20
  import {
21
+ type OutsideServiceFolder,
20
22
  type ServerTrace,
21
23
  traceServer,
22
24
  type Untraceable,
@@ -42,10 +44,16 @@ export type BuildOutput = {
42
44
  trace: TraceSummary;
43
45
  }
44
46
  | {
45
- /** The whole Service folder, with all of `node_modules`, because the server could not be traced. */
47
+ /** The whole Service folder as it is, because the server could not be traced. */
46
48
  kind: "whole folder";
47
49
  reason: Untraceable;
48
50
  }
51
+ | {
52
+ /** The standalone output of a framework's build: a server with only the files of `node_modules` that it loads. */
53
+ kind: "standalone output";
54
+ /** The framework whose build wrote it, such as `Next.js`. */
55
+ framework: string;
56
+ }
49
57
  );
50
58
 
51
59
  /** What the build output of a traced server holds, for the caller to show. Paths are relative to the Service folder. */
@@ -65,6 +73,8 @@ const SCRIPT_FILE = /\.(c|m)?js$/;
65
73
  * - Static files: the folder the build wrote.
66
74
  * - A start command: the source files and the trace of the server it starts, in `.prisma/output`.
67
75
  * - A start command whose server cannot be traced: the whole Service folder.
76
+ *
77
+ * A server that loads files from outside the Service folder gets no build output.
68
78
  */
69
79
  export async function writeBuildOutput(options: {
70
80
  serviceDir: string;
@@ -74,15 +84,22 @@ export async function writeBuildOutput(options: {
74
84
  packageJson: PackageJson;
75
85
  outputDirectories: OutputDirectories;
76
86
  signal?: AbortSignal;
77
- }): Promise<BuildOutput> {
87
+ }): Promise<Result<BuildOutput, OutsideServiceFolder>> {
78
88
  const { start } = options;
79
89
  // The trace holds real paths, so every path here starts from the real path of the Service folder.
80
90
  const serviceDir = realpathSync(options.serviceDir);
91
+ const dir = path.join(serviceDir, BUILD_OUTPUT_FOLDER);
92
+ // An earlier build may have written this folder. It must not stay when the build output is the Service folder itself.
93
+ await rm(dir, { recursive: true, force: true });
81
94
  if (start.kind === "static") {
82
- const dir = path.join(serviceDir, start.dir);
83
- writeLauncher(dir, { kind: "static", dir: ".", port: options.port });
95
+ const staticDir = path.join(serviceDir, start.dir);
96
+ writeLauncher(staticDir, { kind: "static", dir: ".", port: options.port });
84
97
 
85
- return { dir, entrypoint: LAUNCHER_FILE, kind: "static site" };
98
+ return Result.ok({
99
+ dir: staticDir,
100
+ entrypoint: LAUNCHER_FILE,
101
+ kind: "static site",
102
+ });
86
103
  }
87
104
 
88
105
  const plan: StartPlan = {
@@ -106,18 +123,19 @@ export async function writeBuildOutput(options: {
106
123
  ),
107
124
  signal: options.signal,
108
125
  });
109
- const dir = path.join(serviceDir, BUILD_OUTPUT_FOLDER);
110
- // An earlier build may have written this folder. It must not stay in a whole-folder build output.
111
- await rm(dir, { recursive: true, force: true });
112
126
  if (typeof trace === "string") {
113
127
  writeLauncher(serviceDir, plan);
114
128
 
115
- return {
129
+ return Result.ok({
116
130
  dir: serviceDir,
117
131
  entrypoint: LAUNCHER_FILE,
118
132
  kind: "whole folder",
119
133
  reason: trace,
120
- };
134
+ });
135
+ }
136
+
137
+ if ("outside" in trace) {
138
+ return Result.err(trace);
121
139
  }
122
140
 
123
141
  const copied = await copyTracedServer(serviceDir, dir, source, trace);
@@ -125,7 +143,7 @@ export async function writeBuildOutput(options: {
125
143
 
126
144
  const relative = (file: string) => path.relative(serviceDir, file);
127
145
 
128
- return {
146
+ return Result.ok({
129
147
  dir,
130
148
  entrypoint: LAUNCHER_FILE,
131
149
  kind: "traced server",
@@ -136,7 +154,7 @@ export async function writeBuildOutput(options: {
136
154
  bins: trace.bins,
137
155
  optionalPeerDependencies: trace.optionalPeerDependencies,
138
156
  },
139
- };
157
+ });
140
158
  }
141
159
 
142
160
  /** Copies the source files and the trace into the build output folder, each to the place it has in the Service folder. */
@@ -167,7 +185,8 @@ async function copyTracedServer(
167
185
  return copy;
168
186
  }
169
187
 
170
- function writeLauncher(dir: string, plan: StartPlan): void {
188
+ /** Writes the Launcher and the Start plan into a build output folder. */
189
+ export function writeLauncher(dir: string, plan: StartPlan): void {
171
190
  mkdirSync(path.join(dir, path.dirname(LAUNCHER_FILE)), { recursive: true });
172
191
  copyFileSync(launcherFile(), path.join(dir, LAUNCHER_FILE));
173
192
  writeFileSync(path.join(dir, START_PLAN_FILE), JSON.stringify(plan));
@@ -3,7 +3,6 @@
3
3
  import { existsSync, realpathSync, statSync } from "node:fs";
4
4
  import path from "node:path";
5
5
  import type { PackageJson } from "../settings/types.ts";
6
- import { excludedFromBuildOutput } from "./exclude.ts";
7
6
 
8
7
  /** What a start command runs. */
9
8
  export interface StartCommand {
@@ -19,17 +18,10 @@ export interface StartCommand {
19
18
  }
20
19
 
21
20
  const SOURCE_FILE = /\.(c|m)?(j|t)sx?$/;
22
- const RUNTIMES = new Set(["node", "bun", "deno", "tsx", "ts-node"]);
21
+ const RUNTIMES = new Set(["node", "bun", "tsx", "ts-node"]);
23
22
  const PACKAGE_MANAGERS = new Set(["npm", "pnpm", "yarn", "bun"]);
24
23
  /** Runtime options that preload a module before the entrypoint: `--require ./setup.js` or `--require=./setup.js`. */
25
- const PRELOAD_OPTIONS = new Set([
26
- "-r",
27
- "--require",
28
- "--import",
29
- "--loader",
30
- "--experimental-loader",
31
- "--preload",
32
- ]);
24
+ const PRELOAD_OPTIONS = new Set(["-r", "--require", "--import", "--preload"]);
33
25
  /** Node.js reads the value of a preload option as a file only when it is a path. Any other value names a package. */
34
26
  const FILE_PATH = /^\.{0,2}\//;
35
27
  /** Words that run the command after them. */
@@ -146,10 +138,8 @@ function wordsOf(simple: string): string[] {
146
138
  /**
147
139
  * The files a runtime runs and the packages it preloads, from the words after its name.
148
140
  *
149
- * Its entrypoint is the first word that names a script by its extension. With none, it is the
150
- * first word that names a file, as `bin/www` in `node ./bin/www`. The value of another option
151
- * can come first, as `.env` in `node --env-file .env server.js`, so a script wins over it
152
- * and a dotenv file is never the entrypoint.
141
+ * Its entrypoint is the first word that names a script. The value of another option can come
142
+ * first, as `.env` in `node --env-file .env server.js`, and is not a script.
153
143
  */
154
144
  function readRuntimeWords(
155
145
  words: string[],
@@ -160,7 +150,6 @@ function readRuntimeWords(
160
150
  } {
161
151
  const files: string[] = [];
162
152
  const packages: string[] = [];
163
- let withoutExtension: string | undefined;
164
153
 
165
154
  for (let index = 0; index < words.length; index++) {
166
155
  const word = words[index] ?? "";
@@ -181,18 +170,9 @@ function readRuntimeWords(
181
170
  if (file !== null && SOURCE_FILE.test(file)) {
182
171
  return { files: [...files, word], packages };
183
172
  }
184
-
185
- const isDotenv = excludedFromBuildOutput(path.basename(file ?? ""));
186
- if (file !== null && !isDotenv) {
187
- withoutExtension ??= word;
188
- }
189
173
  }
190
174
  }
191
175
 
192
- if (withoutExtension !== undefined) {
193
- files.push(withoutExtension);
194
- }
195
-
196
176
  return { files, packages };
197
177
  }
198
178
 
@@ -1,4 +1,5 @@
1
1
  // Follows imports from files with `@vercel/nft`.
2
+ import { existsSync } from "node:fs";
2
3
  import path from "node:path";
3
4
  import { nodeFileTrace } from "@vercel/nft";
4
5
 
@@ -7,6 +8,9 @@ import { nodeFileTrace } from "@vercel/nft";
7
8
  *
8
9
  * Compute runs a Service with Bun, which reads a package's `bun` export condition.
9
10
  * nft's `conditions` replaces the default set, so the imports are followed twice.
11
+ *
12
+ * nft names files that some versions of a package do not have, such as `preload.js` of `semver`,
13
+ * and fails when it reads one. So a file that does not exist is left out.
10
14
  */
11
15
  export async function traceImports(
12
16
  files: string[],
@@ -22,6 +26,9 @@ export async function traceImports(
22
26
  nodeFileTrace(files, {
23
27
  base,
24
28
  processCwd: serviceDir,
29
+ // nft also passes a folder pattern, such as `views/**/*`, before it lists that folder.
30
+ ignore: (file) =>
31
+ !file.includes("*") && !existsSync(path.join(base, file)),
25
32
  ...(conditions ? { conditions } : {}),
26
33
  }),
27
34
  ),
@@ -26,10 +26,16 @@ export interface ServerTrace {
26
26
  optionalPeerDependencies: string[];
27
27
  }
28
28
 
29
- /** Why a server could not be traced. */
29
+ /** Why a server could not be traced. Its build output is then the whole Service folder. */
30
30
  export type Untraceable =
31
31
  | "the start command runs no file and no bin that can be followed"
32
- | "the server imports files from outside the Service folder";
32
+ | `the imports of the server could not be followed: ${string}`;
33
+
34
+ /** The server loads files from outside the Service folder. No build output can hold them. */
35
+ export interface OutsideServiceFolder {
36
+ /** The first such file, relative to the Service folder. */
37
+ outside: string;
38
+ }
33
39
 
34
40
  /**
35
41
  * Traces the server that `command` starts:
@@ -44,7 +50,7 @@ export async function traceServer(options: {
44
50
  /** Scripts in the output directories. A framework's server loads them by path, and they import packages. */
45
51
  builtScripts: string[];
46
52
  signal?: AbortSignal;
47
- }): Promise<ServerTrace | Untraceable> {
53
+ }): Promise<ServerTrace | Untraceable | OutsideServiceFolder> {
48
54
  const { packageJson } = options;
49
55
  // Traced files are real paths, so the Service folder they are compared with must be its real path too.
50
56
  const serviceDir = realpathSync(options.serviceDir);
@@ -58,10 +64,17 @@ export async function traceServer(options: {
58
64
  }
59
65
 
60
66
  options.signal?.throwIfAborted();
61
- const files = await traceImports(
62
- [...entrypoints, ...options.builtScripts],
63
- serviceDir,
64
- );
67
+ let files: string[];
68
+ try {
69
+ files = await traceImports(
70
+ [...entrypoints, ...options.builtScripts],
71
+ serviceDir,
72
+ );
73
+ } catch (error) {
74
+ const cause = error instanceof Error ? error.message : String(error);
75
+
76
+ return `the imports of the server could not be followed: ${cause}`;
77
+ }
65
78
 
66
79
  const packages = binPackages(serviceDir, bins);
67
80
  // A preloaded package goes in whole, as a bin's package does: `tsx` loads its own files by path.
@@ -77,16 +90,11 @@ export async function traceServer(options: {
77
90
  addWithDependencies(peer, packages);
78
91
  }
79
92
 
80
- const inside = (file: string) => {
81
- const relative = path.relative(serviceDir, file);
82
-
83
- return !relative.startsWith("..") && !path.isAbsolute(relative);
84
- };
85
- if (
86
- !files.every(inside) ||
87
- ![...packages.values()].every((found) => inside(found.dir))
88
- ) {
89
- return "the server imports files from outside the Service folder";
93
+ const outside = [...files, ...[...packages.values()].map(({ dir }) => dir)]
94
+ .map((file) => path.relative(serviceDir, file))
95
+ .find((file) => file.startsWith("..") || path.isAbsolute(file));
96
+ if (outside !== undefined) {
97
+ return { outside };
90
98
  }
91
99
 
92
100
  return {