-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathexternals.ts
More file actions
657 lines (538 loc) · 18.2 KB
/
externals.ts
File metadata and controls
657 lines (538 loc) · 18.2 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
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
import * as esbuild from "esbuild";
import { makeRe } from "minimatch";
import { access, mkdir, symlink } from "node:fs/promises";
import { dirname, join } from "node:path";
import { readPackageJSON, resolvePackageJSON } from "pkg-types";
import nodeResolve from "resolve";
import { BuildTarget } from "@trigger.dev/core/v3/schemas";
import {
alwaysExternal,
BuildExtension,
BuildLogger,
ResolvedConfig,
} from "@trigger.dev/core/v3/build";
import { logger } from "../utilities/logger.js";
import { CliApiClient } from "../apiClient.js";
import { resolvePathSync as esmResolveSync } from "mlly";
import braces from "braces";
import { builtinModules } from "node:module";
import { tryCatch } from "@trigger.dev/core/v3";
import { resolveModule } from "./resolveModule.js";
/**
* externals in dev might not be resolvable from the worker directory
* for example, if the external is not an immediate dependency of the project
* and the project is not hoisting the dependency (e.g. pnpm, npm with nested)
*
* This function will create a symbolic link from a place where the external is resolvable
* to the actual resolved external path
*/
async function linkUnresolvableExternals(
externals: Array<CollectedExternal>,
resolveDir: string,
logger: BuildLogger
) {
for (const external of externals) {
if (!(await isExternalResolvable(external, resolveDir, logger))) {
await linkExternal(external, resolveDir, logger);
}
}
}
async function linkExternal(external: CollectedExternal, resolveDir: string, logger: BuildLogger) {
const destinationPath = join(resolveDir, "node_modules");
await mkdir(destinationPath, { recursive: true });
logger.debug("[externals] Make a symbolic link", {
fromPath: external.path,
destinationPath,
external,
});
// For scoped packages, we need to ensure the scope directory exists
if (external.name.startsWith("@")) {
// Get the scope part (e.g., '@huggingface')
const scopeDir = external.name.split("/")[0];
if (scopeDir) {
const scopePath = join(destinationPath, scopeDir);
logger.debug("[externals] Ensure scope directory exists", {
scopeDir,
scopePath,
});
await mkdir(scopePath, { recursive: true });
} else {
logger.debug("[externals] Unable to get the scope directory", {
external,
});
}
}
const symbolicLinkPath = join(destinationPath, external.name);
// Make sure the symbolic link does not exist
try {
await symlink(external.path, symbolicLinkPath, "dir");
} catch (e) {
logger.debug("[externals] Unable to create symbolic link", {
error: e,
fromPath: external.path,
destinationPath,
external,
});
}
}
async function isExternalResolvable(
external: CollectedExternal,
resolveDir: string,
logger: BuildLogger
) {
try {
const resolvedPath = resolveSync(external.name, resolveDir);
logger.debug("[externals][isExternalResolvable] Resolved external", {
resolveDir,
external,
resolvedPath,
});
if (!resolvedPath.includes(external.path)) {
logger.debug(
"[externals][isExternalResolvable] resolvedPath does not match the external.path",
{
resolveDir,
external,
resolvedPath,
}
);
return false;
}
return true;
} catch (e) {
logger.debug("[externals][isExternalResolvable] Unable to resolve external", {
resolveDir,
external,
error: e,
});
return false;
}
}
export type CollectedExternal = {
name: string;
path: string;
version: string;
};
export type ExternalsCollector = {
externals: Array<CollectedExternal>;
plugin: esbuild.Plugin;
};
function createExternalsCollector(
target: BuildTarget,
resolvedConfig: ResolvedConfig,
forcedExternal: string[] = []
): ExternalsCollector {
const externals: Array<CollectedExternal> = [];
const maybeExternals = discoverMaybeExternals(target, resolvedConfig, forcedExternal);
// Cache: resolvedPath (dir) -> packageJsonPath (null = failed to resolve)
const packageJsonCache = new Map<string, string | null>();
// Cache: packageRoot (dir) -> boolean (true = mark as external)
const isExternalCache = new Map<string, boolean>();
return {
externals,
plugin: {
name: "externals",
setup: (build) => {
build.onStart(async () => {
externals.splice(0);
isExternalCache.clear();
});
const autoDetectExternal =
resolvedConfig.build?.autoDetectExternal ??
resolvedConfig.build?.experimental_autoDetectExternal ??
true;
build.onEnd(async () => {
logger.debug("[externals][onEnd] Collected externals", {
externals,
maybeExternals,
autoDetectExternal,
packageJsonCache: packageJsonCache.size,
isExternalCache: isExternalCache.size,
});
});
maybeExternals.forEach((external) => {
build.onResolve({ filter: external.filter, namespace: "file" }, async (args) => {
// Check if the external is already in the externals collection
if (externals.find((e) => e.name === external.raw)) {
return {
external: true,
};
}
const packageName = packageNameForImportPath(args.path);
try {
const resolvedPath = resolveSync(packageName, args.resolveDir);
logger.debug("[externals][onResolve] Resolved external", {
external,
resolvedPath,
args,
packageName,
});
const packageJsonPath = await resolvePackageJSON(dirname(resolvedPath));
if (!packageJsonPath) {
return undefined;
}
logger.debug("[externals][onResolve] Found package.json", {
packageJsonPath,
external,
resolvedPath,
args,
packageName,
});
const packageJson = await readPackageJSON(packageJsonPath);
if (!packageJson || !packageJson.name) {
return undefined;
}
if (!external.filter.test(packageJson.name)) {
logger.debug("[externals][onResolve] Package name does not match", {
external,
packageJson,
resolvedPath,
packageName,
});
return undefined;
}
if (!packageJson.version) {
logger.debug("[externals][onResolve] No version found in package.json", {
external,
packageJson,
resolvedPath,
});
return undefined;
}
externals.push({
name: packageName,
path: dirname(packageJsonPath),
version: packageJson.version,
});
logger.debug("[externals][onResolve] adding external to the externals collection", {
external,
resolvedPath,
args,
packageName,
resolvedExternal: {
name: packageJson.name,
path: dirname(packageJsonPath),
version: packageJson.version,
},
});
return {
external: true,
};
} catch (error) {
logger.debug("[externals][onResolve] Unable to resolve external", {
external,
error,
args,
packageName,
});
return undefined;
}
});
});
if (autoDetectExternal) {
build.onResolve(
{ filter: /.*/, namespace: "file" },
async (args: esbuild.OnResolveArgs): Promise<esbuild.OnResolveResult | undefined> => {
if (!isBareModuleImport(args.path)) {
// Not an npm package
return;
}
if (isBuiltinModule(args.path)) {
// Builtin module
return;
}
if (args.path === "_sentry-debug-id-injection-stub") {
// Ignore sentry stub
return;
}
// Try to resolve the actual file path
const [resolveError, resolvedPath] = await tryCatch(
resolveModule(args.path, args.resolveDir)
);
if (resolveError) {
logger.debug("[externals][auto] Resolve module error", {
path: args.path,
resolveError,
});
return;
}
// Find nearest package.json
const packageJsonPath = await findNearestPackageJson(resolvedPath, packageJsonCache);
if (!packageJsonPath) {
logger.debug("[externals][auto] Failed to resolve package.json path", {
path: args.path,
resolvedPath,
});
return;
}
const packageRoot = dirname(packageJsonPath);
// Check cache first
if (isExternalCache.has(packageRoot)) {
const isExternal = isExternalCache.get(packageRoot);
if (isExternal) {
return { path: args.path, external: true };
}
return;
}
const [readError, packageJson] = await tryCatch(readPackageJSON(packageRoot));
if (readError) {
logger.debug("[externals][auto] Unable to read package.json", {
error: readError,
packageRoot,
});
isExternalCache.set(packageRoot, false);
return;
}
const packageName = packageJson.name;
const packageVersion = packageJson.version;
if (!packageName || !packageVersion) {
logger.debug("[externals][auto] No package name or version found in package.json", {
packageRoot,
packageJson,
});
return;
}
const markExternal = (reason: string): esbuild.OnResolveResult => {
const detectedPackage = {
name: packageName,
path: packageRoot,
version: packageVersion,
} satisfies CollectedExternal;
logger.debug(`[externals][auto] Marking as external - ${reason}`, {
detectedPackage,
});
externals.push(detectedPackage);
// Cache the result
isExternalCache.set(packageRoot, true);
return { path: args.path, external: true };
};
// If the path ends with .wasm or .node, we should mark it as external
if (resolvedPath.endsWith(".wasm") || resolvedPath.endsWith(".node")) {
return markExternal("path ends with .wasm or .node");
}
// Check files, main, module fields for native files
const files = Array.isArray(packageJson.files) ? packageJson.files : [];
const fields = [packageJson.main, packageJson.module, packageJson.browser].filter(
(f): f is string => typeof f === "string"
);
const allFiles = files.concat(fields);
// We need to expand any braces in the files array, e.g. ["{js,ts}"] -> ["js", "ts"]
const allFilesExpanded = braces(allFiles, { expand: true });
// Use a regexp to match native-related extensions
const nativeExtRegexp = /\.(wasm|node|gyp|c|cc|cpp|cxx|h|hpp|hxx)$/;
const hasNativeFile = allFilesExpanded.some((file) => nativeExtRegexp.test(file));
if (hasNativeFile) {
return markExternal("has native file");
}
// Check if binding.gyp exists (native addon)
const bindingGypPath = join(packageRoot, "binding.gyp");
// If access succeeds, binding.gyp exists
const [accessError] = await tryCatch(access(bindingGypPath));
if (!accessError) {
return markExternal("binding.gyp exists");
}
// Cache the negative result
isExternalCache.set(packageRoot, false);
return undefined;
}
);
}
},
},
};
}
type MaybeExternal = { raw: string; filter: RegExp };
function discoverMaybeExternals(
target: BuildTarget,
config: ResolvedConfig,
forcedExternal: string[] = []
): Array<MaybeExternal> {
const external: Array<MaybeExternal> = [];
for (const externalName of forcedExternal) {
const externalRegex = makeRe(externalName);
if (!externalRegex) {
continue;
}
external.push({
raw: externalName,
filter: new RegExp(`^${externalName}$|${externalRegex.source}`),
});
}
if (config.build?.external) {
for (const externalName of config.build?.external) {
const externalRegex = makeExternalRegexp(externalName);
if (!externalRegex) {
continue;
}
external.push({
raw: externalName,
filter: externalRegex,
});
}
}
for (const externalName of config.instrumentedPackageNames ?? []) {
const externalRegex = makeExternalRegexp(externalName);
if (!externalRegex) {
continue;
}
external.push({
raw: externalName,
filter: externalRegex,
});
}
for (const buildExtension of config.build?.extensions ?? []) {
const moduleExternals = buildExtension.externalsForTarget?.(target);
for (const externalName of moduleExternals ?? []) {
const externalRegex = makeExternalRegexp(externalName);
if (!externalRegex) {
continue;
}
external.push({
raw: externalName,
filter: externalRegex,
});
}
}
return external;
}
export function createExternalsBuildExtension(
target: BuildTarget,
config: ResolvedConfig,
forcedExternal: string[] = []
): BuildExtension {
const { externals, plugin } = createExternalsCollector(target, config, forcedExternal);
return {
name: "externals",
onBuildStart(context) {
context.registerPlugin(plugin, {
target,
// @ts-expect-error
placement: "$head", // cheat to get to the front of the plugins
});
},
onBuildComplete: async (context, manifest) => {
if (context.target === "dev") {
await linkUnresolvableExternals(externals, manifest.outputPath, context.logger);
}
context.addLayer({
id: "externals",
dependencies: externals.reduce(
(acc, external) => {
acc[external.name] = external.version;
return acc;
},
{} as Record<string, string>
),
});
},
};
}
function makeExternalRegexp(packageName: string): RegExp {
// Escape special regex characters in the package name
const escapedPkg = packageName.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
// Create the regex pattern
const pattern = `^${escapedPkg}(?:/[^'"]*)?$`;
return new RegExp(pattern);
}
function packageNameForImportPath(importPath: string): string {
// Remove any leading '@' to handle it separately
const withoutAtSign = importPath.replace(/^@/, "");
// Split the path by '/'
const parts = withoutAtSign.split("/");
// Handle scoped packages
if (importPath.startsWith("@")) {
// Return '@org/package' for scoped packages
return "@" + parts.slice(0, 2).join("/");
} else {
// Return just the first part for non-scoped packages
return parts[0] as string;
}
}
export async function resolveAlwaysExternal(client: CliApiClient): Promise<string[]> {
try {
const response = await client.retrieveExternals();
if (response.success) {
return response.data.externals;
}
return alwaysExternal;
} catch (error) {
logger.debug("[externals][resolveAlwaysExternal] Unable to retrieve externals", {
error,
});
return alwaysExternal;
}
}
function resolveSync(id: string, resolveDir: string) {
try {
return nodeResolve.sync(id, { basedir: resolveDir });
} catch (error) {
return esmResolveSync(id, { url: resolveDir });
}
}
function isBareModuleImport(path: string): boolean {
const excludes = [".", "/", "~", "file:", "data:"];
return !excludes.some((exclude) => path.startsWith(exclude));
}
function isBuiltinModule(path: string): boolean {
return builtinModules.includes(path.replace("node:", ""));
}
async function isMainPackageJson(filePath: string): Promise<boolean> {
try {
const packageJson = await readPackageJSON(filePath);
// Allowlist of non-informative fields that can appear with 'type: module | commonjs' in marker package.json files
const markerFields = new Set([
"type",
"sideEffects",
"browser",
"main",
"module",
"react-native",
"name",
]);
if (!packageJson.type) {
return true;
}
const keys = Object.keys(packageJson);
if (keys.every((k) => markerFields.has(k))) {
return false; // type marker
}
return true;
} catch (error) {
if (!(error instanceof Error)) {
logger.debug("[externals][containsEsmTypeMarkers] Unknown error", {
error,
});
return false;
}
if ("code" in error && error.code !== "ENOENT") {
logger.debug("[externals][containsEsmTypeMarkers] Error", {
error: error.message,
});
}
return false;
}
}
async function findNearestPackageJson(
basePath: string,
cache: Map<string, string | null>
): Promise<string | null> {
const baseDir = dirname(basePath);
if (cache.has(baseDir)) {
const resolvedPath = cache.get(baseDir);
if (!resolvedPath) {
return null;
}
return resolvedPath;
}
const [error, packageJsonPath] = await tryCatch(
resolvePackageJSON(dirname(basePath), {
test: isMainPackageJson,
})
);
if (error) {
cache.set(baseDir, null);
return null;
}
cache.set(baseDir, packageJsonPath);
return packageJsonPath;
}