-
Notifications
You must be signed in to change notification settings - Fork 11
/
utils.mjs
440 lines (405 loc) · 12.5 KB
/
utils.mjs
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
import fg from 'fast-glob';
import fs from 'fs-extra';
import os from 'os';
import path from 'path';
import resolvePackage from 'resolve';
import url from 'url';
const MAX_RETRY = 30;
const packageJSONMap = new Map;
const getLocalIP = () => {
const interfaces = os.networkInterfaces();
for (const intfs of Object.values(interfaces)) {
for (const intf of intfs) {
if (intf.family === 'IPv4' && !intf.internal) return intf;
}
}
return null;
};
const { address: LOCAL_IP } = getLocalIP();
const WORKER_REXP = /(worker|sw)\d*\b/i;
export const HTTP_CODES = {
INTERNAL_SERVER_ERROR: 500,
NOT_ACCEPTABLE: 406,
NOT_FOUND: 404,
NOT_MODIFIED: 304,
OK: 200,
};
export const WATCH_EXTENSIONS = [
'pug',
'html',
'css',
'scss',
'sass',
'less',
'js',
'jsx',
'es6',
'mjs',
'vue',
'svelte',
'json',
'ts',
'tsx',
'coffee',
'png',
'jpg',
'jpeg',
'gif',
'svg',
'webp',
'glsl',
'vert',
'frag',
];
export const pathToURL = filePath => url.pathToFileURL(filePath).href.slice('file://'.length).replace(/^[a-zA-Z]:/, '');
export const urlToPath = urlPath => path.sep === '\\' ? urlPath.replace(/\//g, '\\') : urlPath;
export const getVersion = (dependencies, name) => {
if (!dependencies) return {};
const version = dependencies[name];
if (!version) return {};
const [ major, minor, patch ] = version.match(/\d+/g);
return {
major: Number(major),
minor: Number(minor),
patch: Number(patch),
};
};
const matchesModule = (filePath, module) =>
filePath === `/node_modules/${module}` || filePath.startsWith(`/node_modules/${module}/`);
export const isMap = filePath => path.extname(filePath).toLowerCase() === '.map';
export const isTest = filePath => filePath.startsWith('/test/');
export const isVendor = filePath => filePath.startsWith('/node_modules/');
export const isPolyfill = filePath => matchesModule(filePath, 'core-js') ||
matchesModule(filePath, 'buffer') ||
matchesModule(filePath, 'base64-js') ||
matchesModule(filePath, 'ieee754') ||
matchesModule(filePath, 'process') ||
matchesModule(filePath, 'regenerator-runtime');
export const isInternal = filePath =>
filePath.includes('/hq-livereload.js') || filePath.includes('/hq-empty-module.js');
export const isCertificate = (filePath, app) => app.certs.includes(filePath);
export const isWorker = filePath => WORKER_REXP.test(filePath);
export const isDefaultFavicon = filePath => filePath.endsWith('favicon.ico');
export const isAngularCompiler = filePath => filePath.endsWith('compiler/fesm5/compiler.js');
export const isSource = ext => [
'.pug',
'.html',
'.css',
'.scss',
'.sass',
'.less',
'.js',
'.jsx',
'.mjs',
'.es6',
'.vue',
'.svelte',
'.ts',
'.tsx',
'.coffee',
'.map',
].includes(ext);
export const getResType = ext => {
switch (ext) {
case '.jsx':
case '.ts':
case '.tsx':
case '.es6':
case '.vue':
case '.svelte':
case '.coffee': return '.js';
case '.scss':
case '.sass':
case '.less': return '.css';
case '.pug': return '.html';
default: return ext;
}
};
/* eslint-disable complexity */
// TODO: delete this method it is unused
export const getLinkType = (ext, name) => {
// TODO add other types https://w3c.github.io/preload/#as-attribute
switch (ext) {
case '.js':
case '.jsx':
case '.es6':
case '.vue':
case '.svelte':
case '.ts':
case '.tsx':
case '.coffee':
case '.mjs': return WORKER_REXP.test(name) ? 'worker' : 'script';
case '.json': return 'script';
case '.scss':
case '.sass':
case '.less':
case '.css': return 'style';
case '.pug':
case '.html': return 'document';
case '.woff':
case '.woff2': return 'font';
case '.gif':
case '.png':
case '.jpg':
case '.jpeg':
case '.svg':
case '.webp': return 'image';
default: return '';
}
};
/* eslint-enable complexity */
export const findExistingExtension = async filepath => {
if (filepath.endsWith('index') && await fs.pathExists(`${filepath}.html`)) return '.html';
else if (await fs.pathExists(`${filepath}.jsx`)) return '.jsx';
else if (await fs.pathExists(`${filepath}.vue`)) return '.vue';
else if (await fs.pathExists(`${filepath}.svelte`)) return '.svelte';
else if (await fs.pathExists(`${filepath}.mjs`)) return '.mjs';
else if (await fs.pathExists(`${filepath}.json`)) return '.json';
else if (await fs.pathExists(`${filepath}.ts`)) return '.ts';
else if (await fs.pathExists(`${filepath}.tsx`)) return '.tsx';
else if (await fs.pathExists(`${filepath}.coffee`)) return '.coffee';
else if (await fs.pathExists(`${filepath}.es6`)) return '.es6';
else if (await fs.pathExists(`${filepath}.js`)) return '.js';
else if (await fs.pathExists(filepath)) return '';
else if (!filepath.endsWith('index') && await fs.pathExists(`${filepath}.html`)) return '.html';
else throw new Error(`File ${filepath} not found`);
};
export const getModulePath = filepath => {
const parts = pathToURL(filepath).split('/node_modules/');
return `/node_modules/${parts[parts.length - 1]}`;
};
export const getPackageJSONDir = async dir => {
let dirPath = dir;
let prev = '';
while (dirPath !== prev && !await fs.pathExists(path.join(dirPath, 'package.json'))) {
prev = dirPath;
dirPath = path.join(dirPath, '..');
}
if (!await fs.pathExists(path.join(dirPath, 'package.json'))) return null;
return dirPath;
};
export const readPackageJSON = async (
dir,
{ search = true } = {},
fields = [ 'browser', 'exports', 'main', 'module', 'version' ],
) => {
const dirPath = search ? await getPackageJSONDir(dir) : dir;
if (packageJSONMap.has(dirPath)) return packageJSONMap.get(dirPath);
try {
const packageJSON = JSON.parse(await fs.readFile(path.join(dirPath, 'package.json'), { encoding: 'utf8' }));
const filteredJSON = {};
for (const field of fields) {
filteredJSON[field] = packageJSON[field];
}
packageJSONMap.set(dirPath, filteredJSON);
return filteredJSON;
} catch {
return {};
}
};
export const resolvePackageMain = async (dir, { search = false } = {}) => {
const dirPath = search ? await getPackageJSONDir(dir) : dir;
const packageJSON = await readPackageJSON(dirPath, { search: false });
return (
typeof packageJSON.browser === 'string' && packageJSON.browser) ||
(
typeof packageJSON.browser === 'object' &&
packageJSON.browser && packageJSON.main &&
(packageJSON.browser[`./${packageJSON.main}`] || packageJSON.browser[packageJSON.main])
) ||
packageJSON.module ||
(typeof packageJSON.exports === 'string' && packageJSON.exports) ||
packageJSON.main ||
`index${await findExistingExtension(`${dirPath}/index`)}`;
};
const resolveOrModify = (pkgPath, pkg, { emptyPath, resolve, result }) => {
const pkgBasename = pkgPath.slice(0, -path.extname(pkgPath).length);
if (typeof pkg.browser[pkgPath] === 'string') {
result.modified = true;
pkg.main = pkg.browser[pkgPath];
} else if (typeof pkg.browser[pkgPath] === 'boolean') {
result.resolved = true;
resolve(emptyPath);
} else if (typeof pkg.browser[`./${pkgPath}`] === 'string') {
result.modified = true;
pkg.main = pkg.browser[`./${pkgPath}`];
} else if (typeof pkg.browser[`./${pkgPath}`] === 'boolean') {
result.resolved = true;
resolve(emptyPath);
} else if (typeof pkg.browser[`./${pkgPath}.js`] === 'string') {
result.modified = true;
pkg.main = pkg.browser[`./${pkgPath}.js`];
} else if (typeof pkg.browser[`./${pkgPath}.js`] === 'boolean') {
result.resolved = true;
resolve(emptyPath);
} else if (typeof pkg.browser[`./${pkgBasename}.js`] === 'string') {
result.modified = true;
pkg.main = pkg.browser[`./${pkgBasename}.js`];
} else if (typeof pkg.browser[`./${pkgBasename}.js`] === 'boolean') {
result.resolved = true;
resolve(emptyPath);
}
};
export const resolvePackageFrom = (basedir, dpath, hqroot) => new Promise((resolve, reject) => {
const emptyPath = path.resolve(hqroot, 'hq-empty-module.js');
const parts = dpath.split('/node_modules/');
const modName = parts[parts.length - 1];
const modPath = modName
.split('/')
.slice(1)
.join('/');
const modResolve = resolvePackage.isCore(modName) ? `${modName}/` : modName;
const result = {
modified: false,
resolved: false,
};
return resolvePackage(
modResolve,
{
basedir,
extensions: [
'.js',
'.jsx',
'.mjs',
'.es6',
'.vue',
'.svelte',
'.ts',
'.tsx',
'.coffee',
'.css',
'.scss',
'.sass',
'.less',
'.pug',
'.html',
],
packageFilter(pkg) {
const { main: pkgMain } = pkg;
if (pkg.module) pkg.main = pkg.module;
else if (typeof pkg.exports === 'string') pkg.main = pkg.exports;
if (typeof pkg.browser === 'string') pkg.main = pkg.browser;
else if (typeof pkg.browser === 'object' && pkg.browser) {
if (modPath) {
resolveOrModify(modPath, pkg, { emptyPath, resolve, result });
} else if (pkgMain) {
resolveOrModify(pkgMain, pkg, { emptyPath, resolve, result });
} else if (pkg.module) {
resolveOrModify(pkg.module, pkg, { emptyPath, resolve, result });
}
}
return pkg;
},
pathFilter(pkg, fullPath, relativePath) {
return result.modified ? pkg.main : relativePath;
},
},
(err, p) => {
if (result.resolved) return;
if (err) reject(err);
resolve(p);
},
);
});
export const readPlugins = async (app, config) => {
try {
const { plugins } = JSON.parse(await fs.readFile(config, { encoding: 'utf-8' }));
const pluginsConfig = await Promise.all(plugins.map(async p => {
const [ pluginName, ...args ] = Array.isArray(p) ? p : [ p ];
const pluginPath = await resolvePackageFrom(app.root, `/node_modules/${pluginName}`, app.hqroot);
const { default: plugin } = await import(pluginPath);
return { args, plugin };
}));
return pluginsConfig.map(({ args, plugin }) => plugin(...args));
} catch {
return [];
}
};
/* eslint-disable no-unused-expressions */
const getFreeServer = ({
app,
certs,
cfg,
host,
net,
port,
retry,
root,
s,
secure,
}) => new Promise((resolve, reject) => {
const server = secure ?
net.createSecureServer({ allowHTTP1: true, ...cfg }, app.callback()) :
net.createServer(app.callback());
server.unref();
server.on('error', reject);
// Next 2 lines required for vscode plugin
server.localIP = LOCAL_IP;
server.protocol = `http${s}`;
server.listen(port, host, () => {
if (!app.build) {
console.log(`Start time: ${process.uptime().toFixed(1)} s`);
console.log(`Visit http${s}://localhost:${port}\nor http${s}://${LOCAL_IP}:${port} within local network`);
} else {
console.log('Building...');
}
import('./compilers/html.mjs');
resolve({
certs: certs.map(crt => crt.slice(root.length)),
server,
});
});
}).catch(err => {
if (retry > MAX_RETRY) throw err;
return getFreeServer({ app, certs, cfg, host, net, port: port + 1, retry: retry + 1, root, s, secure });
});
/* eslint-enable no-unused-expressions */
export const getServer = async ({ app, host, port, root }) => {
const certs = await fg(`${root}/**/*.pem`, { ignore: [ `${root}/node_modules/**` ] });
const cfg = (await Promise.all(certs.slice(0, 2).map(crt => fs.readFile(crt))))
.reduce(
({ cert, key }, file, index) => certs[index].endsWith('key.pem') ?
{ cert, key: file } :
{ cert: file, key },
{ cert: null, key: null },
);
const secure = Boolean(cfg.cert && cfg.key);
const s = secure ? 's' : '';
const net = await (secure ?
import('http2') :
import('http')
);
return getFreeServer({
app,
certs,
cfg,
host,
net,
port,
retry: 0,
root,
s,
secure,
});
};
export const getSrc = async root => {
const [ packageJSON, rootHTML, srcHTML, srcExists ] = await Promise.all([
readPackageJSON(root),
fs.pathExists(path.join(root, './index.html')),
fs.pathExists(path.join(root, 'src/index.html')),
fs.pathExists(path.join(root, 'src')),
]);
return packageJSON.module ?
path.dirname(packageJSON.module) :
typeof packageJSON.exports === 'string' ?
path.dirname(packageJSON.exports) :
srcHTML ?
'src' :
rootHTML ?
'.' :
srcExists ?
'src' :
packageJSON.main ?
path.dirname(packageJSON.main) :
'.';
};