Repository navigation
Expand file tree
/
Copy pathindex.js
More file actions
56 lines (51 loc) · 1.71 KB
/
Copy pathindex.js
File metadata and controls
56 lines (51 loc) · 1.71 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
const fs = require('fs')
const path = require('path')
const mime = require('mime')
const resolve = require('resolve')
function resolvePath (root, filepath, url) {
try {
// ignore full urls
new URL(url)
return url
} catch (e) {}
try {
const result = path.relative(path.dirname(filepath), resolve.sync(url, {
basedir: path.dirname(filepath),
packageFilter: (pkg) => {
pkg.main = pkg.module || pkg['jsnext:main'] || pkg.main
return pkg
}
}))
return result.startsWith('.') ? result : './' + result
} catch (e) {}
return url
}
function transformJs (root, filepath, src) {
return src
.replace(/import(\s*\(?)(|[\{\*\w][^"']*)["']([^"']+)["'][\t ]*($|;|\/\/|\/\*|\))/gm,
(match, s, pre, url, post) => `import${s}${pre}'${resolvePath(root, filepath, url)}'${post}`)
.replace(/export\s*([\{\*\w][^"']*)\s*from\s*["']([^"']+)["'][\t ]*($|;|\/\/|\/\*)/gm,
(match, pre, url, post) => `export ${pre} from '${resolvePath(root, filepath, url)}'${post}`)
}
function middleware (root) {
return function (req, res, next) {
const reqpath = path.normalize(req.path).slice(1)
if (reqpath.length < 1) {
return next()
}
const filepath = path.resolve(root, reqpath)
if (fs.existsSync(filepath)) {
const filetype = mime.getType(filepath) || 'application/octet-stream'
res.setHeader('Content-Type', filetype)
if (filetype.startsWith('text/javascript') || filetype.startsWith('application/javascript')) {
const content = fs.readFileSync(filepath, { encoding: 'utf-8' })
return res.end(transformJs(root, filepath, content), 'utf-8')
} else {
const content = fs.readFileSync(filepath)
return res.end(content)
}
}
next()
}
}
module.exports = { resolvePath, transformJs, middleware }