-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
109 lines (92 loc) · 2.67 KB
/
app.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
const express = require('express')
const morgan = require('morgan')
const validate = require('validate-npm-package-name')
const chalk = require('chalk')
const debug = require('debug')('amdfiy')
const axios = require('axios')
const rjs = require('./rjs')
const apm = require('./apm')
const registry = require('./registry')
const currentPkg = require('./package.json')
const app = express()
const port = process.env.PORT || 8132
const AMDIFY_PREFIX = chalk.cyan('amdify')
app.use(morgan('dev'))
app.use(express.static('dist'))
app.get('/', function (req, res) {
res.json({
usage: 'Navigate to /<pkgname>.js to get optimized amd package.',
amdfly: currentPkg
})
})
app.get('*.js', function (req, res, next) {
if (!req.path.endsWith('.js')) {
return res.end('please append .js to your url.')
}
const pkg = req.path.replace(/^\/+/, '').replace(/\.js$/, '')
let [exp, pkgName, verQuery] = pkg.match(/(^.[^@]+)@?(.*)$/)
if (!validate(pkgName).validForOldPackages) {
return res.status(400).end('Package name invalid.')
}
registry.findPackageVersion(pkgName, verQuery)
.then(ver => {
if (ver !== verQuery) {
return res.redirect(302, `/${pkgName}@${ver}.js`)
}
return servePkg(pkgName, ver)
.then(file => {
res.sendFile(file, { root: __dirname })
})
})
.catch(err => {
next(err)
})
})
const installPromises = new Map()
function servePkg(pkgName, pkgVer) {
pkgId = `${pkgName}@${pkgVer}`
debug(`fallback to script process, ${pkgId}`)
let promise
if (installPromises.has(pkgId)) {
debug(`${pkgId} promise is in the cache`)
promise = installPromises.get(pkgId)
} else {
debug(`${pkgId} is not in the cache`)
if (!apm.hasInstalled(pkgName, pkgVer)) {
debug(`${pkgId} is not installed`)
console.log(`${AMDIFY_PREFIX} Installing ${pkgId} ...`)
promise = apm.install(pkgName, pkgVer)
} else {
debug(`${pkgId} is installed`)
promise = Promise.resolve()
}
promise = promise
.then(() => {
console.log(`${AMDIFY_PREFIX} Optimizing ${pkgId} ...`)
return rjs.optimize(pkgName, pkgVer)
})
.then((log) => {
debug(`optimized ${pkgId}`, log)
console.log(`${AMDIFY_PREFIX} Optimized ${pkgId}`)
})
installPromises.set(pkgId, promise)
}
return promise
.then(() => {
installPromises.delete(pkgId)
return `dist/${pkgId}.js`
}, err => {
debug(`${pkgId} error`, err)
throw err
})
}
app.use(function (err, req, res, next) {
console.error(err)
res.status(500).end(err.message)
})
app.listen(port, function (err) {
if (err) {
throw err
}
console.log(`${AMDIFY_PREFIX} listened on port ${port}`)
})