-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
300 lines (294 loc) · 10.1 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
#!/usr/bin/env node
import {existsSync, readFileSync, rmSync, writeFileSync} from "fs"
import {execSync} from "child_process"
import {join} from "path"
import maxSatisfying from "semver/ranges/max-satisfying.js"
const config = {
"audit": true,
"dedup": true,
/** @type {number|"\t"} */
"indent": 4,
"npm": {
"force": false,
"global": false,
"ignoreScripts": false,
"legacy": false,
"silent": false,
"verbose": false
},
/** @type {{[name: string]: string}} */
"overrides": {},
"prefixChar": ""
}
/**
* Find the version of a package by direct version matching or semver range.
* @param {string[]} versions - The list of versions available.
* @param {string} range - The version range to search for.
*/
const findByRange = (versions, range) => {
if (versions.includes(range)) {
return range
}
return maxSatisfying(versions, range)
}
/**
* Find the type of version selector, such as semver, alias or git package.
* @param {string} name
* @param {string} version
*/
const findVersionType = (name, version) => {
/** @type {"semver"|"alias"|"git"|"url"|"file"} */
let verType = "semver"
let alias = null
if (version.startsWith("npm:")) {
alias = version.replace(/^npm:/, "")
.split("@").slice(0, -1).join("@")
verType = "alias"
}
const hasSlashes = name.includes("/") || version.includes("/")
if (hasSlashes && !name.startsWith("@")) {
verType = "git"
if (version.startsWith("http:") || version.startsWith("https:")) {
verType = "url"
} else if (version.startsWith("file:")) {
verType = "file"
}
}
return {alias, verType}
}
/**
* Find the wanted version for a given package based on desired version string.
* @param {{
* alias?: string|null,
* desired: string,
* name: string,
* paddedName: string,
* verType: "alias"|"semver",
* version: string,
* }} opts
*/
const findWantedVersion = ({
alias, desired, name, paddedName, verType, version
}) => {
/** @type {{
* "dist-tags": {[name: string]: string|null},
* "versions": string[]
* }|null} */
let info = null
try {
info = JSON.parse(execSync(
`npm view ${alias ?? name} --json`, {"encoding": "utf8"}))
} catch {
// Can't update package without this info, next if will be entered.
}
if (!info?.["dist-tags"] || !info?.versions) {
console.info(`X ${paddedName}${version} (${desired})`)
console.warn(`X Failed, npm request for ${
name} gave invalid info, sticking to ${version}`)
return null
}
let {latest} = info["dist-tags"]
if (desired === "latest" && config.prefixChar) {
latest = config.prefixChar + latest
}
let wanted = latest
if (desired !== "latest") {
wanted = info["dist-tags"][desired]
?? findByRange(info.versions, desired)
}
if (!wanted || !latest) {
console.info(`X ${paddedName}${version} (${desired})`)
console.warn(`X Failed, no ${desired} version for ${
name}, sticking to ${version}`)
return null
}
if (verType === "alias") {
wanted = `npm:${alias}@${wanted}`
}
if (wanted === version) {
console.info(` ${paddedName}${version} (${desired})`)
} else {
console.info(`> ${paddedName}${
version} => ${wanted} (${desired})`)
}
if (desired !== "latest") {
console.info(` (latest is ${latest})`)
}
return wanted
}
const packageJson = join(process.cwd(), "package.json")
/** @type {import('./package.json')|null} */
let pack = null
try {
const packStr = readFileSync(packageJson, {"encoding": "utf8"}).toString()
const line = packStr.split("\n").find(
l => l.startsWith(" ") || l.startsWith("\t")) ?? ""
config.indent = line.search(/\S|$/) ?? config.indent
if (line.startsWith("\t")) {
config.indent = "\t"
}
pack = JSON.parse(packStr)
} catch {
console.warn("X No package.json found in the current directory")
process.exit(1)
}
const nusConfigFile = join(process.cwd(), "nus.config.js")
if (existsSync(nusConfigFile)) {
let customConfig = null
try {
customConfig = await import(nusConfigFile)
customConfig = customConfig.default ?? customConfig
} catch {
console.warn("X Ignoring 'nus.config.js' config, invalid JS")
}
if (customConfig) {
/** @type {(keyof typeof config.npm)[]} */
const npmArgs = [
"force",
"global",
"ignoreScripts",
"legacy",
"silent",
"verbose"
]
for (const npmArg of npmArgs) {
if (typeof customConfig?.npm?.[npmArg] === "boolean") {
config.npm[npmArg] = customConfig.npm[npmArg]
} else if (customConfig?.npm?.[npmArg] !== undefined) {
console.warn(`X Ignoring config for 'npm.${
npmArg}', must be boolean`)
}
}
/** @type {("audit"|"dedup")[]} */
const boolOpts = ["audit", "dedup"]
for (const arg of boolOpts) {
if (typeof customConfig?.[arg] === "boolean") {
config[arg] = customConfig[arg]
} else if (customConfig[arg] !== undefined) {
console.warn(`X Ignoring config for 'npm.${
arg}', must be boolean`)
}
}
if (customConfig.indent === "\t" || customConfig.indent === "\\t") {
config.indent = "\t"
} else if (typeof customConfig.indent === "number") {
config.indent = customConfig.indent
} else if (customConfig.indent !== undefined) {
console.warn("X Ignoring config for 'indent', "
+ "must be number or '\\t'")
}
const validPrefixes = ["", "<", ">", "<=", ">=", "=", "~", "^"]
if (validPrefixes.includes(customConfig.prefixChar)) {
config.prefixChar = customConfig.prefixChar
} else if (customConfig.prefixChar !== undefined) {
console.warn(`X Ignoring config for 'prefixChar', must be one of: ${
validPrefixes.join(" ")}`)
}
if (typeof customConfig.overrides === "object") {
for (const [key, value] of Object.entries(customConfig.overrides)) {
if (typeof value !== "string") {
console.warn(`X Ignoring override '${key}',`
+ " value must be string")
continue
}
config.overrides[key] = value
}
} else if (customConfig.overrides !== undefined) {
console.warn("X Ignoring config for 'overrides', "
+ "must be a flat string-string object")
}
}
}
const nusOverridesFile = join(process.cwd(), "nus.overrides.json")
if (existsSync(nusOverridesFile)) {
try {
const overrides = JSON.parse(readFileSync(nusOverridesFile).toString())
if (typeof overrides === "object" && !Array.isArray(overrides)) {
for (const [key, value] of Object.entries(overrides)) {
if (typeof value !== "string") {
console.warn(`X Ignoring override '${key}',`
+ " value must be string")
continue
}
config.overrides[key] = value
}
} else if (overrides !== undefined) {
console.warn("X Ignoring config from 'nus.overrides.json', "
+ "must be a flat string-string object")
}
} catch {
console.warn("X Ignoring 'nus.overrides.json' config, invalid JSON")
}
}
let longestName = 20
if (pack?.dependencies) {
for (const name of Object.keys(pack.dependencies)) {
longestName = Math.max(longestName, name.length)
}
}
if (pack?.devDependencies) {
for (const name of Object.keys(pack.devDependencies)) {
longestName = Math.max(longestName, name.length)
}
}
/** @type {("dependencies"|"devDependencies")[]} */
const depTypes = ["dependencies", "devDependencies"]
for (const depType of depTypes) {
if (!pack || !pack[depType]) {
continue
}
console.info(`= Updating ${depType} =`)
for (const [name, version] of Object.entries(pack[depType])) {
const paddedName = `${name.padEnd(longestName, " ")} `
const {verType, alias} = findVersionType(name, version)
const desired = config.overrides[name] ?? "latest"
if (verType === "file" || verType === "git" || verType === "url") {
const hash = desired.replace(/^#+/g, "")
if (hash === "latest" || verType !== "git") {
console.info(`- ${paddedName}${verType}`)
} else {
console.info(`- ${paddedName}git#${hash}`)
// @ts-expect-error Indexing does not take depType into account
pack[depType][name] = `${version.split("#")[0]}#${hash}`
}
} else {
const wanted = findWantedVersion({
alias, desired, name, paddedName, verType, version
})
if (wanted) {
// @ts-expect-error Indexing does not take depType into account
pack[depType][name] = wanted
}
}
}
}
console.info(`= Installing =`)
writeFileSync(packageJson, `${JSON.stringify(pack, null, config.indent)}\n`)
rmSync(join(process.cwd(), "package-lock.json"), {"force": true})
rmSync(join(process.cwd(), "node_modules"), {"force": true, "recursive": true})
let args = ""
if (config.npm.force) {
args += " --force"
}
if (config.npm.global) {
args += " --global"
}
if (config.npm.ignoreScripts) {
args += " --ignore-scripts"
}
if (config.npm.legacy) {
args += " --legacy-peer-deps"
}
if (config.npm.silent) {
args += " --silent"
}
if (config.npm.verbose) {
args += " --verbose"
}
execSync(`npm install${args}`, {"encoding": "utf8", "stdio": "inherit"})
if (config.audit) {
execSync(`npm audit fix${args}`, {"encoding": "utf8", "stdio": "inherit"})
}
if (config.dedup) {
execSync(`npm dedup${args}`, {"encoding": "utf8", "stdio": "inherit"})
}