-
Notifications
You must be signed in to change notification settings - Fork 313
/
yarn.ts
292 lines (253 loc) · 9.79 KB
/
yarn.ts
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
import memoize from 'fast-memoize'
import fs from 'fs/promises'
import yaml from 'js-yaml'
import jsonlines from 'jsonlines'
import curry from 'lodash/curry'
import os from 'os'
import path from 'path'
import spawn from 'spawn-please'
import exists from '../lib/exists'
import findLockfile from '../lib/findLockfile'
import { keyValueBy } from '../lib/keyValueBy'
import { print } from '../lib/logging'
import { GetVersion } from '../types/GetVersion'
import { Index } from '../types/IndexType'
import { NpmConfig } from '../types/NpmConfig'
import { NpmOptions } from '../types/NpmOptions'
import { Options } from '../types/Options'
import { SpawnOptions } from '../types/SpawnOptions'
import { VersionSpec } from '../types/VersionSpec'
import {
distTag as npmDistTag,
greatest as npmGreatest,
latest as npmLatest,
minor as npmMinor,
newest as npmNewest,
patch as npmPatch,
} from './npm'
interface ParsedDep {
version: string
from: string
required?: {
version: string
}
}
export interface NpmScope {
npmAlwaysAuth?: boolean
npmAuthToken?: string
npmRegistryServer?: string
}
interface YarnConfig {
npmScopes?: Index<NpmScope>
}
/** Safely interpolates a string as a template string. */
const interpolate = (s: string, data: Index<string | undefined>): string =>
s.replace(
/\$\{([^:-]+)(?:(:)?-([^}]*))?\}/g,
(match, key, name, fallbackOnEmpty, fallback) => data[key] || (fallbackOnEmpty ? fallback : ''),
)
/** Reads an auth token from a yarn config, interpolates it, and returns it as an npm config key-value pair. */
export const npmAuthTokenKeyValue = curry((npmConfig: Index<string | boolean>, dep: string, scopedConfig: NpmScope) => {
if (scopedConfig.npmAuthToken) {
// get registry server from this config or a previous config (assumes setNpmRegistry has already been called on all npm scopes)
const registryServer = scopedConfig.npmRegistryServer || (npmConfig[`@${dep}:registry`] as string | undefined)
// interpolate environment variable fallback
// https://yarnpkg.com/configuration/yarnrc
if (registryServer) {
let trimmedRegistryServer = registryServer.replace(/^https?:/, '')
if (trimmedRegistryServer.endsWith('/')) {
trimmedRegistryServer = trimmedRegistryServer.slice(0, -1)
}
return {
[`${trimmedRegistryServer}/:_authToken`]: interpolate(scopedConfig.npmAuthToken, process.env),
}
}
}
return null
})
/** Reads a registry from a yarn config. interpolates it, and returns it as an npm config key-value pair. */
const npmRegistryKeyValue = (dep: string, scopedConfig: NpmScope): null | Index<VersionSpec> =>
scopedConfig.npmRegistryServer
? { [`@${dep}:registry`]: interpolate(scopedConfig.npmRegistryServer, process.env) }
: null
/**
* Returns the path to the local .yarnrc.yml, or undefined. This doesn't
* actually check that the .yarnrc.yml file exists.
*
* Exported for test purposes only.
*
* @param readdirSync This is only a parameter so that it can be used in tests.
*/
export async function getPathToLookForYarnrc(
options: Options,
readdir: (_path: string) => Promise<string[]> = fs.readdir,
): Promise<string | undefined> {
if (options.global) return undefined
const directoryPath = (await findLockfile(options, readdir))?.directoryPath
if (!directoryPath) return undefined
return path.join(directoryPath, '.yarnrc.yml')
}
// If private registry auth is specified in npmScopes in .yarnrc.yml, read them in and convert them to npm config variables.
// Define as a memoized function to efficiently call existsSync and readFileSync only once, and only if yarn is being used.
// https://github.com/raineorshine/npm-check-updates/issues/1036
const npmConfigFromYarn = memoize(async (options: Options): Promise<NpmConfig> => {
const yarnrcLocalPath = await getPathToLookForYarnrc(options)
const yarnrcUserPath = path.join(os.homedir(), '.yarnrc.yml')
const yarnrcLocalExists = typeof yarnrcLocalPath === 'string' && (await exists(yarnrcLocalPath))
const yarnrcUserExists = await exists(yarnrcUserPath)
const yarnrcLocal = yarnrcLocalExists ? await fs.readFile(yarnrcLocalPath, 'utf-8') : ''
const yarnrcUser = yarnrcUserExists ? await fs.readFile(yarnrcUserPath, 'utf-8') : ''
const yarnConfigLocal: YarnConfig = yaml.load(yarnrcLocal) as YarnConfig
const yarnConfigUser: YarnConfig = yaml.load(yarnrcUser) as YarnConfig
let npmConfig: Index<string | boolean> = {
...keyValueBy(yarnConfigUser?.npmScopes || {}, npmRegistryKeyValue),
...keyValueBy(yarnConfigLocal?.npmScopes || {}, npmRegistryKeyValue),
}
// npmAuthTokenKeyValue uses scoped npmRegistryServer, so must come after npmRegistryKeyValue
npmConfig = {
...npmConfig,
...keyValueBy(yarnConfigUser?.npmScopes || {}, npmAuthTokenKeyValue(npmConfig)),
...keyValueBy(yarnConfigLocal?.npmScopes || {}, npmAuthTokenKeyValue(npmConfig)),
}
// set auth token after npm registry, since auth token syntax uses regitry
if (yarnrcLocalExists) {
print(options, `\nUsing local yarn config at ${yarnrcLocalPath}:`, 'verbose')
print(options, yarnConfigLocal, 'verbose')
}
if (yarnrcUserExists) {
print(options, `\nUsing user yarn config at ${yarnrcUserPath}:`, 'verbose')
print(options, yarnConfigLocal, 'verbose')
}
if (Object.keys(npmConfig)) {
print(options, '\nMerged yarn config in npm format:', 'verbose')
print(options, npmConfig, 'verbose')
}
return npmConfig
})
/**
* Parse JSON lines and throw an informative error on failure.
*
* Note: although this is similar to the NPM parseJson() function we always return the
* same concrete-type here, for now.
*
* @param result Output from `yarn list --json` to be parsed
*/
function parseJsonLines(result: string): Promise<{ dependencies: Index<ParsedDep> }> {
return new Promise((resolve, reject) => {
const dependencies: Index<ParsedDep> = {}
const parser = jsonlines.parse()
parser.on('data', d => {
// only parse info data
// ignore error info, e.g. "Visit https://yarnpkg.com/en/docs/cli/list for documentation about this command."
if (d.type === 'info' && !d.data.match(/^Visit/)) {
// parse package name and version number from info data, e.g. "nodemon@2.0.4" has binaries
const [, pkgName, pkgVersion] = d.data.match(/"(@?.*)@(.*)"/) || []
dependencies[pkgName] = {
version: pkgVersion,
from: pkgName,
}
} else if (d.type === 'error') {
reject(new Error(d.data))
}
})
parser.on('end', () => {
resolve({ dependencies })
})
parser.on('error', reject)
parser.write(result)
parser.end()
})
}
/**
* Spawn yarn requires a different command on Windows.
*
* @param args
* @param [yarnOptions={}]
* @param [spawnOptions={}]
* @returns
*/
async function spawnYarn(
args: string | string[],
yarnOptions: NpmOptions = {},
spawnOptions?: SpawnOptions,
): Promise<string> {
const cmd = process.platform === 'win32' ? 'yarn.cmd' : 'yarn'
const fullArgs = [
...(yarnOptions.global ? 'global' : []),
...(Array.isArray(args) ? args : [args]),
'--depth=0',
...(yarnOptions.prefix ? `--prefix=${yarnOptions.prefix}` : []),
'--json',
'--no-progress',
]
return spawn(cmd, fullArgs, spawnOptions)
}
/**
* Get platform-specific default prefix to pass on to yarn.
*
* @param options
* @param [options.global]
* @param [options.prefix]
* @returns
*/
export async function defaultPrefix(options: Options): Promise<string> {
if (options.prefix) {
return Promise.resolve(options.prefix)
}
const cmd = process.platform === 'win32' ? 'yarn.cmd' : 'yarn'
const prefix = await spawn(cmd, ['global', 'dir'])
// yarn 2.0 does not support yarn global
// catch error to prevent process from crashing
// https://github.com/raineorshine/npm-check-updates/issues/873
.catch(() => {
/* empty */
})
// FIX: for ncu -g doesn't work on homebrew or windows #146
// https://github.com/raineorshine/npm-check-updates/issues/146
return options.global && prefix && prefix.match('Cellar')
? '/usr/local'
: // Workaround: get prefix on windows for global packages
// Only needed when using npm api directly
process.platform === 'win32' && options.global && !process.env.prefix
? prefix
? prefix.trim()
: `${process.env.LOCALAPPDATA}\\Yarn\\Data\\global`
: null
}
/**
* Fetches the list of all installed packages.
*
* @param [options]
* @param [options.cwd]
* @param [options.global]
* @param [options.prefix]
* @returns
*/
export const list = async (options: Options = {}, spawnOptions?: SpawnOptions): Promise<Index<string | undefined>> => {
const jsonLines: string = await spawnYarn('list', options as Index<string>, {
...(options.cwd ? { cwd: options.cwd } : {}),
...spawnOptions,
})
const json: { dependencies: Index<ParsedDep> } = await parseJsonLines(jsonLines)
const keyValues: Index<string | undefined> = keyValueBy<ParsedDep, string | undefined>(
json.dependencies,
(name, info): { [key: string]: string | undefined } => ({
// unmet peer dependencies have a different structure
[name]: info.version || info.required?.version,
}),
)
return keyValues
}
/** Wraps a GetVersion function and passes the yarn config. */
const withNpmConfigFromYarn =
(getVersion: GetVersion): GetVersion =>
async (packageName, currentVersion, options = {}) =>
getVersion(packageName, currentVersion, options, await npmConfigFromYarn(options))
export const distTag = withNpmConfigFromYarn(npmDistTag)
export const greatest = withNpmConfigFromYarn(npmGreatest)
export const latest = withNpmConfigFromYarn(npmLatest)
export const minor = withNpmConfigFromYarn(npmMinor)
export const newest = withNpmConfigFromYarn(npmNewest)
export const patch = withNpmConfigFromYarn(npmPatch)
export const semver = withNpmConfigFromYarn(npmPatch)
export default spawnYarn