@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,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
@@ -0,0 +1,177 @@
1
+ // The host and the files an install reads, checked, as given or read from the
2
+ // project as pnpm reads them from disk.
3
+
4
+ import { LockfileError, YamlError, parsePnpmLockfile } from '@preventive/lockfile/pnpm.js'
5
+ import { parseYaml } from '@preventive/lockfile/yaml.js'
6
+ import { compareVersions, valid } from '@preventive/upstream/semver.js'
7
+ import { normalize } from '@preventive/vfs/path.js'
8
+ import { DeptreeError, quote } from '../error.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'
12
+ import { readers } from './readers.js'
13
+ import { checkWorkspace, findProjects, linkedManifest } from './workspace.js'
14
+
15
+ const LIBC = new Set(['glibc', 'musl', 'unknown'])
16
+
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' }
43
+ function majorOf(pnpm) {
44
+ const major = Number(valid(pnpm)?.split('.')[0])
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')
47
+ return major
48
+ }
49
+
50
+ // `root` reads the root package.json, only where host.pnpm is left out.
51
+ function pnpmOf(pnpm, root) {
52
+ if (pnpm !== undefined && (typeof pnpm !== 'string' || pnpm === '')) throw new TypeError('host.pnpm must be a non-empty string, or left out')
53
+ const version = pnpm ?? pinnedPnpm(root()?.packageManager)
54
+ if (version === undefined) throw new TypeError('host.pnpm must be given where the root package.json\'s packageManager pins no pnpm')
55
+ return { pnpm: version, major: majorOf(version) }
56
+ }
57
+
58
+ // All of host but its pnpm, which pnpmOf reads.
59
+ export function checkHost(host) {
60
+ checkHostKeys(host, ['node', 'os', 'cpu', 'libc'], 'node, os, cpu and libc, and pnpm where it is not pinned')
61
+ const { node, os, libc } = host
62
+ if (valid(node) === null) throw new DeptreeError(`${quote(node)} is not an exact version`, 'host.node')
63
+ if (os === 'win32') throw new DeptreeError('Windows is not supported: pnpm links there with junctions to absolute paths', 'host.os')
64
+ if (!LIBC.has(libc)) throw new DeptreeError(`expected "glibc", "musl" or "unknown", found ${quote(libc)}`, 'host.libc')
65
+ return { node, os, cpu: host.cpu, libc }
66
+ }
67
+
68
+ // Both files are YAML: unnamed, a refusal of one reads as one of the other.
69
+ function readNamed(file, read, text) {
70
+ try {
71
+ return read(text)
72
+ } catch (error) {
73
+ if (error instanceof LockfileError || error instanceof YamlError) throw new DeptreeError(error.message, file, { cause: error })
74
+ throw error
75
+ }
76
+ }
77
+
78
+ export function readLockfile(text) {
79
+ const read = readNamed('pnpm-lock.yaml', parsePnpmLockfile, text)
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')
81
+ return read
82
+ }
83
+
84
+ // One of comments alone, or empty, sets nothing, as pnpm reads it.
85
+ const readWorkspace = (text) => (text === undefined || /^(?:[\t ]*(?:#.*)?(?:\r?\n|$))*$/u.test(text) ? undefined : readNamed('pnpm-workspace.yaml', parseYaml, text))
86
+
87
+ // A root package.json that is a link is refused unread, as findProjects does.
88
+ const ROOT = 'manifests["."]'
89
+ function readRoot(project) {
90
+ if (typeOf(project, '/package.json', false) === 'symlink') throw linkedManifest('package.json')
91
+ const text = readText(project, '/package.json', ROOT)
92
+ return text === undefined ? undefined : readManifest(text, ROOT)
93
+ }
94
+
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 `**`.
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
+ }
105
+ if (major < 12 || text !== undefined) return workspace
106
+ const listed = root()?.workspaces
107
+ const packages = Array.isArray(listed) ? listed.filter((pattern) => typeof pattern === 'string' && pattern !== '') : []
108
+ return packages.length === 0 ? workspace : { packages }
109
+ }
110
+
111
+ // Read before the rest of pnpm-workspace.yaml, to find the projects by.
112
+ function packagesOf(workspace) {
113
+ if (workspace !== undefined && (workspace === null || typeof workspace !== 'object' || Array.isArray(workspace))) throw new DeptreeError('expected a mapping', 'pnpm-workspace.yaml')
114
+ return workspace?.packages === undefined ? undefined : readers.globs(workspace.packages, 'pnpm-workspace.yaml: packages')
115
+ }
116
+
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.
129
+ export function findPnpmProjects(options) {
130
+ const { project, host } = options ?? {}
131
+ checkProject(project)
132
+ if (host !== undefined && (host === null || typeof host !== 'object')) throw new TypeError('host must be an object, or left out')
133
+ const { major, packages } = readInstalls(project, host?.pnpm)
134
+ return findProjects(project, packages, major)
135
+ }
136
+
137
+ const LOCKFILE = 'lockfile must be the text of pnpm-lock.yaml, or left out with a project given to read it from'
138
+
139
+ export function inputsOf(options) {
140
+ const { lockfile, manifests, workspace, npmrc, patches, project } = options
141
+ if (lockfile === undefined) {
142
+ if (project === undefined) throw new TypeError(LOCKFILE)
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') }
148
+ }
149
+ if (typeof lockfile !== 'string') throw new TypeError(LOCKFILE)
150
+ checkTexts({ workspace, npmrc })
151
+ return { reading: false, lockfile, manifests, workspace, npmrc, patches }
152
+ }
153
+
154
+ // An importer the globs do not take is refused first; one they take that pnpm
155
+ // does not find has no package.json.
156
+ export function manifestsOf(inputs, lockfile, pnpm) {
157
+ if (!inputs.reading) {
158
+ const workspace = readWorkspace(inputs.workspace)
159
+ const manifests = readManifests(inputs.manifests, lockfile)
160
+ const installs = pnpmOf(pnpm, () => manifests.get('.'))
161
+ return { manifests, ...installs, workspace: workspaceOf(workspace, inputs.workspace, installs.major, () => manifests.get('.')) }
162
+ }
163
+ const { project } = inputs
164
+ const { packages, ...installs } = readInstalls(project, pnpm)
165
+ checkWorkspace(Object.keys(lockfile.importers), packages, installs.major)
166
+ const ids = findProjects(project, packages, installs.major)
167
+ return { manifests: readManifests(readManifestTexts(project, ids), lockfile), ...installs }
168
+ }
169
+
170
+ export function patchesOf(inputs, configured) {
171
+ if (inputs.reading) return readPatches(inputs.project, configured)
172
+ const entries = inputs.patches instanceof Map ? [...inputs.patches] : Object.entries(inputs.patches ?? {})
173
+ for (const [path, text] of entries) {
174
+ if (typeof text !== 'string') throw new TypeError(`patches[${quote(path)}] must be a string`)
175
+ }
176
+ return entries
177
+ }