forked from fex-team/fis3-hook-node_modules
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
577 lines (455 loc) · 13.9 KB
/
index.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
var path = require('path');
var resolve = require('resolve');
var moduleRoot;
var fs = require('fs');
var assign = require('object-assign');
var _ = require('lodash');
var semver = require('semver');
var componentsInfo = null;
var disabled = [];
var replaced = [];
var moduleVersion = {};
var moduleMaps = {};
var npmVersion = null;
var lookup = require('fis3-hook-commonjs/lookup.js')
// 兼容node的全局变量
var vars = {
process: function () {
return 'var process = require(\'process/browser\');';
},
global: function () {
return 'var global = typeof global !== "undefined" ? global : '
+ 'typeof self !== "undefined" ? self : '
+ 'typeof window !== "undefined" ? window : {};'
;
},
Buffer: function () {
return 'var Buffer = require("buffer").Buffer;';
},
'Buffer.isBuffer': function () {
return 'Buffer.isBuffer = require("is-buffer");';
}
};
// 替换node的一些全局变量
var replaceVars = {
__filename: function (file, basedir) {
var filename = '/' + path.relative(basedir, file);
return JSON.stringify(filename);
},
__dirname: function (file, basedir) {
var dir = path.dirname('/' + path.relative(basedir, file));
return JSON.stringify(dir);
}
}
function checkNpmVersion (fis, opts) {
moduleRoot = path.join(fis.project.getProjectPath(), opts.baseUrl || '.');
var rootDir = moduleRoot;
var rootJson = getPackageJSON(rootDir);
var npmVersion = false; // 3.x
var _modulesV2 = {};
var _modulesV3 = {};
// 适用于npm 2版的查找方式
function _findV2 (root, dependencies) {
var modules = dependencies.map(function (name) {
return path.join(root, 'node_modules', name);
});
modules.forEach(function (val) {
if (!checkPackageJSON(val)) {
return;
}
var json = getPackageJSON(val);
var name = json.name;
_modulesV2[name] = true;
// 查找模块内部依赖
if (json.dependencies && Object.keys(json.dependencies).length > 0) {
_findV2(val, Object.keys(json.dependencies));
}
})
}
// 使用与npm 3版的查找方式
function _findV3 (root, dependencies) {
var modules = dependencies.map(function (name) {
return path.join(root, 'node_modules', name);
});
modules.forEach(function (val) {
if (!checkPackageJSON(val)) {
return;
}
var json = getPackageJSON(val);
var name = json.name;
_modulesV3[name] = true;
// 查找模块内部依赖
if (json.dependencies && Object.keys(json.dependencies).length > 0) {
_findV3(root, Object.keys(json.dependencies));
}
})
}
// 尝试用v2的方式查找
_findV2(rootDir, Object.keys(rootJson.dependencies));
// 尝试用v3的方式查找
_findV3(rootDir, Object.keys(rootJson.dependencies));
// 对比查找的差异 嵌套
var difference = _.difference(Object.keys(_modulesV2), Object.keys(_modulesV3))
if (difference > 0) {
console.warn('detected you had installed your node_modules with different npm versions, please remove your node_modules and reinstall')
process.exit(1)
}
_.each(_modulesV2, function (val, name) {
if (!checkPackageJSON(path.join(rootDir, 'node_modules', name))) {
npmVersion = true;
}
})
return npmVersion;
}
function indexOfCollection (arr, obj, name) {
for (var i = 0, len = arr.length; i < len; i++) {
if (name) {
if (_.isEqual(arr[i][name], obj[name])) {
return i;
}
}
else {
if (_.isEqual(arr[i], obj)) {
return i;
}
}
}
return -1;
}
function getComponentsInfo (fis, opts) {
var rootDir = moduleRoot;
var rootJson = getPackageJSON(rootDir);
componentsInfo = {
version: rootJson.version
}
function _find (root, dependencies, info) {
var modules = dependencies.map(function (name) {
return path.join(root, 'node_modules', name);
});
modules.forEach(function (val, index) {
if (!checkPackageJSON(val)) {
return;
}
var json = getPackageJSON(val);
var version = json.version;
var name = json.name;
if (!info.dependencies) {
info.dependencies = {};
}
// 如果moduleVersion中一个模块是空的, 那说明还没有这个模块,
// 数组个数为一, 说明在root下面
// 数组个数大于一, 说明还有一些其他版本分布在其他模块内部
if (!moduleVersion[name]) {
moduleVersion[name] = [];
}
if (!moduleMaps[name]) {
moduleMaps[name] = [];
}
var versionObj = {
version: version,
name: name,
modulePath: val
}
// 重复版本的模块直接忽略
if (indexOfCollection(moduleVersion[name], versionObj, 'version') < 0) {
if (info.dependencies[name]) {
console.log(versionObj, info.dependencies[name]);
}
else {
info.dependencies[name] = {
version: version,
location: val,
_dependencies: json.dependencies
}
}
moduleVersion[name].push(versionObj);
moduleMaps[name].push(createPath(val));
}
// 查找模块内部依赖
if (json.dependencies && Object.keys(json.dependencies).length > 0 && info.dependencies[name]) {
var rawSubDependencies = Object.keys(json.dependencies);
// 根据是否存在于moduleVerions来判断是否已经找到相关模块
// 还需要判断重复模块的版本
var rootDependencies = rawSubDependencies.filter(function (sname) {
return (!moduleVersion[sname] && !checkPackageJSON(path.join(moduleRoot, 'node_modules', sname))) ||
(!checkPackageJSON(path.join(moduleRoot, 'node_modules', sname))
&& semver.satisfies(moduleVersion[sname].version, json.dependencies[sname])
)
})
var subDependencies = _.difference(rawSubDependencies, rootDependencies);
if (npmVersion === '2') {
_find(val, rootDependencies, componentsInfo);
}
else {
_find(root, rootDependencies, componentsInfo);
}
_find(val, subDependencies, info.dependencies[name])
}
})
}
_find(rootDir, Object.keys(rootJson.dependencies), componentsInfo);
if (opts.useDev) {
_find(rootDir, Object.keys(rootJson.devDependencies), componentsInfo)
}
return componentsInfo;
}
// 没有参数返回true, 有则进行判断
function xorEqual (pre, next, fn) {
console.log(pre, next)
if (!pre) {
return true;
}
if (fn) {
return fn(pre, next);
}
return pre === next;
}
function getEntrance (json, rest) {
var main = json.main;
if (json.browser) {
var browser = json.browser;
if (typeof browser === 'string') {
return browser
}
if (_.isObject(browser)) {
for (var key in browser) {
if (browser.hasOwnProperty(key)) {
if (key === main) {
main = browser[key];
continue;
}
var obj = {};
var jsReg = /([\w\.\/]+).js$/;
var jsName = jsReg.exec(key)[1];
obj[jsName] = browser[key];
if (!browser[key] && indexOfCollection(disabled, obj) < 0) {
disabled.push(obj);
}
else if (indexOfCollection(replaced, obj) < 0) {
replaced.push(obj);
}
}
}
}
}
return main;
}
function getPackageJSON (basedir) {
var jsonPath = path.join(basedir, 'package.json');
return JSON.parse(fs.readFileSync(jsonPath));
}
function getProjectRelativePath (dirname) {
return '/' + path.relative(moduleRoot, dirname);
}
function onReleaseStart (fis, opts) {
// 读取组件信息, 这是项目路径
npmVersion = checkNpmVersion(fis, opts) ? '2' : '3';
console.log('detect your installed node_modules type: ', 'npm v' + npmVersion + '.x');
disabled = [];
replaced = [];
moduleVersion = {};
moduleMaps = {};
componentsInfo = getComponentsInfo(fis, opts);
}
function followPath (path) {
var paths = path.split('/')
var target = null
paths.shift();
function find (root, next) {
var module = next.shift();
var name = module.split('@')[0];
var version = module.split('@')[1];
var findOne;
if (root.dependencies && root.dependencies[name]) {
findOne = root.dependencies[name]
}
else {
findOne = componentsInfo.dependencies[name];
}
if (next.length == 0) {
if (findOne) {
target = findOne
}
return;
}
find(findOne, next)
}
find(componentsInfo, paths)
return target
}
function createPath (dirname) {
var relaPath = path.join('/', path.relative(moduleRoot, dirname)).replace(/\\/g, '/');
var modulePath = relaPath.split('/node_modules/');
var root = 'root@' + componentsInfo.version;
modulePath.shift();
var pathMaps = modulePath.map(function (val, index) {
var mPath = modulePath.slice(0, index + 1);
var target = '';
function find (root, next) {
var moduleName = next.shift();
var module;
if (root.dependencies && root.dependencies[moduleName]) {
module = root.dependencies[moduleName];
}
else {
module = componentsInfo.dependencies[moduleName];
}
if (moduleName === 'async-validator') {
}
var moduleVersion = module.version;
target = moduleName + '@' + moduleVersion;
if (next.length > 0) {
find(module, next);
}
}
find(componentsInfo, mPath)
return target;
}).join('/');
if (pathMaps.length === 0) {
return root;
}
else {
return root + '/' + pathMaps
}
}
function _findResource (name, filePath) {
var extList = ['.js', '.jsx', '.coffee', '.css', '.sass', '.scss', '.less', '.html', '.tpl', '.vm', '.js', '.jsx', '.es', '.ts', '.tsx'];
var info = fis.uri(name, filePath);
var entrance = ['', 'index'];
for (var i = 0, len = extList.length; i < len && !info.file; i++) {
info = fis.uri(name + extList[i], filePath);
}
for (var j = 0, jlen = extList.length; j < jlen && !info.file; j++) {
for (var x = 0, xlen = entrance.length; x < xlen && !info.file; x++) {
info = fis.uri(path.join(name, entrance[x]) + extList[j], filePath);
}
}
return info;
}
function checkPackageJSON (dirname) {
if (!dirname) {
return false;
}
return fs.existsSync(path.join(dirname, 'package.json'));
}
function onFileLookUp (info, file) {
// 如果已经找到了,没必要再找了。
if (info.file || file && file.useShortPath === false) {
return;
}
var rest = info.rest;
replaced.forEach(function (val) {
if (val[info.rest]) {
rest = val[info.rest];
}
});
var m = /^([0-9a-zA-Z\.\-_]+)(?:\/(.+))?$/.exec(rest);
if (m) {
var cName = m[1];
var subpath = m[2];
var resolved;
var filePath;
if (moduleVersion[cName]) {
var dirname = file.dirname;
var relaDir = dirname.split('/');
var moduleDir = null;
do {
var isModule = checkPackageJSON(relaDir.join('/'));
if (isModule) {
moduleDir = relaDir.join('/');
}
else {
relaDir.pop();
}
}
while (relaDir.length > 0 && !moduleDir);
var rleaModulePath = createPath(moduleDir);
var targetPath = null;
var maps = moduleMaps[cName].map(function (val) {
return val.replace(rleaModulePath, '');
}).sort(function (pre, next) {
return pre.split('/').length > next.split('/').length;
})
if (maps.length > 0) {
targetPath = rleaModulePath + maps.shift();
}
else {
targetPath = moduleMaps[cName][0];
}
var moduleInfo = followPath(targetPath);
var modulePath = moduleInfo.location;
if (!subpath) {
var json = getPackageJSON(modulePath)
var entrance = getEntrance(json, rest);
filePath = path.join(modulePath, entrance || 'index')
}
else {
filePath = path.join(modulePath, subpath)
}
}
else if (cName[0] === '.') {
// 丢失的相对路径文件, 能找到就找到,找不到就算
// 还有一个用途是对于package.json的browser属性中路径的替换
filePath = path.join(file.dirname, rest);
}
else {
try {
filePath = resolve.sync(rest, {basedir: moduleRoot})
} catch (e) {
fis.log.warning(e.message)
}
}
if (!filePath) {
var errmsg = cName + (subpath ? '/' + subpath : '');
return console.log('\n missing file: ' + errmsg + '\n');
}
resolved = _findResource(getProjectRelativePath(filePath))
// 根据规则找到了。
if (resolved.file) {
info.id = resolved.file.getId();
info.file = resolved.file;
}
}
}
function onPreprocess (file) {
var content = file.getContent().toString();
var pushContent = [];
var rest = file.rest;
var basedir = moduleRoot;
if (!file.isJsLike || !file.isMod) {
return;
}
Object.keys(vars).forEach(function (name) {
if (RegExp('\\b' + name + '\\b').test(content) && !(file.fullname.indexOf(name.toLowerCase()) >= 0)) {
pushContent.push(vars[name](rest, basedir))
}
})
Object.keys(replaceVars).forEach(function (name) {
content = content.replace(name, replaceVars[name](rest, basedir));
})
disabled.forEach(function (name) {
content = content.replace(new RegExp("require\\(\\s?['\"]" + name.replace('.', '\\.') + "['\"]\\s?\\)", "g"), '{}');
})
content = pushContent.join('\n') + '\n' + content;
file.setContent(content);
}
var entry = module.exports = function (fis, opts) {
lookup.lookupList = [
lookup.tryFisIdLookUp,
lookup.tryPathsLookUp,
lookup.tryPackagesLookUp,
onFileLookUp,
lookup.tryFolderLookUp,
lookup.tryNoExtLookUp,
lookup.tryBaseUrlLookUp,
lookup.tryRootLookUp
];
fis.on('release:start', onReleaseStart.bind(null, fis, opts));
fis.on('lookup:file', onFileLookUp);
fis.on('process:start', onPreprocess);
fis.set('component.type', 'node_modules');
};
entry.defaultOptions = {
// 加载 devDependencies 的模块
useDev: false
};