-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathbuildWorker.ts
More file actions
268 lines (238 loc) · 8.64 KB
/
Copy pathbuildWorker.ts
File metadata and controls
268 lines (238 loc) · 8.64 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
import { ResolvedConfig } from "@trigger.dev/core/v3/build";
import { BuildManifest, BuildTarget } from "@trigger.dev/core/v3/schemas";
import { BundleResult, bundleWorker, createBuildManifestFromBundle } from "./bundle.js";
import { bundleSkills } from "./bundleSkills.js";
import {
createBuildContext,
notifyExtensionOnBuildComplete,
notifyExtensionOnBuildStart,
resolvePluginsForContext,
} from "./extensions.js";
import { createExternalsBuildExtension } from "./externals.js";
import { tmpdir } from "node:os";
import { mkdtemp, rm } from "node:fs/promises";
import { join, relative, sep } from "node:path";
import { generateContainerfile } from "../deploy/buildImage.js";
import { writeFile } from "node:fs/promises";
import { buildManifestToJSON } from "../utilities/buildManifest.js";
import { readPackageJSON } from "pkg-types";
import { writeJSONFile } from "../utilities/fileSystem.js";
import { isWindows } from "std-env";
import { pathToFileURL } from "node:url";
import { logger } from "../utilities/logger.js";
import { SdkVersionExtractor } from "./plugins.js";
import { spinner } from "../utilities/windows.js";
export type BuildWorkerEventListener = {
onBundleStart?: () => void;
onBundleComplete?: (result: BundleResult) => void;
};
export type BuildWorkerOptions = {
destination: string;
target: BuildTarget;
environment: string;
branch?: string;
resolvedConfig: ResolvedConfig;
listener?: BuildWorkerEventListener;
envVars?: Record<string, string>;
rewritePaths?: boolean;
forcedExternals?: string[];
plain?: boolean;
};
export async function buildWorker(options: BuildWorkerOptions) {
logger.debug("Starting buildWorker", {
options,
});
const resolvedConfig = options.resolvedConfig;
const externalsExtension = createExternalsBuildExtension(
options.target,
resolvedConfig,
options.forcedExternals
);
const buildContext = createBuildContext(options.target, resolvedConfig, {
logger: options.plain
? {
debug: (...args) => console.log(...args),
log: (...args) => console.log(...args),
warn: (...args) => console.log(...args),
progress: (message) => console.log(message),
spinner: (message) => {
const $spinner = spinner({ plain: true });
$spinner.start(message);
return $spinner;
},
}
: undefined,
});
buildContext.prependExtension(externalsExtension);
await notifyExtensionOnBuildStart(buildContext);
const pluginsFromExtensions = resolvePluginsForContext(buildContext);
const sdkVersionExtractor = new SdkVersionExtractor();
options.listener?.onBundleStart?.();
const bundleResult = await bundleWorker({
target: options.target,
cwd: resolvedConfig.workingDir,
destination: options.destination,
watch: false,
resolvedConfig,
plugins: [sdkVersionExtractor.plugin, ...pluginsFromExtensions],
jsxFactory: resolvedConfig.build.jsx.factory,
jsxFragment: resolvedConfig.build.jsx.fragment,
jsxAutomatic: resolvedConfig.build.jsx.automatic,
});
options.listener?.onBundleComplete?.(bundleResult);
let buildManifest = await createBuildManifestFromBundle({
bundle: bundleResult,
destination: options.destination,
resolvedConfig,
environment: options.environment,
branch: options.branch,
target: options.target,
envVars: options.envVars,
});
// Built-in skill bundler — discovers `ai.defineSkill` registrations
// via a local indexer run and copies each skill folder into
// `{destination}/.trigger/skills/{id}/` before Docker COPY picks up
// the bundle. First-class, not a build extension.
const skillsTmpDir = await mkdtemp(join(tmpdir(), "trigger-skills-"));
const skillsBuildManifestPath = join(skillsTmpDir, "build.json");
try {
await writeFile(skillsBuildManifestPath, JSON.stringify(buildManifest));
const skillsResult = await bundleSkills({
buildManifest,
buildManifestPath: skillsBuildManifestPath,
workingDir: resolvedConfig.workingDir,
env: {
...process.env,
...(options.envVars ?? {}),
},
logger: buildContext.logger,
});
buildManifest = skillsResult.buildManifest;
} catch (err) {
logger.warn("Skill bundling failed; continuing without skills", err);
} finally {
await rm(skillsTmpDir, { recursive: true, force: true }).catch(() => {});
}
buildManifest = await notifyExtensionOnBuildComplete(buildContext, buildManifest);
if (options.target !== "dev") {
buildManifest = options.rewritePaths
? rewriteBuildManifestPaths(buildManifest, options.destination)
: buildManifest;
await writeDeployFiles({
buildManifest,
resolvedConfig,
outputPath: options.destination,
bundleResult,
});
}
return buildManifest;
}
export function rewriteBuildManifestPaths(
buildManifest: BuildManifest,
destinationDir: string
): BuildManifest {
return {
...buildManifest,
files: buildManifest.files.map((file) => ({
...file,
entry: cleanEntryPath(file.entry),
out: rewriteOutputPath(destinationDir, file.out),
})),
outputPath: rewriteOutputPath(destinationDir, buildManifest.outputPath),
configPath: rewriteOutputPath(destinationDir, buildManifest.configPath),
runControllerEntryPoint: buildManifest.runControllerEntryPoint
? rewriteOutputPath(destinationDir, buildManifest.runControllerEntryPoint)
: undefined,
runWorkerEntryPoint: rewriteOutputPath(destinationDir, buildManifest.runWorkerEntryPoint),
indexControllerEntryPoint: buildManifest.indexControllerEntryPoint
? rewriteOutputPath(destinationDir, buildManifest.indexControllerEntryPoint)
: undefined,
indexWorkerEntryPoint: rewriteOutputPath(destinationDir, buildManifest.indexWorkerEntryPoint),
loaderEntryPoint: buildManifest.loaderEntryPoint
? rewriteOutputPath(destinationDir, buildManifest.loaderEntryPoint)
: undefined,
initEntryPoint: buildManifest.initEntryPoint
? rewriteOutputPath(destinationDir, buildManifest.initEntryPoint)
: undefined,
};
}
// Remove any query parameters from the entry path
// For example, src/trigger/ai.ts?sentryProxyModule=true -> src/trigger/ai.ts
function cleanEntryPath(entry: string): string {
return entry.split("?")[0]!;
}
function rewriteOutputPath(destinationDir: string, filePath: string) {
if (isWindows) {
return `/app/${relative(
pathToFileURL(destinationDir).pathname,
pathToFileURL(filePath).pathname
)
.split(sep)
.join("/")}`;
} else {
return `/app/${relative(destinationDir, filePath)}`;
}
}
async function writeDeployFiles({
buildManifest,
resolvedConfig,
outputPath,
bundleResult,
}: {
buildManifest: BuildManifest;
resolvedConfig: ResolvedConfig;
outputPath: string;
bundleResult: BundleResult;
}) {
// Step 1. Read the package.json file
const packageJson = await readProjectPackageJson(resolvedConfig.packageJsonPath);
if (!packageJson) {
throw new Error("Could not read the package.json file");
}
const dependencies =
buildManifest.externals?.reduce(
(acc, external) => {
acc[external.name] = external.version;
return acc;
},
{} as Record<string, string>
) ?? {};
// Step 3: Write the resolved dependencies to the package.json file
await writeJSONFile(
join(outputPath, "package.json"),
{
...packageJson,
name: packageJson.name ?? "trigger-project",
dependencies: {
...dependencies,
},
trustedDependencies: Object.keys(dependencies).sort(),
devDependencies: {},
peerDependencies: {},
scripts: {},
},
true
);
await writeJSONFile(join(outputPath, "build.json"), buildManifestToJSON(buildManifest));
await writeContainerfile(outputPath, buildManifest);
}
async function readProjectPackageJson(packageJsonPath: string) {
const packageJson = await readPackageJSON(packageJsonPath);
return packageJson;
}
async function writeContainerfile(outputPath: string, buildManifest: BuildManifest) {
if (!buildManifest.runControllerEntryPoint || !buildManifest.indexControllerEntryPoint) {
throw new Error("Something went wrong with the build. Aborting deployment. [code 7789]");
}
const containerfile = await generateContainerfile({
runtime: buildManifest.runtime,
entrypoint: buildManifest.runControllerEntryPoint,
build: buildManifest.build,
image: buildManifest.image,
indexScript: buildManifest.indexControllerEntryPoint,
});
const containerfilePath = join(outputPath, "Containerfile");
logger.debug("Writing Containerfile", { containerfilePath });
logger.debug(containerfile);
await writeFile(containerfilePath, containerfile);
}