-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnrmrc.mjs
More file actions
105 lines (96 loc) · 2.59 KB
/
nrmrc.mjs
File metadata and controls
105 lines (96 loc) · 2.59 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
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
import { homedir } from 'node:os'
import { resolve } from 'node:path'
import { createReadStream } from 'node:fs'
import { createInterface } from 'node:readline'
import { appendFile, writeFile } from 'node:fs/promises'
import { existsSync } from 'node:fs'
const nrmrcPath = resolve(homedir(), '.nrmrc')
/**
* Read config line by line, stop when invalid.
*/
export async function readNrmrc() {
if (!existsSync(nrmrcPath)) {
return new Map()
}
const rl = createInterface(createReadStream(nrmrcPath))
/**
* false: [name]
* true : registry=https://registry.url
*/
let state = false
let name = ''
let url = ''
/** @type {Array<[string, string]>} */
const entries = []
for await (let line of rl) {
line = line.trim()
if (line.length === 0) continue
if (state) {
const prefix = 'registry='
if (!line.startsWith(prefix)) continue
url = line.slice(prefix.length).trim() // remove prefix
entries.push([name, url])
} else {
if (!(line.startsWith('[') && line.endsWith(']'))) break
name = line.slice(1, -1)
if (name.length === 0) break
name = decodeName(name)
}
state = !state
}
return new Map(entries)
}
// name is `name`, not `[name]`
// the '[' and ']' should be removed first
/**
* @param {string} name
*/
export function encodeName(name) {
if (name.length > 1 && name.startsWith('"') && name.endsWith('"')) {
return `"${name.replaceAll('"', String.raw`\"`)}"`
} else {
return name
}
}
/**
* @param {string} name
*/
export function decodeName(name) {
if (name.length > 1 && name.startsWith('"') && name.endsWith('"')) {
return name.slice(1, -1).replaceAll(String.raw`\"`, '"')
} else {
return name
}
}
/**
* @param {string} url
*/
function resolveUrl(url) {
if (!url.endsWith('/')) url = url + '/'
if (url.startsWith('/') || url.startsWith('\\')) return resolve(url)
return url
}
/**
* @param {string} name
* @param {string} url
*/
export async function appendNrmrc(name, url) {
return await appendFile(
nrmrcPath,
`[${encodeName(name)}]\nregistry=${resolveUrl(url)}\n\n`,
)
}
/**
* @param {Map<string, string>} registries
*/
export async function writeNrmrc(registries) {
return await writeFile(
nrmrcPath,
Array.from(registries.entries())
.map(
([name, url]) =>
`[${encodeName(name)}]\nregistry=${resolveUrl(url)}`,
)
.join('\n\n'),
)
}