@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
package/src/pnpm/tree.js CHANGED
@@ -1,72 +1,61 @@
1
- // A node_modules tree as pnpm 10, 11 or 12 installs it from a frozen lockfile
2
- // with the isolated linker, held in a Vfs rooted at the lockfile's directory:
3
- // each package's files at node_modules/.pnpm/<its directory>/node_modules/
4
- // <its name>, its dependencies linked beside it, the hoisted aliases in
5
- // node_modules/.pnpm/node_modules and node_modules, and each project's
6
- // direct dependencies in its own node_modules. Every link is relative, as
7
- // pnpm makes them outside Windows, and a `link:` leads where the lockfile
8
- // says whether or not anything is there: the tree holds node_modules and
9
- // nothing else of the projects.
10
- //
11
- // Not written: bins and their shims (node_modules/.bin), though what
12
- // linking them does to the files they run is (bins.js); .modules.yaml,
13
- // .pnpm/lock.yaml and the workspace state, which are pnpm's own; and
14
- // anything a lifecycle script would build. The tree is always the one
15
- // `pnpm install --ignore-scripts` makes: no script is run, a project's or
16
- // a dependency's, whatever the settings allow, and patches are applied all
17
- // the same, as pnpm applies them before any script.
18
- //
19
- // Each package is fetched once, and each snapshot's files composed in
20
- // memory — its package's, patched, bins fixed — before one write of each.
1
+ // The node_modules tree pnpm 9, 10, 11 or 12 installs from a frozen lockfile
2
+ // with the isolated linker and --ignore-scripts, in a Vfs rooted at the
3
+ // lockfile's directory; patched still, as pnpm patches before scripts. Bins are
4
+ // not linked, though what linking does to their files is (bins.js).
21
5
 
22
6
  import { packageKeyOf } from '@preventive/lockfile/pnpm.js'
23
- import { Vfs, VfsError } from '@preventive/vfs'
7
+ import { compareVersions } from '@preventive/upstream/semver.js'
8
+ import { Vfs } from '@preventive/vfs'
24
9
  import { dirname, relative } from '@preventive/vfs/path.js'
25
10
  import { eachConcurrently } from '../concurrent.js'
26
- import { DeptreeError, quote } from '../error.js'
27
- import { checkNoModules, mount } from '../mount.js'
11
+ import { DeptreeError, quote, refusalOf } from '../error.js'
12
+ import { checkNoModules, checkWrite, fold, isInside, makeDirs, mount, writeLink } from '../mount.js'
28
13
  import { applyPatch, parsePatch } from '../patch.js'
29
- import { REGISTRY, checkDependencies, checkManifest, fetchPackage, sameBytes, tarballUrl } from '../tarball.js'
30
- import { binTargets, checkPatchOfBins, fixBin, requiresBuild } from './bins.js'
14
+ import { checkProject, typeOf } from '../project.js'
15
+ import { REGISTRY, tarballUrl } from '../tarball.js'
16
+ import { binTargets, checkPatchOfBins, executableMode, fixBin, hoistedBinTargets, requiresBuild } from './bins.js'
31
17
  import { buildGraph } from './graph.js'
32
18
  import { hoist } from './hoist.js'
19
+ import { hoistedBuilds, hoistedLayout, hoistedModules, packageIdOf, prodPackages, workspaceHoists } from './hoisted.js'
33
20
  import { checkLocalOverrides, createFreshnessCheck, readDirectoryPackage, readLinked } from './local.js'
34
21
  import { createPatchedCheck, skippedSnapshots } from './install.js'
35
- import { checkCollisions, checkLinks, checkOptional } from './checks.js'
22
+ import { checkDependencies, fetchPackage } from './package.js'
23
+ import { checkLinks, checkOptional } from './checks.js'
36
24
  import { createHook } from './hook.js'
37
25
  import { listOverrides } from './overrides.js'
38
26
  import { checkHost, inputsOf, manifestsOf, patchesOf, readLockfile } from './inputs.js'
39
- import { checkProject } from './project.js'
40
27
  import { checkProjects, pinsPnpm, workspaceNames } from './projects.js'
41
28
  import { readSettings } from './settings.js'
42
29
  import { checkUpToDate } from './uptodate.js'
43
30
  import { checkWorkspace } from './workspace.js'
44
31
 
45
- // What the lockfile holds that no tree is built for here.
46
- function checkLockfile(lockfile) {
32
+ // A project inside a node_modules would be inside the tree; on macOS, a
33
+ // node_modules in any case is one.
34
+ function checkProjectsOutside(ids, folded) {
35
+ for (const id of ids) {
36
+ if (id.split('/').some((name) => name === 'node_modules' || (folded && fold(name) === 'node_modules'))) throw new DeptreeError('a project inside node_modules would be inside the tree', `importers[${quote(id)}]`)
37
+ }
38
+ }
39
+
40
+ function checkLockfile(lockfile, folded) {
47
41
  if (lockfile.settings.excludeLinksFromLockfile) throw new DeptreeError('links left out of the lockfile would be left out of the tree', 'settings.excludeLinksFromLockfile')
48
42
  if (lockfile.settings.injectWorkspacePackages) throw new DeptreeError('injected workspace packages are not supported', 'settings.injectWorkspacePackages')
49
43
  if (lockfile.pnpmfileChecksum !== undefined) throw new DeptreeError('a pnpmfile\'s hooks are not run here', 'pnpmfileChecksum')
44
+ checkProjectsOutside(Object.keys(lockfile.importers), folded)
50
45
  for (const [id, importer] of Object.entries(lockfile.importers)) {
51
46
  if (id === '..' || id.startsWith('../')) throw new DeptreeError('a project outside the lockfile\'s directory is not supported', `importers[${quote(id)}]`)
52
- if (id.split('/').includes('node_modules')) throw new DeptreeError('a project inside node_modules would be inside the tree', `importers[${quote(id)}]`)
53
47
  for (const [name, meta] of Object.entries(importer.dependenciesMeta)) {
54
48
  if (meta.injected) throw new DeptreeError('an injected dependency is not supported', `importers[${quote(id)}].dependenciesMeta[${quote(name)}]`)
55
49
  }
56
50
  }
57
51
  }
58
52
 
59
- // A package fetched here comes from the public registry, as upstream
60
- // fetches it: its key is its name and version, and its resolution a
61
- // tarball there with a sha512. One pnpm installs from a directory is one
62
- // a `file:` override names, in `installed`, as local.js reads it, and is
63
- // not patched: pnpm installs its files by hardlinks, so a patch would be
64
- // applied to the directory's own.
53
+ // The lockfile reader holds a directory's key to it.
65
54
  function checkSource(node, installed) {
66
55
  const { key, pkg } = node
67
56
  const { resolution } = pkg
68
57
  if (resolution.type === 'directory') {
69
- if (packageKeyOf(key) !== `${pkg.name}@file:${resolution.directory}` || !installed.has(resolution.directory)) throw new DeptreeError('a dependency on a local directory is supported only where a file: override names it', quote(key))
58
+ if (!installed.has(resolution.directory)) throw new DeptreeError('a dependency on a local directory is supported only where a file: override names it', quote(key))
70
59
  if (pkg.patchHash !== undefined) throw new DeptreeError('a patch to a package pnpm installs from a directory is not supported: it would be applied to the directory\'s own files, which pnpm hardlinks', quote(key))
71
60
  return
72
61
  }
@@ -76,91 +65,60 @@ function checkSource(node, installed) {
76
65
  if (!resolution.integrity?.startsWith('sha512-')) throw new DeptreeError('expected a sha512 integrity', quote(key))
77
66
  }
78
67
 
79
- // What a package's snapshots all have of it, and it is fetched and held to.
80
- const PACKAGE_FIELDS = ['resolution', 'os', 'cpu', 'libc', 'hasBin', 'bundledDependencies']
81
- const packageFields = (pkg) => JSON.stringify(PACKAGE_FIELDS.map((field) => pkg[field]))
82
-
83
- // Each package's files and package.json, by its name and version: a
84
- // package is fetched once however many snapshots it has, a few at a time.
85
- // One installed from a directory is read from `project`, as npm-packlist
86
- // picks its files.
87
- async function fetchAll(nodes, project, major) {
88
- const packages = new Map()
89
- for (const { key, pkg } of nodes.values()) {
90
- const id = packageKeyOf(key)
91
- if (!packages.has(id)) packages.set(id, pkg)
92
- else if (packageFields(packages.get(id)) !== packageFields(pkg)) throw new DeptreeError(`its snapshots differ on what the package is: ${PACKAGE_FIELDS.join(', ')}`, quote(id))
93
- }
68
+ // By name@version, as the lockfile reader gives a package's snapshots one
69
+ // resolution and manifest.
70
+ async function fetchAll(nodes, project, host) {
71
+ const packages = new Map([...nodes.values()].map(({ key, pkg }) => [packageKeyOf(key), pkg]))
94
72
  const fetched = new Map()
95
73
  await eachConcurrently(packages, async ([id, pkg]) => {
96
- try {
97
- if (pkg.resolution.type === 'directory') {
98
- const got = readDirectoryPackage(project, pkg, quote(id), major)
99
- checkManifest(got.manifest, pkg, quote(id), major)
100
- fetched.set(id, { ...got, local: true })
101
- } else fetched.set(id, await fetchPackage(pkg, quote(id), major))
102
- } catch (error) {
103
- throw error instanceof DeptreeError ? error : new DeptreeError(error.message, quote(id), { cause: error })
104
- }
105
- })
74
+ fetched.set(id, pkg.resolution.type === 'directory' ? readDirectoryPackage(project, pkg, quote(id), host) : await fetchPackage(pkg, quote(id), host.major))
75
+ }, ([id]) => quote(id))
106
76
  return fetched
107
77
  }
108
78
 
109
- // Each node with its package's files and package.json, by its directory:
110
- // its dependencies held to the package.json, as `hook` reads it once for
111
- // each package; and the number of tarballs fetched.
112
- async function fetchNodes(nodes, hook, project, major, fresh) {
113
- const fetched = await fetchAll(nodes, project, major)
79
+ async function fetchNodes(nodes, lockfile, hook, project, host) {
80
+ const fetched = await fetchAll(nodes, project, host)
81
+ const fresh = createFreshnessCheck(lockfile, host.major)
114
82
  const byDir = new Map()
115
83
  for (const node of nodes.values()) {
116
84
  const id = packageKeyOf(node.key)
117
85
  const got = fetched.get(id)
118
86
  got.read ??= hook(got.manifest, `${quote(id)}: package.json`)
119
- checkDependencies(got.manifest, got.read, node.pkg, quote(node.key))
87
+ checkDependencies(got.manifest, got.read, node.pkg, lockfile.packages, quote(node.key))
120
88
  fresh?.(node, got.read)
121
89
  byDir.set(node.dir, { ...node, files: got.files, manifest: got.manifest })
122
90
  }
123
91
  return { byDir, tarballs: [...fetched.values()].filter((got) => !got.local).length }
124
92
  }
125
93
 
126
- // A package installed from a directory has one file for each of its
127
- // files, hardlinked into each of its snapshots: fixBin makes it
128
- // executable in all of them, though a CRLF `#!` line it rewrites is
129
- // written as a file of that snapshot's own. Each snapshot has its own
130
- // copy instead where pnpm builds the package, or, with pnpm 11 and 12,
131
- // where packageImportMethod is other than auto or hardlink. By
132
- // directory, the files a snapshot has made executable by another's:
133
- // `targets` is binTargets's.
94
+ // pnpm hardlinks a directory package's files into each of its snapshots, so a
95
+ // file fixBin makes executable in one is so in all (a CRLF `#!` it rewrites
96
+ // stays that snapshot's own), but where pnpm builds the package or, with
97
+ // pnpm 11 and 12, packageImportMethod is neither auto nor hardlink.
134
98
  function executableElsewhere(byDir, targets, packageImportMethod, major) {
135
- const linked = major < 11 || packageImportMethod === 'auto' || packageImportMethod === 'hardlink'
136
- const shared = [...byDir.values()].filter((node) => linked && node.pkg.resolution.type === 'directory' && !requiresBuild(node.manifest, node.files, major))
137
- const byPackage = new Map()
138
- for (const node of shared) {
139
- const id = packageKeyOf(node.key)
140
- if (!byPackage.has(id)) byPackage.set(id, new Set())
141
- for (const path of targets.get(node.dir) ?? []) byPackage.get(id).add(path)
142
- }
143
- const executable = new Map()
144
- for (const node of shared) {
99
+ if (major >= 11 && packageImportMethod !== 'auto' && packageImportMethod !== 'hardlink') return new Map()
100
+ const shared = [...byDir.values()].filter((node) => node.pkg.resolution.type === 'directory' && !requiresBuild(node.manifest, node.files, major))
101
+ const byPackage = Map.groupBy(shared, (node) => packageKeyOf(node.key))
102
+ return new Map(shared.map((node) => {
145
103
  const own = targets.get(node.dir) ?? new Set()
146
- executable.set(node.dir, new Set([...byPackage.get(packageKeyOf(node.key))].filter((path) => !own.has(path))))
147
- }
148
- return executable
104
+ const all = byPackage.get(packageKeyOf(node.key)).flatMap((other) => [...targets.get(other.dir) ?? []])
105
+ return [node.dir, new Set(all.filter((path) => !own.has(path)))]
106
+ }))
107
+ }
108
+
109
+ // A patch of `patches`, parsed once.
110
+ function parsedPatch(patches, hash) {
111
+ const patch = patches.get(hash)
112
+ patch.parsed ??= parsePatch(patch.text, patch.path)
113
+ return patch
149
114
  }
150
115
 
151
- // A snapshot's files as pnpm leaves them: its package's, the patch the
152
- // snapshot names applied, and what linking bins does to them: fixBin run
153
- // on `targets`, and `executable` made so. `checkPatched` is
154
- // createPatchedCheck's.
155
116
  function compose(node, patches, { targets, executable }, { major, checkPatched }) {
156
117
  const where = quote(node.key)
157
118
  let files = node.files
158
119
  const { patchHash } = node.pkg
159
120
  if (patchHash !== undefined) {
160
- if (!patches.has(patchHash)) throw new DeptreeError(`the patch ${patchHash} is not given`, where)
161
- const patch = patches.get(patchHash)
162
- patch.parsed ??= parsePatch(patch.text, patch.path)
163
- // Once for each package, whatever its snapshots.
121
+ const patch = parsedPatch(patches, patchHash)
164
122
  patch.applied ??= new WeakMap()
165
123
  if (!patch.applied.has(files)) patch.applied.set(files, applyPatch(files, patch.parsed, { createdMode: major >= 12 ? 0o644 : undefined }))
166
124
  files = patch.applied.get(files)
@@ -170,40 +128,79 @@ function compose(node, patches, { targets, executable }, { major, checkPatched }
170
128
  if (targets.size === 0 && executable.size === 0) return files
171
129
  files = new Map(files)
172
130
  for (const path of targets) files.set(path, fixBin(files.get(path), `${where}: ${quote(path)}`, major))
173
- for (const path of executable) files.set(path, { ...files.get(path), mode: 0o755 })
131
+ for (const path of executable) files.set(path, { ...files.get(path), mode: executableMode(files.get(path).mode, major) })
174
132
  return files
175
133
  }
176
134
 
177
- // Writes a file where nothing is, or the same file is: a write never
178
- // replaces anything else. The tree holds no links yet.
179
- function writeOnce(vfs, path, { data, mode }) {
180
- let there
181
- try {
182
- there = vfs.lstat(path)
183
- } catch (error) {
184
- if (!(error instanceof VfsError)) throw error
185
- vfs.mkdir(dirname(path), { recursive: true })
186
- vfs.writeFile(path, data, { mode })
187
- return true
135
+ function addMade(made, dir) {
136
+ for (let at = dir; !made.has(at) && at !== '/'; at = dirname(at)) made.add(at)
137
+ }
138
+
139
+ // Only this node writes under `dir`, and the tree holds no links yet, so `made`
140
+ // knows every directory there and no write needs a look first, which costs a
141
+ // thrown error where nothing is.
142
+ function writeNode(vfs, dir, files, stats) {
143
+ const root = `/${dir}`
144
+ if (typeOf(vfs, root, false) !== undefined) throw new DeptreeError('would be written over with something else', quote(dir))
145
+ const real = new Set()
146
+ makeDirs(vfs, dir, real)
147
+ const made = new Set([root])
148
+ for (const [path, file] of files) {
149
+ const at = `${root}/${path}`
150
+ if (file.directory) {
151
+ if (!isInside(path)) throw new DeptreeError('is not a path within the package', quote(at.slice(1)))
152
+ makeDirs(vfs, at.slice(1), real)
153
+ addMade(made, at)
154
+ continue
155
+ }
156
+ if (made.has(at)) throw new DeptreeError('would be written over with something else', quote(at.slice(1)))
157
+ const parent = dirname(at)
158
+ if (!made.has(parent)) {
159
+ makeDirs(vfs, parent.slice(1), real)
160
+ addMade(made, parent)
161
+ }
162
+ vfs.writeFile(checkWrite(vfs, dir, path, real), file.data, { mode: file.mode })
163
+ stats.files++
164
+ stats.bytes += file.data.length
188
165
  }
189
- if (there.type === 'file' && there.mode === mode && sameBytes(vfs.readFile(path), data)) return false
190
- throw new DeptreeError('would be written over with something else', quote(path.slice(1)))
191
166
  }
192
167
 
193
- // A link's target spelled from the directory the link is in, as pnpm's
194
- // symlink-dir spells it; a target may climb out of the tree, so both are
195
- // read under as many directories as it climbs.
168
+ // As pnpm's symlink-dir spells it. A target may climb out of the tree, so both
169
+ // are resolved under as many dummy directories as it climbs.
196
170
  function linkTarget(path, target) {
197
- const climbs = target.split('/').filter((segment) => segment === '..').length
198
- const root = '/_'.repeat(climbs)
171
+ const root = '/_'.repeat(target.split('/').filter((segment) => segment === '..').length)
199
172
  return relative(`${root}/${dirname(path)}`, `${root}/${target}`) || '.'
200
173
  }
201
174
 
202
- // Every link in the tree, by its path: each node's children beside it and,
203
- // but with pnpm 12, itself inside it where it depends on itself, then what
204
- // is hoisted, then each project's direct dependencies, which win over a
205
- // hoisted alias.
206
- // `byDir` is the graph by directory, and `hoisting` graph.js's.
175
+ // What no project's dependencies or optionalDependencies reach is dev-only.
176
+ function reachedInProd(importers, nodes, byDir) {
177
+ const reached = new Set(Object.values(importers)
178
+ .flatMap(({ dependencies, optionalDependencies }) => [...Object.values(dependencies), ...Object.values(optionalDependencies)])
179
+ .map((target) => nodes.get(target)?.dir)
180
+ .filter((dir) => byDir.has(dir)))
181
+ for (const dir of reached) {
182
+ for (const child of byDir.get(dir).children.values()) if (byDir.has(child)) reached.add(child)
183
+ }
184
+ return reached
185
+ }
186
+
187
+ function installedOf(node, dev, patches) {
188
+ const { key, name, dir, pkg: { version, resolution, optional, patchHash } } = node
189
+ return {
190
+ path: dir,
191
+ key,
192
+ name,
193
+ version,
194
+ integrity: resolution.integrity,
195
+ directory: resolution.directory,
196
+ dev,
197
+ optional,
198
+ patch: patchHash === undefined ? undefined : { hash: patchHash, path: patches.get(patchHash).path },
199
+ }
200
+ }
201
+
202
+ // Later links win: each node's children, then what is hoisted, then each
203
+ // project's direct dependencies.
207
204
  function linksOf(byDir, direct, settings, projects, major, hoisting) {
208
205
  const links = new Map()
209
206
  for (const node of byDir.values()) {
@@ -218,6 +215,59 @@ function linksOf(byDir, direct, settings, projects, major, hoisting) {
218
215
  return links
219
216
  }
220
217
 
218
+ // The import methods with which each copy of a package is its own.
219
+ const COPYING = new Set(['copy', 'clone', 'clone-or-copy'])
220
+
221
+ // The hoisted layout of pnpm 10 and 11 (hoisted.js): nothing but the packages
222
+ // and links, each copy a parent before what lands in its node_modules, as
223
+ // pnpm keeps only its state in node_modules/.pnpm.
224
+ async function buildHoisted({ lockfile, settings, host, project, hook, installed, manifests, names, patched, skipped }) {
225
+ const { major } = host
226
+ const since = (version) => compareVersions(host.pnpm, version) >= 0
227
+ if (!COPYING.has(settings.packageImportMethod)) {
228
+ throw new DeptreeError(`${quote(settings.packageImportMethod)} is not supported with the hoisted layout, which is built only where each copy of a package is its own: with copy, clone or clone-or-copy`, 'packageImportMethod')
229
+ }
230
+ const directories = since('11.24.0')
231
+ const { placed, links, projects } = hoistedLayout(lockfile, { autoInstallPeers: settings.autoInstallPeers, skipped, directories, rootLinks: since('11.28.1') })
232
+ if (since('11.28.0')) for (const [path, id] of workspaceHoists(placed, lockfile, settings, names)) links.set(path, id)
233
+ for (const node of placed.values()) checkSource(node, installed)
234
+ const { byDir, tarballs } = await fetchNodes(placed, lockfile, hook, project, host)
235
+ const linked = readLinked(links, byDir, manifests, project)
236
+ // pnpm builds where any patch is configured, though scripts are ignored.
237
+ const building = Object.keys(settings.patchedDependencies ?? {}).length > 0
238
+ const hardlinks = since('10.21.0')
239
+ const keepsModules = since('11.25.0')
240
+ const idOf = since('11.23.0') ? (key) => packageIdOf(key, lockfile.packages[key], directories) : (key) => key
241
+ const changesOf = (node) => parsedPatch(patched, node.pkg.patchHash).parsed
242
+ const builds = building ? hoistedBuilds(byDir, new Set(projects), (node) => node.pkg.patchHash !== undefined || requiresBuild(node.manifest, node.files, major), { hardlinks, keepsModules, idOf, changesOf, pnpm: host.pnpm }) : []
243
+ const targets = hoistedBinTargets({ nodes: byDir, projects: new Map([...manifests, ...linked]), modules: hoistedModules(byDir, links, projects, manifests, lockfile), builds, hardlinks, keepsModules, idOf, major })
244
+ const prod = prodPackages(lockfile, skipped, directories)
245
+ return { byDir, links, targets, executable: new Map(), tarballs, dev: (node) => !prod.has(packageIdOf(node.key, node.pkg, directories)) }
246
+ }
247
+
248
+ // The isolated layout: each package in node_modules/.pnpm, linked from what
249
+ // needs it and where it is hoisted.
250
+ async function buildIsolated({ lockfile, settings, host, project, hook, installed, manifests, names, skipped }) {
251
+ const { major } = host
252
+ const { nodes, direct, hoisting } = await buildGraph(lockfile, skipped, settings.virtualStoreDirMaxLength, major)
253
+ for (const node of nodes.values()) checkSource(node, installed)
254
+ const { byDir, tarballs } = await fetchNodes(nodes, lockfile, hook, project, host)
255
+ const links = linksOf(byDir, direct, settings, names, major, hoisting)
256
+ const linked = readLinked(links, byDir, manifests, project)
257
+ const targets = binTargets({
258
+ nodes: byDir,
259
+ projects: new Map([...manifests, ...linked]),
260
+ direct,
261
+ links,
262
+ publicHoist: settings.publicHoistPattern?.length > 0,
263
+ building: Object.keys(settings.patchedDependencies ?? {}).length > 0,
264
+ peers: settings.autoInstallPeers,
265
+ major,
266
+ })
267
+ const prod = reachedInProd(lockfile.importers, nodes, byDir)
268
+ return { byDir, links, targets, executable: executableElsewhere(byDir, targets, settings.packageImportMethod, major), tarballs, dev: (node) => !prod.has(node.dir) }
269
+ }
270
+
221
271
  export async function buildPnpmTree(options) {
222
272
  const { project, host: given, vfs: into } = options ?? {}
223
273
  if (into !== undefined && !(into instanceof Vfs)) throw new TypeError('vfs must be a Vfs, or left out')
@@ -230,75 +280,53 @@ export async function buildPnpmTree(options) {
230
280
  const { lockfile, env } = readLockfile(inputs.lockfile)
231
281
  if (!('.' in lockfile.importers)) throw new DeptreeError('expected the root project, whose package.json holds settings', 'importers')
232
282
  // Before the project is read for any importer: none leads out of it.
233
- checkLockfile(lockfile)
283
+ checkLockfile(lockfile, folded)
234
284
  const { manifests, pnpm, major, workspace } = manifestsOf(inputs, lockfile, given.pnpm)
285
+ // Again with the projects given that the lockfile has no importer for.
286
+ checkProjectsOutside(Object.keys(lockfile.importers), folded)
235
287
  const host = { pnpm, major, ...machine }
236
- // pnpm 11 locks config dependencies there, which are refused, and the
237
- // pnpm a project pins, which leaves the tree as it is.
238
- if (env !== undefined && host.major < 11) throw new DeptreeError('the env document pnpm 11 writes is not supported', 'env')
288
+ // The env document locks config dependencies, refused, and the pnpm a project
289
+ // pins, which leaves the tree as it is.
290
+ if (env !== undefined && major < 11) throw new DeptreeError('the env document pnpm 11 writes is not supported', 'env')
239
291
  if (env !== undefined && Object.keys(env.importers['.'].configDependencies).length > 0) throw new DeptreeError('config dependencies are not supported', 'env.importers["."].configDependencies')
240
- const settings = readSettings({ workspace, npmrc: inputs.npmrc, manifest: manifests.get('.'), major: host.major, pinned: pinsPnpm(manifests.get('.'), host.pnpm) })
241
- checkWorkspace(Object.keys(lockfile.importers), settings.packages, host.major)
242
- const overrides = listOverrides(settings.overrides, settings.catalogs, host.major)
292
+ // As pnpm 9, 10 and 11 write the lockfile's own directory.
293
+ const empty = major >= 12 ? Object.keys(lockfile.packages).find((key) => packageKeyOf(key).endsWith('@file:')) : undefined
294
+ if (empty !== undefined) throw new DeptreeError('pnpm 12 refuses as broken a lockfile with `file:` and an empty path', quote(empty))
295
+ const settings = readSettings({ workspace, npmrc: inputs.npmrc, manifest: manifests.get('.'), major, pinned: pinsPnpm(manifests.get('.'), host.pnpm) })
296
+ checkWorkspace(Object.keys(lockfile.importers), settings.packages, major)
297
+ const overrides = listOverrides(settings.overrides, settings.catalogs, major)
243
298
  const installed = checkLocalOverrides(overrides, project)
244
- const patches = patchesOf(inputs, settings.patchedDependencies)
245
- const patched = await checkUpToDate(lockfile, settings, overrides, patches, host.major)
246
- const hook = createHook({ overrides, ignored: settings.ignoredOptionalDependencies, major: host.major })
299
+ const patched = await checkUpToDate(lockfile, settings, overrides, patchesOf(inputs, settings.patchedDependencies), major)
300
+ const hook = createHook({ overrides, ignored: settings.ignoredOptionalDependencies, major })
247
301
  checkProjects(lockfile, manifests, { hook, host, settings, env })
248
302
  checkOptional(lockfile)
249
- const projects = settings.hoistWorkspacePackages ? workspaceNames(manifests) : new Map()
303
+ const names = settings.hoistWorkspacePackages ? workspaceNames(manifests) : new Map()
250
304
  const { skipped, incompatible } = skippedSnapshots(lockfile, { host, settings })
251
- const { nodes, direct, hoisting } = await buildGraph(lockfile, skipped, settings.virtualStoreDirMaxLength, host.major)
252
- for (const node of nodes.values()) checkSource(node, installed)
253
-
254
- const { byDir, tarballs } = await fetchNodes(nodes, hook, project, host.major, createFreshnessCheck(lockfile, host.major))
255
- const links = linksOf(byDir, direct, settings, projects, host.major, hoisting)
256
- const linked = readLinked(links, byDir, manifests, project)
257
- const targets = binTargets({
258
- nodes: byDir,
259
- projects: new Map([...manifests, ...linked]),
260
- direct,
261
- links,
262
- publicHoist: settings.publicHoistPattern?.length > 0,
263
- building: Object.keys(settings.patchedDependencies ?? {}).length > 0,
264
- peers: settings.autoInstallPeers,
265
- major: host.major,
266
- })
267
- const executable = executableElsewhere(byDir, targets, settings.packageImportMethod, host.major)
305
+ const hoisted = settings.nodeLinker === 'hoisted'
306
+ const { byDir, links, targets, executable, tarballs, dev } = await (hoisted ? buildHoisted : buildIsolated)({ lockfile, settings, host, project, hook, installed, manifests, names, patched, skipped })
268
307
 
269
308
  const vfs = new Vfs()
270
- vfs.mkdir('/node_modules/.pnpm', { recursive: true })
271
- const stats = { projects: manifests.size, snapshots: Object.keys(lockfile.packages).length, installed: nodes.size, skipped: skipped.size, incompatible: incompatible.size, tarballs, patched: 0, files: 0, bytes: 0, links: links.size }
272
- const composing = { major: host.major, checkPatched: createPatchedCheck({ host, settings }) }
309
+ if (!hoisted) makeDirs(vfs, 'node_modules/.pnpm')
310
+ const stats = { projects: manifests.size, snapshots: Object.keys(lockfile.packages).length, installed: byDir.size, skipped: skipped.size, incompatible: incompatible.size, tarballs, patched: [...byDir.values()].filter((node) => node.pkg.patchHash !== undefined).length, files: 0, bytes: 0, links: links.size }
311
+ const listed = []
312
+ const composing = { major, checkPatched: createPatchedCheck({ host, settings }) }
273
313
  // Each node is let go once written, and a package's files with its last.
274
314
  for (const node of byDir.values()) {
275
315
  byDir.delete(node.dir)
276
- if (node.pkg.patchHash !== undefined) stats.patched++
277
316
  try {
278
- vfs.mkdir(`/${node.dir}`, { recursive: true })
279
- for (const [path, file] of compose(node, patched, { targets: targets.get(node.dir) ?? new Set(), executable: executable.get(node.dir) ?? new Set() }, composing)) {
280
- if (file.directory) vfs.mkdir(`/${node.dir}/${path}`, { recursive: true })
281
- else if (writeOnce(vfs, `/${node.dir}/${path}`, file)) {
282
- stats.files++
283
- stats.bytes += file.data.length
284
- }
285
- }
317
+ writeNode(vfs, node.dir, compose(node, patched, { targets: targets.get(node.dir) ?? new Set(), executable: executable.get(node.dir) ?? new Set() }, composing), stats)
286
318
  } catch (error) {
287
- if (error instanceof DeptreeError) throw error
288
- throw new DeptreeError(error.message, quote(node.key), { cause: error })
319
+ throw refusalOf(error, quote(node.key))
289
320
  }
321
+ listed.push(installedOf(node, dev(node), patched))
290
322
  }
291
323
  for (const [path, target] of links) {
292
324
  try {
293
- vfs.mkdir(dirname(`/${path}`), { recursive: true })
294
- vfs.symlink(linkTarget(path, target), `/${path}`)
325
+ writeLink(vfs, path, linkTarget(path, target))
295
326
  } catch (error) {
296
327
  throw new DeptreeError(`cannot be linked: ${error.message}`, quote(path), { cause: error })
297
328
  }
298
329
  }
299
330
  checkLinks(vfs, links)
300
- if (folded) checkCollisions(vfs)
301
- if (into === undefined) return { vfs, stats }
302
- mount(vfs, into, folded)
303
- return { vfs: into, stats }
331
+ return { vfs: mount(vfs, into, folded), stats, installed: listed }
304
332
  }
@@ -1,32 +1,21 @@
1
- // Whether the lockfile is the one pnpm would install as it is. Before a
2
- // frozen install pnpm holds it to the settings that shaped its resolution
3
- // (@pnpm/lockfile.settings-checker's getOutdatedLockfileSetting): the
4
- // catalogs, the overrides, the package extensions' checksum, the optional
5
- // dependencies left out, the patches, and a few of its own settings. Where
6
- // one differs, `--frozen-lockfile` refuses to install, and so does this,
7
- // naming the setting as pnpm names it. An install here is always frozen.
8
- // pnpm 11 takes two git specifiers of one commit in a catalog alike, and
9
- // holds the patch hashes in the peers of a key to the patches too.
10
- //
11
- // The patches are hashed here, all of them, as pnpm reads every one it is
12
- // configured with, whether or not a package installed uses it; each has to
13
- // be given, by the path the settings name it by, and nothing else may be.
14
- // Only one a package installed uses is read as a patch, where it is
15
- // applied, as pnpm reads it.
1
+ // Refuses a lockfile a frozen install would refuse as out of date with the
2
+ // settings (@pnpm/lockfile.settings-checker's getOutdatedLockfileSetting),
3
+ // naming the setting as pnpm names it. pnpm 9 holds the lockfile to neither the
4
+ // catalogs nor dedupePeers.
16
5
 
17
6
  import { normalize } from '@preventive/vfs/path.js'
18
7
  import { DeptreeError, difference, quote } from '../error.js'
19
- import { sha256Hex } from '../hash.js'
8
+ import { md5Base32, sha256Hex } from '../hash.js'
20
9
  import { sameSpecifier } from './frozen.js'
10
+ import { catalogEntry } from './overrides.js'
21
11
  import { checkPatchUse, checkPeerPatches } from './patches.js'
22
12
 
23
13
  const outdated = (name, detail) => new DeptreeError(`${detail}, which a frozen install refuses`, name)
24
14
 
25
15
  const SIDES = ['the lockfile', 'the settings']
26
16
 
27
- // By selector, the hash and path pnpm computes of each configured patch,
28
- // and by hash, the patch's text and path. `given` is the files by path.
29
- async function hashPatches(configured, given) {
17
+ // `hashes` is { hash, path } by selector, `byHash` { text, path } by hash.
18
+ async function hashPatches(configured, given, major) {
30
19
  const texts = new Map()
31
20
  for (const [key, text] of given) {
32
21
  const path = normalize(key)
@@ -41,7 +30,9 @@ async function hashPatches(configured, given) {
41
30
  named.add(path)
42
31
  if (!texts.has(path)) throw new DeptreeError(`the patch ${quote(path)} is not given, and pnpm reads every patch it is configured with`, `patchedDependencies[${quote(selector)}]`)
43
32
  const text = texts.get(path)
44
- const hash = await sha256Hex(text.replaceAll('\r\n', '\n'), `patches[${quote(path)}]`)
33
+ const normalized = text.replaceAll('\r\n', '\n')
34
+ const where = `patches[${quote(path)}]`
35
+ const hash = major < 10 ? md5Base32(normalized, where) : await sha256Hex(normalized, where)
45
36
  hashes[selector] = { hash, path }
46
37
  if (!byHash.has(hash)) byHash.set(hash, { text, path })
47
38
  }
@@ -58,14 +49,11 @@ function checkPatches(locked, hashes, major) {
58
49
  if (detail !== undefined) throw outdated('patchedDependencies', `the patches differ: ${detail}`)
59
50
  }
60
51
 
61
- // Throws where pnpm would not install the lockfile as it is; hands back the
62
- // patches by hash, their text and path, to apply where a snapshot names one.
63
- // `overrides` is listOverrides's.
64
52
  export async function checkUpToDate(lockfile, settings, overrides, given, major) {
65
- const { hashes, byHash } = await hashPatches(settings.patchedDependencies, given)
66
- for (const [name, catalog] of Object.entries(lockfile.catalogs)) {
53
+ const { hashes, byHash } = await hashPatches(settings.patchedDependencies, given, major)
54
+ for (const [name, catalog] of major < 10 ? [] : Object.entries(lockfile.catalogs)) {
67
55
  for (const [alias, { specifier }] of Object.entries(catalog)) {
68
- const configured = settings.catalogs[name]?.[alias]
56
+ const configured = catalogEntry(settings.catalogs, name, alias)
69
57
  if (!sameSpecifier(specifier, configured, major)) throw outdated('catalogs', `${quote(alias)} is ${quote(specifier)} in the lockfile's catalog ${quote(name)}, and ${configured === undefined ? 'nothing' : quote(configured)} in the settings`)
70
58
  }
71
59
  }
@@ -79,9 +67,9 @@ export async function checkUpToDate(lockfile, settings, overrides, given, major)
79
67
  checkPatches(lockfile.patchedDependencies, hashes, major)
80
68
  const locked = lockfile.settings
81
69
  if (locked.autoInstallPeers !== undefined && locked.autoInstallPeers !== settings.autoInstallPeers) throw outdated('settings.autoInstallPeers', `autoInstallPeers is ${locked.autoInstallPeers} in the lockfile`)
82
- if (Boolean(locked.dedupePeers) !== settings.dedupePeers) throw outdated('settings.dedupePeers', `dedupePeers is ${Boolean(locked.dedupePeers)} in the lockfile`)
70
+ if (major >= 10 && Boolean(locked.dedupePeers) !== settings.dedupePeers) throw outdated('settings.dedupePeers', `dedupePeers is ${Boolean(locked.dedupePeers)} in the lockfile`)
83
71
  if ((locked.peersSuffixMaxLength ?? 1000) !== settings.peersSuffixMaxLength) throw outdated('settings.peersSuffixMaxLength', `peersSuffixMaxLength is ${locked.peersSuffixMaxLength ?? 'left at 1000'} in the lockfile`)
84
- checkPatchUse(lockfile, hashes)
72
+ checkPatchUse(lockfile, hashes, major)
85
73
  if (major >= 11) checkPeerPatches(lockfile, hashes)
86
74
  return byHash
87
75
  }