@preventive/deptree 1.0.0-alpha.1 → 1.0.0-alpha.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. package/LICENSE-APACHE +202 -0
  2. package/bin/compare.js +132 -0
  3. package/bin/deptree.js +211 -0
  4. package/bin/npmrc.js +21 -0
  5. package/cargo.d.ts +223 -0
  6. package/cargo.js +6 -0
  7. package/npm.d.ts +325 -0
  8. package/npm.js +7 -0
  9. package/package.json +92 -11
  10. package/pnpm.d.ts +401 -81
  11. package/pnpm.js +4 -9
  12. package/soldeer.d.ts +235 -0
  13. package/soldeer.js +6 -0
  14. package/src/cargo/crate.js +183 -0
  15. package/src/cargo/inputs.js +81 -0
  16. package/src/cargo/members.js +90 -0
  17. package/src/cargo/registry.js +65 -0
  18. package/src/cargo/tree.js +125 -0
  19. package/src/cargo/workspace.js +177 -0
  20. package/src/concurrent.js +32 -0
  21. package/src/error.js +8 -10
  22. package/src/glob.js +55 -0
  23. package/src/hash.js +51 -16
  24. package/src/manifest.js +52 -0
  25. package/src/matcher.js +60 -10
  26. package/src/mount.js +124 -42
  27. package/src/npm/bins.js +54 -0
  28. package/src/npm/compat.js +97 -0
  29. package/src/npm/dev-engines.js +52 -0
  30. package/src/npm/graph.js +68 -0
  31. package/src/npm/inputs.js +75 -0
  32. package/src/npm/manifests.js +130 -0
  33. package/src/npm/package.js +96 -0
  34. package/src/npm/ratio.js +34 -0
  35. package/src/npm/settings.js +67 -0
  36. package/src/npm/tree.js +139 -0
  37. package/src/npm/versions.js +20 -0
  38. package/src/npmrc.js +24 -0
  39. package/src/patch.js +26 -45
  40. package/src/pnpm/bins.js +202 -322
  41. package/src/pnpm/checks.js +8 -35
  42. package/src/pnpm/commands.js +230 -0
  43. package/src/pnpm/filename.js +19 -16
  44. package/src/pnpm/frozen.js +29 -73
  45. package/src/pnpm/gitignore.js +138 -0
  46. package/src/pnpm/glob.js +65 -0
  47. package/src/pnpm/graph.js +26 -34
  48. package/src/pnpm/hoist.js +96 -59
  49. package/src/pnpm/hoisted.js +234 -0
  50. package/src/pnpm/hook.js +26 -31
  51. package/src/pnpm/inputs.js +177 -0
  52. package/src/pnpm/install.js +123 -124
  53. package/src/pnpm/local.js +95 -40
  54. package/src/pnpm/minimatch.js +319 -0
  55. package/src/pnpm/nm-hoist-graph.js +299 -0
  56. package/src/pnpm/nm-hoist.js +149 -0
  57. package/src/pnpm/npm-packlist.js +217 -0
  58. package/src/pnpm/overrides.js +11 -51
  59. package/src/pnpm/package.js +123 -0
  60. package/src/pnpm/packlist.js +176 -81
  61. package/src/pnpm/patches.js +18 -25
  62. package/src/pnpm/projects.js +132 -89
  63. package/src/pnpm/readers.js +122 -77
  64. package/src/pnpm/settings.js +74 -95
  65. package/src/pnpm/tree.js +216 -237
  66. package/src/pnpm/uptodate.js +16 -28
  67. package/src/pnpm/workspace.js +152 -126
  68. package/src/project.js +56 -0
  69. package/src/soldeer/config.js +63 -0
  70. package/src/soldeer/git.js +52 -0
  71. package/src/soldeer/inputs.js +30 -0
  72. package/src/soldeer/tree.js +83 -0
  73. package/src/soldeer/zip.js +121 -0
  74. package/src/tarball.js +123 -131
  75. package/src/yarn1/bins.js +28 -0
  76. package/src/yarn1/compat.js +67 -0
  77. package/src/yarn1/hoist.js +249 -0
  78. package/src/yarn1/inputs.js +83 -0
  79. package/src/yarn1/manifest.js +64 -0
  80. package/src/yarn1/package.js +206 -0
  81. package/src/yarn1/peers.js +51 -0
  82. package/src/yarn1/requests.js +74 -0
  83. package/src/yarn1/resolve.js +289 -0
  84. package/src/yarn1/settings.js +95 -0
  85. package/src/yarn1/tree.js +219 -0
  86. package/yarn1.d.ts +368 -0
  87. package/yarn1.js +7 -0
  88. package/src/pnpm/npmrc.js +0 -31
  89. /package/{LICENSE → LICENSE-MIT} +0 -0
@@ -0,0 +1,74 @@
1
+ // What yarn 1 asks for at the top (install.js's fetchRequestFromCwd).
2
+
3
+ import { clean } from '@preventive/upstream/semver.js'
4
+ import { quote } from '../error.js'
5
+ import { matchesGlob } from '../glob.js'
6
+ import { cleanDependencies, globsOf } from './manifest.js'
7
+ import { kindOf } from './resolve.js'
8
+
9
+ // yarn names the workspace aggregator at random; this stands for it, and
10
+ // sorts where a name starting so sorts.
11
+ export const AGGREGATOR = 'workspace-aggregator-00000000-0000-0000-0000-000000000000'
12
+
13
+ const KINDS = ['dependencies', 'devDependencies', 'optionalDependencies']
14
+
15
+ // In the order yarn's resolveWorkspaces finds them, glob by glob, matches as
16
+ // node-glob sorts them; the lockfile reader has held `manifests` to the globs.
17
+ export function workspacesOf(manifests) {
18
+ const root = manifests.get('.')
19
+ const workspaces = new Map()
20
+ const found = new Set()
21
+ for (const glob of globsOf(root)) {
22
+ const dirs = [...manifests.keys()].filter((dir) => dir !== '.' && !found.has(dir) && matchesGlob(glob, dir))
23
+ dirs.sort((a, b) => `${a}/package.json`.localeCompare(`${b}/package.json`, 'en'))
24
+ for (const dir of dirs) {
25
+ found.add(dir)
26
+ const manifest = manifests.get(dir)
27
+ const version = clean(manifest.version, { loose: true }) || manifest.version
28
+ workspaces.set(manifest.name, { name: manifest.name, dir, version, manifest })
29
+ }
30
+ }
31
+ return workspaces
32
+ }
33
+
34
+ // The virtual manifest yarn makes of the root and the workspaces.
35
+ export function aggregatorOf(root, workspaces) {
36
+ const dependencies = { ...root.dependencies }
37
+ for (const workspace of workspaces.values()) dependencies[workspace.name] = workspace.version
38
+ const manifest = { name: AGGREGATOR, version: '1.0.0', dependencies, devDependencies: { ...root.devDependencies }, optionalDependencies: { ...root.optionalDependencies } }
39
+ return { name: AGGREGATOR, dir: '.', version: '1.0.0', manifest: cleanDependencies(manifest), aggregator: true }
40
+ }
41
+
42
+ // The resolutions as resolution-map.js reads them: to a semver range, or to a
43
+ // source, as kindOf takes one. One to neither a range nor a source, which
44
+ // yarn passes over, the lockfile reader refuses.
45
+ export function rulesOf(root) {
46
+ const rules = Object.entries(root.resolutions ?? {}).map(([path, range]) => {
47
+ const names = path.match(/(?:@[^/]+\/)?[^/]+/gu) ?? [path]
48
+ const name = names.at(-1)
49
+ kindOf(range, `manifests["."].resolutions[${quote(path)}]`)
50
+ return { path, name, glob: names.length === 1 ? `**/${path}` : path, pattern: `${name}@${range}` }
51
+ })
52
+ return [...Map.groupBy(rules, ({ name }) => name).values()].flat()
53
+ }
54
+
55
+ // The top-level requests in yarn's order; `asked`, all but the resolutions'.
56
+ export function topRequests(root, workspaces, rules) {
57
+ const asked = []
58
+ const push = (deps, optional, dev = false) => {
59
+ for (const [name, range] of Object.entries(deps ?? {})) asked.push({ pattern: `${name}@${range}`, optional, dev })
60
+ }
61
+ push(root.dependencies, false)
62
+ push(root.devDependencies, false, true)
63
+ push(root.optionalDependencies, true)
64
+ if (workspaces.size > 0) {
65
+ push({ [AGGREGATOR]: '1.0.0' }, false)
66
+ const implicit = {}
67
+ for (const workspace of workspaces.values()) {
68
+ if (workspace.aggregator || KINDS.some((kind) => Object.hasOwn(root[kind] ?? {}, workspace.name))) continue
69
+ implicit[workspace.name] = workspace.version
70
+ }
71
+ push(implicit, false)
72
+ }
73
+ return { requests: [...rules.map((rule) => ({ pattern: rule.pattern, optional: false })), ...asked], asked }
74
+ }
@@ -0,0 +1,289 @@
1
+ // yarn 1's resolver (package-resolver.js, package-request.js) on a frozen
2
+ // lockfile. Which request makes a reference, and so whose names its requests
3
+ // carry, turns on yarn's order: top-level requests run one after another.
4
+
5
+ import { satisfies, validRange } from '@preventive/upstream/semver.js'
6
+ import { DeptreeError, quote } from '../error.js'
7
+ import { matchesGlob } from '../glob.js'
8
+
9
+ // Beneath a top-level request, all run at once, each taking these microtask
10
+ // turns, by its resolver, before it checks for a package of its version: a
11
+ // tarball URL as many as the registry. A directory is read at the top level
12
+ // alone, where nothing runs beside it; beneath, only one read already is
13
+ // asked for again, which yarn reads once all else has run, and takes the
14
+ // first's package for.
15
+ const TURNS = { registry: 5, workspace: 3, directory: 1 }
16
+
17
+ // yarn's normalizePattern.
18
+ export function splitPattern(pattern) {
19
+ const scoped = pattern.startsWith('@')
20
+ const [name, ...parts] = (scoped ? pattern.slice(1) : pattern).split('@')
21
+ const version = parts.join('@')
22
+ return { name: scoped ? `@${name}` : name, range: parts.length === 0 ? 'latest' : version || '*', hasVersion: version !== '' }
23
+ }
24
+
25
+ // yarn's normalizeRange: any range but a semver range or one with a `:`,
26
+ // such as an `npm:` alias, is a tag. Of the sources getExoticResolver takes,
27
+ // in its order, a tarball first, where a path ends in .tgz: the registry's
28
+ // own tarball by its URL, on npm's registry or yarn's mirror; and a
29
+ // directory, by `file:` or a path.
30
+ const TAG = /^[\w~-][\w.~-]*$/u
31
+ const TARBALL = /^https?:\/\/|^[^@]*\.(?:tgz|tar\.gz)$/u
32
+ const REGISTRY_TARBALL = /^https:\/\/registry\.(?:npmjs\.org|yarnpkg\.com)\/[^#?]+\.tgz$/u
33
+ const DIRECTORY = /^(?:file:|\.{1,2}\/|\/)/u
34
+ export function kindOf(range, where) {
35
+ if (validRange(range)) return 'range'
36
+ if (range.startsWith('npm:')) return 'alias'
37
+ if (TARBALL.test(range)) {
38
+ if (REGISTRY_TARBALL.test(range)) return 'tarball'
39
+ } else if (DIRECTORY.test(range)) return 'directory'
40
+ else if (TAG.test(range)) return 'tag'
41
+ throw new DeptreeError('only a semver range, an npm: alias, a tag, a file: directory or the registry\'s own tarball URL is supported', where)
42
+ }
43
+
44
+ // The directory a `file:` range names, as yarn resolves it from the
45
+ // lockfile's: one within the project, which it is read from.
46
+ function directoryOf(range, where) {
47
+ const path = range.replace(/^file:/u, '')
48
+ const segments = []
49
+ for (const segment of path.split('/')) {
50
+ if (segment === '..') {
51
+ if (segments.pop() === undefined) throw new DeptreeError(`${quote(path)} is outside the project, which is not supported`, where)
52
+ } else if (segment !== '' && segment !== '.') segments.push(segment)
53
+ }
54
+ if (path.startsWith('/')) throw new DeptreeError(`${quote(path)} is an absolute path, which is not supported`, where)
55
+ if (segments.length === 0) throw new DeptreeError('the project\'s own directory is not supported', where)
56
+ return segments.join('/')
57
+ }
58
+
59
+ // What a package asks for, in yarn's order. A lockfile entry's are patterns;
60
+ // one the lockfile reader links to a workspace has lost its range.
61
+ function asked(info, where) {
62
+ const workspace = info.kind === 'workspace'
63
+ const lists = workspace ? info.workspace.manifest : info.entry
64
+ const kinds = [['dependencies', false, false], ['optionalDependencies', true, false], ...workspace ? [['devDependencies', false, true]] : []]
65
+ return kinds.flatMap(([kind, optional, dev]) => Object.entries(lists[kind] ?? {}).map(([name, value]) => {
66
+ if (!workspace && value.startsWith('link:')) throw new DeptreeError(`its dependency on ${quote(name)} is a workspace, which is not supported`, where)
67
+ return { pattern: workspace ? `${name}@${value}` : value, optional, dev }
68
+ }))
69
+ }
70
+
71
+ // Where yarn's cache keeps a package (generateModuleCachePath), which is
72
+ // what its hoister tells two references apart by: two of one package, as
73
+ // a tag or an alias asked for twice makes, are one there.
74
+ function locOf({ kind, name, version, entry, dir }) {
75
+ if (kind === 'workspace') return `workspace\n${name}`
76
+ if (kind === 'directory') return `copy\n${dir}`
77
+ const { uid } = entry
78
+ const { sha1, integrity } = entry.resolution ?? {}
79
+ return `npm\n${name}\n${version}\n${uid !== undefined && uid !== version ? uid : sha1 ?? ''}\n${integrity ? 'integrity' : ''}`
80
+ }
81
+
82
+ class Resolver {
83
+ constructor({ lockfile, workspaces, rules, isDirectory }) {
84
+ Object.assign(this, { lockfile, workspaces, rules, isDirectory })
85
+ this.patterns = new Map()
86
+ this.byName = new Map()
87
+ this.delayed = []
88
+ this.late = []
89
+ this.diverted = []
90
+ }
91
+
92
+ addPattern(pattern, ref) {
93
+ ref.patterns.push(pattern)
94
+ this.patterns.set(pattern, ref)
95
+ if (!this.byName.has(ref.name)) this.byName.set(ref.name, [])
96
+ const list = this.byName.get(ref.name)
97
+ if (!list.includes(pattern)) list.push(pattern)
98
+ }
99
+
100
+ // isLockfileEntryOutdated: yarn resolves anew an entry out of its pattern's
101
+ // range, which --frozen-lockfile fails on only at the top level.
102
+ infoOf(request) {
103
+ const { name, range, hasVersion } = splitPattern(request.pattern)
104
+ const workspace = this.workspaces.get(name)
105
+ if (workspace !== undefined && satisfies(workspace.version, range, { loose: true })) return { kind: 'workspace', name: workspace.name, version: workspace.version, workspace }
106
+ const where = quote(request.pattern)
107
+ const kind = kindOf(range, where)
108
+ const entry = this.lockfile.packages[request.pattern]
109
+ if (entry === undefined) throw new DeptreeError('yarn would resolve this pattern anew: the lockfile has no entry for it', where)
110
+ if (hasVersion && validRange(range) && !satisfies(entry.version, range)) {
111
+ throw new DeptreeError(`yarn would resolve this pattern anew: the lockfile has ${entry.version}, which the range does not take`, where)
112
+ }
113
+ if (kind !== 'directory') return { kind: 'registry', name, version: entry.version, entry, tag: kind === 'tag' }
114
+ const dir = directoryOf(range, where)
115
+ if (request.parentNames !== undefined && this.copyOf(name, dir) === undefined) {
116
+ throw new DeptreeError('a file: directory asked for beneath the top level, and not by the root or a resolution first, is not supported', where)
117
+ }
118
+ return { kind, name, version: entry.version, entry, dir }
119
+ }
120
+
121
+ // exoticRangeMatch: the package of `name` copied from `dir` already.
122
+ copyOf(name, dir) {
123
+ return this.byName.get(name)?.map((pattern) => this.patterns.get(pattern)).find((ref) => ref.kind === 'directory' && ref.dir === dir)
124
+ }
125
+
126
+ // No resolution applies to a top-level request.
127
+ ruleOf({ pattern, parentNames }) {
128
+ if (parentNames === undefined) return undefined
129
+ const { name } = splitPattern(pattern)
130
+ const path = [...parentNames, name].join('/')
131
+ return this.rules.find((rule) => rule.name === name && matchesGlob(rule.glob, path))
132
+ }
133
+
134
+ // The package a request of `name` and `range` finds resolved already.
135
+ resolvedOf(name, range, info) {
136
+ return info.kind === 'directory' ? this.copyOf(name, info.dir) : this.exactMatch(name, validRange(range) ? info.version : range)
137
+ }
138
+
139
+ exactMatch(name, version) {
140
+ return this.byName.get(name)?.map((pattern) => this.patterns.get(pattern)).find((ref) => ref.version === version)
141
+ }
142
+
143
+ // Waits where a package of its name and version is resolved already; else
144
+ // makes the reference and hands back its own requests. A tag or an alias
145
+ // never finds one, so each request of one makes a reference of its own,
146
+ // the last of which its pattern names.
147
+ check(request, info) {
148
+ const { name, range } = splitPattern(request.pattern)
149
+ if (this.resolvedOf(name, range, info) !== undefined) {
150
+ this.delayed.push(request)
151
+ return []
152
+ }
153
+ const ref = {
154
+ name: info.name,
155
+ version: info.version,
156
+ loc: locOf(info),
157
+ kind: info.kind,
158
+ entry: info.entry,
159
+ workspace: info.workspace,
160
+ dir: info.dir,
161
+ patterns: [],
162
+ requests: [request],
163
+ asked: asked(info, quote(request.pattern)),
164
+ optional: request.optional,
165
+ }
166
+ this.addPattern(request.pattern, ref)
167
+ const parentNames = [...request.parentNames ?? [], name]
168
+ return ref.asked.map((dep) => ({ pattern: dep.pattern, parentNames, optional: dep.optional || (!dep.dev && request.optional) }))
169
+ }
170
+
171
+ divert(request, rule) {
172
+ const target = this.patterns.get(rule.pattern)
173
+ if (target === undefined) throw new DeptreeError(`the resolution ${quote(rule.path)} applies to it, and yarn never resolves ${quote(rule.pattern)}`, quote(request.pattern))
174
+ this.addPattern(request.pattern, target)
175
+ }
176
+
177
+ // Given the resolution's package where one applies, or else timed for its
178
+ // check; a tag's request waits, never counting down, for answer().
179
+ start(request) {
180
+ const rule = this.ruleOf(request)
181
+ if (rule !== undefined) {
182
+ if (this.patterns.has(rule.pattern)) this.divert(request, rule)
183
+ else this.diverted.push([request, rule])
184
+ return undefined
185
+ }
186
+ const info = this.infoOf(request)
187
+ if (info.kind === 'directory' && request.parentNames !== undefined) {
188
+ this.late.push(request)
189
+ return undefined
190
+ }
191
+ return { request, info, left: info.tag ? Infinity : TURNS[info.kind] }
192
+ }
193
+
194
+ // The names a request would add a package or a pattern under, through all
195
+ // it would resolve that is not resolved already; undefined where a
196
+ // resolution or a directory may come in, or something is refused.
197
+ namesOf(request) {
198
+ const names = new Set()
199
+ const seen = new Set()
200
+ const queue = [request]
201
+ try {
202
+ while (queue.length > 0) {
203
+ const next = queue.pop()
204
+ if (seen.has(next.pattern)) continue
205
+ seen.add(next.pattern)
206
+ const { name, range } = splitPattern(next.pattern)
207
+ if (this.rules.some((rule) => rule.name === name)) return undefined
208
+ const info = this.infoOf(next)
209
+ const deps = asked(info, quote(next.pattern))
210
+ if (info.kind === 'directory') return undefined
211
+ names.add(name).add(info.name)
212
+ if (this.resolvedOf(name, range, info) === undefined) queue.push(...deps)
213
+ }
214
+ } catch (error) {
215
+ if (error instanceof DeptreeError) return undefined
216
+ throw error
217
+ }
218
+ return names
219
+ }
220
+
221
+ // A tag waits on the filesystem, and each it answers resolves all beneath
222
+ // it before the next: in an order not set, which changes nothing where no
223
+ // two would add under one name, and no resolution or directory comes in.
224
+ apart(waiting) {
225
+ if (this.late.length > 0) return false
226
+ const taken = new Set()
227
+ for (const { request } of waiting) {
228
+ const names = this.namesOf(request)
229
+ if (names === undefined || !names.isDisjointFrom(taken)) return false
230
+ for (const name of names) taken.add(name)
231
+ }
232
+ return true
233
+ }
234
+
235
+ // Where none is a directory of the project, the first goes on.
236
+ answer(waiting) {
237
+ const reading = [...waiting.map(({ request }) => request), ...this.late]
238
+ if (reading.length > 1 && !this.apart(waiting)) throw new DeptreeError(`yarn resolves these in the order the filesystem answers it, which is not set: ${reading.map(({ pattern }) => quote(pattern)).join(', ')}`)
239
+ for (const { request } of waiting) {
240
+ const where = quote(request.pattern)
241
+ const { range } = splitPattern(request.pattern)
242
+ const found = this.isDirectory(range)
243
+ if (found === undefined) throw new DeptreeError(`yarn installs the directory ${quote(range)} for it where the project has one, which is known only with the project read`, where)
244
+ if (found) throw new DeptreeError(`yarn installs the directory ${quote(range)} for it, which is not supported`, where)
245
+ }
246
+ waiting[0].left = 1
247
+ return waiting
248
+ }
249
+
250
+ // A microtask turn: the requests a check makes start where it stood.
251
+ turn(strands) {
252
+ const next = []
253
+ for (const strand of strands) {
254
+ if (--strand.left > 0) next.push(strand)
255
+ else next.push(...this.check(strand.request, strand.info).map((child) => this.start(child)).filter(Boolean))
256
+ }
257
+ return next
258
+ }
259
+
260
+ run(request) {
261
+ let strands = [this.start(request)].filter(Boolean)
262
+ while (strands.length > 0) {
263
+ if (strands.every((strand) => strand.left === Infinity)) strands = this.answer(strands)
264
+ strands = this.turn(strands)
265
+ }
266
+ this.delayed.push(...this.late)
267
+ this.late = []
268
+ }
269
+
270
+ // yarn's resolveToExistingVersion for the delayed, then the diverted.
271
+ settle() {
272
+ for (const request of this.delayed) {
273
+ const { name } = splitPattern(request.pattern)
274
+ const info = this.infoOf(request)
275
+ const ref = info.kind === 'directory' ? this.copyOf(name, info.dir) : this.exactMatch(name, info.version)
276
+ ref.requests.push(request)
277
+ this.addPattern(request.pattern, ref)
278
+ if (!request.optional) ref.optional = false
279
+ }
280
+ for (const [request, rule] of this.diverted) this.divert(request, rule)
281
+ }
282
+ }
283
+
284
+ export function resolve({ top, ...options }) {
285
+ const resolver = new Resolver(options)
286
+ for (const request of top) resolver.run(request)
287
+ resolver.settle()
288
+ return { patterns: resolver.patterns, byName: resolver.byName }
289
+ }
@@ -0,0 +1,95 @@
1
+ // The project's .yarnrc and .npmrc, as far as yarn 1 reads them for an
2
+ // install, the .yarnrc's options over the .npmrc's. ignore-platform is
3
+ // followed only as a flag, as yarn reads the option and does not act on it.
4
+ // Options that change the tree are refused; the rest are for where and how
5
+ // yarn fetches, and the tree is held to the lockfile's integrities. A `--`
6
+ // line of .yarnrc is a flag yarn adds to its command line.
7
+
8
+ import { DeptreeError, quote } from '../error.js'
9
+ import { parseNpmrc } from '../npmrc.js'
10
+
11
+ // yarn 1.22's flags that do not change the tree.
12
+ const PASSED = new Set([
13
+ 'verbose', 'silent', 'json', 'har', 'emoji', 'no-emoji', 'progress', 'no-progress', 'non-interactive', 'no-node-version-check',
14
+ 'offline', 'prefer-offline', 'registry', 'proxy', 'https-proxy', 'network-concurrency', 'network-timeout', 'otp', 'mutex',
15
+ 'cache-folder', 'preferred-cache-folder', 'ignore-scripts', 'scripts-prepend-node-path', 'force', 'skip-integrity-check',
16
+ 'check-files', 'pure-lockfile', 'frozen-lockfile', 'audit', 'disable-pnp',
17
+ ])
18
+
19
+ // Of the options yarn 1.22 reads by config.getOption, those that change the
20
+ // tree, and yarn-path, which runs another yarn. global-folder may be the
21
+ // project's directory, where yarn reads no package.json with validate(),
22
+ // which drops a name listed twice from all but one of its lists.
23
+ const REFUSED = new Set([
24
+ 'ignore-optional', 'production', 'bin-links', 'workspaces-experimental', 'workspaces-nohoist-experimental', 'plugnplay-override',
25
+ 'yarn-link-file-dependencies', 'enable-meta-folder', 'experimental-pack-script-packages-in-mirror', 'global-folder', 'yarn-path',
26
+ 'yarnPath',
27
+ ])
28
+
29
+ const FOLLOWED = new Set(['ignore-engines', 'ignore-platform'])
30
+
31
+ function flagOf(key) {
32
+ const match = /^--(?:(.*?)\.)?(.*)$/u.exec(key)
33
+ return match === null ? undefined : { command: match[1] ?? '*', name: match[2] }
34
+ }
35
+
36
+ function check(key, where) {
37
+ const flag = flagOf(key)
38
+ if (flag === undefined ? REFUSED.has(key) : !PASSED.has(flag.name)) throw new DeptreeError(`${quote(key)} is a setting not supported here: it may change what yarn installs`, where)
39
+ }
40
+
41
+ // .yarnrc as yarn's parser reads it, as far as a key and a value per line
42
+ // go, each bare or quoted as JSON writes it. The last line of a key wins; a
43
+ // bare value but true or false, or none, is undefined.
44
+ const TOKEN = /"(?:[^"\\]|\\.)*"|[^\s"]+/gu
45
+
46
+ function unquote(token, what, where) {
47
+ try {
48
+ return JSON.parse(token)
49
+ } catch {
50
+ throw new DeptreeError(`${what} is not a string as JSON writes it`, where)
51
+ }
52
+ }
53
+
54
+ const BARE = new Map([['true', true], ['false', false]])
55
+
56
+ function readYarnrc(text) {
57
+ const settings = new Map()
58
+ for (const [index, raw] of text.split(/\r?\n/u).entries()) {
59
+ const where = `.yarnrc:${index + 1}`
60
+ const line = raw.trim()
61
+ if (line === '' || line.startsWith('#')) continue
62
+ if (/^\s/u.test(raw)) throw new DeptreeError('an indented line, which yarn reads into the setting above it, is not supported', where)
63
+ const tokens = line.match(TOKEN) ?? []
64
+ if (tokens.join(' ') !== line.replace(/\s+/gu, ' ') || tokens.length > 2) throw new DeptreeError('expected a setting and its value', where)
65
+ const [key, value] = tokens.map((token) => (token.startsWith('"') ? unquote(token, 'a setting', where) : token))
66
+ settings.set(key, { value: tokens[1]?.startsWith('"') === false ? BARE.get(value) : value, where })
67
+ }
68
+ return settings
69
+ }
70
+
71
+ export function readSettings({ yarnrc, npmrc }) {
72
+ const flags = new Set()
73
+ let option
74
+ for (const [key, setting] of yarnrc === undefined ? [] : readYarnrc(yarnrc)) {
75
+ const flag = flagOf(key)
76
+ const name = flag?.name ?? key
77
+ if (!FOLLOWED.has(name)) check(key, setting.where)
78
+ else if (flag === undefined) {
79
+ // yarn reads the option as truthy or not, a quoted "false" as true.
80
+ if (setting.value === undefined) throw new DeptreeError(`expected true, false or a quoted string for ${quote(key)}`, setting.where)
81
+ if (name === 'ignore-engines') option = Boolean(setting.value)
82
+ } else {
83
+ if (typeof setting.value !== 'boolean') throw new DeptreeError(`expected true or false for ${quote(key)}`, setting.where)
84
+ if (setting.value && (flag.command === '*' || flag.command === 'install')) flags.add(name)
85
+ }
86
+ }
87
+ let npmOption
88
+ for (const { key, value, list, line } of npmrc === undefined ? [] : parseNpmrc(npmrc)) {
89
+ const where = `.npmrc:${line}`
90
+ if (!FOLLOWED.has(key)) check(key, where)
91
+ else if (list || (value !== 'true' && value !== 'false')) throw new DeptreeError(`expected true or false for ${quote(key)}`, where)
92
+ else if (key === 'ignore-engines') npmOption = value === 'true'
93
+ }
94
+ return { ignoreEngines: flags.has('ignore-engines') || (option ?? npmOption ?? false), ignorePlatform: flags.has('ignore-platform') }
95
+ }