@ohos-ports/parcel-package-manager 2.9.3-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/LICENSE +21 -0
  2. package/index.d.ts +22 -0
  3. package/lib/index.js +4967 -0
  4. package/lib/index.js.map +1 -0
  5. package/lib/types.d.ts +47 -0
  6. package/package.json +69 -0
  7. package/src/JSONParseStream.js +39 -0
  8. package/src/MockPackageInstaller.js +90 -0
  9. package/src/NodePackageManager.js +583 -0
  10. package/src/Npm.js +94 -0
  11. package/src/Pnpm.js +194 -0
  12. package/src/Yarn.js +157 -0
  13. package/src/index.js +8 -0
  14. package/src/installPackage.js +274 -0
  15. package/src/promiseFromProcess.js +19 -0
  16. package/src/types.js +63 -0
  17. package/src/utils.js +92 -0
  18. package/src/validateModuleSpecifier.js +12 -0
  19. package/test/NodePackageManager.test.js +310 -0
  20. package/test/fixtures/empty/package.json +1 -0
  21. package/test/fixtures/has-a-not-yet-installed/package.json +5 -0
  22. package/test/fixtures/has-foo/node_modules/foo/index.js +1 -0
  23. package/test/fixtures/has-foo/node_modules/foo/package.json +3 -0
  24. package/test/fixtures/has-foo/node_modules/index.js +0 -0
  25. package/test/fixtures/has-foo/package.json +5 -0
  26. package/test/fixtures/has-foo/subpackage/package.json +1 -0
  27. package/test/fixtures/packages/a/index.js +1 -0
  28. package/test/fixtures/packages/a/package.json +3 -0
  29. package/test/fixtures/packages/foo-2.0/index.js +1 -0
  30. package/test/fixtures/packages/foo-2.0/package.json +4 -0
  31. package/test/fixtures/packages/peers/index.js +1 -0
  32. package/test/fixtures/packages/peers/package.json +7 -0
  33. package/test/fixtures/packages/peers-2.0/index.js +1 -0
  34. package/test/fixtures/packages/peers-2.0/package.json +7 -0
  35. package/test/validateModuleSpecifiers.test.js +38 -0
@@ -0,0 +1,583 @@
1
+ // @flow
2
+ import type {FilePath, DependencySpecifier, SemverRange} from '@parcel/types';
3
+ import type {FileSystem} from '@parcel/fs';
4
+ import type {
5
+ ModuleRequest,
6
+ PackageManager,
7
+ PackageInstaller,
8
+ InstallOptions,
9
+ Invalidations,
10
+ } from './types';
11
+ import type {ResolveResult} from './types';
12
+
13
+ import {registerSerializableClass} from '@parcel/core';
14
+ import ThrowableDiagnostic, {
15
+ encodeJSONKeyComponent,
16
+ escapeMarkdown,
17
+ generateJSONCodeHighlights,
18
+ md,
19
+ } from '@parcel/diagnostic';
20
+ import {NodeFS} from '@parcel/fs';
21
+ import nativeFS from 'fs';
22
+ import Module from 'module';
23
+ import path from 'path';
24
+ import semver from 'semver';
25
+ import logger from '@parcel/logger';
26
+ import nullthrows from 'nullthrows';
27
+
28
+ import {getModuleParts} from '@parcel/utils';
29
+ import {getConflictingLocalDependencies} from './utils';
30
+ import {installPackage} from './installPackage';
31
+ import pkg from '../package.json';
32
+ import {ResolverBase} from '@parcel/node-resolver-core';
33
+ import {pathToFileURL} from 'url';
34
+
35
+ // Package.json fields. Must match package_json.rs.
36
+ const MAIN = 1 << 0;
37
+ const SOURCE = 1 << 2;
38
+ const ENTRIES =
39
+ MAIN |
40
+ (process.env.PARCEL_BUILD_ENV !== 'production' ||
41
+ process.env.PARCEL_SELF_BUILD
42
+ ? SOURCE
43
+ : 0);
44
+
45
+ // There can be more than one instance of NodePackageManager, but node has only a single module cache.
46
+ // Therefore, the resolution cache and the map of parent to child modules should also be global.
47
+ const cache = new Map<DependencySpecifier, ResolveResult>();
48
+ const children = new Map<FilePath, Set<DependencySpecifier>>();
49
+ const invalidationsCache = new Map<string, Invalidations>();
50
+
51
+ // This implements a package manager for Node by monkey patching the Node require
52
+ // algorithm so that it uses the specified FileSystem instead of the native one.
53
+ // It also handles installing packages when they are required if not already installed.
54
+ // See https://github.com/nodejs/node/blob/master/lib/internal/modules/cjs/loader.js
55
+ // for reference to Node internals.
56
+ export class NodePackageManager implements PackageManager {
57
+ fs: FileSystem;
58
+ projectRoot: FilePath;
59
+ installer: ?PackageInstaller;
60
+ resolver: ResolverBase;
61
+
62
+ constructor(
63
+ fs: FileSystem,
64
+ projectRoot: FilePath,
65
+ installer?: ?PackageInstaller,
66
+ ) {
67
+ this.fs = fs;
68
+ this.projectRoot = projectRoot;
69
+ this.installer = installer;
70
+ }
71
+
72
+ _createResolver(): ResolverBase {
73
+ return new ResolverBase(this.projectRoot, {
74
+ fs:
75
+ this.fs instanceof NodeFS && process.versions.pnp == null
76
+ ? undefined
77
+ : {
78
+ canonicalize: path => this.fs.realpathSync(path),
79
+ read: path => this.fs.readFileSync(path),
80
+ isFile: path => this.fs.statSync(path).isFile(),
81
+ isDir: path => this.fs.statSync(path).isDirectory(),
82
+ },
83
+ mode: 2,
84
+ entries: ENTRIES,
85
+ packageExports: true,
86
+ moduleDirResolver:
87
+ process.versions.pnp != null
88
+ ? (module, from) => {
89
+ // $FlowFixMe[prop-missing]
90
+ let pnp = Module.findPnpApi(path.dirname(from));
91
+
92
+ return pnp.resolveToUnqualified(
93
+ // append slash to force loading builtins from npm
94
+ module + '/',
95
+ from,
96
+ );
97
+ }
98
+ : undefined,
99
+ });
100
+ }
101
+
102
+ static deserialize(opts: any): NodePackageManager {
103
+ return new NodePackageManager(opts.fs, opts.projectRoot, opts.installer);
104
+ }
105
+
106
+ serialize(): {|
107
+ $$raw: boolean,
108
+ fs: FileSystem,
109
+ projectRoot: FilePath,
110
+ installer: ?PackageInstaller,
111
+ |} {
112
+ return {
113
+ $$raw: false,
114
+ fs: this.fs,
115
+ projectRoot: this.projectRoot,
116
+ installer: this.installer,
117
+ };
118
+ }
119
+
120
+ async require(
121
+ name: DependencySpecifier,
122
+ from: FilePath,
123
+ opts: ?{|
124
+ range?: ?SemverRange,
125
+ shouldAutoInstall?: boolean,
126
+ saveDev?: boolean,
127
+ |},
128
+ ): Promise<any> {
129
+ let {resolved, type} = await this.resolve(name, from, opts);
130
+ if (type === 2) {
131
+ logger.warn({
132
+ message: 'ES module dependencies are experimental.',
133
+ origin: '@parcel/package-manager',
134
+ codeFrames: [
135
+ {
136
+ filePath: resolved,
137
+ codeHighlights: [],
138
+ },
139
+ ],
140
+ });
141
+
142
+ // On Windows, Node requires absolute paths to be file URLs.
143
+ if (process.platform === 'win32' && path.isAbsolute(resolved)) {
144
+ resolved = pathToFileURL(resolved);
145
+ }
146
+
147
+ // $FlowFixMe
148
+ return import(resolved);
149
+ }
150
+ return this.load(resolved, from);
151
+ }
152
+
153
+ requireSync(name: DependencySpecifier, from: FilePath): any {
154
+ let {resolved} = this.resolveSync(name, from);
155
+ return this.load(resolved, from);
156
+ }
157
+
158
+ load(filePath: FilePath, from: FilePath): any {
159
+ if (!path.isAbsolute(filePath)) {
160
+ // Node builtin module
161
+ // $FlowFixMe
162
+ return require(filePath);
163
+ }
164
+
165
+ // $FlowFixMe[prop-missing]
166
+ const cachedModule = Module._cache[filePath];
167
+ if (cachedModule !== undefined) {
168
+ return cachedModule.exports;
169
+ }
170
+
171
+ // $FlowFixMe
172
+ let m = new Module(filePath, Module._cache[from] || module.parent);
173
+ // $FlowFixMe[prop-missing]
174
+ Module._cache[filePath] = m;
175
+
176
+ // Patch require within this module so it goes through our require
177
+ m.require = id => {
178
+ return this.requireSync(id, filePath);
179
+ };
180
+
181
+ // Patch `fs.readFileSync` temporarily so that it goes through our file system
182
+ let {readFileSync, statSync} = nativeFS;
183
+ // $FlowFixMe
184
+ nativeFS.readFileSync = (filename, encoding) => {
185
+ return this.fs.readFileSync(filename, encoding);
186
+ };
187
+
188
+ // $FlowFixMe
189
+ nativeFS.statSync = filename => {
190
+ return this.fs.statSync(filename);
191
+ };
192
+
193
+ try {
194
+ m.load(filePath);
195
+ } catch (err) {
196
+ // $FlowFixMe[prop-missing]
197
+ delete Module._cache[filePath];
198
+ throw err;
199
+ } finally {
200
+ // $FlowFixMe
201
+ nativeFS.readFileSync = readFileSync;
202
+ // $FlowFixMe
203
+ nativeFS.statSync = statSync;
204
+ }
205
+
206
+ return m.exports;
207
+ }
208
+
209
+ async resolve(
210
+ id: DependencySpecifier,
211
+ from: FilePath,
212
+ options?: ?{|
213
+ range?: ?SemverRange,
214
+ shouldAutoInstall?: boolean,
215
+ saveDev?: boolean,
216
+ |},
217
+ ): Promise<ResolveResult> {
218
+ let basedir = path.dirname(from);
219
+ let key = basedir + ':' + id;
220
+ let resolved = cache.get(key);
221
+ if (!resolved) {
222
+ let [name] = getModuleParts(id);
223
+ try {
224
+ resolved = this.resolveInternal(id, from);
225
+ } catch (e) {
226
+ if (
227
+ e.code !== 'MODULE_NOT_FOUND' ||
228
+ options?.shouldAutoInstall !== true
229
+ ) {
230
+ if (
231
+ e.code === 'MODULE_NOT_FOUND' &&
232
+ options?.shouldAutoInstall !== true
233
+ ) {
234
+ let err = new ThrowableDiagnostic({
235
+ diagnostic: {
236
+ message: escapeMarkdown(e.message),
237
+ hints: [
238
+ 'Autoinstall is disabled, please install this package manually and restart Parcel.',
239
+ ],
240
+ },
241
+ });
242
+ // $FlowFixMe - needed for loadParcelPlugin
243
+ err.code = 'MODULE_NOT_FOUND';
244
+ throw err;
245
+ } else {
246
+ throw e;
247
+ }
248
+ }
249
+
250
+ let conflicts = await getConflictingLocalDependencies(
251
+ this.fs,
252
+ name,
253
+ from,
254
+ this.projectRoot,
255
+ );
256
+
257
+ if (conflicts == null) {
258
+ this.invalidate(id, from);
259
+ await this.install([{name, range: options?.range}], from, {
260
+ saveDev: options?.saveDev ?? true,
261
+ });
262
+
263
+ return this.resolve(id, from, {
264
+ ...options,
265
+ shouldAutoInstall: false,
266
+ });
267
+ }
268
+
269
+ throw new ThrowableDiagnostic({
270
+ diagnostic: conflicts.fields.map(field => ({
271
+ message: md`Could not find module "${name}", but it was listed in package.json. Run your package manager first.`,
272
+ origin: '@parcel/package-manager',
273
+ codeFrames: [
274
+ {
275
+ filePath: conflicts.filePath,
276
+ language: 'json',
277
+ code: conflicts.json,
278
+ codeHighlights: generateJSONCodeHighlights(conflicts.json, [
279
+ {
280
+ key: `/${field}/${encodeJSONKeyComponent(name)}`,
281
+ type: 'key',
282
+ message: 'Defined here, but not installed',
283
+ },
284
+ ]),
285
+ },
286
+ ],
287
+ })),
288
+ });
289
+ }
290
+
291
+ let range = options?.range;
292
+ if (range != null) {
293
+ let pkg = resolved.pkg;
294
+ if (pkg == null || !semver.satisfies(pkg.version, range)) {
295
+ let conflicts = await getConflictingLocalDependencies(
296
+ this.fs,
297
+ name,
298
+ from,
299
+ this.projectRoot,
300
+ );
301
+
302
+ if (conflicts == null && options?.shouldAutoInstall === true) {
303
+ this.invalidate(id, from);
304
+ await this.install([{name, range}], from);
305
+ return this.resolve(id, from, {
306
+ ...options,
307
+ shouldAutoInstall: false,
308
+ });
309
+ } else if (conflicts != null) {
310
+ throw new ThrowableDiagnostic({
311
+ diagnostic: {
312
+ message: md`Could not find module "${name}" satisfying ${range}.`,
313
+ origin: '@parcel/package-manager',
314
+ codeFrames: [
315
+ {
316
+ filePath: conflicts.filePath,
317
+ language: 'json',
318
+ code: conflicts.json,
319
+ codeHighlights: generateJSONCodeHighlights(
320
+ conflicts.json,
321
+ conflicts.fields.map(field => ({
322
+ key: `/${field}/${encodeJSONKeyComponent(name)}`,
323
+ type: 'key',
324
+ message: 'Found this conflicting local requirement.',
325
+ })),
326
+ ),
327
+ },
328
+ ],
329
+ },
330
+ });
331
+ }
332
+
333
+ let version = pkg?.version;
334
+ let message = md`Could not resolve package "${name}" that satisfies ${range}.`;
335
+ if (version != null) {
336
+ message += md` Found ${version}.`;
337
+ }
338
+
339
+ throw new ThrowableDiagnostic({
340
+ diagnostic: {
341
+ message,
342
+ hints: [
343
+ 'Looks like the incompatible version was installed transitively. Add this package as a direct dependency with a compatible version range.',
344
+ ],
345
+ },
346
+ });
347
+ }
348
+ }
349
+
350
+ cache.set(key, resolved);
351
+ invalidationsCache.clear();
352
+
353
+ // Add the specifier as a child to the parent module.
354
+ // Don't do this if the specifier was an absolute path, as this was likely a dynamically resolved path
355
+ // (e.g. babel uses require() to load .babelrc.js configs and we don't want them to be added as children of babel itself).
356
+ if (!path.isAbsolute(name)) {
357
+ let moduleChildren = children.get(from);
358
+ if (!moduleChildren) {
359
+ moduleChildren = new Set();
360
+ children.set(from, moduleChildren);
361
+ }
362
+
363
+ moduleChildren.add(name);
364
+ }
365
+ }
366
+
367
+ return resolved;
368
+ }
369
+
370
+ resolveSync(name: DependencySpecifier, from: FilePath): ResolveResult {
371
+ let basedir = path.dirname(from);
372
+ let key = basedir + ':' + name;
373
+ let resolved = cache.get(key);
374
+ if (!resolved) {
375
+ resolved = this.resolveInternal(name, from);
376
+ cache.set(key, resolved);
377
+ invalidationsCache.clear();
378
+
379
+ if (!path.isAbsolute(name)) {
380
+ let moduleChildren = children.get(from);
381
+ if (!moduleChildren) {
382
+ moduleChildren = new Set();
383
+ children.set(from, moduleChildren);
384
+ }
385
+
386
+ moduleChildren.add(name);
387
+ }
388
+ }
389
+
390
+ return resolved;
391
+ }
392
+
393
+ async install(
394
+ modules: Array<ModuleRequest>,
395
+ from: FilePath,
396
+ opts?: InstallOptions,
397
+ ) {
398
+ await installPackage(this.fs, this, modules, from, this.projectRoot, {
399
+ packageInstaller: this.installer,
400
+ ...opts,
401
+ });
402
+ }
403
+
404
+ getInvalidations(name: DependencySpecifier, from: FilePath): Invalidations {
405
+ let basedir = path.dirname(from);
406
+ let cacheKey = basedir + ':' + name;
407
+ let resolved = cache.get(cacheKey);
408
+
409
+ if (resolved && path.isAbsolute(resolved.resolved)) {
410
+ let cached = invalidationsCache.get(resolved.resolved);
411
+ if (cached != null) {
412
+ return cached;
413
+ }
414
+
415
+ let res = {
416
+ invalidateOnFileCreate: [],
417
+ invalidateOnFileChange: new Set(),
418
+ invalidateOnStartup: false,
419
+ };
420
+
421
+ let seen = new Set();
422
+ let addKey = (name, from) => {
423
+ let basedir = path.dirname(from);
424
+ let key = basedir + ':' + name;
425
+ if (seen.has(key)) {
426
+ return;
427
+ }
428
+
429
+ seen.add(key);
430
+ let resolved = cache.get(key);
431
+ if (!resolved || !path.isAbsolute(resolved.resolved)) {
432
+ return;
433
+ }
434
+
435
+ res.invalidateOnFileCreate.push(...resolved.invalidateOnFileCreate);
436
+ res.invalidateOnFileChange.add(resolved.resolved);
437
+
438
+ for (let file of resolved.invalidateOnFileChange) {
439
+ res.invalidateOnFileChange.add(file);
440
+ }
441
+
442
+ let moduleChildren = children.get(resolved.resolved);
443
+ if (moduleChildren) {
444
+ for (let specifier of moduleChildren) {
445
+ addKey(specifier, resolved.resolved);
446
+ }
447
+ }
448
+ };
449
+
450
+ addKey(name, from);
451
+
452
+ // If this is an ES module, we won't have any of the dependencies because import statements
453
+ // cannot be intercepted. Instead, ask the resolver to parse the file and recursively analyze the deps.
454
+ if (resolved.type === 2) {
455
+ let invalidations = this.resolver.getInvalidations(resolved.resolved);
456
+ invalidations.invalidateOnFileChange.forEach(i =>
457
+ res.invalidateOnFileChange.add(i),
458
+ );
459
+ invalidations.invalidateOnFileCreate.forEach(i =>
460
+ res.invalidateOnFileCreate.push(i),
461
+ );
462
+ res.invalidateOnStartup ||= invalidations.invalidateOnStartup;
463
+ if (res.invalidateOnStartup) {
464
+ logger.warn({
465
+ message: md`${path.relative(
466
+ this.projectRoot,
467
+ resolved.resolved,
468
+ )} contains non-statically analyzable dependencies in its module graph. This causes Parcel to invalidate the cache on startup.`,
469
+ origin: '@parcel/package-manager',
470
+ });
471
+ }
472
+ }
473
+
474
+ invalidationsCache.set(resolved.resolved, res);
475
+ return res;
476
+ }
477
+
478
+ return {
479
+ invalidateOnFileCreate: [],
480
+ invalidateOnFileChange: new Set(),
481
+ invalidateOnStartup: false,
482
+ };
483
+ }
484
+
485
+ invalidate(name: DependencySpecifier, from: FilePath) {
486
+ let seen = new Set();
487
+
488
+ let invalidate = (name, from) => {
489
+ let basedir = path.dirname(from);
490
+ let key = basedir + ':' + name;
491
+ if (seen.has(key)) {
492
+ return;
493
+ }
494
+
495
+ seen.add(key);
496
+ let resolved = cache.get(key);
497
+ if (!resolved || !path.isAbsolute(resolved.resolved)) {
498
+ return;
499
+ }
500
+
501
+ invalidationsCache.delete(resolved.resolved);
502
+
503
+ // $FlowFixMe
504
+ let module = Module._cache[resolved.resolved];
505
+ if (module) {
506
+ // $FlowFixMe
507
+ delete Module._cache[resolved.resolved];
508
+ }
509
+
510
+ let moduleChildren = children.get(resolved.resolved);
511
+ if (moduleChildren) {
512
+ for (let specifier of moduleChildren) {
513
+ invalidate(specifier, resolved.resolved);
514
+ }
515
+ }
516
+
517
+ children.delete(resolved.resolved);
518
+ cache.delete(key);
519
+ };
520
+
521
+ invalidate(name, from);
522
+ this.resolver = this._createResolver();
523
+ }
524
+
525
+ resolveInternal(name: string, from: string): ResolveResult {
526
+ if (this.resolver == null) {
527
+ this.resolver = this._createResolver();
528
+ }
529
+
530
+ let res = this.resolver.resolve({
531
+ filename: name,
532
+ specifierType: 'commonjs',
533
+ parent: from,
534
+ });
535
+
536
+ // Invalidate whenever the .pnp.js file changes.
537
+ // TODO: only when we actually resolve a node_modules package?
538
+ if (process.versions.pnp != null && res.invalidateOnFileChange) {
539
+ // $FlowFixMe[prop-missing]
540
+ let pnp = Module.findPnpApi(path.dirname(from));
541
+ res.invalidateOnFileChange.push(pnp.resolveToUnqualified('pnpapi', null));
542
+ }
543
+
544
+ if (res.error) {
545
+ let e = new Error(`Could not resolve module "${name}" from "${from}"`);
546
+ // $FlowFixMe
547
+ e.code = 'MODULE_NOT_FOUND';
548
+ throw e;
549
+ }
550
+ let getPkg;
551
+ switch (res.resolution.type) {
552
+ case 'Path':
553
+ getPkg = () => {
554
+ let pkgPath = this.fs.findAncestorFile(
555
+ ['package.json'],
556
+ nullthrows(res.resolution.value),
557
+ this.projectRoot,
558
+ );
559
+ return pkgPath
560
+ ? JSON.parse(this.fs.readFileSync(pkgPath, 'utf8'))
561
+ : null;
562
+ };
563
+ // fallthrough
564
+ case 'Builtin':
565
+ return {
566
+ resolved: res.resolution.value,
567
+ invalidateOnFileChange: new Set(res.invalidateOnFileChange),
568
+ invalidateOnFileCreate: res.invalidateOnFileCreate,
569
+ type: res.moduleType,
570
+ get pkg() {
571
+ return getPkg();
572
+ },
573
+ };
574
+ default:
575
+ throw new Error('Unknown resolution type');
576
+ }
577
+ }
578
+ }
579
+
580
+ registerSerializableClass(
581
+ `${pkg.version}:NodePackageManager`,
582
+ NodePackageManager,
583
+ );
package/src/Npm.js ADDED
@@ -0,0 +1,94 @@
1
+ // @flow strict-local
2
+
3
+ import type {PackageInstaller, InstallerOptions} from './types';
4
+
5
+ import path from 'path';
6
+ import spawn from 'cross-spawn';
7
+ import logger from '@parcel/logger';
8
+ import promiseFromProcess from './promiseFromProcess';
9
+ import {registerSerializableClass} from '@parcel/core';
10
+ import {npmSpecifierFromModuleRequest} from './utils';
11
+
12
+ // $FlowFixMe
13
+ import pkg from '../package.json';
14
+
15
+ const NPM_CMD = 'npm';
16
+
17
+ export class Npm implements PackageInstaller {
18
+ async install({
19
+ modules,
20
+ cwd,
21
+ fs,
22
+ packagePath,
23
+ saveDev = true,
24
+ }: InstallerOptions): Promise<void> {
25
+ // npm doesn't auto-create a package.json when installing,
26
+ // so create an empty one if needed.
27
+ if (packagePath == null) {
28
+ await fs.writeFile(path.join(cwd, 'package.json'), '{}');
29
+ }
30
+
31
+ let args = ['install', '--json', saveDev ? '--save-dev' : '--save'].concat(
32
+ modules.map(npmSpecifierFromModuleRequest),
33
+ );
34
+
35
+ // When Parcel is run by npm (e.g. via package.json scripts), several environment variables are
36
+ // added. When parcel in turn calls npm again, these can cause npm to behave stragely, so we
37
+ // filter them out when installing packages.
38
+ let env = {};
39
+ for (let key in process.env) {
40
+ if (!key.startsWith('npm_') && key !== 'INIT_CWD' && key !== 'NODE_ENV') {
41
+ env[key] = process.env[key];
42
+ }
43
+ }
44
+
45
+ let installProcess = spawn(NPM_CMD, args, {cwd, env});
46
+ let stdout = '';
47
+ installProcess.stdout.on('data', (buf: Buffer) => {
48
+ stdout += buf.toString();
49
+ });
50
+
51
+ let stderr = [];
52
+ installProcess.stderr.on('data', (buf: Buffer) => {
53
+ stderr.push(buf.toString().trim());
54
+ });
55
+
56
+ try {
57
+ await promiseFromProcess(installProcess);
58
+
59
+ let results: NPMResults = JSON.parse(stdout);
60
+ let addedCount = results.added.length;
61
+ if (addedCount > 0) {
62
+ logger.log({
63
+ origin: '@parcel/package-manager',
64
+ message: `Added ${addedCount} packages via npm`,
65
+ });
66
+ }
67
+
68
+ // Since we succeeded, stderr might have useful information not included
69
+ // in the json written to stdout. It's also not necessary to log these as
70
+ // errors as they often aren't.
71
+ for (let message of stderr) {
72
+ if (message.length > 0) {
73
+ logger.log({
74
+ origin: '@parcel/package-manager',
75
+ message,
76
+ });
77
+ }
78
+ }
79
+ } catch (e) {
80
+ throw new Error(
81
+ 'npm failed to install modules: ' +
82
+ e.message +
83
+ ' - ' +
84
+ stderr.join('\n'),
85
+ );
86
+ }
87
+ }
88
+ }
89
+
90
+ type NPMResults = {|
91
+ added: Array<{name: string, ...}>,
92
+ |};
93
+
94
+ registerSerializableClass(`${pkg.version}:Npm`, Npm);