forked from vercel/pkg
-
-
Notifications
You must be signed in to change notification settings - Fork 62
Expand file tree
/
Copy pathwalker.ts
More file actions
1427 lines (1216 loc) · 37.4 KB
/
walker.ts
File metadata and controls
1427 lines (1216 loc) · 37.4 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
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import assert from 'assert';
import fs from 'fs/promises';
import path from 'path';
import module, { builtinModules } from 'module';
import picomatch from 'picomatch';
import { globSync } from 'tinyglobby';
import {
ALIAS_AS_RELATIVE,
ALIAS_AS_RESOLVABLE,
STORE_BLOB,
STORE_CONTENT,
STORE_LINKS,
STORE_STAT,
isDotJS,
isDotJSON,
isDotNODE,
isPackageJson,
unlikelyJavascript,
normalizePath,
toNormalizedRealPath,
isESMFile,
} from './common';
import { pc } from './colors';
import { follow } from './follow';
import { log, wasReported } from './log';
import * as detector from './detector';
import { transformESMtoCJS, rewriteMjsRequirePaths } from './esm-transformer';
import {
ConfigDictionary,
FileRecord,
FileRecords,
Marker,
Patches,
PackageJson,
SymLinks,
WalkerParams,
} from './types';
import pkgOptions from './options';
export type { Marker, WalkerParams };
interface Task {
file: string;
data?: unknown;
reason?: string;
marker?: Marker;
store: number;
}
interface Derivative {
alias: string;
mayExclude?: boolean;
mustExclude?: boolean;
aliasType: number;
fromDependencies?: boolean;
}
// Note: as a developer, you can set the PKG_STRICT_VER variable.
// this will turn on some assertion in the walker code below
// to assert that each file content/state that we appending
// to the virtual file system applies to a real file,
// not a symlink.
// By default assertion are disabled as they can have a
// performance hit.
const strictVerify = Boolean(process.env.PKG_STRICT_VER);
const win32 = process.platform === 'win32';
// Extensions to try when resolving modules
// Includes .mjs to support ESM files that get transformed to .js
const MODULE_RESOLVE_EXTENSIONS = ['.js', '.json', '.node', '.mjs'];
/**
* Checks if a module is a core module
* module.isBuiltin is available in Node.js 16.17.0 or later. Use that if available
* as prefix-only modules (those starting with 'node:') can only be checked that way.
*/
function isBuiltin(moduleName: string) {
if (
Reflect.has(module, 'isBuiltin') &&
typeof module.isBuiltin === 'function'
) {
return module.isBuiltin(moduleName);
}
const moduleNameWithoutPrefix = moduleName.startsWith('node:')
? moduleName.slice(5)
: moduleName;
return builtinModules.includes(moduleNameWithoutPrefix);
}
function isPublic(config: PackageJson) {
if (config.private) {
return false;
}
const { licenses } = config;
let { license } = config;
if (licenses) {
license = licenses;
}
if (license && !Array.isArray(license)) {
license = typeof license === 'string' ? license : license.type;
}
if (Array.isArray(license)) {
license = license.map((c) => String(c.type || c)).join(',');
}
if (!license) {
return false;
}
if (/^\(/.test(license)) {
license = license.slice(1);
}
if (/\)$/.test(license)) {
license = license.slice(0, -1);
}
license = license.toLowerCase();
const allLicenses = Array.prototype.concat(
license.split(' or '),
license.split(' and '),
license.split('/'),
license.split(','),
);
let result = false;
const foss = [
'isc',
'mit',
'apache-2.0',
'apache 2.0',
'public domain',
'bsd',
'bsd-2-clause',
'bsd-3-clause',
'wtfpl',
'cc-by-3.0',
'x11',
'artistic-2.0',
'gplv3',
'mpl',
'mplv2.0',
'unlicense',
'apache license 2.0',
'zlib',
'mpl-2.0',
'nasa-1.3',
'apache license, version 2.0',
'lgpl-2.1+',
'cc0-1.0',
];
for (const c of allLicenses) {
result = foss.indexOf(c) >= 0;
if (result) {
break;
}
}
return result;
}
function upon(p: string, base: string) {
if (typeof p !== 'string') {
throw wasReported('Config items must be strings. See examples');
}
let negate = false;
if (p[0] === '!') {
p = p.slice(1);
negate = true;
}
p = path.join(base, p);
if (win32) {
p = p.replace(/\\/g, '/');
}
if (negate) {
p = `!${p}`;
}
return p;
}
function collect(ps: string[]) {
return globSync(ps, { absolute: true, dot: true });
}
function expandFiles(efs: string | string[], base: string) {
if (!Array.isArray(efs)) {
efs = [efs];
}
efs = collect(efs.map((p) => upon(p, base)));
return efs;
}
async function stepRead(record: FileRecord) {
if (strictVerify) {
assert(record.file === toNormalizedRealPath(record.file));
}
let body;
try {
body = await fs.readFile(record.file);
} catch (error) {
const exception = error as NodeJS.ErrnoException;
log.error(`Cannot read file, ${exception.code}`, record.file);
throw wasReported(exception.message);
}
record.body = body;
}
// Strip BOM and shebang from the file body.
//
// IMPORTANT: leave `record.body` untouched on no-op. Reassigning it (e.g.
// `record.body = body.toString('utf8')`) would convert Buffer → string even
// when nothing was stripped, defeating the in-memory body reuse optimization
// in `sea-assets.ts`: the SEA archive writer trusts that an unmodified body
// equals the disk content byte-for-byte, so we must not silently retype it.
function stepStrip(record: FileRecord) {
const original = (record.body || '').toString('utf8');
let body = original;
if (/^\ufeff/.test(body)) {
body = body.replace(/^\ufeff/, '');
}
if (/^#!/.test(body)) {
body = body.replace(/^#![^\n]*\n/, '\n');
}
if (body !== original) {
record.body = body;
}
}
function stepDetect(
record: FileRecord,
marker: Marker,
derivatives: Derivative[],
) {
let { body = '' } = record;
if (body instanceof Buffer) {
body = body.toString();
}
try {
detector.detect(
body,
(node, trying) => {
const { toplevel } = marker;
let d = detector.visitorSuccessful(node) as unknown as Derivative;
if (d) {
if (d.mustExclude) {
return false;
}
d.mayExclude = d.mayExclude || trying;
derivatives.push(d);
return false;
}
d = detector.visitorNonLiteral(node) as unknown as Derivative;
if (d) {
if (typeof d === 'object' && d.mustExclude) {
return false;
}
const debug = !toplevel || d.mayExclude || trying;
const level = debug ? 'debug' : 'warn';
log[level](`Cannot resolve '${d.alias}'`, [
record.file,
'Dynamic require may fail at run time, because the requested file',
'is unknown at compilation time and not included into executable.',
"Use a string literal as an argument for 'require', or leave it",
"as is and specify the resolved file name in 'scripts' option.",
]);
return false;
}
d = detector.visitorMalformed(node) as unknown as Derivative;
if (d) {
// there is no 'mustExclude'
const debug = !toplevel || trying;
const level = debug ? 'debug' : 'warn'; // there is no 'mayExclude'
log[level](`Malformed requirement for '${d.alias}'`, [record.file]);
return false;
}
d = detector.visitorUseSCWD(node) as unknown as Derivative;
if (d) {
// there is no 'mustExclude'
const level = 'debug'; // there is no 'mayExclude'
log[level](`Path.resolve(${d.alias}) is ambiguous`, [
record.file,
"It resolves relatively to 'process.cwd' by default, however",
"you may want to use 'path.dirname(require.main.filename)'",
]);
return false;
}
return true; // can i go inside?
},
record.file,
);
} catch (error) {
log.error((error as Error).message, record.file);
throw wasReported((error as Error).message);
}
}
/**
* Find a common junction point between a symlink and the real file path.
*
* @param {string} file The file path, including symlink(s).
* @param {string} realFile The real path to the file.
*
* @throws {Error} If no common junction point is found prior to hitting the
* filesystem root.
*/
async function findCommonJunctionPoint(file: string, realFile: string) {
// find common denominator => where the link changes
while (true) {
const stats = await fs.lstat(file);
if (stats.isSymbolicLink()) {
return { file, realFile };
}
file = path.dirname(file);
realFile = path.dirname(realFile);
// If the directory is /, break out of the loop and log an error.
if (
file === path.parse(file).root ||
realFile === path.parse(realFile).root
) {
throw new Error(
'Reached root directory without finding a common junction point',
);
}
}
}
class Walker {
private params: WalkerParams;
private symLinks: SymLinks;
private patches: Patches;
private tasks: Task[];
private records: FileRecords;
private dictionary: ConfigDictionary;
constructor() {
this.tasks = [];
this.records = {};
this.dictionary = {};
this.patches = {};
this.params = {};
this.symLinks = {};
}
appendRecord({ file, store }: Task) {
if (this.records[file]) {
return;
}
if (
store === STORE_BLOB ||
store === STORE_CONTENT ||
store === STORE_LINKS
) {
// make sure we have a real file
if (strictVerify) {
assert(file === toNormalizedRealPath(file));
}
}
this.records[file] = { file };
}
private append(task: Task) {
if (strictVerify) {
assert(typeof task.file === 'string');
assert(task.file === normalizePath(task.file));
}
this.appendRecord(task);
this.tasks.push(task);
const what = {
[STORE_BLOB]: 'Bytecode of',
[STORE_CONTENT]: 'Content of',
[STORE_LINKS]: 'Directory',
[STORE_STAT]: 'Stat info of',
}[task.store];
if (task.reason) {
log.debug(
`${what} ${task.file} is added to queue. It was required from ${task.reason}`,
);
} else {
log.debug(`${what} ${task.file} is added to queue.`);
}
}
async appendSymlink(file: string, realFile: string) {
const a = await findCommonJunctionPoint(file, realFile);
file = a.file;
realFile = a.realFile;
if (!this.symLinks[file]) {
const dn = path.dirname(file);
this.appendFileInFolder({
file: dn,
store: STORE_LINKS,
data: path.basename(file),
});
log.debug(`adding symlink ${file} => ${path.relative(file, realFile)}`);
this.symLinks[file] = realFile;
this.appendStat({
file: realFile,
store: STORE_STAT,
});
this.appendStat({
file: dn,
store: STORE_STAT,
});
this.appendStat({
file,
store: STORE_STAT,
});
}
}
appendStat(task: Task) {
assert(task.store === STORE_STAT);
this.append(task);
}
appendFileInFolder(task: Task) {
if (strictVerify) {
assert(task.store === STORE_LINKS);
assert(typeof task.file === 'string');
}
const realFile = toNormalizedRealPath(task.file);
if (realFile === task.file) {
this.append(task);
return;
}
this.append({ ...task, file: realFile });
this.appendStat({
file: task.file,
store: STORE_STAT,
});
this.appendStat({
file: path.dirname(task.file),
store: STORE_STAT,
});
}
async appendBlobOrContent(task: Task) {
if (strictVerify) {
assert(task.file === normalizePath(task.file));
}
assert(task.store === STORE_BLOB || task.store === STORE_CONTENT);
// In SEA mode, always store as content (no V8 bytecode compilation)
if (this.params.seaMode && task.store === STORE_BLOB) {
task.store = STORE_CONTENT;
}
assert(typeof task.file === 'string');
const realFile = toNormalizedRealPath(task.file);
const { ignore } = pkgOptions.get();
if (ignore) {
// check if the file matches one of the ignore regex patterns
const match = picomatch.isMatch(realFile, ignore, {
windows: win32,
});
if (match) {
log.debug(
`Ignoring file: ${realFile} due to top level config ignore pattern`,
);
return;
}
}
if (realFile === task.file) {
this.append(task);
return;
}
this.append({ ...task, file: realFile });
await this.appendSymlink(task.file, realFile);
this.appendStat({
file: task.file,
store: STORE_STAT,
});
}
async appendFilesFromConfig(marker: Marker) {
const { config, configPath, base } = marker;
const pkgConfig = config?.pkg;
if (pkgConfig) {
let { scripts } = pkgConfig;
if (scripts) {
scripts = expandFiles(scripts, base);
for (const script of scripts) {
const stat = await fs.stat(script);
if (stat.isFile()) {
if (!isDotJS(script) && !isDotJSON(script) && !isDotNODE(script)) {
log.warn("Non-javascript file is specified in 'scripts'.", [
'Pkg will probably fail to parse. Specify *.js in glob.',
script,
]);
}
await this.appendBlobOrContent({
file: normalizePath(script),
marker,
store: STORE_BLOB,
reason: configPath,
});
}
}
}
let { assets } = pkgConfig;
if (assets) {
assets = expandFiles(assets, base);
for (const asset of assets) {
log.debug(' Adding asset : .... ', asset);
const stat = await fs.stat(asset);
if (stat.isFile()) {
await this.appendBlobOrContent({
file: normalizePath(asset),
marker,
store: STORE_CONTENT,
reason: configPath,
});
}
}
}
} else if (config) {
let { files } = config;
if (files) {
files = expandFiles(files, base);
for (let file of files) {
file = normalizePath(file);
const stat = await fs.stat(file);
if (stat.isFile()) {
// 1) remove sources of top-level(!) package 'files' i.e. ship as BLOB
// 2) non-source (non-js) files of top-level package are shipped as CONTENT
// 3) parsing some js 'files' of non-top-level packages fails, hence all CONTENT
if (marker.toplevel) {
await this.appendBlobOrContent({
file,
marker,
store: isDotJS(file) ? STORE_BLOB : STORE_CONTENT,
reason: configPath,
});
} else {
await this.appendBlobOrContent({
file,
marker,
store: STORE_CONTENT,
reason: configPath,
});
}
}
}
}
}
}
async stepActivate(marker: Marker, derivatives: Derivative[]) {
if (!marker) {
assert(false);
}
if (marker.activated) {
return;
}
const { config, base } = marker;
if (!config) {
assert(false);
}
const { name } = config;
if (name) {
const d = this.dictionary[name];
if (d) {
if (
typeof config.dependencies === 'object' &&
typeof d.dependencies === 'object'
) {
Object.assign(config.dependencies, d.dependencies);
delete d.dependencies;
}
Object.assign(config, d);
marker.hasDictionary = true;
}
}
const { dependencies } = config;
if (typeof dependencies === 'object') {
for (const dependency in dependencies) {
// it may be `undefined` - overridden
// in dictionary (see publicsuffixlist)
if (dependencies[dependency]) {
derivatives.push({
alias: dependency,
aliasType: ALIAS_AS_RESOLVABLE,
fromDependencies: true,
});
derivatives.push({
alias: `${dependency}/package.json`,
aliasType: ALIAS_AS_RESOLVABLE,
fromDependencies: true,
});
}
}
}
const pkgConfig = config.pkg;
if (pkgConfig) {
const { patches } = pkgConfig;
if (patches) {
for (const key in patches) {
if (patches[key]) {
const p = path.join(base, key);
this.patches[p] = patches[key];
}
}
}
const { deployFiles } = pkgConfig;
if (deployFiles) {
marker.hasDeployFiles = true;
for (const deployFile of deployFiles) {
const type = deployFile[2] || 'file';
log.warn(`Cannot include ${type} %1 into executable.`, [
`The ${type} must be distributed with executable as %2.`,
`%1: ${path.relative(
process.cwd(),
path.join(base, deployFile[0]),
)}`,
`%2: path-to-executable/${deployFile[1]}`,
]);
}
}
if (pkgConfig.log) {
pkgConfig.log(log, { packagePath: base });
}
}
await this.appendFilesFromConfig(marker);
marker.public = isPublic(config);
if (!marker.public && marker.toplevel) {
marker.public = this.params.publicToplevel;
}
if (!marker.public && !marker.toplevel && this.params.publicPackages) {
marker.public =
this.params.publicPackages[0] === '*' ||
(!!name && this.params.publicPackages.indexOf(name) !== -1);
}
marker.activated = true;
// assert no further work with config
delete marker.config;
}
hasPatch(record: FileRecord) {
const patch = this.patches[record.file];
if (!patch) {
return;
}
return true;
}
needsSeaRead(record: FileRecord): boolean {
return (
!!this.params.seaMode && (isDotJS(record.file) || isESMFile(record.file))
);
}
stepPatch(record: FileRecord) {
const patch = this.patches[record.file];
if (!patch) {
return;
}
let body = (record.body || '').toString('utf8');
for (let i = 0; i < patch.length; i += 2) {
if (typeof patch[i] === 'object') {
if (patch[i].do === 'erase') {
body = patch[i + 1];
} else if (patch[i].do === 'prepend') {
body = patch[i + 1] + body;
} else if (patch[i].do === 'append') {
body += patch[i + 1];
}
} else if (typeof patch[i] === 'string') {
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
// function escapeRegExp
const esc = patch[i].replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const regexp = new RegExp(esc, 'g');
body = body.replace(regexp, patch[i + 1]);
}
}
record.body = body;
}
async stepDerivatives_ALIAS_AS_RELATIVE(
record: FileRecord,
marker: Marker,
derivative: Derivative,
) {
const file = normalizePath(
path.join(path.dirname(record.file), derivative.alias),
);
let stat;
try {
stat = await fs.stat(file);
} catch (error) {
const { toplevel } = marker;
const exception = error as NodeJS.ErrnoException;
const debug = !toplevel && exception.code === 'ENOENT';
const level = debug ? 'debug' : 'warn';
log[level](`Cannot stat, ${exception.code}`, [
file,
`The file was required from '${record.file}'`,
]);
}
if (stat && stat.isFile()) {
await this.appendBlobOrContent({
file,
marker,
store: STORE_CONTENT,
reason: record.file,
});
}
}
async stepDerivatives_ALIAS_AS_RESOLVABLE(
record: FileRecord,
marker: Marker,
derivative: Derivative,
) {
const newPackages: { packageJson: string; marker?: Marker }[] = [];
const catchReadFile = (file: string) => {
assert(isPackageJson(file), `walker: ${file} must be package.json`);
newPackages.push({ packageJson: file });
};
const catchPackageFilter = (config: PackageJson, base: string) => {
const newPackage = newPackages[newPackages.length - 1];
newPackage.marker = {
config,
configPath: newPackage.packageJson,
base,
};
};
let newFile = '';
let failure: Error | undefined;
const basedir = path.dirname(record.file);
try {
newFile = await follow(derivative.alias, {
basedir,
// default is extensions: ['.js'], but
// it is not enough because 'typos.json'
// is not taken in require('./typos')
// in 'normalize-package-data/lib/fixer.js'
// Also include .mjs to support ESM files that get transformed to .js
extensions: MODULE_RESOLVE_EXTENSIONS,
catchReadFile,
catchPackageFilter,
});
} catch (error) {
failure = error as Error;
}
if (failure) {
const { toplevel } = marker;
const mainNotFound =
newPackages.length > 0 && !newPackages[0].marker?.config?.main;
const debug =
!toplevel ||
derivative.mayExclude ||
(mainNotFound && derivative.fromDependencies);
const level = debug ? 'debug' : 'warn';
if (mainNotFound) {
const message = "Entry 'main' not found in %1";
log[level](message, [
`%1: ${newPackages[0].packageJson}`,
`%2: ${record.file}`,
]);
} else {
log[level](`${pc.yellow(failure.message)} in ${record.file}`);
}
return;
}
let newPackageForNewRecords;
for (const newPackage of newPackages) {
let newFile2;
try {
newFile2 = await follow(derivative.alias, {
basedir: path.dirname(record.file),
extensions: MODULE_RESOLVE_EXTENSIONS,
ignoreFile: newPackage.packageJson,
});
if (strictVerify) {
assert(newFile2 === normalizePath(newFile2));
}
} catch (_) {
// not setting is enough
}
if (newFile2 !== newFile) {
newPackageForNewRecords = newPackage;
break;
}
}
// Add all discovered package.json files, not just the one determined by the double-resolution logic
// This is necessary because ESM resolution may bypass the standard packageFilter mechanism
// However, only include package.json files that are either:
// 1. Inside node_modules (dependencies)
// 2. Inside the base directory of the current marker (application being packaged)
// This prevents including pkg's own package.json when used from source
for (const newPackage of newPackages) {
if (newPackage.marker) {
const file = newPackage.packageJson;
const isInNodeModules = file.includes(
`${path.sep}node_modules${path.sep}`,
);
const isInMarkerBase = marker.base && file.startsWith(marker.base);
if (isInNodeModules || isInMarkerBase) {
await this.appendBlobOrContent({
file,
marker: newPackage.marker,
store: STORE_CONTENT,
reason: record.file,
});
}
}
}
// Keep the original logic for determining the marker for the resolved file
if (newPackageForNewRecords) {
if (strictVerify) {
assert(
newPackageForNewRecords.packageJson ===
normalizePath(newPackageForNewRecords.packageJson),
);
}
}
await this.appendBlobOrContent({
file: newFile,
marker: newPackageForNewRecords ? newPackageForNewRecords.marker : marker,
store: STORE_BLOB,
reason: record.file,
});
// Also include files from other export conditions (e.g., module-sync, import)
// that Node.js may resolve to at runtime instead of the default/require entry.
// Without this, .mjs files referenced by module-sync would be missing from the snapshot.
const effectiveMarker = newPackageForNewRecords
? newPackageForNewRecords.marker
: marker;
if (effectiveMarker?.configPath) {
await this.includeAlternateExportEntries(
effectiveMarker,
newFile,
record.file,
);
}
}
/**
* Include alternate export entry points (module-sync, import) from a package's
* exports field. These files may be loaded by Node.js at runtime instead of the
* default/require entry, so they must be in the snapshot.
*/
private async includeAlternateExportEntries(
marker: Marker | undefined,
resolvedFile: string,
reason: string,
) {
if (!marker?.configPath || !marker.config) return;
const pkgExports = (marker.config as Record<string, unknown>).exports;
if (!pkgExports) return;
const pkgDir = path.dirname(marker.configPath);
const alternateFiles = this.collectAlternateExportFiles(pkgExports);
for (const relFile of alternateFiles) {
const absFile = normalizePath(path.resolve(pkgDir, relFile));
// Skip the file we already resolved
if (absFile === resolvedFile) continue;
try {
const stat = await fs.stat(absFile);
if (stat.isFile()) {
await this.appendBlobOrContent({
file: absFile,
marker,
store: STORE_CONTENT,
reason,
});
}
} catch {
// File doesn't exist, skip
}
}
}
/**
* Collect file paths from export conditions that Node.js may use at runtime.
* Specifically targets module-sync and import conditions.
*/
private collectAlternateExportFiles(
exports: unknown,
files: Set<string> = new Set(),