-
Notifications
You must be signed in to change notification settings - Fork 6
/
npm-utils.js
695 lines (665 loc) · 20.3 KB
/
npm-utils.js
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
/**
* @module system-npm/utils
*
* Helpers that are used by npm-extension and the npm plugin.
* This should be kept small and not have helpers exclusive to npm.
* However, it can have all npm-extension helpers.
*/
// A regex to test if a moduleName is npm-like.
var slice = Array.prototype.slice;
var npmModuleRegEx = /.+@.+\..+\..+#.+/;
var conditionalModuleRegEx = /#\{[^\}]+\}|#\?.+$/;
var gitUrlEx = /(git|http(s?)):\/\//;
var supportsSet = typeof Set === "function";
var utils = {
extend: function(d, s, deep, set){
var val;
if(deep) {
if(!set) {
if(supportsSet) {
set = new Set();
} else {
set = [];
}
}
if(supportsSet) {
if(set.has(s)) {
return s;
} else {
set.add(s);
}
} else {
if(set.indexOf(s) !== -1) {
return s;
} else {
set.push(s);
}
}
}
for(var prop in s) {
val = s[prop];
if(deep) {
if(utils.isArray(val)) {
d[prop] = slice.call(val);
} else if(utils.isPlainObject(val)) {
d[prop] = utils.extend({}, val, deep, set);
} else {
d[prop] = s[prop];
}
} else {
d[prop] = s[prop];
}
}
return d;
},
map: function(arr, fn){
var i = 0, len = arr.length, out = [];
for(; i < len; i++) {
out.push(fn.call(arr, arr[i]));
}
return out;
},
filter: function(arr, fn){
var i = 0, len = arr.length, out = [], res;
for(; i < len; i++) {
res = fn.call(arr, arr[i]);
if(res) {
out.push(arr[i]);
}
}
return out;
},
forEach: function(arr, fn) {
var i = 0, len = arr.length;
for(; i < len; i++) {
fn.call(arr, arr[i], i);
}
},
isObject: function(obj){
return typeof obj === "object";
},
isPlainObject: function(obj){
// A plain object has a proto that is the Object
return utils.isObject(obj) && (!obj || obj.__proto__ === Object.prototype);
},
isArray: Array.isArray || function(arr){
return Object.prototype.toString.call(arr) === "[object Array]";
},
isEnv: function(name) {
return this.isEnv ? this.isEnv(name) : this.env === name;
},
isGitUrl: function(str) {
return gitUrlEx.test(str);
},
warnOnce: function(msg){
var w = this._warnings = this._warnings || {};
if(w[msg]) return;
w[msg] = true;
this.warn(msg);
},
warn: function(msg){
if(typeof steal !== "undefined" && typeof console !== "undefined" && console.warn) {
steal.done().then(function(){
if(steal.dev && steal.dev.warn){
steal.dev.warn(msg)
} else if(console.warn) {
console.warn("steal.js WARNING: "+msg);
} else {
console.log(msg);
}
});
}
},
relativeURI: function(baseURL, url) {
return typeof steal !== "undefined" ? steal.relativeURI(baseURL, url) : url;
},
moduleName: {
/**
* @function moduleName.create
* Converts a parsed module name to a string
*
* @param {system-npm/parsed_npm} descriptor
*/
create: function (descriptor, standard) {
if(standard) {
return descriptor.moduleName;
} else {
if(descriptor === "@empty") {
return descriptor;
}
var modulePath;
if(descriptor.modulePath) {
modulePath = descriptor.modulePath.substr(0,2) === "./" ? descriptor.modulePath.substr(2) : descriptor.modulePath;
}
return descriptor.packageName
+ (descriptor.version ? '@' + descriptor.version : '')
+ (modulePath ? '#' + modulePath : '')
+ (descriptor.plugin ? descriptor.plugin : '');
}
},
/**
* @function moduleName.isNpm
* Determines whether a moduleName is npm-like.
* @return {Boolean}
*/
isNpm: function(moduleName){
return npmModuleRegEx.test(moduleName);
},
/**
* @function moduleName.isConditional
* Determines whether a moduleName includes a condition.
* @return {Boolean}
*/
isConditional: function(moduleName){
return conditionalModuleRegEx.test(moduleName);
},
/**
* @function moduleName.isFullyConvertedModuleName
* Determines whether a moduleName is a fully npm name, not npm-like
* With a parsed module name we can make sure there is a package name,
* package version, and module path.
*/
isFullyConvertedNpm: function(parsedModuleName){
return !!(parsedModuleName.packageName &&
parsedModuleName.version && parsedModuleName.modulePath);
},
/**
* @function moduleName.isScoped
* Determines whether a moduleName is from a scoped package.
* @return {Boolean}
*/
isScoped: function(moduleName){
return moduleName[0] === "@";
},
/**
* @function moduleName.parse
* Breaks a string moduleName into parts.
* packageName@version!plugin#modulePath
* "./lib/bfs"
*
* @return {system-npm/parsed_npm}
*/
parse: function (moduleName, currentPackageName, global) {
var pluginParts = moduleName.split('!');
var modulePathParts = pluginParts[0].split("#");
var versionParts = modulePathParts[0].split("@");
// it could be something like `@empty`
if(!modulePathParts[1] && !versionParts[0]) {
versionParts = ["@"+versionParts[1]];
}
// it could be a scope package
if(versionParts.length === 3 && utils.moduleName.isScoped(moduleName)) {
versionParts.splice(0, 1);
versionParts[0] = "@"+versionParts[0];
}
var packageName,
modulePath;
// if the module name is relative
// use the currentPackageName
if (currentPackageName && utils.path.isRelative(moduleName)) {
packageName = currentPackageName;
modulePath = versionParts[0];
// if the module name starts with the ~ (tilde) operator
// use the currentPackageName
} else if (currentPackageName && utils.path.startsWithTildeSlash(moduleName)) {
packageName = currentPackageName;
modulePath = versionParts[0].split("/").slice(1).join("/");
} else {
if(modulePathParts[1]) { // [email protected]#./path
packageName = versionParts[0];
modulePath = modulePathParts[1];
} else {
// test/abc
var folderParts = versionParts[0].split("/");
// Detect scoped packages
if(folderParts.length && folderParts[0][0] === "@") {
packageName = folderParts.splice(0, 2).join("/");
} else {
packageName = folderParts.shift();
}
modulePath = folderParts.join("/");
}
}
modulePath = utils.path.removeJS(modulePath);
return {
plugin: pluginParts.length === 2 ? "!"+pluginParts[1] : undefined,
version: versionParts[1],
modulePath: modulePath,
packageName: packageName,
moduleName: moduleName,
isGlobal: global
};
},
/**
* @function moduleName.parseFromPackage
*
* Given the package that loads the dependency, the dependency name,
* and the moduleName of what loaded the package, return
* a [system-npm/parsed_npm].
*
* @param {Loader} loader
* @param {NpmPackage} refPkg The package `name` is a dependency of.
* @param {moduleName} name
* @param {moduleName} parentName
* @return {system-npm/parsed_npm}
*
*/
parseFromPackage: function(loader, refPkg, name, parentName) {
// Get the name of the
var packageName = utils.pkg.name(refPkg),
parsedModuleName = utils.moduleName.parse(name, packageName),
isRelative = utils.path.isRelative(parsedModuleName.modulePath);
if(isRelative && !parentName) {
throw new Error("Cannot resolve a relative module identifier " +
"with no parent module:", name);
}
// If the module needs to be loaded relative.
if(isRelative) {
// get the location of the parent
var parentParsed = utils.moduleName.parse(parentName, packageName);
// If the parentModule and the currentModule are from the same parent
if( parentParsed.packageName === parsedModuleName.packageName && parentParsed.modulePath ) {
var makePathRelative = true;
if(name === "../" || name === "./" || name === "..") {
var relativePath = utils.path.relativeTo(
parentParsed.modulePath, name);
var isInRoot = utils.path.isPackageRootDir(relativePath);
if(isInRoot) {
parsedModuleName.modulePath = utils.pkg.main(refPkg);
makePathRelative = false;
} else {
parsedModuleName.modulePath = name +
(utils.path.endsWithSlash(name) ? "" : "/") +
"index";
}
}
if(makePathRelative) {
// Make the path relative to the parentName's path.
parsedModuleName.modulePath = utils.path.makeRelative(
utils.path.joinURIs(parentParsed.modulePath,
parsedModuleName.modulePath)
);
}
}
}
// we have the moduleName without the version
// we check this against various configs
var mapName = utils.moduleName.create(parsedModuleName),
refSteal = utils.pkg.config(refPkg),
mappedName;
// The refPkg might have a browser [https://github.com/substack/node-browserify#browser-field] mapping.
// Perform that mapping here.
if(refPkg.browser && (typeof refPkg.browser !== "string") &&
(mapName in refPkg.browser) &&
(!refSteal || !refSteal.ignoreBrowser)) {
mappedName = refPkg.browser[mapName] === false ?
"@empty" : refPkg.browser[mapName];
}
// globalBrowser looks like: {moduleName: aliasName, pgk: aliasingPkg}
var global = loader && loader.globalBrowser &&
loader.globalBrowser[mapName];
if(global) {
mappedName = global.moduleName === false ? "@empty" :
global.moduleName;
}
if(mappedName) {
return utils.moduleName.parse(mappedName, packageName, !!global);
} else {
return parsedModuleName;
}
},
nameAndVersion: function(parsedModuleName){
return parsedModuleName.packageName + "@" + parsedModuleName.version;
}
},
pkg: {
/**
* Returns a package's name. The system config allows one to set this to
* something else.
* @return {String}
*/
name: function(pkg){
var steal = utils.pkg.config(pkg);
return (steal && steal.name) || pkg.name;
},
main: function(pkg) {
var main;
var steal = utils.pkg.config(pkg);
if(steal && steal.main) {
main = steal.main;
} else if(typeof pkg.browser === "string") {
if(utils.path.endsWithSlash(pkg.browser)) {
main = pkg.browser + "index";
} else {
main = pkg.browser;
}
} else if(typeof pkg.jam === "object" && pkg.jam.main) {
main = pkg.jam.main;
} else if(pkg.main) {
main = pkg.main;
} else {
main = "index";
}
return utils.path.removeJS(
utils.path.removeDotSlash(main)
);
},
rootDir: function(pkg, isRoot) {
var root = isRoot ?
utils.path.removePackage( pkg.fileUrl ) :
utils.path.pkgDir(pkg.fileUrl);
var lib = utils.pkg.directoriesLib(pkg);
if(lib) {
root = utils.path.joinURIs(utils.path.addEndingSlash(root), lib);
}
return root;
},
/**
* @function pkg.isRoot
* Determines whether a module is the loader's root module.
* @return {Boolean}
*/
isRoot: function(loader, pkg) {
var root = utils.pkg.getDefault(loader);
return pkg.name === root.name && pkg.version === root.version;
},
getDefault: function(loader) {
return loader.npmPaths.__default;
},
/**
* Returns packageData given a module's name or module's address.
*
* Given a moduleName, it tries to return the package it belongs to.
* If a moduleName isn't provided, but a moduleA
*
* @param {Loader} loader
* @param {String} [moduleName]
* @param {String} [moduleAddress]
* @return {NpmPackage|undefined}
*/
findByModuleNameOrAddress: function(loader, moduleName, moduleAddress) {
if(loader.npm) {
if(moduleName) {
var parsed = utils.moduleName.parse(moduleName);
if(parsed.version && parsed.packageName) {
var name = parsed.packageName+"@"+parsed.version;
if(name in loader.npm) {
return loader.npm[name];
}
}
}
if(moduleAddress) {
// Remove the baseURL so that folderAddress only detects
// node_modules that are within the baseURL. Otherwise
// you cannot load a project that is itself within
// node_modules
var startingAddress = utils.relativeURI(loader.baseURL,
moduleAddress);
var packageFolder = utils.pkg.folderAddress(startingAddress);
return packageFolder ? loader.npmPaths[packageFolder] : utils.pkg.getDefault(loader);
} else {
return utils.pkg.getDefault(loader);
}
}
},
folderAddress: function (address){
var nodeModules = "/node_modules/",
nodeModulesIndex = address.lastIndexOf(nodeModules),
nextSlash = address.indexOf("/", nodeModulesIndex+nodeModules.length);
if(nodeModulesIndex >= 0) {
return nextSlash>=0 ? address.substr(0, nextSlash) : address;
}
},
/**
* Finds a dependency by its saved resolutions. This will only be called
* after we've first successful found a package the "hard way" by doing
* semver matching.
*/
findDep: function(loader, refPkg, name){
if(loader.npm && refPkg && !utils.path.startsWithDotSlash(name)) {
var nameAndVersion = name + "@" + refPkg.resolutions[name];
var pkg = loader.npm[nameAndVersion];
return pkg;
}
},
/**
* Walks up npmPaths looking for a [name]/package.json. Returns
* the package data it finds.
*
* @param {Loader} loader
* @param {NpmPackage} refPackage
* @param {packgeName} name the package name we are looking for.
*
* @return {undefined|NpmPackage}
*/
findDepWalking: function (loader, refPackage, name) {
if(loader.npm && refPackage && !utils.path.startsWithDotSlash(name)) {
// Todo .. first part of name
var curPackage = utils.path.depPackageDir(refPackage.fileUrl, name);
while(curPackage) {
var pkg = loader.npmPaths[curPackage];
if(pkg) {
return pkg;
}
var parentAddress = utils.path.parentNodeModuleAddress(curPackage);
if(!parentAddress) {
return;
}
curPackage = parentAddress+"/"+name;
}
}
},
findByName: function(loader, name) {
if(loader.npm && !utils.path.startsWithDotSlash(name)) {
return loader.npm[name];
}
},
findByNameAndVersion: function(loader, name, version) {
if(loader.npm && !utils.path.startsWithDotSlash(name)) {
var nameAndVersion = name + "@" + version;
return loader.npm[nameAndVersion];
}
},
findByUrl: function(loader, url) {
if(loader.npm) {
url = utils.pkg.folderAddress(url);
return loader.npmPaths[url];
}
},
directoriesLib: function(pkg) {
var steal = utils.pkg.config(pkg);
var lib = steal && steal.directories && steal.directories.lib;
var ignores = [".", "/"], ignore;
if(!lib) return undefined;
while(!!(ignore = ignores.shift())) {
if(lib[0] === ignore) {
lib = lib.substr(1);
}
}
return lib;
},
hasDirectoriesLib: function(pkg) {
var steal = utils.pkg.config(pkg);
return steal && steal.directories && !!steal.directories.lib;
},
findPackageInfo: function(context, pkg){
var pkgInfo = context.pkgInfo;
if(pkgInfo) {
var out;
utils.forEach(pkgInfo, function(p){
if(pkg.name === p.name && pkg.version === p.version) {
out = p;
}
});
return out;
}
},
saveResolution: function(context, refPkg, pkg){
var npmPkg = utils.pkg.findPackageInfo(context, refPkg);
npmPkg.resolutions[pkg.name] = refPkg.resolutions[pkg.name] =
pkg.version;
},
config: function(pkg){
return pkg.steal || pkg.system;
}
},
path: {
makeRelative: function(path){
if( utils.path.isRelative(path) && path.substr(0,1) !== "/" ) {
return path;
} else {
return "./"+path;
}
},
removeJS: function(path) {
return path.replace(/\.js(!|$)/,function(whole, part){return part;});
},
removePackage: function (path){
return path.replace(/\/package\.json.*/,"");
},
addJS: function(path){
// Don't add `.js` for types that need to work without an extension.
if(/\.js(on)?$/.test(path)) {
return path;
} else {
return path+".js";
}
},
isRelative: function(path) {
return path.substr(0,1) === ".";
},
startsWithTildeSlash: function( path ) {
return path.substr(0,2) === "~/";
},
joinURIs: function(base, href) {
function removeDotSegments(input) {
var output = [];
input.replace(/^(\.\.?(\/|$))+/, '')
.replace(/\/(\.(\/|$))+/g, '/')
.replace(/\/\.\.$/, '/../')
.replace(/\/?[^\/]*/g, function (p) {
if (p === '/..') {
output.pop();
} else {
output.push(p);
}
});
return output.join('').replace(/^\//, input.charAt(0) === '/' ? '/' : '');
}
href = parseURI(href || '');
base = parseURI(base || '');
return !href || !base ? null : (href.protocol || base.protocol) +
(href.protocol || href.authority ? href.authority : base.authority) +
removeDotSegments(href.protocol || href.authority || href.pathname.charAt(0) === '/' ? href.pathname : (href.pathname ? ((base.authority && !base.pathname ? '/' : '') + base.pathname.slice(0, base.pathname.lastIndexOf('/') + 1) + href.pathname) : base.pathname)) +
(href.protocol || href.authority || href.pathname ? href.search : (href.search || base.search)) +
href.hash;
},
startsWithDotSlash: function( path ) {
return path.substr(0,2) === "./";
},
removeDotSlash: function(path) {
return utils.path.startsWithDotSlash(path) ?
path.substr(2) :
path;
},
endsWithSlash: function(path){
return path[path.length -1] === "/";
},
addEndingSlash: function(path){
return utils.path.endsWithSlash(path) ? path : path+"/";
},
// Returns a package.json path one node_modules folder deeper than the
// parentPackageAddress
depPackage: function (parentPackageAddress, childName){
var packageFolderName = parentPackageAddress.replace(/\/package\.json.*/,"");
return (packageFolderName ? packageFolderName+"/" : "")+"node_modules/" + childName + "/package.json";
},
peerPackage: function(parentPackageAddress, childName){
var packageFolderName = parentPackageAddress.replace(/\/package\.json.*/,"");
return packageFolderName.substr(0, packageFolderName.lastIndexOf("/"))
+ "/" + childName + "/package.json";
},
// returns the package directory one level deeper.
depPackageDir: function(parentPackageAddress, childName){
return utils.path.depPackage(parentPackageAddress, childName).replace(/\/package\.json.*/,"");
},
peerNodeModuleAddress: function(address) {
var nodeModules = "/node_modules/",
nodeModulesIndex = address.lastIndexOf(nodeModules);
if(nodeModulesIndex >= 0) {
return address.substr(0, nodeModulesIndex+nodeModules.length - 1 );
}
},
// /node_modules/a/node_modules/b/node_modules/c -> /node_modules/a/node_modules/
parentNodeModuleAddress: function(address) {
var nodeModules = "/node_modules/",
nodeModulesIndex = address.lastIndexOf(nodeModules),
prevModulesIndex = address.lastIndexOf(nodeModules, nodeModulesIndex-1);
if(prevModulesIndex >= 0) {
return address.substr(0, prevModulesIndex+nodeModules.length - 1 );
}
},
pkgDir: function(address){
var nodeModules = "/node_modules/",
nodeModulesIndex = address.lastIndexOf(nodeModules),
nextSlash = address.indexOf("/", nodeModulesIndex+nodeModules.length);
// Scoped packages
if(address[nodeModulesIndex+nodeModules.length] === "@") {
nextSlash = address.indexOf("/", nextSlash+1);
}
if(nodeModulesIndex >= 0) {
return nextSlash>=0 ? address.substr(0, nextSlash) : address;
}
},
basename: function(address){
var parts = address.split("/");
return parts[parts.length - 1];
},
relativeTo: function(modulePath, rel) {
var parts = modulePath.split("/");
var idx = 1;
while(rel[idx] === ".") {
parts.pop();
idx++;
}
return parts.join("/");
},
isPackageRootDir: function(pth) {
return pth.indexOf("/") === -1;
}
},
json: {
/**
* if a jsonOptions transformer is provided (by the System.config)
* use it for all json files, package.json's are also included
* @param loader
* @param load
* @param data
* @returns data
*/
transform: function(loader, load, data) {
// harmonize steal config
data.steal = utils.pkg.config(data);
var fn = loader.jsonOptions && loader.jsonOptions.transform;
if(!fn) return data;
return fn.call(loader, load, data);
}
},
includeInBuild: true
};
function parseURI(url) {
var m = String(url).replace(/^\s+|\s+$/g, '').match(/^([^:\/?#]+:)?(\/\/(?:[^:@]*(?::[^:@]*)?@)?(([^:\/?#]*)(?::(\d*))?))?([^?#]*)(\?[^#]*)?(#[\s\S]*)?/);
// authority = '//' + user + ':' + pass '@' + hostname + ':' port
return (m ? {
href : m[0] || '',
protocol : m[1] || '',
authority: m[2] || '',
host : m[3] || '',
hostname : m[4] || '',
port : m[5] || '',
pathname : m[6] || '',
search : m[7] || '',
hash : m[8] || ''
} : null);
}
module.exports = utils;