Skip to content

Commit daa891b

Browse files
committed
Stop bundling the compile command to allow for more granular testing
1 parent f0436a0 commit daa891b

File tree

7 files changed

+87
-119
lines changed

7 files changed

+87
-119
lines changed

packages/cli-v3/e2e/compile.ts

Lines changed: 40 additions & 59 deletions
Original file line numberDiff line numberDiff line change
@@ -1,84 +1,49 @@
11
#!/usr/bin/env node
22

33
import { esbuildDecorators } from "@anatine/esbuild-decorators";
4-
import { Command, Option } from "commander";
54
import { build } from "esbuild";
65
import { readFileSync } from "node:fs";
76
import { mkdir, writeFile } from "node:fs/promises";
8-
import { join, posix } from "node:path";
7+
import { basename, join, posix, resolve } from "node:path";
98
import invariant from "tiny-invariant";
10-
import { z } from "zod";
11-
import { fromZodError } from "zod-validation-error";
129

1310
import {
1411
bundleDependenciesPlugin,
1512
mockServerOnlyPlugin,
1613
workerSetupImportConfigPlugin,
1714
} from "../src/utilities/build.js";
18-
import { readConfig } from "../src/utilities/configFiles.js";
15+
import { ReadConfigResult } from "../src/utilities/configFiles.js";
1916
import { writeJSONFile } from "../src/utilities/fileSystem.js";
2017
import { logger } from "../src/utilities/logger.js";
21-
import { cliRootPath } from "../src/utilities/resolveInternalFilePath.js";
2218
import { createTaskFileImports, gatherTaskFiles } from "../src/utilities/taskFiles.js";
23-
import { escapeImportPath, spinner } from "../src/utilities/windows.js";
24-
25-
const CompileCommandOptionsSchema = z.object({
26-
logLevel: z.enum(["debug", "info", "log", "warn", "error", "none"]).default("log"),
27-
skipTypecheck: z.boolean().default(false),
28-
outputMetafile: z.string().optional(),
29-
});
30-
31-
export type CompileCommandOptions = z.infer<typeof CompileCommandOptionsSchema>;
32-
33-
export function configureCompileCommand(program: Command) {
34-
program
35-
.command("deploy-compile")
36-
.argument(
37-
"[dir]",
38-
"The project root directory. Usually where the top level package.json is located."
39-
)
40-
.option(
41-
"-l, --log-level <level>",
42-
"The CLI log level to use (debug, info, log, warn, error, none). This does not effect the log level of your trigger.dev tasks.",
43-
"log"
44-
)
45-
.option("--skip-typecheck", "Whether to skip the pre-build typecheck")
46-
.addOption(
47-
new Option(
48-
"--output-metafile <path>",
49-
"If provided, will save the esbuild metafile for the build to the specified path"
50-
).hideHelp()
51-
)
52-
.action(compile);
53-
}
54-
55-
async function compile(dir: string, options: CompileCommandOptions) {
56-
const parsedOptions = CompileCommandOptionsSchema.safeParse(options);
57-
if (!parsedOptions.success) {
58-
throw new Error(fromZodError(parsedOptions.error).toString());
59-
}
60-
logger.loggerLevel = parsedOptions.data.logLevel;
19+
import { escapeImportPath } from "../src/utilities/windows.js";
6120

62-
const resolvedConfig = await readConfig(dir);
21+
type CompileOptions = {
22+
outputMetafile?: string;
23+
resolvedConfig: ReadConfigResult;
24+
};
6325

64-
if (resolvedConfig.status === "error") {
65-
throw new Error(`cannot resolve config in directory ${dir}`);
26+
export async function compile(options: CompileOptions) {
27+
if (options.resolvedConfig.status === "error") {
28+
throw new Error("cannot resolve config");
6629
}
67-
68-
const { config } = resolvedConfig;
69-
const configPath = resolvedConfig.status === "file" ? resolvedConfig.path : undefined;
30+
const { config } = options.resolvedConfig;
31+
const configPath =
32+
options.resolvedConfig.status === "file" ? options.resolvedConfig.path : undefined;
7033

7134
// COPIED FROM compileProject()
7235
// const compileSpinner = spinner();
7336
// compileSpinner.start(`Building project in ${config.projectDir}`);
7437

7538
const taskFiles = await gatherTaskFiles(config);
7639
const workerFacade = readFileSync(
77-
join(cliRootPath(), "workers", "prod", "worker-facade.js"),
40+
resolve("./dist/workers/prod/worker-facade.js"),
41+
// join(cliRootPath(), "workers", "prod", "worker-facade.js"),
7842
"utf-8"
7943
);
8044

81-
const workerSetupPath = join(cliRootPath(), "workers", "prod", "worker-setup.js");
45+
// const workerSetupPath = join(cliRootPath(), "workers", "prod", "worker-setup.js");
46+
const workerSetupPath = resolve("./dist/workers/prod/worker-setup.js");
8247

8348
let workerContents = workerFacade
8449
.replace("__TASKS__", createTaskFileImports(taskFiles))
@@ -106,7 +71,8 @@ async function compile(dir: string, options: CompileCommandOptions) {
10671
const result = await build({
10772
stdin: {
10873
contents: workerContents,
109-
resolveDir: process.cwd(),
74+
// resolveDir: process.cwd(),
75+
resolveDir: config.projectDir,
11076
sourcefile: "__entryPoint.ts",
11177
},
11278
bundle: true,
@@ -118,7 +84,8 @@ async function compile(dir: string, options: CompileCommandOptions) {
11884
platform: "node",
11985
format: "cjs", // This is needed to support opentelemetry instrumentation that uses module patching
12086
target: ["node18", "es2020"],
121-
outdir: "out",
87+
// outdir: "out",
88+
outdir: resolve(config.projectDir, "out"),
12289
banner: {
12390
js: `process.on("uncaughtException", function(error, origin) { if (error instanceof Error) { process.send && process.send({ type: "EVENT", message: { type: "UNCAUGHT_EXCEPTION", payload: { error: { name: error.name, message: error.message, stack: error.stack }, origin }, version: "v1" } }); } else { process.send && process.send({ type: "EVENT", message: { type: "UNCAUGHT_EXCEPTION", payload: { error: { name: "Error", message: typeof error === "string" ? error : JSON.stringify(error) }, origin }, version: "v1" } }); } });`,
12491
},
@@ -155,14 +122,16 @@ async function compile(dir: string, options: CompileCommandOptions) {
155122
}
156123

157124
const entryPointContents = readFileSync(
158-
join(cliRootPath(), "workers", "prod", "entry-point.js"),
125+
resolve("./dist/workers/prod/entry-point.js"),
126+
// join(cliRootPath(), "workers", "prod", "entry-point.js"),
159127
"utf-8"
160128
);
161129

162130
const entryPointResult = await build({
163131
stdin: {
164132
contents: entryPointContents,
165-
resolveDir: process.cwd(),
133+
// resolveDir: process.cwd(),
134+
resolveDir: config.projectDir,
166135
sourcefile: "index.ts",
167136
},
168137
bundle: true,
@@ -175,7 +144,8 @@ async function compile(dir: string, options: CompileCommandOptions) {
175144
packages: "external",
176145
format: "cjs", // This is needed to support opentelemetry instrumentation that uses module patching
177146
target: ["node18", "es2020"],
178-
outdir: "out",
147+
// outdir: "out",
148+
outdir: resolve(config.projectDir, "out"),
179149
define: {
180150
__PROJECT_CONFIG__: JSON.stringify(config),
181151
},
@@ -210,12 +180,21 @@ async function compile(dir: string, options: CompileCommandOptions) {
210180
logger.debug(`Writing compiled files to ${tempDir}`);
211181

212182
// Get the metaOutput for the result build
213-
const metaOutput = result.metafile!.outputs[posix.join("out", "stdin.js")];
183+
// const metaOutput = result.metafile!.outputs[posix.join("out", "stdin.js")];
184+
const metaOutput =
185+
result.metafile!.outputs[
186+
posix.join("e2e", "fixtures", basename(config.projectDir), "out", "stdin.js")
187+
];
214188

215189
invariant(metaOutput, "Meta output for the result build is missing");
216190

217191
// Get the metaOutput for the entryPoint build
218-
const entryPointMetaOutput = entryPointResult.metafile!.outputs[posix.join("out", "stdin.js")];
192+
// const entryPointMetaOutput =
193+
// entryPointResult.metafile!.outputs[posix.join("out", "stdin.js")];
194+
const entryPointMetaOutput =
195+
entryPointResult.metafile!.outputs[
196+
posix.join("e2e", "fixtures", basename(config.projectDir), "out", "stdin.js")
197+
];
219198

220199
invariant(entryPointMetaOutput, "Meta output for the entryPoint build is missing");
221200

@@ -249,4 +228,6 @@ async function compile(dir: string, options: CompileCommandOptions) {
249228
await writeFile(join(tempDir!, "worker.js.map"), workerSourcemapFile.text);
250229
// Save the entryPoint outputFile to /tmp/dir/index.js
251230
await writeFile(join(tempDir!, "index.js"), entryPointOutputFile.text);
231+
232+
return { metaOutput, entryPointMetaOutput };
252233
}

packages/cli-v3/e2e/index.test.ts

Lines changed: 34 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,14 @@
11
import { execa, execaNode } from "execa";
2+
import { readFileSync } from "node:fs";
3+
import { rename, rm } from "node:fs/promises";
24
import { join, resolve } from "node:path";
5+
36
import { typecheckProject } from "../src/commands/deploy";
47
import { readConfig } from "../src/utilities/configFiles";
5-
import { rename, rm } from "node:fs/promises";
6-
import { readFileSync } from "node:fs";
8+
import { compile } from "./compile";
9+
import { Metafile } from "esbuild";
10+
import { Loglevel, LogLevelSchema, PackageManager, PackageManagerSchema } from ".";
11+
import { logger } from "../src/utilities/logger";
712

813
type TestCase = {
914
name: string;
@@ -25,16 +30,31 @@ const testCases = process.env.MOD
2530
? allTestCases.filter(({ name }) => process.env.MOD === name)
2631
: allTestCases;
2732

28-
const commandPath = resolve(join(process.cwd(), "dist/e2e.js"));
29-
const logLevel = process.env.LOG || "log";
30-
const packageManager = process.env.PM || "npm";
33+
let logLevel: Loglevel = "log";
34+
let packageManager: PackageManager = "npm";
35+
36+
try {
37+
logLevel = LogLevelSchema.parse(process.env.LOG);
38+
} catch (e) {
39+
console.error(e);
40+
console.log("Using default log level 'log'");
41+
}
42+
43+
logger.loggerLevel = logLevel;
44+
45+
try {
46+
packageManager = PackageManagerSchema.parse(process.env.PM);
47+
} catch (e) {
48+
console.error(e);
49+
console.log("Using default package manager 'npm'");
50+
}
3151

3252
if (testCases.length > 0) {
3353
console.log(`Using ${packageManager}`);
3454

3555
describe.each(testCases)("fixture $name", async ({ name, skipTypecheck }) => {
3656
const fixtureDir = resolve(join(process.cwd(), "e2e/fixtures", name));
37-
const resolvedConfig = await readConfig(fixtureDir);
57+
const resolvedConfig = await readConfig(fixtureDir, { cwd: fixtureDir });
3858

3959
if (resolvedConfig.status === "error") {
4060
throw new Error(`cannot resolve config in directory ${fixtureDir}`);
@@ -97,16 +117,19 @@ if (testCases.length > 0) {
97117
});
98118
}
99119

120+
let entrypointMetadata: Metafile["outputs"]["out/stdin.js"];
121+
let workerMetadata: Metafile["outputs"]["out/stdin.js"];
122+
100123
test(
101124
"compiles",
102125
async () => {
103-
let compileArgs = ["deploy-compile", fixtureDir, "--log-level", logLevel];
104-
if (skipTypecheck) compileArgs.push("--skip-typecheck");
105-
106126
await expect(
107127
(async () => {
108-
const { stdout } = await execaNode(commandPath, compileArgs, { cwd: fixtureDir });
109-
console.log(stdout);
128+
const { entryPointMetaOutput, metaOutput } = await compile({
129+
resolvedConfig,
130+
});
131+
entrypointMetadata = entryPointMetaOutput;
132+
workerMetadata = metaOutput;
110133
})()
111134
).resolves.not.toThrowError();
112135
},

packages/cli-v3/e2e/index.ts

Lines changed: 8 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,8 @@
1-
#!/usr/bin/env node
2-
3-
import { Command } from "commander";
4-
5-
import { logger } from "../src/utilities/logger.js";
6-
import { configureCompileCommand } from "./compile.js";
7-
8-
const program = new Command();
9-
10-
program.name("trigger.e2e").description("trigger.dev program integration and e2e testing");
11-
12-
configureCompileCommand(program);
13-
14-
const main = async () => {
15-
await program.parseAsync();
16-
};
17-
18-
main().catch((err) => {
19-
if (err instanceof Error) {
20-
logger.error(err);
21-
} else {
22-
logger.error("An unknown error has occurred. Please open an issue on github with the below:");
23-
logger.error(err);
24-
}
25-
process.exit(1);
26-
});
1+
import { z } from "zod";
2+
3+
export const LogLevelSchema = z
4+
.enum(["debug", "info", "log", "warn", "error", "none"])
5+
.default("log");
6+
export type Loglevel = z.infer<typeof LogLevelSchema>;
7+
export const PackageManagerSchema = z.enum(["bun", "npm", "pnpm", "yarn"]).default("npm");
8+
export type PackageManager = z.infer<typeof PackageManagerSchema>;

packages/cli-v3/package.json

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,6 @@
6060
"typecheck": "tsc -p tsconfig.check.json",
6161
"build": "npm run clean && run-p build:**",
6262
"build:main": "tsup",
63-
"build:e2e": "tsup --config tsup.e2e.config.ts",
6463
"build:workers": "tsup --config tsup.workers.config.ts",
6564
"build:prod-containerfile": "cpy --flat src/Containerfile.prod dist/",
6665
"dev": "npm run clean && run-p dev:**",

packages/cli-v3/src/utilities/configFiles.ts

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,7 @@ async function findFilePath(dir: string, fileName: string): Promise<string | und
115115
export type ReadConfigOptions = {
116116
projectRef?: string;
117117
configFile?: string;
118+
cwd?: string;
118119
};
119120

120121
export type ReadConfigResult =
@@ -137,7 +138,7 @@ export async function readConfig(
137138
dir: string,
138139
options?: ReadConfigOptions
139140
): Promise<ReadConfigResult> {
140-
const absoluteDir = path.resolve(process.cwd(), dir);
141+
const absoluteDir = path.resolve(options?.cwd || process.cwd(), dir);
141142

142143
const configPath = await getConfigPath(dir, options?.configFile);
143144

@@ -226,7 +227,7 @@ export async function resolveConfig(path: string, config: Config): Promise<Resol
226227
config.triggerDirectories = await findTriggerDirectories(path);
227228
}
228229

229-
config.triggerDirectories = resolveTriggerDirectories(config.triggerDirectories);
230+
config.triggerDirectories = resolveTriggerDirectories(path, config.triggerDirectories);
230231

231232
logger.debug("Resolved trigger directories", { triggerDirectories: config.triggerDirectories });
232233

packages/cli-v3/src/utilities/taskFiles.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -67,8 +67,8 @@ async function gatherTaskFilesFromDir(
6767
return taskFiles;
6868
}
6969

70-
export function resolveTriggerDirectories(dirs: string[]): string[] {
71-
return dirs.map((dir) => resolve(dir));
70+
export function resolveTriggerDirectories(projectDir: string, dirs: string[]): string[] {
71+
return dirs.map((dir) => resolve(projectDir, dir));
7272
}
7373

7474
const IGNORED_DIRS = ["node_modules", ".git", "dist", "build"];

packages/cli-v3/tsup.e2e.config.ts

Lines changed: 0 additions & 18 deletions
This file was deleted.

0 commit comments

Comments
 (0)