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

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 +321 -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 +57 -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,249 @@
1
+ // yarn 1's PackageHoister (package-hoister.js), quirks and all: a prepass
2
+ // seeds at the top, of several versions of a package, the one most others
3
+ // depend on, and a level's requests go by pattern, then those with peers,
4
+ // which a check meant to put them after their peers always puts last.
5
+ // Departs from yarn only in leaving out nohoist, --focus and --flat, refused
6
+ // before it runs, and yarn's record of each step; in comparing `loc` where
7
+ // yarn compares cache paths, and references where it compares manifests;
8
+ // and in reachedBut, its own.
9
+
10
+ import { DeptreeError, quote } from '../error.js'
11
+
12
+ // yarn's prepass recurses down every chain of dependencies, as this one
13
+ // does, keeping each one's ancestry: a chain deeper than this is refused
14
+ // before it runs out of stack, or of memory.
15
+ const DEEPEST = 1000
16
+
17
+ const sortAlpha = (a, b) => (a < b ? -1 : a > b ? 1 : 0)
18
+
19
+ const implode = (parts) => parts.join('#')
20
+
21
+ export class Hoister {
22
+ constructor(patterns, peersOf) {
23
+ this.patterns = patterns
24
+ this.peersOf = peersOf
25
+ this.tainted = new Map()
26
+ this.levelQueue = []
27
+ this.tree = new Map()
28
+ }
29
+
30
+ resolved(pattern) {
31
+ const ref = this.patterns.get(pattern)
32
+ if (ref === undefined) throw new Error(`no package for ${pattern}`)
33
+ return ref
34
+ }
35
+
36
+ // A key reserved for a package, unless it is for another already.
37
+ taintKey(key, info) {
38
+ const existing = this.tainted.get(key)
39
+ if (!existing || existing.ref.loc === info.ref.loc) this.tainted.set(key, info)
40
+ }
41
+
42
+ // resolver.dedupePatterns: the first pattern of each package.
43
+ dedupe(patterns) {
44
+ return [...Map.groupBy(patterns, (pattern) => this.resolved(pattern)).values()].map(([first]) => first)
45
+ }
46
+
47
+ seed(patterns) {
48
+ this.prepass(patterns)
49
+ for (const pattern of this.dedupe(patterns)) this.seedOne(pattern, { isDirectRequire: true })
50
+ while (this.levelQueue.length > 0) {
51
+ let queue = this.levelQueue.sort(([a], [b]) => sortAlpha(a, b))
52
+ this.levelQueue = []
53
+ const sorted = []
54
+ const available = new Set()
55
+ let changed = true
56
+ while (queue.length > 0 && changed) {
57
+ changed = false
58
+ const copy = queue
59
+ queue = []
60
+ for (const item of copy) {
61
+ const [pattern] = item
62
+ if (this.peersOf(this.resolved(pattern)).every((peer) => available.has(peer))) {
63
+ sorted.push(item)
64
+ available.add(pattern)
65
+ changed = true
66
+ } else queue.push(item)
67
+ }
68
+ }
69
+ for (const [pattern, parent] of sorted.concat(queue)) {
70
+ const info = this.seedOne(pattern, { isDirectRequire: false, parent })
71
+ if (info) this.hoist(info)
72
+ }
73
+ }
74
+ this.propagateRequired()
75
+ }
76
+
77
+ seedOne(pattern, { isDirectRequire, parent }) {
78
+ const ref = this.resolved(pattern)
79
+ if (parent && !this.tree.get(parent.key)) return null
80
+ const isIncompatible = ref.incompatible === true
81
+ const isRequired = !isIncompatible && (isDirectRequire || parent?.isRequired === true)
82
+ const parts = (parent?.parts ?? []).concat(ref.name)
83
+ const key = implode(parts)
84
+ const info = { key, parts, ref, isDirectRequire, isRequired, isIncompatible }
85
+ this.tree.set(key, info)
86
+ this.taintKey(key, info)
87
+ for (const dependency of new Set(ref.dependencies)) this.levelQueue.push([dependency, info])
88
+ return info
89
+ }
90
+
91
+ propagateRequired() {
92
+ const toVisit = [...this.tree.values()].filter((info) => info.isRequired)
93
+ // In yarn's order, but by index, as shift() copies a long array.
94
+ for (let i = 0; i < toVisit.length; i++) {
95
+ const info = toVisit[i]
96
+ for (const dependency of info.ref.dependencies) {
97
+ const found = this.lookupDependency(info, dependency)
98
+ if (found && !found.isRequired && !found.isIncompatible) {
99
+ found.isRequired = true
100
+ toVisit.push(found)
101
+ }
102
+ }
103
+ }
104
+ }
105
+
106
+ // Not yarn's: the places reached from `asked`, peers included, by requests
107
+ // whose `kind` (`dev` or `optional`) is not set, past none the host cannot
108
+ // run; every other place is reached by dev, or optional, dependencies alone.
109
+ reachedBut(kind, asked) {
110
+ const queue = [{ parts: [], ref: { asked } }]
111
+ const reached = new Set()
112
+ while (queue.length > 0) {
113
+ const info = queue.pop()
114
+ for (const dep of info.ref.asked) {
115
+ if (dep[kind]) continue
116
+ const found = this.lookupDependency(info, dep.pattern)
117
+ if (found === null || found.isIncompatible || reached.has(found)) continue
118
+ reached.add(found)
119
+ queue.push(found)
120
+ }
121
+ }
122
+ return reached
123
+ }
124
+
125
+ lookupDependency(info, pattern) {
126
+ const ref = this.resolved(pattern)
127
+ for (let i = info.parts.length; i >= 0; i--) {
128
+ const existing = this.tree.get(implode(info.parts.slice(0, i).concat(ref.name)))
129
+ if (existing) return existing
130
+ }
131
+ return null
132
+ }
133
+
134
+ newParts(key, info, parts) {
135
+ let stepUp = false
136
+ const stack = []
137
+ const name = parts.pop()
138
+ for (let i = parts.length - 1; i >= 0; i--) {
139
+ const checkParts = parts.slice(0, i).concat(name)
140
+ const existing = this.tree.get(implode(checkParts))
141
+ if (existing) {
142
+ if (existing.ref.loc === info.ref.loc) {
143
+ if (!existing.isRequired && info.isRequired) existing.isRequired = true
144
+ return { parts: checkParts, duplicate: true }
145
+ }
146
+ break
147
+ }
148
+ const taint = this.tainted.get(implode(checkParts))
149
+ if (taint && taint.ref.loc !== info.ref.loc) break
150
+ }
151
+ const peers = this.peersOf(info.ref)
152
+ while (parts.length > 0 && !peers.some((peer) => this.tree.get(implode(parts.concat(peer))))) {
153
+ const checkKey = implode(parts.concat(name))
154
+ if (this.tree.get(checkKey) || (key !== checkKey && this.tainted.has(checkKey))) {
155
+ stepUp = true
156
+ break
157
+ }
158
+ stack.push(parts.pop())
159
+ }
160
+ parts.push(name)
161
+ const isValidPosition = (candidate) => {
162
+ const candidateKey = implode(candidate)
163
+ if (this.tree.get(candidateKey)?.ref.loc === info.ref.loc) return true
164
+ const taint = this.tainted.get(candidateKey)
165
+ return !taint || taint.ref.loc === info.ref.loc
166
+ }
167
+ if (!isValidPosition(parts)) stepUp = true
168
+ while (stepUp && stack.length > 0) {
169
+ parts.pop()
170
+ parts.push(stack.pop(), name)
171
+ if (isValidPosition(parts)) stepUp = false
172
+ }
173
+ return { parts, duplicate: false }
174
+ }
175
+
176
+ hoist(info) {
177
+ const { key: oldKey, parts: rawParts } = info
178
+ this.tree.delete(oldKey)
179
+ const { parts, duplicate } = this.newParts(oldKey, info, rawParts.slice())
180
+ const newKey = implode(parts)
181
+ // yarn's declareRename: each key it passed over reserved for it.
182
+ if (duplicate || newKey !== oldKey) {
183
+ for (let i = parts.length - 1; i < rawParts.length - 1; i++) this.taintKey(implode(rawParts.slice(0, i).concat(info.ref.name)), info)
184
+ }
185
+ if (duplicate) return
186
+ info.key = newKey
187
+ info.parts = parts
188
+ this.tree.set(newKey, info)
189
+ }
190
+
191
+ prepass(rawPatterns) {
192
+ const patterns = this.dedupe(rawPatterns).sort()
193
+ const visited = new Map()
194
+ const occurrences = Object.create(null)
195
+ const visitAdd = (ref, ancestry, pattern) => {
196
+ const versions = (occurrences[ref.name] ??= Object.create(null))
197
+ const version = (versions[ref.version] ??= { occurrences: new Set(), pattern })
198
+ if (ancestry.length > 0) version.occurrences.add(ancestry.at(-1))
199
+ }
200
+ const add = (pattern, ancestry, ancestryPatterns) => {
201
+ const ref = this.resolved(pattern)
202
+ if (ancestry.includes(ref)) return
203
+ if (ancestry.length === DEEPEST) throw new DeptreeError(`a chain of more than ${DEEPEST} dependencies is not supported`, quote(pattern))
204
+ let visitedPattern = visited.get(pattern)
205
+ if (visitedPattern) {
206
+ for (const visit of visitedPattern) visitAdd(visit.ref, visit.ancestry, visit.pattern)
207
+ visitAdd(ref, ancestry, pattern)
208
+ return
209
+ }
210
+ visitAdd(ref, ancestry, pattern)
211
+ for (const dependency of ref.dependencies) add(dependency, ancestry.concat(ref), ancestryPatterns.concat(dependency))
212
+ visitedPattern = visited.get(pattern) ?? []
213
+ visited.set(pattern, visitedPattern)
214
+ visitedPattern.push({ ref, ancestry, pattern })
215
+ for (const ancestryPattern of ancestryPatterns) visited.get(ancestryPattern)?.push({ ref, ancestry, pattern })
216
+ }
217
+ const rootNames = new Set()
218
+ for (const pattern of patterns) {
219
+ rootNames.add(this.resolved(pattern).name)
220
+ add(pattern, [], [])
221
+ }
222
+ for (const name of Object.keys(occurrences).sort()) {
223
+ const versions = occurrences[name]
224
+ if (Object.keys(versions).length === 1 || this.tree.get(name) || rootNames.has(name)) continue
225
+ let mostCount
226
+ let mostPattern
227
+ for (const version of Object.keys(versions).sort()) {
228
+ const { occurrences: occurred, pattern } = versions[version]
229
+ if (!mostCount || occurred.size > mostCount) {
230
+ mostCount = occurred.size
231
+ mostPattern = pattern
232
+ }
233
+ }
234
+ if (mostCount > 1) this.seedOne(mostPattern, { isDirectRequire: false })
235
+ }
236
+ }
237
+
238
+ // As in yarn, leaves out `aggregator` and what stayed directly beneath it.
239
+ flatten(aggregator) {
240
+ const flat = []
241
+ for (const [key, info] of this.tree) {
242
+ if (!info.isRequired) continue
243
+ const names = key.split('#')
244
+ if (aggregator !== undefined && names[0] === aggregator && names.length <= 2) continue
245
+ flat.push({ names, info })
246
+ }
247
+ return flat
248
+ }
249
+ }
@@ -0,0 +1,83 @@
1
+ // What buildYarn1Tree takes, as text or read from the project as yarn does.
2
+
3
+ import { valid } from '@preventive/upstream/semver.js'
4
+ import { DeptreeError, quote } from '../error.js'
5
+ import { readManifest, readManifests } from '../manifest.js'
6
+ import { checkHostKeys, checkLeftOut, checkProject, checkTexts, readText, typeOf } from '../project.js'
7
+ import { walkWorkspaces } from '../glob.js'
8
+ import { globsOf } from './manifest.js'
9
+ import { readSettings } from './settings.js'
10
+
11
+ function yarnOf(yarn, root) {
12
+ if (yarn !== undefined && (typeof yarn !== 'string' || yarn === '')) throw new TypeError('host.yarn must be a non-empty string, or left out')
13
+ const { packageManager } = root
14
+ let pinned
15
+ if (packageManager !== undefined) {
16
+ const match = typeof packageManager === 'string' ? /^([^@]+)@([^+]+)(?:\+.*)?$/u.exec(packageManager) : null
17
+ if (match === null || match[1] !== 'yarn' || valid(match[2]) !== match[2]) throw new DeptreeError(`${quote(String(packageManager))} is not yarn at an exact version, which corepack would run instead`, 'manifests["."].packageManager')
18
+ pinned = match[2]
19
+ }
20
+ const version = yarn ?? pinned
21
+ if (version === undefined) throw new TypeError('host.yarn must be given where the root package.json\'s packageManager pins no yarn')
22
+ if (pinned !== undefined && pinned !== version) throw new DeptreeError(`the project is installed by yarn ${pinned}, which corepack runs, not ${version}`, 'manifests["."].packageManager')
23
+ if (!/^1\.22\.\d+$/u.test(version) || valid(version) !== version) throw new DeptreeError(`yarn ${quote(version)} is not supported: only yarn 1.22.x is`, 'host.yarn')
24
+ return version
25
+ }
26
+
27
+ export function checkHost(host, root) {
28
+ checkHostKeys(host, ['node', 'os', 'cpu'], 'node, os and cpu, and yarn where it is not pinned')
29
+ if (valid(host.node) !== host.node) throw new DeptreeError(`${quote(host.node)} is not an exact version`, 'host.node')
30
+ if (host.os === 'win32') throw new DeptreeError('Windows is not supported: yarn links bins there with shims, and workspaces with junctions', 'host.os')
31
+ return { yarn: yarnOf(host.yarn, root), node: host.node, os: host.os, cpu: host.cpu }
32
+ }
33
+
34
+ const yarnJson = 'a yarn.json, which yarn reads as a manifest too, is not supported'
35
+
36
+ // As yarn's resolveWorkspaces finds them.
37
+ function findWorkspaces(project, globs) {
38
+ return walkWorkspaces(project, globs, {
39
+ manager: 'yarn',
40
+ enter: (path, name, taken, manifest) => {
41
+ if (name === 'node_modules' && manifest) throw new DeptreeError('yarn would read this node_modules as a workspace, which is not supported', quote(path))
42
+ if (name !== 'node_modules' && taken && typeOf(project, `/${path}/yarn.json`) !== undefined) throw new DeptreeError(yarnJson, quote(`${path}/yarn.json`))
43
+ return name !== 'node_modules'
44
+ },
45
+ })
46
+ }
47
+
48
+ function readRoot(project) {
49
+ const text = readText(project, '/package.json', 'manifests["."]')
50
+ if (text === undefined) throw new DeptreeError('the project has no package.json at its root', 'manifests["."]')
51
+ if (typeOf(project, '/yarn.json') !== undefined) throw new DeptreeError(yarnJson, 'yarn.json')
52
+ return readManifest(text, 'manifests["."]')
53
+ }
54
+
55
+ export function findYarn1Workspaces(options) {
56
+ const { project } = options ?? {}
57
+ checkProject(project)
58
+ return ['.', ...findWorkspaces(project, globsOf(readRoot(project)))]
59
+ }
60
+
61
+ const LOCKFILE = 'lockfile must be the text of yarn.lock, or left out with a project given to read it from'
62
+
63
+ export function inputsOf(options) {
64
+ const { lockfile, manifests, yarnrc, npmrc, project } = options
65
+ if (project !== undefined) checkProject(project)
66
+ if (lockfile === undefined) {
67
+ if (project === undefined) throw new TypeError(LOCKFILE)
68
+ checkLeftOut({ manifests, yarnrc, npmrc })
69
+ const text = readText(project, '/yarn.lock')
70
+ if (text === undefined) throw new DeptreeError('the project has no yarn.lock, which a frozen install cannot do without')
71
+ const read = new Map([['.', readRoot(project)]])
72
+ for (const dir of findWorkspaces(project, globsOf(read.get('.')))) {
73
+ read.set(dir, readManifest(readText(project, `/${dir}/package.json`, `manifests[${quote(dir)}]`), `manifests[${quote(dir)}]`))
74
+ }
75
+ if (typeOf(project, '/.yarnrc.yml') !== undefined) throw new DeptreeError('a .yarnrc.yml, whose yarnPath yarn 1.22 runs in its stead, is not supported', '.yarnrc.yml')
76
+ return { lockfile: text, manifests: read, settings: readSettings({ yarnrc: readText(project, '/.yarnrc'), npmrc: readText(project, '/.npmrc') }), project }
77
+ }
78
+ if (typeof lockfile !== 'string') throw new TypeError(LOCKFILE)
79
+ if (manifests === null || typeof manifests !== 'object') throw new TypeError('manifests must map each project\'s directory to its package.json')
80
+ checkTexts({ yarnrc, npmrc })
81
+ const settings = readSettings({ yarnrc, npmrc })
82
+ return { lockfile, manifests: readManifests(manifests), settings, project }
83
+ }
@@ -0,0 +1,64 @@
1
+ // A package.json as yarn 1's util/normalize-manifest reads it.
2
+
3
+ import { DeptreeError, quote } from '../error.js'
4
+
5
+ // yarn's cleanDependencies: a name in several of these lists is kept in the
6
+ // first, at its first range that is neither '' nor '*'.
7
+ export function cleanDependencies(manifest) {
8
+ const kinds = ['optionalDependencies', 'dependencies', 'devDependencies'].filter((kind) => manifest[kind] !== null && typeof manifest[kind] === 'object')
9
+ const ranges = new Map()
10
+ for (const kind of kinds) {
11
+ for (const [name, range] of Object.entries(manifest[kind])) if (!ranges.has(name) && range && range !== '*') ranges.set(name, range)
12
+ }
13
+ const seen = new Set()
14
+ for (const kind of kinds) {
15
+ const list = manifest[kind]
16
+ for (const name of Object.keys(list)) {
17
+ if (seen.has(name)) delete list[name]
18
+ else {
19
+ list[name] = ranges.get(name) ?? list[name]
20
+ seen.add(name)
21
+ }
22
+ }
23
+ }
24
+ return manifest
25
+ }
26
+
27
+ // The lists as normalize-manifest leaves them, a `//` key, a comment, dropped.
28
+ const LISTS = ['resolutions', 'devDependencies', 'dependencies', 'optionalDependencies', 'peerDependencies']
29
+ export function fixLists(manifest) {
30
+ const fixed = { ...manifest }
31
+ for (const kind of LISTS) {
32
+ const list = manifest[kind]
33
+ if (!list || typeof list !== 'object') continue
34
+ const copy = Array.isArray(list) ? [...list] : { ...list }
35
+ delete copy['//']
36
+ for (const name in copy) copy[name] = copy[name] || ''
37
+ fixed[kind] = copy
38
+ }
39
+ return cleanDependencies(fixed)
40
+ }
41
+
42
+ export function globsOf({ workspaces }) {
43
+ return (Array.isArray(workspaces) ? workspaces : workspaces?.packages ?? []).map((glob) => String(glob).replace(/^(?:\.\/)+|\/+$/gu, ''))
44
+ }
45
+
46
+ // What normalize-manifest fails on in the root's name and version, which
47
+ // the lockfile reader does not read; and what of the root is not followed.
48
+ const NAME = /[/@\s+%:]/u
49
+ const validName = (name) => !NAME.test(name) && encodeURIComponent(name) === name
50
+ export function checkRoot(root) {
51
+ const { name, version } = root
52
+ for (const [key, value] of Object.entries({ name, version })) {
53
+ if (value && typeof value !== 'string') throw new DeptreeError('not a string, which yarn fails on', `manifests["."].${key}`)
54
+ }
55
+ if (typeof name === 'string') {
56
+ const parts = name.startsWith('@') ? name.slice(1).split('/') : undefined
57
+ const legal = parts === undefined ? validName(name) : parts.length === 2 && parts.every(validName)
58
+ if (name.startsWith('.') || !legal || ['node_modules', 'favicon.ico'].includes(name.toLowerCase())) throw new DeptreeError(`${quote(name)} is a name yarn fails on`, 'manifests["."].name')
59
+ }
60
+ if (root.installConfig?.pnp) throw new DeptreeError('Plug\'n\'Play is not supported', 'manifests["."].installConfig.pnp')
61
+ if (root.flat) throw new DeptreeError('a flat install is not supported', 'manifests["."].flat')
62
+ const nohoist = root.workspaces?.nohoist
63
+ if (Array.isArray(nohoist) && nohoist.length > 0) throw new DeptreeError('nohoist is not supported', 'manifests["."].workspaces.nohoist')
64
+ }
@@ -0,0 +1,206 @@
1
+ // A registry package as yarn 1 installs it, each mode given 0o644 and masked
2
+ // by a 0o022 umask as yarn's tarball fetcher does with tar-fs. Held to more
3
+ // than yarn holds it to: what npm packs, every entry under one directory,
4
+ // none in its own node_modules (npm packs those only for bundled
5
+ // dependencies), and a package.json of the lockfile's name and version.
6
+ // And a directory by `file:`, as yarn's copy fetcher installs it.
7
+
8
+ import { fromBase64 } from '@exodus/bytes/base64.js'
9
+ import { toHex } from '@exodus/bytes/hex.js'
10
+ import { getPublishTimes } from '@preventive/upstream/npm.js'
11
+ import { normalize } from '@preventive/vfs/path.js'
12
+ import { DeptreeError, quote } from '../error.js'
13
+ import { sha1Hex } from '../hash.js'
14
+ import { readManifest } from '../manifest.js'
15
+ import { decodeUtf8, readBytes, typeOf } from '../project.js'
16
+ import { fetchTarball, fromMirror, isModules, ownTarball, sameFile, withDirs } from '../tarball.js'
17
+ import { fixLists } from './manifest.js'
18
+ import { kindOf, splitPattern } from './resolve.js'
19
+
20
+ const UMASK = 0o022
21
+
22
+ // Paths as tar-fs with `strip: 1` writes them: `.`, `..` and `//` folded.
23
+ function entriesOf(entries, where) {
24
+ const files = new Map()
25
+ const dirs = new Set()
26
+ let top
27
+ for (const entry of entries) {
28
+ const slash = entry.storedName.indexOf('/')
29
+ const first = slash === -1 ? entry.storedName : entry.storedName.slice(0, slash)
30
+ if (top !== undefined && first !== top) throw new DeptreeError('the tarball has entries under more than one directory', where)
31
+ top = first
32
+ const path = slash === -1 ? '' : normalize(`/${entry.storedName.slice(slash + 1)}`).slice(1).replace(/\/$/u, '')
33
+ if (isModules(path.split('/')[0])) throw new DeptreeError(`${quote(entry.storedName)} is in the package's own node_modules, where yarn installs its dependencies, which is not supported`, where)
34
+ if (entry.type === 'directory') {
35
+ if (path !== '') dirs.add(path)
36
+ continue
37
+ }
38
+ if (entry.type !== 'file' && entry.type !== 'contiguous-file') throw new DeptreeError(`${quote(entry.storedName)} is a ${entry.type}, which is not supported`, where)
39
+ if (path === '') throw new DeptreeError(`${quote(entry.storedName)} is a file at the top of the tarball`, where)
40
+ const file = { data: entry.data, mode: (entry.mode | 0o644) & ~UMASK & 0o777 }
41
+ const earlier = files.get(path)
42
+ if (earlier !== undefined && !sameFile(earlier, file)) throw new DeptreeError(`${quote(path)} is in the tarball twice`, where)
43
+ files.set(path, file)
44
+ }
45
+ return withDirs(files, where, dirs)
46
+ }
47
+
48
+ const decoder = new TextDecoder('utf-8', { fatal: true })
49
+
50
+ // yarn writes the registry's sha512 where it has one, and else a sha1 of its
51
+ // shasum. Since this time the registry has made one for every version as it
52
+ // was published, by any client: firebase-tools@4.0.3, published then by npm
53
+ // 3.10.8, is the first it signed over one it made, and superstatic@6.0.0, at
54
+ // 2018-08-03T20:22:28.120Z, the last over none. It has since made one for
55
+ // every version published before too.
56
+ export const SHA512_SINCE = '2018-08-05T14:58:16.253Z'
57
+
58
+ // The hex of an integrity that is a sha1 alone.
59
+ function sha1Of(integrity) {
60
+ if (integrity === undefined || !/^sha1-[\d+/A-Za-z]{26}[048AEIMQUYcgkosw]=$/u.test(integrity)) return undefined
61
+ return toHex(fromBase64(integrity.slice(5)))
62
+ }
63
+
64
+ // `name` is the one fetched, as an `npm:` alias asks for it. yarn writes no
65
+ // integrity for a pattern that names the tarball's URL, but the sha1 after
66
+ // its `#`: the tarball is held to that, and to the registry's sha512. One
67
+ // with a sha1 integrity alone is held to it, and to the registry's sha512,
68
+ // where it was published before SHA512_SINCE.
69
+ export function registryTarball(entry, name, where) {
70
+ const { resolution } = entry
71
+ if (resolution === undefined) throw new DeptreeError('a directory, by file: or link:, is not supported', where)
72
+ const url = resolution.type === 'tarball' ? fromMirror(resolution.tarball) : resolution.tarball
73
+ const byUrl = entry.patterns.some((pattern) => kindOf(splitPattern(pattern).range, where) === 'tarball')
74
+ const sha1 = sha1Of(resolution.integrity)
75
+ if (sha1 === undefined) return ownTarball(url, name, entry.version, resolution.integrity, where, byUrl && resolution.sha1 !== undefined)
76
+ return { ...ownTarball(url, name, entry.version, undefined, where, true), sha1 }
77
+ }
78
+
79
+ // `times` keeps getPublishTimes' answer for each name, fetched once.
80
+ async function checkPublished({ name, version }, where, times) {
81
+ if (!times.has(name)) times.set(name, getPublishTimes(name))
82
+ const published = (await times.get(name)).get(version)
83
+ if (published === undefined) throw new DeptreeError(`a sha1 integrity alone, where the registry gives no time ${name}@${version} was published at`, where)
84
+ if (published >= SHA512_SINCE) throw new DeptreeError(`a sha1 integrity alone, which yarn does not write for ${name}@${version}, published at ${published}: the registry has given every version a sha512 since ${SHA512_SINCE}`, where)
85
+ }
86
+
87
+ export function checkSha1(pinned, sha1, where) {
88
+ if (pinned !== undefined && sha1 !== pinned) throw new DeptreeError(`the tarball's sha1 is not ${pinned}`, where)
89
+ }
90
+
91
+ // Another entry of a package yarn's cache keeps in one place, held to the
92
+ // first's, `head`, as fetchYarnPackage holds that one: yarn fetches it once.
93
+ export async function checkShared({ name, version, integrity, sha1: pinned }, head, where, times) {
94
+ if (pinned !== undefined) await checkPublished({ name, version }, where, times)
95
+ checkSha1(pinned, head.sha1, where)
96
+ if (integrity !== undefined && integrity !== head.integrity) throw new DeptreeError(`the tarball is not ${integrity}`, where)
97
+ }
98
+
99
+ // One the lockfile gives no sha512 is fetched by the registry's, as
100
+ // fetchTarball takes it unpinned.
101
+ export async function fetchYarnPackage({ name, version, integrity, sha1: pinned }, where, times, fetching) {
102
+ if (pinned !== undefined) await checkPublished({ name, version }, where, times)
103
+ const fetched = await fetchTarball(name, version, integrity, where, fetching)
104
+ const sha1 = await sha1Hex(fetched.bytes)
105
+ checkSha1(pinned, sha1, where)
106
+ const { files, dirs } = entriesOf(fetched.entries, where)
107
+ const file = files.get('package.json')
108
+ if (file === undefined) throw new DeptreeError('the tarball has no package.json', where)
109
+ let text
110
+ try {
111
+ text = decoder.decode(file.data)
112
+ } catch {
113
+ throw new DeptreeError('package.json is not UTF-8', where)
114
+ }
115
+ const manifest = readManifest(text, `${where}: package.json`)
116
+ if (manifest.name !== name || manifest.version !== version) throw new DeptreeError(`package.json is for ${quote(`${manifest.name}@${manifest.version}`)}`, where)
117
+ return { ...withBins({ files, dirs }, manifest, where), sha1, integrity: fetched.integrity, about: fetched.about }
118
+ }
119
+
120
+ // A directory by `file:`, as yarn's copy fetcher installs it: all in it, each
121
+ // file's mode as it is, but what yarn's copy passes over (tree.js); read from
122
+ // the project, as yarn reads it again at every install. Held to more than
123
+ // yarn holds it to: no link, device or node_modules of its own in it, and a
124
+ // package.json of the name, version and lists its lockfile entry has, which
125
+ // yarn reads anew, installing whatever they are.
126
+ export function readYarnDirectory(project, { name, version, entry, dir }, where) {
127
+ if (typeOf(project, `/${dir}`, false) !== 'directory') throw new DeptreeError(`${quote(dir)} is not a directory of the project`, where)
128
+ const files = new Map()
129
+ const dirs = new Set()
130
+ const walk = (at) => {
131
+ for (const base of project.readdir(`/${dir}${at && `/${at}`}`)) {
132
+ const path = at ? `${at}/${base}` : base
133
+ const { type, mode } = project.lstat(`/${dir}/${path}`)
134
+ if (at === '' && isModules(base)) throw new DeptreeError(`${quote(`${dir}/${path}`)} is its own node_modules, which yarn copies beside what it installs there, and which is not supported`, where)
135
+ if (type === 'directory') {
136
+ dirs.add(path)
137
+ walk(path)
138
+ continue
139
+ }
140
+ if (type !== 'file') throw new DeptreeError(`${quote(`${dir}/${path}`)} is a ${type}, which is not supported`, where)
141
+ if (!Number.isInteger(mode)) throw new TypeError(`project.lstat must give a file's mode, and gives ${String(mode)} for ${quote(`/${dir}/${path}`)}`)
142
+ if ((mode & ~0o777) !== 0) throw new DeptreeError(`${quote(`${dir}/${path}`)} has the mode ${mode.toString(8)}, which is not supported`, where)
143
+ files.set(path, { data: readBytes(project, `/${dir}/${path}`), mode })
144
+ }
145
+ }
146
+ walk('')
147
+ const file = files.get('package.json')
148
+ if (file === undefined) throw new DeptreeError(`${quote(dir)} has no package.json, where yarn makes one up`, where)
149
+ const manifest = readManifest(decodeUtf8(file.data, 'package.json is not UTF-8', where), `${where}: package.json`)
150
+ const why = 'which yarn reads anew, installing what it says'
151
+ if (manifest.name !== name || manifest.version !== version) throw new DeptreeError(`package.json is for ${quote(`${manifest.name}@${manifest.version}`)}, not the lockfile's ${quote(`${name}@${version}`)}, ${why}`, where)
152
+ const fixed = fixLists(manifest)
153
+ for (const kind of ['dependencies', 'optionalDependencies']) {
154
+ const listed = Object.entries(fixed[kind] ?? {}).map(([dep, range]) => `${dep}@${range}`).sort()
155
+ const locked = Object.values(entry[kind] ?? {}).sort()
156
+ if (listed.join('\n') !== locked.join('\n')) throw new DeptreeError(`package.json's ${kind} are not the lockfile's, ${why}`, where)
157
+ }
158
+ return withBins(withDirs(files, where, dirs), manifest, where)
159
+ }
160
+
161
+ // As yarn's fetcher leaves a package in its cache (base-fetcher.js): each
162
+ // bin's target chmod 755, and a .bin made for the links.
163
+ function withBins({ files, dirs }, manifest, where) {
164
+ const bins = binsOf(manifest, { files, dirs })
165
+ if (bins.size > 0 && files.has('.bin')) throw new DeptreeError('.bin is a file, where yarn fails to make a directory for the bins', where)
166
+ for (const target of bins.values()) {
167
+ if (isModules(target.split('/')[0])) throw new DeptreeError(`its bin ${quote(target)} is in its own node_modules, where yarn installs its dependencies, which is not supported`, where)
168
+ const script = files.get(target.replace(/\/$/u, ''))
169
+ if (script !== undefined) script.mode = 0o755
170
+ }
171
+ return { files, dirs, manifest, hasBins: bins.size > 0 }
172
+ }
173
+
174
+ // Bins as yarn's normalize-manifest reads them, targets normalized as Node's
175
+ // path.normalize does it, a trailing `/` kept.
176
+ const VALID_BIN_KEYS = /^(?!\.{0,2}$)[a-z0-9._-]+$/iu
177
+
178
+ const outside = (path) => path.startsWith('/') || path === '..' || path.startsWith('../')
179
+
180
+ function binsOf(manifest, { files, dirs }) {
181
+ let { bin } = manifest
182
+ if (typeof manifest.name === 'string' && typeof bin === 'string' && bin.length > 0) bin = { [manifest.name.replace(/^@[^/]+\//u, '')]: bin }
183
+ const bins = new Map()
184
+ if (bin !== null && typeof bin === 'object') {
185
+ for (const [key, target] of Object.entries(bin)) {
186
+ if (!VALID_BIN_KEYS.test(key)) continue
187
+ if (typeof target !== 'string') throw new DeptreeError(`its bin ${quote(key)} is not a string, which yarn fails on`, quote(manifest.name))
188
+ const path = normalize(target)
189
+ if (!outside(path)) bins.set(key, path)
190
+ }
191
+ return bins
192
+ }
193
+ const binDir = manifest.directories?.bin
194
+ if (typeof binDir === 'string' && binDir) {
195
+ const dir = normalize(binDir).replace(/(?<=.)\/$/u, '')
196
+ if (outside(dir)) throw new DeptreeError(`directories.bin, ${quote(binDir)}, is outside the package, which is not supported`, quote(manifest.name))
197
+ if (files.has(dir)) throw new DeptreeError(`directories.bin, ${quote(binDir)}, is a file, which yarn fails to read as a directory`, quote(manifest.name))
198
+ const prefix = dir === '.' ? '' : `${dir}/`
199
+ for (const path of [...files.keys(), ...dirs]) {
200
+ if (!path.startsWith(prefix)) continue
201
+ const [first] = path.slice(prefix.length).split('/')
202
+ if (first !== '' && !first.startsWith('.')) bins.set(first, `${prefix}${first}`)
203
+ }
204
+ }
205
+ return bins
206
+ }
@@ -0,0 +1,51 @@
1
+ // yarn 1's resolvePeerModules (package-linker.js), run before it hoists: a
2
+ // peer is looked for along the shortest chain of names the package was asked
3
+ // for by, and the nearest in range added; where none is, yarn only warns.
4
+
5
+ import { compareVersions, valid, validRange } from '@preventive/upstream/semver.js'
6
+
7
+ // yarn's util/semver.js: semver's prerelease rule ignored, and `<x` with no
8
+ // prerelease read as `<x-0`, so `<2.0.0` takes no 2.0.0-rc.1.
9
+ const OPERATORS = /^(<=|>=|<|>|=)?(.*)$/u
10
+
11
+ export function satisfiesWithPrereleases(version, range, loose = false) {
12
+ const options = { loose }
13
+ const normalized = validRange(range, options)
14
+ if (normalized === null || !version || valid(version, options) === null) return false
15
+ return normalized.split('||').some((set) => set.split(' ').every((comparator) => {
16
+ const [, operator = '=', bound] = OPERATORS.exec(comparator)
17
+ if (bound === '' || bound === '*') return true
18
+ const order = compareVersions(version, operator === '<' && !bound.includes('-') ? `${bound}-0` : bound, options)
19
+ return { '<': order < 0, '<=': order <= 0, '>': order > 0, '>=': order >= 0, '=': order === 0 }[operator]
20
+ }))
21
+ }
22
+
23
+ export function resolvePeers(resolved, manifests) {
24
+ const { patterns, byName } = resolved
25
+ for (const [ref, manifest] of manifests) {
26
+ const peers = manifest?.peerDependencies
27
+ if (!peers) continue
28
+ const chain = ref.requests.map((request) => request.parentNames ?? []).sort((a, b) => a.length - b.length)[0]
29
+ const distance = (other) => {
30
+ let min = Infinity
31
+ for (const request of other.requests) {
32
+ const names = request.parentNames ?? []
33
+ const d = chain.length - names.length
34
+ if (d >= 0 && d < min && names.every((name, i) => name === chain[i])) min = d
35
+ }
36
+ return min
37
+ }
38
+ for (const [name, range] of Object.entries(peers)) {
39
+ let best = Infinity
40
+ let found
41
+ for (const candidate of new Set((byName.get(name) ?? []).map((pattern) => patterns.get(pattern)))) {
42
+ const d = distance(candidate)
43
+ if (d < best && (range === '*' || satisfiesWithPrereleases(candidate.version, range, true))) {
44
+ best = d
45
+ found = candidate
46
+ }
47
+ }
48
+ if (found !== undefined) ref.asked.push(...found.patterns.map((pattern) => ({ pattern, optional: false, dev: false })))
49
+ }
50
+ }
51
+ }