-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathbundle.ts
More file actions
427 lines (383 loc) · 12.9 KB
/
bundle.ts
File metadata and controls
427 lines (383 loc) · 12.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
import { CORE_VERSION } from "@trigger.dev/core/v3";
import { DEFAULT_RUNTIME, ResolvedConfig } from "@trigger.dev/core/v3/build";
import { BuildManifest, BuildTarget, TaskFile } from "@trigger.dev/core/v3/schemas";
import * as esbuild from "esbuild";
import { createHash } from "node:crypto";
import { basename, join, relative, resolve } from "node:path";
import { createFile, createFileWithStore } from "../utilities/fileSystem.js";
import { logger } from "../utilities/logger.js";
import { resolveFileSources } from "../utilities/sourceFiles.js";
import { VERSION } from "../version.js";
import { createEntryPointManager } from "./entryPoints.js";
import { copyManifestToDir } from "./manifests.js";
import {
getIndexControllerForTarget,
getIndexWorkerForTarget,
getRunControllerForTarget,
getRunWorkerForTarget,
isIndexControllerForTarget,
isIndexWorkerForTarget,
isInitEntryPoint,
isLoaderEntryPoint,
isRunControllerForTarget,
isRunWorkerForTarget,
shims,
} from "./packageModules.js";
import { buildPlugins } from "./plugins.js";
import { cliLink, prettyError } from "../utilities/cliOutput.js";
import { SkipLoggingError } from "../cli/common.js";
export interface BundleOptions {
target: BuildTarget;
destination: string;
cwd: string;
resolvedConfig: ResolvedConfig;
jsxFactory?: string;
jsxFragment?: string;
jsxAutomatic?: boolean;
watch?: boolean;
plugins?: esbuild.Plugin[];
/** Shared store directory for deduplicating chunk files via hardlinks */
storeDir?: string;
}
export type BundleResult = {
contentHash: string;
files: TaskFile[];
configPath: string;
metafile: esbuild.Metafile;
loaderEntryPoint: string | undefined;
runWorkerEntryPoint: string | undefined;
runControllerEntryPoint: string | undefined;
indexWorkerEntryPoint: string | undefined;
indexControllerEntryPoint: string | undefined;
initEntryPoint: string | undefined;
stop: (() => Promise<void>) | undefined;
/** Maps output file paths to their content hashes for deduplication */
outputHashes: Record<string, string>;
};
export class BundleError extends Error {
constructor(
message: string,
public readonly issues?: esbuild.Message[]
) {
super(message);
}
}
export async function bundleWorker(options: BundleOptions): Promise<BundleResult> {
const { resolvedConfig } = options;
let currentContext: esbuild.BuildContext | undefined;
const entryPointManager = await createEntryPointManager(
resolvedConfig.dirs,
resolvedConfig,
options.target,
typeof options.watch === "boolean" ? options.watch : false,
async (newEntryPoints) => {
if (currentContext) {
// Rebuild with new entry points
await currentContext.cancel();
await currentContext.dispose();
const buildOptions = await createBuildOptions({
...options,
entryPoints: newEntryPoints,
});
logger.debug("Rebuilding worker with options", buildOptions);
currentContext = await esbuild.context(buildOptions);
await currentContext.watch();
}
}
);
if (entryPointManager.entryPoints.length === 0) {
const errorMessageBody = `
Dirs config:
${resolvedConfig.dirs.join("\n- ")}
Search patterns:
${entryPointManager.patterns.join("\n- ")}
Possible solutions:
1. Check if the directory paths in your config are correct
2. Verify that your files match the search patterns
3. Update the search patterns in your config
`.replace(/^ {6}/gm, "");
prettyError(
"No trigger files found",
errorMessageBody,
cliLink("View the config docs", "https://trigger.dev/docs/config/config-file")
);
throw new SkipLoggingError();
}
let initialBuildResult: (result: esbuild.BuildResult) => void;
const initialBuildResultPromise = new Promise<esbuild.BuildResult>(
(resolve) => (initialBuildResult = resolve)
);
const buildResultPlugin: esbuild.Plugin = {
name: "Initial build result plugin",
setup(build) {
build.onEnd(initialBuildResult);
},
};
const buildOptions = await createBuildOptions({
...options,
entryPoints: entryPointManager.entryPoints,
buildResultPlugin,
});
let result: esbuild.BuildResult<typeof buildOptions>;
let stop: BundleResult["stop"];
logger.debug("Building worker with options", buildOptions);
if (options.watch) {
currentContext = await esbuild.context(buildOptions);
await currentContext.watch();
result = await initialBuildResultPromise;
if (result.errors.length > 0) {
throw new BundleError("Failed to build", result.errors);
}
stop = async function () {
await entryPointManager.stop();
await currentContext?.dispose();
};
} else {
result = await esbuild.build(buildOptions);
stop = async function () {
await entryPointManager.stop();
};
}
const bundleResult = await getBundleResultFromBuild(
options.target,
options.cwd,
options.resolvedConfig,
result,
options.storeDir
);
if (!bundleResult) {
throw new Error("Failed to get bundle result");
}
return { ...bundleResult, stop };
}
// Helper function to create build options
async function createBuildOptions(
options: BundleOptions & { entryPoints: string[]; buildResultPlugin?: esbuild.Plugin }
): Promise<esbuild.BuildOptions & { metafile: true }> {
const customConditions = options.resolvedConfig.build?.conditions ?? [];
const conditions = [...customConditions, "trigger.dev", "module", "node"];
const keepNames =
options.resolvedConfig.build?.keepNames ??
options.resolvedConfig.build?.experimental_keepNames ??
true;
const minify =
options.resolvedConfig.build?.minify ??
options.resolvedConfig.build?.experimental_minify ??
false;
const $buildPlugins = await buildPlugins(options.target, options.resolvedConfig);
return {
entryPoints: options.entryPoints,
outdir: options.destination,
absWorkingDir: options.cwd,
bundle: true,
metafile: true,
write: false,
minify,
splitting: true,
charset: "utf8",
platform: "node",
sourcemap: true,
sourcesContent: options.target === "dev",
conditions,
keepNames,
format: "esm",
target: ["node20", "es2022"],
loader: {
".js": "jsx",
".mjs": "jsx",
".cjs": "jsx",
".wasm": "copy",
},
outExtension: { ".js": ".mjs" },
inject: [...shims], // TODO: copy this into the working dir to work with Yarn PnP
jsx: options.jsxAutomatic ? "automatic" : undefined,
jsxDev: options.jsxAutomatic && options.target === "dev" ? true : undefined,
plugins: [
...$buildPlugins,
...(options.plugins ?? []),
...(options.buildResultPlugin ? [options.buildResultPlugin] : []),
],
...(options.jsxFactory && { jsxFactory: options.jsxFactory }),
...(options.jsxFragment && { jsxFragment: options.jsxFragment }),
logLevel: "silent",
logOverride: {
"empty-glob": "silent",
"package.json": "silent",
},
};
}
export async function getBundleResultFromBuild(
target: BuildTarget,
workingDir: string,
resolvedConfig: ResolvedConfig,
result: esbuild.BuildResult<{ metafile: true; write: false }>,
storeDir?: string
): Promise<Omit<BundleResult, "stop"> | undefined> {
const hasher = createHash("md5");
const outputHashes: Record<string, string> = {};
for (const outputFile of result.outputFiles) {
hasher.update(outputFile.hash);
// Store the hash for each output file (keyed by path)
outputHashes[outputFile.path] = outputFile.hash;
if (storeDir) {
// Use content-addressable store with esbuild's built-in hash for ALL files
await createFileWithStore(outputFile.path, outputFile.contents, storeDir, outputFile.hash);
} else {
await createFile(outputFile.path, outputFile.contents);
}
}
const files: Array<{ entry: string; out: string }> = [];
let configPath: string | undefined;
let loaderEntryPoint: string | undefined;
let runWorkerEntryPoint: string | undefined;
let runControllerEntryPoint: string | undefined;
let indexWorkerEntryPoint: string | undefined;
let indexControllerEntryPoint: string | undefined;
let initEntryPoint: string | undefined;
const configEntryPoint = resolvedConfig.configFile
? relative(resolvedConfig.workingDir, resolvedConfig.configFile)
: "trigger.config.ts";
for (const [outputPath, outputMeta] of Object.entries(result.metafile.outputs)) {
if (outputPath.endsWith(".mjs")) {
const $outputPath = resolve(workingDir, outputPath);
if (!outputMeta.entryPoint) {
continue;
}
if (outputMeta.entryPoint.startsWith(configEntryPoint)) {
configPath = $outputPath;
} else if (isLoaderEntryPoint(outputMeta.entryPoint)) {
loaderEntryPoint = $outputPath;
} else if (isRunControllerForTarget(outputMeta.entryPoint, target)) {
runControllerEntryPoint = $outputPath;
} else if (isRunWorkerForTarget(outputMeta.entryPoint, target)) {
runWorkerEntryPoint = $outputPath;
} else if (isIndexControllerForTarget(outputMeta.entryPoint, target)) {
indexControllerEntryPoint = $outputPath;
} else if (isIndexWorkerForTarget(outputMeta.entryPoint, target)) {
indexWorkerEntryPoint = $outputPath;
} else if (isInitEntryPoint(outputMeta.entryPoint, resolvedConfig.dirs)) {
initEntryPoint = $outputPath;
} else {
if (
!outputMeta.entryPoint.startsWith("..") &&
!outputMeta.entryPoint.includes("node_modules")
) {
files.push({
entry: outputMeta.entryPoint,
out: $outputPath,
});
}
}
}
}
if (!configPath) {
return undefined;
}
return {
files,
configPath: configPath,
loaderEntryPoint,
runWorkerEntryPoint,
runControllerEntryPoint,
indexWorkerEntryPoint,
indexControllerEntryPoint,
initEntryPoint,
contentHash: hasher.digest("hex"),
metafile: result.metafile,
outputHashes,
};
}
// Converts a directory to a glob that matches all the entry points in that
function dirToEntryPointGlob(dir: string): string[] {
return [
join(dir, "**", "*.ts"),
join(dir, "**", "*.tsx"),
join(dir, "**", "*.mts"),
join(dir, "**", "*.cts"),
join(dir, "**", "*.js"),
join(dir, "**", "*.jsx"),
join(dir, "**", "*.mjs"),
join(dir, "**", "*.cjs"),
];
}
export function logBuildWarnings(warnings: esbuild.Message[]) {
const logs = esbuild.formatMessagesSync(warnings, { kind: "warning", color: true });
for (const log of logs) {
console.warn(log);
}
}
/**
* Logs all errors/warnings associated with an esbuild BuildFailure in the same
* style esbuild would.
*/
export function logBuildFailure(errors: esbuild.Message[], warnings: esbuild.Message[]) {
const logs = esbuild.formatMessagesSync(errors, { kind: "error", color: true });
for (const log of logs) {
console.error(log);
}
logBuildWarnings(warnings);
}
export async function createBuildManifestFromBundle({
bundle,
destination,
resolvedConfig,
workerDir,
environment,
branch,
target,
envVars,
sdkVersion,
storeDir,
}: {
bundle: BundleResult;
destination: string;
resolvedConfig: ResolvedConfig;
workerDir?: string;
environment: string;
branch?: string;
target: BuildTarget;
envVars?: Record<string, string>;
sdkVersion?: string;
storeDir?: string;
}): Promise<BuildManifest> {
const buildManifest: BuildManifest = {
contentHash: bundle.contentHash,
runtime: resolvedConfig.runtime ?? DEFAULT_RUNTIME,
environment: environment,
branch,
packageVersion: sdkVersion ?? CORE_VERSION,
cliPackageVersion: VERSION,
target: target,
files: bundle.files,
sources: await resolveFileSources(bundle.files, resolvedConfig),
externals: [],
config: {
project: resolvedConfig.project,
dirs: resolvedConfig.dirs,
},
outputPath: destination,
indexControllerEntryPoint:
bundle.indexControllerEntryPoint ?? getIndexControllerForTarget(target),
indexWorkerEntryPoint: bundle.indexWorkerEntryPoint ?? getIndexWorkerForTarget(target),
runControllerEntryPoint: bundle.runControllerEntryPoint ?? getRunControllerForTarget(target),
runWorkerEntryPoint: bundle.runWorkerEntryPoint ?? getRunWorkerForTarget(target),
loaderEntryPoint: bundle.loaderEntryPoint,
initEntryPoint: bundle.initEntryPoint,
configPath: bundle.configPath,
customConditions: resolvedConfig.build.conditions ?? [],
deploy: {
env: envVars ?? {},
},
build: {},
otelImportHook: {
include: resolvedConfig.instrumentedPackageNames ?? [],
},
// `outputHashes` is only needed for dev builds for the deduplication mechanism during rebuilds.
// For deploys builds, we omit it to ensure deterministic builds
outputHashes: target === "dev" ? bundle.outputHashes : {},
};
if (!workerDir) {
return buildManifest;
}
return copyManifestToDir(buildManifest, destination, workerDir, storeDir);
}