@preventive/deptree 1.0.0-alpha.5 → 1.0.0-alpha.7

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 (79) hide show
  1. package/LICENSE-APACHE +202 -0
  2. package/npm.d.ts +288 -0
  3. package/npm.js +7 -0
  4. package/package.json +41 -12
  5. package/pnpm.d.ts +158 -25
  6. package/pnpm.js +2 -10
  7. package/soldeer.d.ts +13 -0
  8. package/soldeer.js +1 -7
  9. package/src/concurrent.js +16 -17
  10. package/src/error.js +5 -9
  11. package/src/glob.js +55 -0
  12. package/src/hash.js +60 -13
  13. package/src/manifest.js +52 -0
  14. package/src/matcher.js +60 -10
  15. package/src/mount.js +104 -44
  16. package/src/npm/bins.js +54 -0
  17. package/src/npm/compat.js +97 -0
  18. package/src/npm/dev-engines.js +52 -0
  19. package/src/npm/graph.js +68 -0
  20. package/src/npm/inputs.js +75 -0
  21. package/src/npm/manifests.js +130 -0
  22. package/src/npm/package.js +57 -0
  23. package/src/npm/ratio.js +34 -0
  24. package/src/npm/settings.js +67 -0
  25. package/src/npm/tree.js +136 -0
  26. package/src/npm/versions.js +20 -0
  27. package/src/npmrc.js +24 -0
  28. package/src/patch.js +22 -41
  29. package/src/pnpm/bins.js +152 -131
  30. package/src/pnpm/checks.js +8 -35
  31. package/src/pnpm/commands.js +53 -96
  32. package/src/pnpm/filename.js +10 -21
  33. package/src/pnpm/frozen.js +29 -75
  34. package/src/pnpm/gitignore.js +139 -0
  35. package/src/pnpm/glob.js +65 -0
  36. package/src/pnpm/graph.js +15 -43
  37. package/src/pnpm/hoist.js +68 -61
  38. package/src/pnpm/hoisted.js +234 -0
  39. package/src/pnpm/hook.js +26 -31
  40. package/src/pnpm/inputs.js +73 -56
  41. package/src/pnpm/install.js +85 -131
  42. package/src/pnpm/local.js +21 -40
  43. package/src/pnpm/minimatch.js +319 -0
  44. package/src/pnpm/nm-hoist-graph.js +299 -0
  45. package/src/pnpm/nm-hoist.js +149 -0
  46. package/src/pnpm/npm-packlist.js +217 -0
  47. package/src/pnpm/overrides.js +11 -51
  48. package/src/pnpm/package.js +121 -0
  49. package/src/pnpm/packlist.js +169 -109
  50. package/src/pnpm/patches.js +18 -25
  51. package/src/pnpm/projects.js +63 -107
  52. package/src/pnpm/readers.js +63 -83
  53. package/src/pnpm/settings.js +64 -100
  54. package/src/pnpm/tree.js +197 -169
  55. package/src/pnpm/uptodate.js +16 -28
  56. package/src/pnpm/workspace.js +124 -133
  57. package/src/project.js +57 -0
  58. package/src/soldeer/config.js +8 -24
  59. package/src/soldeer/inputs.js +5 -15
  60. package/src/soldeer/tree.js +22 -60
  61. package/src/soldeer/zip.js +17 -36
  62. package/src/tarball.js +55 -140
  63. package/src/yarn1/bins.js +9 -19
  64. package/src/yarn1/compat.js +9 -28
  65. package/src/yarn1/hoist.js +53 -68
  66. package/src/yarn1/inputs.js +19 -61
  67. package/src/yarn1/manifest.js +8 -23
  68. package/src/yarn1/package.js +24 -63
  69. package/src/yarn1/peers.js +8 -15
  70. package/src/yarn1/requests.js +19 -37
  71. package/src/yarn1/resolve.js +36 -113
  72. package/src/yarn1/settings.js +15 -43
  73. package/src/yarn1/tree.js +67 -91
  74. package/yarn1.d.ts +34 -5
  75. package/yarn1.js +1 -8
  76. package/src/pnpm/npmrc.js +0 -31
  77. package/src/pnpm/project.js +0 -97
  78. package/src/yarn1/glob.js +0 -52
  79. /package/{LICENSE → LICENSE-MIT} +0 -0
@@ -0,0 +1,234 @@
1
+ // Where the hoisted linker (nodeLinker: hoisted) of pnpm 10 and 11 puts
2
+ // each package: @pnpm/real-hoist makes a tree of the lockfile, the root's
3
+ // dependencies and each other project's under the root, which @yarnpkg/nm
4
+ // hoists (nm-hoist.js; what pnpm 11 has of it, 4.0.7 to 4.1.1, differs
5
+ // only with hoistingLimits, which is not supported); each package is then
6
+ // copied to node_modules/<alias> under where it landed, and each project's
7
+ // own lands in its node_modules. A project's `link:` dependencies are linked
8
+ // there, as are none of a package's.
9
+
10
+ import { packageKeyOf } from '@preventive/lockfile/pnpm.js'
11
+ import { valid } from '@preventive/upstream/semver.js'
12
+ import { relative } from '@preventive/vfs/path.js'
13
+ import { DeptreeError, quote } from '../error.js'
14
+ import { createMatcher } from '../matcher.js'
15
+ import { REGULAR, WORKSPACE, depthFirst, hoist, reachable } from './nm-hoist.js'
16
+
17
+ // pnpm's name@version of a snapshot, by which it takes every snapshot of a
18
+ // package for the first it comes to. A directory has no version in the
19
+ // lockfile, so all of one name are one; from pnpm 11.24 (`directories`),
20
+ // each snapshot of one is its own.
21
+ export function packageIdOf(key, pkg, directories = false) {
22
+ if (directories && pkg.resolution.type === 'directory') return key
23
+ const base = packageKeyOf(key)
24
+ const name = base.slice(0, base.indexOf('@', 1))
25
+ const version = pkg.resolution.type === 'directory' ? undefined : valid(base.slice(name.length + 1)) ?? undefined
26
+ return `${name}@${version}`
27
+ }
28
+
29
+ const modulesOf = (id) => (id === '.' ? 'node_modules' : `${id}/node_modules`)
30
+
31
+ // A project's dependencies as pnpm reads them from the lockfile, a link
32
+ // spelled from the project, as pnpm writes it.
33
+ function asWritten(id, deps) {
34
+ return Object.fromEntries(Object.entries(deps).map(([alias, target]) => [alias, target.startsWith('link:') ? `link:${relative(`/${id}`, `/${target.slice(5)}`)}` : target]))
35
+ }
36
+
37
+ // A link pnpm from 11.28.1 takes for one into the package that asks for it,
38
+ // which it does not hoist: `link:<root>/` and a plain path.
39
+ const rootLink = (ref) => ref.startsWith('link:<root>/') && ref.slice('link:<root>/'.length).split('/').every((name) => name !== '' && name !== '.' && name !== '..' && !name.includes('\\') && !name.includes(':'))
40
+
41
+ // real-hoist's tree: a node by alias and snapshot, each made once and with
42
+ // its own dependencies made before the next, depth first as pnpm recurses.
43
+ function treeOf(lockfile, autoInstallPeers, { directories, rootLinks }) {
44
+ const nodes = new Map()
45
+ const referenceById = new Map()
46
+ const nodeOf = (alias, ref) => {
47
+ if (ref.startsWith('link:')) return { name: alias, identName: alias, reference: ref, dependencyKind: rootLinks && rootLink(ref) ? WORKSPACE : REGULAR, dependencies: new Set(), peerNames: new Set() }
48
+ const pkg = lockfile.packages[ref]
49
+ const id = packageIdOf(ref, pkg, directories)
50
+ if (!referenceById.has(id)) referenceById.set(id, ref)
51
+ const peerNames = new Set(autoInstallPeers ? [] : [...Object.keys(pkg.peerDependencies), ...pkg.transitivePeerDependencies])
52
+ return { name: alias, identName: pkg.name, reference: referenceById.get(id), dependencyKind: REGULAR, dependencies: new Set(), peerNames }
53
+ }
54
+ const toTree = (deps) => {
55
+ const top = new Set()
56
+ depthFirst({ items: Object.entries(deps).values(), into: top }, ([alias, ref], { into }) => {
57
+ const key = `${alias}:${ref}`
58
+ const made = !nodes.has(key)
59
+ if (made) nodes.set(key, nodeOf(alias, ref))
60
+ const node = nodes.get(key)
61
+ into.add(node)
62
+ if (!made || ref.startsWith('link:')) return undefined
63
+ const pkg = lockfile.packages[ref]
64
+ return { items: Object.entries({ ...pkg.dependencies, ...pkg.optionalDependencies }).values(), into: node.dependencies }
65
+ })
66
+ return top
67
+ }
68
+ const projectNode = (id, name, reference) => {
69
+ const { dependencies, devDependencies, optionalDependencies } = lockfile.importers[id]
70
+ return { name, identName: name, reference, peerNames: new Set(), dependencyKind: WORKSPACE, dependencies: toTree(asWritten(id, { ...dependencies, ...devDependencies, ...optionalDependencies })) }
71
+ }
72
+ const tree = projectNode('.', '.', '')
73
+ for (const [id, importer] of Object.entries(lockfile.importers)) {
74
+ if (id !== '.' && !importer.made) tree.dependencies.add(projectNode(id, encodeURIComponent(id), `workspace:${id}`))
75
+ }
76
+ return tree
77
+ }
78
+
79
+ // pnpm reads a package's link as its writer left it, which the lockfile
80
+ // reader does not keep.
81
+ function checkNoPackageLinks(lockfile) {
82
+ for (const [key, pkg] of Object.entries(lockfile.packages)) {
83
+ for (const [alias, target] of Object.entries({ ...pkg.dependencies, ...pkg.optionalDependencies })) {
84
+ if (target.startsWith('link:')) throw new DeptreeError('a package\'s `link:` dependency is not supported with the hoisted linker', `packages[${quote(key)}].dependencies[${quote(alias)}]`)
85
+ }
86
+ }
87
+ }
88
+
89
+ // The tree as hoisted, of nodes with a name, an identName, references and
90
+ // dependencies; with `directories` from pnpm 11.24, and `rootLinks` from
91
+ // 11.28.1.
92
+ export function hoistedTree(lockfile, autoInstallPeers, bounds, { directories = false, rootLinks = false } = {}) {
93
+ checkNoPackageLinks(lockfile)
94
+ return hoist(treeOf(lockfile, autoInstallPeers, { directories, rootLinks }), bounds)
95
+ }
96
+
97
+ // Each directory a package is copied to, from the lockfile's, in the order
98
+ // pnpm makes them, a parent before what lands in its node_modules, with the
99
+ // snapshot copied there, the node_modules it is in and its alias there; the
100
+ // `link:`s of each project, by where they go; and the node_modules of the
101
+ // projects pnpm fills, the root's first. `skipped` are the snapshots left
102
+ // out, which are hoisted all the same. pnpm hoists from the importers the
103
+ // lockfile has, not those made for projects it has none for.
104
+ export function hoistedLayout(lockfile, { autoInstallPeers, skipped, directories = false, rootLinks = false }, bounds) {
105
+ const tree = hoistedTree(lockfile, autoInstallPeers, bounds, { directories, rootLinks })
106
+ const placed = new Map()
107
+ const place = (modules, deps) => depthFirst({ modules, items: deps.values() }, (dep, frame) => {
108
+ const [key] = dep.references
109
+ if (skipped.has(key) || key.startsWith('workspace:') || !(key in lockfile.packages)) return undefined
110
+ const dir = `${frame.modules}/${dep.name}`
111
+ const pkg = lockfile.packages[key]
112
+ placed.set(dir, { key, pkg, name: pkg.name, dir, modules: frame.modules, alias: dep.name })
113
+ return { modules: `${dir}/node_modules`, items: dep.dependencies.values() }
114
+ })
115
+ place('node_modules', tree.dependencies)
116
+ const projects = ['node_modules']
117
+ for (const dep of tree.dependencies) {
118
+ const [reference] = dep.references
119
+ if (!reference.startsWith('workspace:')) continue
120
+ const modules = modulesOf(reference.slice('workspace:'.length))
121
+ projects.push(modules)
122
+ place(modules, dep.dependencies)
123
+ }
124
+ const links = new Map()
125
+ for (const [id, importer] of Object.entries(lockfile.importers)) {
126
+ for (const [alias, target] of Object.entries({ ...importer.devDependencies, ...importer.dependencies, ...importer.optionalDependencies })) {
127
+ if (target.startsWith('link:')) links.set(`${modulesOf(id)}/${alias}`, target.slice(5))
128
+ }
129
+ }
130
+ return { placed, links, projects }
131
+ }
132
+
133
+ // pnpm from 11.28 links each project named in `names` into the root's
134
+ // node_modules by its name where a hoist pattern matches it, unless the root
135
+ // depends on that name, or a package landed there by it, with their case
136
+ // folded.
137
+ export function workspaceHoists(placed, lockfile, { hoistPattern, publicHoistPattern }, names) {
138
+ const isPublic = createMatcher(publicHoistPattern ?? [])
139
+ const isPrivate = createMatcher(hoistPattern ?? [])
140
+ const { dependencies, devDependencies, optionalDependencies } = lockfile.importers['.']
141
+ const taken = new Set(Object.keys({ ...dependencies, ...devDependencies, ...optionalDependencies }).map((alias) => alias.toLowerCase()))
142
+ for (const { modules, alias } of placed.values()) if (modules === 'node_modules') taken.add(alias.toLowerCase())
143
+ const links = new Map()
144
+ for (const [id, name] of names) {
145
+ if ((!isPublic(name) && !isPrivate(name)) || taken.has(name.toLowerCase())) continue
146
+ taken.add(name.toLowerCase())
147
+ links.set(`node_modules/${name}`, id)
148
+ }
149
+ return links
150
+ }
151
+
152
+ // What pnpm's build pass does where any patch is configured, which it runs
153
+ // though scripts are ignored: it builds each package patched or with an
154
+ // install script in one of its copies, the first it comes to of those a
155
+ // project's node_modules reaches through each package's dependencies, each
156
+ // at the first copy of its snapshot, or from pnpm 11.23 of its package
157
+ // (`idOf`). Then it links the built copy's files into every other: from
158
+ // 10.21 (`hardlinks`) it puts a copy of hardlinks in place of the copy, with
159
+ // no node_modules, which drops the copy's own; before, in place, where a
160
+ // file is not already, which leaves the others unpatched. From pnpm 11.25
161
+ // (`keepsModules`) it links each file but those under a node_modules in
162
+ // place of the copy's own, and leaves the copy's node_modules and what the
163
+ // built one has not. Which copy it builds turns on its build order, which is
164
+ // not followed here. `projects` are the node_modules of the projects;
165
+ // `byDir` the copies, in the order pnpm makes them; `changesOf` the changes
166
+ // of a patched one's patch; `pnpm` the version, for what is refused.
167
+ export function hoistedBuilds(byDir, projects, builds, { hardlinks, keepsModules = false, idOf = (key) => key, changesOf, pnpm = '10' }) {
168
+ const first = new Map()
169
+ const placedIn = new Set()
170
+ for (const node of byDir.values()) {
171
+ if (!first.has(idOf(node.key))) first.set(idOf(node.key), node.dir)
172
+ placedIn.add(node.modules)
173
+ }
174
+ const childrenOf = (node) => Object.entries({ ...node.pkg.dependencies, ...node.pkg.optionalDependencies }).map(([alias, key]) => [alias, first.get(idOf(key))]).filter(([, dir]) => dir !== undefined)
175
+ const tops = [...byDir.values()].filter((node) => projects.has(node.modules)).map((node) => node.dir)
176
+ const reached = reachable(tops, (dir) => childrenOf(byDir.get(dir)).map(([, child]) => child))
177
+ const built = []
178
+ for (const [key, copies] of Map.groupBy(byDir.values(), (node) => node.key)) {
179
+ const [node] = copies
180
+ if (!builds(node)) continue
181
+ const candidates = copies.filter((copy) => reached.has(copy.dir)).map((copy) => copy.dir)
182
+ const patched = node.pkg.patchHash !== undefined
183
+ if (candidates.length === 0) {
184
+ if (patched) throw new DeptreeError(`pnpm ${pnpm} reaches none of its copies through the dependencies it builds by, and leaves it unpatched, which is not supported`, quote(key))
185
+ continue
186
+ }
187
+ if (copies.length > 1 && !hardlinks) {
188
+ if (patched) throw new DeptreeError('pnpm 10 before 10.21 patches one of its copies alone, and leaves the others as they were, which is not supported', quote(key))
189
+ } else if (copies.length > 1 && keepsModules) {
190
+ for (const { path, change } of patched ? changesOf(node) : []) {
191
+ if (change === 'delete') throw new DeptreeError(`pnpm ${pnpm} patches one of its copies, and links its files into the others, which keep ${quote(path)} the patch deletes, which is not supported`, quote(key))
192
+ if (path.split('/').includes('node_modules')) throw new DeptreeError(`pnpm ${pnpm} patches one of its copies, and links its files but those under a node_modules into the others, which leaves ${quote(path)} unpatched there, which is not supported`, quote(key))
193
+ }
194
+ } else if (copies.length > 1) {
195
+ const own = node.files.keys().find((path) => path.split('/').includes('node_modules'))
196
+ if (own !== undefined) throw new DeptreeError(`pnpm ${pnpm} builds one of its copies where any patch is configured, and makes the others hardlinks of it, with no ${quote(own)}, which is not supported`, quote(key))
197
+ const nested = copies.find((copy) => placedIn.has(`${copy.dir}/node_modules`))
198
+ if (nested !== undefined) throw new DeptreeError(`pnpm ${pnpm} builds one of its copies where any patch is configured, and makes the others hardlinks of it, dropping their node_modules: ${quote(`${nested.dir}/node_modules`)} may be dropped, which is not supported`, quote(key))
199
+ }
200
+ built.push({ key, copies: copies.map((copy) => copy.dir), candidates, children: childrenOf(node) })
201
+ }
202
+ return built
203
+ }
204
+
205
+ // What linkBins reads to link bins (bins.js): each node_modules pnpm fills,
206
+ // with what it put there, the projects' first, then each project's with its
207
+ // links too.
208
+ export function hoistedModules(byDir, links, projects, manifests, lockfile) {
209
+ const placedIn = new Map()
210
+ const add = (modules, alias, dir) => {
211
+ if (!placedIn.has(modules)) placedIn.set(modules, [])
212
+ placedIn.get(modules).push([alias, dir])
213
+ }
214
+ for (const { dir, modules, alias } of byDir.values()) add(modules, alias, dir)
215
+ const filled = [...projects, ...[...byDir.keys()].map((dir) => `${dir}/node_modules`)]
216
+ const all = filled.filter((dir) => placedIn.has(dir)).map((dir) => ({ dir, entries: placedIn.get(dir) }))
217
+ for (const [path, target] of links) {
218
+ const end = path.lastIndexOf('/node_modules/') + '/node_modules'.length
219
+ add(path.slice(0, end), path.slice(end + 1), target)
220
+ }
221
+ for (const id of Object.keys(lockfile.importers)) {
222
+ const dir = modulesOf(id)
223
+ if (placedIn.has(dir)) all.push({ dir, entries: placedIn.get(dir), manifest: manifests.get(id) })
224
+ }
225
+ return all
226
+ }
227
+
228
+ // The snapshots `pnpm install --prod` would install, by pnpm's name@version.
229
+ export function prodPackages(lockfile, skipped, directories) {
230
+ const edges = ({ dependencies, optionalDependencies }) => [...Object.values(dependencies), ...Object.values(optionalDependencies)]
231
+ const reached = reachable(Object.values(lockfile.importers).flatMap(edges), (key) => edges(lockfile.packages[key]), (key) => key.startsWith('link:') || skipped.has(key))
232
+ return new Set([...reached].map((key) => packageIdOf(key, lockfile.packages[key], directories)))
233
+ }
234
+
package/src/pnpm/hook.js CHANGED
@@ -1,29 +1,17 @@
1
- // What pnpm 10 makes of a package.json before it reads its dependencies:
2
- // its read-package hook (@pnpm/hooks.read-package-hook), less what is
3
- // refused elsewhere — package extensions and a pnpmfile's readPackage —
4
- // and less Yarn's compatibility database, which adds dependencies to a few
5
- // packages by name and is not reproduced. Overrides replace or, as `-`,
6
- // remove what the package asks for (createVersionsOverrider), and
7
- // ignoredOptionalDependencies removes the optional dependencies it names.
8
- // pnpm runs it on every package it resolves and on every project's
9
- // package.json before holding it to its importer, which is why a project
10
- // overridden is recorded as overridden.
11
- //
12
- // An override to a directory, `link:` or `file:`, is written into a
13
- // project relative to it, as pnpm writes it; pnpm 11 takes a path alone
14
- // for one too, where pnpm 10 writes it as it is. pnpm 11 also converges
15
- // where no override is chosen (overrides.js), and drops a peer's
16
- // peerDependenciesMeta with the peer.
1
+ // pnpm's read-package hook (@pnpm/hooks.read-package-hook), less package
2
+ // extensions and a pnpmfile's readPackage, refused elsewhere, and Yarn's
3
+ // compatibility database, not reproduced. pnpm runs it on every package and on
4
+ // each project's package.json before holding it to its importer.
17
5
 
18
6
  import { intersects, satisfies, validRange } from '@preventive/upstream/semver.js'
19
7
  import { relative } from '@preventive/vfs/path.js'
20
8
  import { DeptreeError } from '../error.js'
9
+ import { checkNesting } from '../manifest.js'
21
10
  import { createMatcher } from '../matcher.js'
22
11
 
23
12
  const KINDS = ['dependencies', 'optionalDependencies', 'devDependencies']
24
13
 
25
- // pnpm's isIntersectingRange: no range is any, one range is itself, and
26
- // two ranges meet where some version is in both.
14
+ // pnpm's isIntersectingRange.
27
15
  const meets = (range, spec) => !range || spec === range || (validRange(spec) !== null && validRange(range) !== null && intersects(spec, range))
28
16
 
29
17
  // pickMostSpecificVersionOverride, with its own comparator and sort: the
@@ -32,8 +20,6 @@ const mostSpecific = (overrides) => overrides.sort((a, b) => (meets(b.target.ran
32
20
 
33
21
  const isPeerRange = (spec) => validRange(spec) !== null || spec.includes('workspace:') || spec.includes('catalog:')
34
22
 
35
- // An override to a directory, `local` as listOverrides has it, as pnpm
36
- // writes it into the project at `dir`: relative to it.
37
23
  function localSpec({ protocol, dir: to }, dir) {
38
24
  const path = relative(dir, to) || '.'
39
25
  return protocol === '' && !path.startsWith('.') ? `./${path}` : `${protocol}${path}`
@@ -49,13 +35,16 @@ function checkFields(manifest, where) {
49
35
  }
50
36
  }
51
37
 
52
- // `overrides` is listOverrides's; `ignored` the ignoredOptionalDependencies
53
- // patterns; `major` pnpm's major version. The hook hands back a changed
54
- // copy of a package.json; `dir` is the directory of a project's, where an
55
- // override to a path is written into it as pnpm writes it, and undefined
56
- // for a package's, whose specifiers are not read.
38
+ // semver's satisfies, which throws a TypeError on a version that is neither
39
+ // a string nor falsy, as pnpm then fails.
40
+ function inParentRange(version, range, where) {
41
+ if (version && typeof version !== 'string') throw new DeptreeError('not a string, which pnpm fails on where an override names this package with a range', `${where}.version`)
42
+ return satisfies(version, range)
43
+ }
44
+
45
+ // The hook's `dir` is a project's directory, which directory overrides are
46
+ // written relative to; undefined for a package.
57
47
  export function createHook({ overrides, ignored, major = 10 }) {
58
- // Each list by the name it overrides, in order.
59
48
  const byName = (list) => Map.groupBy(list, ({ target }) => target.name)
60
49
  const withParent = overrides.filter(({ parent }) => parent !== undefined)
61
50
  const generic = byName(overrides.filter(({ parent, converge }) => parent === undefined && !converge))
@@ -63,16 +52,18 @@ export function createHook({ overrides, ignored, major = 10 }) {
63
52
  const isIgnored = createMatcher(ignored)
64
53
  return (manifest, where, { dir } = {}) => {
65
54
  checkFields(manifest, where)
66
- const copy = structuredClone(manifest)
55
+ const copy = structuredClone(checkNesting(manifest, where))
67
56
  if (overrides.length > 0) {
68
- const scoped = byName(withParent.filter(({ parent }) => parent.name === copy.name && (!parent.range || satisfies(copy.version, parent.range))))
57
+ const scoped = byName(withParent.filter(({ parent }) => parent.name === copy.name && (!parent.range || inParentRange(copy.version, parent.range, where))))
69
58
  const pick = (list, spec) => mostSpecific((list ?? []).filter(({ target }) => meets(target.range, spec)))
70
59
  const override = (deps, peers) => {
71
60
  for (const [name, spec] of Object.entries(peers ?? deps)) {
72
61
  const chosen = pick(scoped.get(name), spec) ?? pick(generic.get(name), spec)
73
62
  const version = converging.get(name)
74
- if (chosen === undefined && version !== undefined && validRange(spec, { loose: true }) !== null && satisfies(version, spec, { loose: true })) (peers ?? deps)[name] = version
75
- if (chosen === undefined) continue
63
+ if (chosen === undefined) {
64
+ if (version !== undefined && validRange(spec, { loose: true }) !== null && satisfies(version, spec, { loose: true })) (peers ?? deps)[name] = version
65
+ continue
66
+ }
76
67
  if (chosen.spec === '-') {
77
68
  delete (peers ?? deps)[name]
78
69
  if (peers !== undefined && major >= 11) delete copy.peerDependenciesMeta?.[name]
@@ -85,7 +76,11 @@ export function createHook({ overrides, ignored, major = 10 }) {
85
76
  }
86
77
  }
87
78
  for (const kind of KINDS) if (copy[kind] !== undefined) override(copy[kind])
88
- if (copy.peerDependencies !== undefined) override(copy.dependencies ??= {}, copy.peerDependencies)
79
+ if (copy.peerDependencies !== undefined) {
80
+ // pnpm 9 overrides a peer in place whatever the override is.
81
+ if (major < 10) override(copy.peerDependencies)
82
+ else override(copy.dependencies ??= {}, copy.peerDependencies)
83
+ }
89
84
  }
90
85
  for (const name of Object.keys(copy.optionalDependencies ?? {})) {
91
86
  if (!isIgnored(name)) continue
@@ -1,32 +1,53 @@
1
- // What buildPnpmTree and findPnpmProjects take, checked: the host pnpm
2
- // would install on, and the files an install reads — given as text, or
3
- // read from the project (project.js) as pnpm reads them from disk.
1
+ // The host and the files an install reads, checked, as given or read from the
2
+ // project as pnpm reads them from disk.
4
3
 
5
4
  import { LockfileError, YamlError, parsePnpmLockfile } from '@preventive/lockfile/pnpm.js'
6
5
  import { parseYaml } from '@preventive/lockfile/yaml.js'
7
6
  import { compareVersions, valid } from '@preventive/upstream/semver.js'
7
+ import { normalize } from '@preventive/vfs/path.js'
8
8
  import { DeptreeError, quote } from '../error.js'
9
- import { checkProject, readManifestTexts, readPatches, readRootFiles, readText, readWorkspaceText, typeOf } from './project.js'
10
- import { pinnedPnpm, readManifest, readManifests } from './projects.js'
9
+ import { readManifest } from '../manifest.js'
10
+ import { checkHostKeys, checkLeftOut, checkProject, checkTexts, readText, typeOf } from '../project.js'
11
+ import { pinnedPnpm, readManifests } from './projects.js'
11
12
  import { readers } from './readers.js'
12
13
  import { checkWorkspace, findProjects, linkedManifest } from './workspace.js'
13
14
 
14
15
  const LIBC = new Set(['glibc', 'musl', 'unknown'])
15
16
 
16
- // The major version of `pnpm`, 10, 11 or 12: what pnpm 11 and 12 do
17
- // differently is read by it, where it is. pnpm 12 before 12.8.1 installs
18
- // otherwise in places, and is refused.
17
+ const MISNAMED = ['pnpm-workspaces.yaml', 'pnpm-workspaces.yml', 'pnpm-workspace.yml', '.pnpm-workspace.yaml', '.pnpm-workspace.yml', '.pnpm-workspaces.yaml', '.pnpm-workspaces.yml']
18
+ const MISNAMED_9 = ['pnpm-workspace.yml']
19
+ function readWorkspaceText(project, major) {
20
+ const text = readText(project, '/pnpm-workspace.yaml')
21
+ const misnamed = text === undefined ? (major < 10 ? MISNAMED_9 : MISNAMED).find((name) => typeOf(project, `/${name}`) === 'file') : undefined
22
+ if (misnamed !== undefined) throw new DeptreeError('pnpm refuses a workspace manifest not named pnpm-workspace.yaml', quote(misnamed))
23
+ return text
24
+ }
25
+
26
+ const readManifestTexts = (project, ids) => new Map(ids.map((id) => [id, readText(project, id === '.' ? '/package.json' : `/${id}/package.json`, `manifests[${quote(id)}]`)]))
27
+
28
+ // By path from the lockfile's directory; one that is not there is left out.
29
+ function readPatches(project, configured) {
30
+ const texts = new Map()
31
+ for (const [selector, spec] of Object.entries(configured ?? {})) {
32
+ const path = normalize(spec)
33
+ if (path === '..' || path.startsWith('../') || path.startsWith('/')) throw new DeptreeError(`the patch ${quote(spec)} is not in the project: it is outside the lockfile's directory`, `patchedDependencies[${quote(selector)}]`)
34
+ const text = readText(project, `/${path}`, `patches[${quote(path)}]`)
35
+ if (text !== undefined) texts.set(path, text)
36
+ }
37
+ return texts
38
+ }
39
+
40
+ // pnpm 9 before 9.15.0, and pnpm 12 before 12.8.1, install otherwise in
41
+ // places, and are refused.
42
+ const SINCE = { 9: '9.15.0', 12: '12.8.1' }
19
43
  function majorOf(pnpm) {
20
44
  const major = Number(valid(pnpm)?.split('.')[0])
21
- if (major !== 10 && major !== 11 && major !== 12) throw new DeptreeError(`pnpm ${quote(pnpm)} is not supported: only pnpm 10, 11 and 12 are`, 'host.pnpm')
22
- if (major === 12 && compareVersions(pnpm, '12.8.1') < 0) throw new DeptreeError(`pnpm ${quote(pnpm)} is not supported: pnpm 12 is from 12.8.1 on`, 'host.pnpm')
45
+ if (major < 9 || major > 12 || !Number.isInteger(major)) throw new DeptreeError(`pnpm ${quote(pnpm)} is not supported: only pnpm 9, 10, 11 and 12 are`, 'host.pnpm')
46
+ if (major in SINCE && compareVersions(pnpm, SINCE[major]) < 0) throw new DeptreeError(`pnpm ${quote(pnpm)} is not supported: pnpm ${major} is from ${SINCE[major]} on`, 'host.pnpm')
23
47
  return major
24
48
  }
25
49
 
26
- // The pnpm that installs, and its major version: `pnpm`, host.pnpm, or
27
- // where that is left out, the one the root package.json pins by its
28
- // packageManager, which is the only one it takes; `root` gives that
29
- // package.json as parsed, and is called only then.
50
+ // `root` reads the root package.json, only where host.pnpm is left out.
30
51
  function pnpmOf(pnpm, root) {
31
52
  if (pnpm !== undefined && (typeof pnpm !== 'string' || pnpm === '')) throw new TypeError('host.pnpm must be a non-empty string, or left out')
32
53
  const version = pnpm ?? pinnedPnpm(root()?.packageManager)
@@ -36,10 +57,7 @@ function pnpmOf(pnpm, root) {
36
57
 
37
58
  // All of host but its pnpm, which pnpmOf reads.
38
59
  export function checkHost(host) {
39
- if (host === null || typeof host !== 'object') throw new TypeError('host must be an object with node, os, cpu and libc, and pnpm where it is not pinned')
40
- for (const key of ['node', 'os', 'cpu', 'libc']) {
41
- if (typeof host[key] !== 'string' || host[key] === '') throw new TypeError(`host.${key} must be a non-empty string`)
42
- }
60
+ checkHostKeys(host, ['node', 'os', 'cpu', 'libc'], 'node, os, cpu and libc, and pnpm where it is not pinned')
43
61
  const { node, os, libc } = host
44
62
  if (valid(node) === null) throw new DeptreeError(`${quote(node)} is not an exact version`, 'host.node')
45
63
  if (os === 'win32') throw new DeptreeError('Windows is not supported: pnpm links there with junctions to absolute paths', 'host.os')
@@ -57,19 +75,16 @@ function readNamed(file, read, text) {
57
75
  }
58
76
  }
59
77
 
60
- // Before any install, pnpm 11 may write the env document alone, with no lockfile to install from.
61
78
  export function readLockfile(text) {
62
79
  const read = readNamed('pnpm-lock.yaml', parsePnpmLockfile, text)
63
80
  if (read.lockfile === undefined) throw new DeptreeError('it holds the env document pnpm 11 writes alone, not the project\'s lockfile, which a frozen install cannot do without', 'pnpm-lock.yaml')
64
81
  return read
65
82
  }
66
83
 
67
- // pnpm-workspace.yaml as parsed; one of comments alone, or nothing, sets
68
- // nothing, as pnpm reads it.
84
+ // One of comments alone, or empty, sets nothing, as pnpm reads it.
69
85
  const readWorkspace = (text) => (text === undefined || /^(?:[\t ]*(?:#.*)?(?:\r?\n|$))*$/u.test(text) ? undefined : readNamed('pnpm-workspace.yaml', parseYaml, text))
70
86
 
71
- // The root package.json in `project`, as parsed, where there is one; one
72
- // that is a link is refused unread, as findProjects refuses it.
87
+ // A root package.json that is a link is refused unread, as findProjects does.
73
88
  const ROOT = 'manifests["."]'
74
89
  function readRoot(project) {
75
90
  if (typeOf(project, '/package.json', false) === 'symlink') throw linkedManifest('package.json')
@@ -77,79 +92,81 @@ function readRoot(project) {
77
92
  return text === undefined ? undefined : readManifest(text, ROOT)
78
93
  }
79
94
 
80
- // pnpm-workspace.yaml as pnpm 12 has it where there is none: of the root
81
- // package.json's `workspaces` list, its strings but empty ones are the
82
- // packages, as pnpm 12 writes a pnpm-workspace.yaml of them. `text` is
83
- // pnpm-workspace.yaml's, and `workspace` as parsed.
95
+ // Where there is no pnpm-workspace.yaml, pnpm 12 writes one whose packages are
96
+ // the root package.json's non-empty `workspaces` strings. pnpm 9 takes one that
97
+ // sets nothing for `**`.
84
98
  function workspaceOf(workspace, text, major, root) {
99
+ if (major < 10) {
100
+ const mapping = workspace !== null && typeof workspace === 'object' && !Array.isArray(workspace)
101
+ if (text !== undefined && (workspace == null || (mapping && Object.keys(workspace).length === 0))) return { packages: ['**'] }
102
+ if (mapping && !workspace.packages) throw new DeptreeError('pnpm 9 fails on a workspace manifest that sets anything and no packages', 'pnpm-workspace.yaml: packages')
103
+ return workspace
104
+ }
85
105
  if (major < 12 || text !== undefined) return workspace
86
106
  const listed = root()?.workspaces
87
107
  const packages = Array.isArray(listed) ? listed.filter((pattern) => typeof pattern === 'string' && pattern !== '') : []
88
108
  return packages.length === 0 ? workspace : { packages }
89
109
  }
90
110
 
91
- // The packages of `workspace`, pnpm-workspace.yaml as parsed, read here
92
- // before the rest of it is, to find the projects by.
111
+ // Read before the rest of pnpm-workspace.yaml, to find the projects by.
93
112
  function packagesOf(workspace) {
94
113
  if (workspace !== undefined && (workspace === null || typeof workspace !== 'object' || Array.isArray(workspace))) throw new DeptreeError('expected a mapping', 'pnpm-workspace.yaml')
95
114
  return workspace?.packages === undefined ? undefined : readers.globs(workspace.packages, 'pnpm-workspace.yaml: packages')
96
115
  }
97
116
 
98
- // The directories of the projects pnpm finds in `project`, which
99
- // buildPnpmTree takes the package.json of each of.
117
+ // The pnpm that installs and the workspace it reads, from disk, with the root
118
+ // package.json read at most once.
119
+ function readInstalls(project, pnpm) {
120
+ let read
121
+ const root = () => (read ??= readRoot(project))
122
+ const installs = pnpmOf(pnpm, root)
123
+ const text = readWorkspaceText(project, installs.major)
124
+ const workspace = workspaceOf(readWorkspace(text), text, installs.major, root)
125
+ return { ...installs, workspace, packages: packagesOf(workspace) }
126
+ }
127
+
128
+ // The directories of the projects whose package.json buildPnpmTree takes.
100
129
  export function findPnpmProjects(options) {
101
130
  const { project, host } = options ?? {}
102
131
  checkProject(project)
103
132
  if (host !== undefined && (host === null || typeof host !== 'object')) throw new TypeError('host must be an object, or left out')
104
- const { major } = pnpmOf(host?.pnpm, () => readRoot(project))
105
- const text = readWorkspaceText(project)
106
- return findProjects(project, packagesOf(workspaceOf(readWorkspace(text), text, major, () => readRoot(project))), major)
133
+ const { major, packages } = readInstalls(project, host?.pnpm)
134
+ return findProjects(project, packages, major)
107
135
  }
108
136
 
109
137
  const LOCKFILE = 'lockfile must be the text of pnpm-lock.yaml, or left out with a project given to read it from'
110
138
 
111
- // The files an install reads but the package.json and the patches: given,
112
- // with `lockfile`, or read from `project` without it.
113
139
  export function inputsOf(options) {
114
140
  const { lockfile, manifests, workspace, npmrc, patches, project } = options
115
141
  if (lockfile === undefined) {
116
142
  if (project === undefined) throw new TypeError(LOCKFILE)
117
- for (const [name, value] of Object.entries({ manifests, workspace, npmrc, patches })) {
118
- if (value !== undefined) throw new TypeError(`${name} must be left out where lockfile is: both are read from project`)
119
- }
120
- return { reading: true, project, ...readRootFiles(project) }
143
+ checkLeftOut({ manifests, workspace, npmrc, patches })
144
+ const text = readText(project, '/pnpm-lock.yaml')
145
+ if (text === undefined) throw new DeptreeError('the project has no pnpm-lock.yaml, which a frozen install cannot do without')
146
+ // pnpm-workspace.yaml is read once the pnpm that installs is known.
147
+ return { reading: true, project, lockfile: text, npmrc: readText(project, '/.npmrc') }
121
148
  }
122
149
  if (typeof lockfile !== 'string') throw new TypeError(LOCKFILE)
123
- for (const [name, value] of Object.entries({ workspace, npmrc })) {
124
- if (value !== undefined && typeof value !== 'string') throw new TypeError(`${name} must be a string, or left out`)
125
- }
150
+ checkTexts({ workspace, npmrc })
126
151
  return { reading: false, lockfile, manifests, workspace, npmrc, patches }
127
152
  }
128
153
 
129
- // The package.json of every project, the pnpm that installs as pnpmOf
130
- // reads it from the root one, and pnpm-workspace.yaml as workspaceOf has
131
- // it: as given, or read from the project for each project pnpm finds
132
- // there, and no other, as pnpm reads them: an importer the globs do not
133
- // take is refused first, and one they take that pnpm does not find has
134
- // none. `pnpm` is host.pnpm.
154
+ // An importer the globs do not take is refused first; one they take that pnpm
155
+ // does not find has no package.json.
135
156
  export function manifestsOf(inputs, lockfile, pnpm) {
136
- const workspace = readWorkspace(inputs.workspace)
137
157
  if (!inputs.reading) {
158
+ const workspace = readWorkspace(inputs.workspace)
138
159
  const manifests = readManifests(inputs.manifests, lockfile)
139
160
  const installs = pnpmOf(pnpm, () => manifests.get('.'))
140
161
  return { manifests, ...installs, workspace: workspaceOf(workspace, inputs.workspace, installs.major, () => manifests.get('.')) }
141
162
  }
142
163
  const { project } = inputs
143
- const installs = pnpmOf(pnpm, () => readRoot(project))
144
- const effective = workspaceOf(workspace, inputs.workspace, installs.major, () => readRoot(project))
145
- const packages = packagesOf(effective)
164
+ const { packages, ...installs } = readInstalls(project, pnpm)
146
165
  checkWorkspace(Object.keys(lockfile.importers), packages, installs.major)
147
166
  const ids = findProjects(project, packages, installs.major)
148
- return { manifests: readManifests(readManifestTexts(project, ids), lockfile), ...installs, workspace: effective }
167
+ return { manifests: readManifests(readManifestTexts(project, ids), lockfile), ...installs }
149
168
  }
150
169
 
151
- // The patch files, by path: as given, or read from the project, each that
152
- // `configured`, patchedDependencies, names.
153
170
  export function patchesOf(inputs, configured) {
154
171
  if (inputs.reading) return readPatches(inputs.project, configured)
155
172
  const entries = inputs.patches instanceof Map ? [...inputs.patches] : Object.entries(inputs.patches ?? {})