-
Notifications
You must be signed in to change notification settings - Fork 16
/
index.js
201 lines (159 loc) · 4.32 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
// Native
const {URL} = require('url');
const {join} = require('path');
const fs = require('fs');
const {promisify} = require('util');
const {tmpdir} = require('os');
// Packages
const registryUrl = require('registry-url');
const writeFile = promisify(fs.writeFile);
const mkdir = promisify(fs.mkdir);
const readFile = promisify(fs.readFile);
const compareVersions = (a, b) => a.localeCompare(b, 'en-US', {numeric: true});
const encode = value => encodeURIComponent(value).replace(/^%40/, '@');
const getFile = async (details, distTag) => {
const rootDir = tmpdir();
const subDir = join(rootDir, 'update-check');
if (!fs.existsSync(subDir)) {
await mkdir(subDir);
}
let name = `${details.name}-${distTag}.json`;
if (details.scope) {
name = `${details.scope}-${name}`;
}
return join(subDir, name);
};
const evaluateCache = async (file, time, interval) => {
if (fs.existsSync(file)) {
const content = await readFile(file, 'utf8');
const {lastUpdate, latest} = JSON.parse(content);
const nextCheck = lastUpdate + interval;
// As long as the time of the next check is in
// the future, we don't need to run it yet
if (nextCheck > time) {
return {
shouldCheck: false,
latest
};
}
}
return {
shouldCheck: true,
latest: null
};
};
const updateCache = async (file, latest, lastUpdate) => {
const content = JSON.stringify({
latest,
lastUpdate
});
await writeFile(file, content, 'utf8');
};
const loadPackage = (url, authInfo) => new Promise((resolve, reject) => {
const options = {
host: url.hostname,
path: url.pathname,
port: url.port,
headers: {
accept: 'application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8, */*'
},
timeout: 2000
};
if (authInfo) {
options.headers.authorization = `${authInfo.type} ${authInfo.token}`;
}
const {get} = require(url.protocol === 'https:' ? 'https' : 'http');
get(options, response => {
const {statusCode} = response;
if (statusCode !== 200) {
const error = new Error(`Request failed with code ${statusCode}`);
error.code = statusCode;
reject(error);
// Consume response data to free up RAM
response.resume();
return;
}
let rawData = '';
response.setEncoding('utf8');
response.on('data', chunk => {
rawData += chunk;
});
response.on('end', () => {
try {
const parsedData = JSON.parse(rawData);
resolve(parsedData);
} catch (e) {
reject(e);
}
});
}).on('error', reject).on('timeout', reject);
});
const getMostRecent = async ({full, scope}, distTag) => {
const regURL = registryUrl(scope);
const url = new URL(full, regURL);
let spec = null;
try {
spec = await loadPackage(url);
} catch (err) {
// We need to cover:
// 401 or 403 for when we don't have access
// 404 when the package is hidden
if (err.code && String(err.code).startsWith(4)) {
// We only want to load this package for when we
// really need to use the token
const registryAuthToken = require('registry-auth-token');
const authInfo = registryAuthToken(regURL, {recursive: true});
spec = await loadPackage(url, authInfo);
} else {
throw err;
}
}
const version = spec['dist-tags'][distTag];
if (!version) {
throw new Error(`Distribution tag ${distTag} is not available`);
}
return version;
};
const defaultConfig = {
interval: 3600000,
distTag: 'latest'
};
const getDetails = name => {
const spec = {
full: encode(name)
};
if (name.includes('/')) {
const parts = name.split('/');
spec.scope = parts[0];
spec.name = parts[1];
} else {
spec.scope = null;
spec.name = name;
}
return spec;
};
module.exports = async (pkg, config) => {
if (typeof pkg !== 'object') {
throw new Error('The first parameter should be your package.json file content');
}
const details = getDetails(pkg.name);
const time = Date.now();
const {distTag, interval} = Object.assign({}, defaultConfig, config);
const file = await getFile(details, distTag);
let latest = null;
let shouldCheck = true;
({shouldCheck, latest} = await evaluateCache(file, time, interval));
if (shouldCheck) {
latest = await getMostRecent(details, distTag);
// If we pulled an update, we need to update the cache
await updateCache(file, latest, time);
}
const comparision = compareVersions(pkg.version, latest);
if (comparision === -1) {
return {
latest,
fromCache: !shouldCheck
};
}
return null;
};