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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. package/LICENSE-APACHE +202 -0
  2. package/bin/compare.js +132 -0
  3. package/bin/deptree.js +211 -0
  4. package/bin/npmrc.js +21 -0
  5. package/cargo.d.ts +223 -0
  6. package/cargo.js +6 -0
  7. package/npm.d.ts +321 -0
  8. package/npm.js +7 -0
  9. package/package.json +93 -11
  10. package/pnpm.d.ts +422 -60
  11. package/pnpm.js +3 -8
  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 +128 -39
  27. package/src/npm/bins.js +54 -0
  28. package/src/npm/compat.js +97 -0
  29. package/src/npm/dev-engines.js +52 -0
  30. package/src/npm/graph.js +68 -0
  31. package/src/npm/inputs.js +75 -0
  32. package/src/npm/manifests.js +130 -0
  33. package/src/npm/package.js +57 -0
  34. package/src/npm/ratio.js +34 -0
  35. package/src/npm/settings.js +67 -0
  36. package/src/npm/tree.js +139 -0
  37. package/src/npm/versions.js +20 -0
  38. package/src/npmrc.js +24 -0
  39. package/src/patch.js +26 -45
  40. package/src/pnpm/bins.js +207 -327
  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 +47 -81
  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 +97 -59
  49. package/src/pnpm/hoisted.js +234 -0
  50. package/src/pnpm/hook.js +37 -51
  51. package/src/pnpm/inputs.js +177 -0
  52. package/src/pnpm/install.js +140 -130
  53. package/src/pnpm/local.js +105 -34
  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 +20 -53
  59. package/src/pnpm/package.js +123 -0
  60. package/src/pnpm/packlist.js +194 -0
  61. package/src/pnpm/patches.js +21 -28
  62. package/src/pnpm/projects.js +150 -101
  63. package/src/pnpm/readers.js +122 -77
  64. package/src/pnpm/settings.js +85 -93
  65. package/src/pnpm/tree.js +234 -188
  66. package/src/pnpm/uptodate.js +17 -29
  67. package/src/pnpm/workspace.js +210 -53
  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 -125
  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
package/src/pnpm/tree.js CHANGED
@@ -1,288 +1,334 @@
1
- // A node_modules tree as pnpm 10 or 11 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
- import { packageKeyOf, parsePnpmLockfile } from '@preventive/lockfile/pnpm.js'
23
- import { parseYaml } from '@preventive/lockfile/yaml.js'
6
+ import { packageKeyOf } from '@preventive/lockfile/pnpm.js'
7
+ import { compareVersions } from '@preventive/upstream/semver.js'
24
8
  import { Vfs } from '@preventive/vfs'
25
9
  import { dirname, relative } from '@preventive/vfs/path.js'
26
- import { valid } from '@preventive/upstream/semver.js'
27
- import { DeptreeError, quote } from '../error.js'
28
- import { checkNoModules, mount } from '../mount.js'
10
+ import { eachConcurrently } from '../concurrent.js'
11
+ import { DeptreeError, quote, refusalOf } from '../error.js'
12
+ import { checkNoModules, checkWrite, fold, isInside, makeDirs, mount, writeLink } from '../mount.js'
29
13
  import { applyPatch, parsePatch } from '../patch.js'
30
- import { REGISTRY, checkDependencies, fetchPackage, tarballUrl } from '../tarball.js'
31
- import { binTargets, checkPatchOfBins, fixBin } from './bins.js'
14
+ import { checkProject, typeOf } from '../project.js'
15
+ import { NO_ABOUT, REGISTRY, fetchingOf, tarballUrl } from '../tarball.js'
16
+ import { binTargets, checkPatchOfBins, executableMode, fixBin, hoistedBinTargets, requiresBuild } from './bins.js'
32
17
  import { buildGraph } from './graph.js'
33
18
  import { hoist } from './hoist.js'
34
- import { checkLocalOverrides, readLinked } from './local.js'
35
- import { checkPatchedEngines, createCheck, skippedSnapshots } from './install.js'
36
- import { checkCollisions, checkLinks, checkOptional } from './checks.js'
19
+ import { hoistedBuilds, hoistedLayout, hoistedModules, packageIdOf, prodPackages, workspaceHoists } from './hoisted.js'
20
+ import { checkLocalOverrides, createFreshnessCheck, readDirectoryPackage, readLinked } from './local.js'
21
+ import { createPatchedCheck, skippedSnapshots } from './install.js'
22
+ import { checkDependencies, fetchPackage } from './package.js'
23
+ import { checkLinks, checkOptional } from './checks.js'
37
24
  import { createHook } from './hook.js'
38
25
  import { listOverrides } from './overrides.js'
39
- import { checkProjects, readManifests, workspaceNames } from './projects.js'
26
+ import { checkHost, inputsOf, manifestsOf, patchesOf, readLockfile } from './inputs.js'
27
+ import { checkProjects, pinsPnpm, workspaceNames } from './projects.js'
40
28
  import { readSettings } from './settings.js'
41
29
  import { checkUpToDate } from './uptodate.js'
42
30
  import { checkWorkspace } from './workspace.js'
43
31
 
44
- const CONCURRENCY = 8
45
- const LIBC = new Set(['glibc', 'musl', 'unknown'])
46
-
47
- function checkHost(host) {
48
- if (host === null || typeof host !== 'object') throw new TypeError('host must be an object with pnpm, node, os, cpu and libc')
49
- for (const key of ['pnpm', 'node', 'os', 'cpu', 'libc']) {
50
- if (typeof host[key] !== 'string' || host[key] === '') throw new TypeError(`host.${key} must be a non-empty string`)
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)}]`)
51
37
  }
52
- const { pnpm, node, os, libc } = host
53
- const major = Number(valid(pnpm)?.split('.')[0])
54
- // What pnpm 11 does differently is read below, by `major`, where it is.
55
- if (major !== 10 && major !== 11) throw new DeptreeError(`pnpm ${quote(pnpm)} is not supported: only pnpm 10 and 11 are`, 'host.pnpm')
56
- if (valid(node) === null) throw new DeptreeError(`${quote(node)} is not an exact version`, 'host.node')
57
- if (os === 'win32') throw new DeptreeError('Windows is not supported: pnpm links there with junctions to absolute paths', 'host.os')
58
- if (!LIBC.has(libc)) throw new DeptreeError(`expected "glibc", "musl" or "unknown", found ${quote(libc)}`, 'host.libc')
59
- return { pnpm, major, node, os, cpu: host.cpu, libc }
60
38
  }
61
39
 
62
- // What the lockfile holds that no tree is built for here.
63
- function checkLockfile(lockfile) {
40
+ function checkLockfile(lockfile, folded) {
64
41
  if (lockfile.settings.excludeLinksFromLockfile) throw new DeptreeError('links left out of the lockfile would be left out of the tree', 'settings.excludeLinksFromLockfile')
65
42
  if (lockfile.settings.injectWorkspacePackages) throw new DeptreeError('injected workspace packages are not supported', 'settings.injectWorkspacePackages')
66
43
  if (lockfile.pnpmfileChecksum !== undefined) throw new DeptreeError('a pnpmfile\'s hooks are not run here', 'pnpmfileChecksum')
44
+ checkProjectsOutside(Object.keys(lockfile.importers), folded)
67
45
  for (const [id, importer] of Object.entries(lockfile.importers)) {
68
46
  if (id === '..' || id.startsWith('../')) throw new DeptreeError('a project outside the lockfile\'s directory is not supported', `importers[${quote(id)}]`)
69
- if (id.split('/').includes('node_modules')) throw new DeptreeError('a project inside node_modules would be inside the tree', `importers[${quote(id)}]`)
70
47
  for (const [name, meta] of Object.entries(importer.dependenciesMeta)) {
71
48
  if (meta.injected) throw new DeptreeError('an injected dependency is not supported', `importers[${quote(id)}].dependenciesMeta[${quote(name)}]`)
72
49
  }
73
50
  }
74
51
  }
75
52
 
76
- // A package fetched here comes from the public registry, as upstream
77
- // fetches it: its key is its name and version, and its resolution a
78
- // tarball there with a sha512.
79
- function checkRegistry(node) {
53
+ // The lockfile reader holds a directory's key to it.
54
+ function checkSource(node, installed) {
80
55
  const { key, pkg } = node
81
56
  const { resolution } = pkg
57
+ if (resolution.type === 'directory') {
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))
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))
60
+ return
61
+ }
82
62
  const fromRegistry = pkg.version !== undefined && packageKeyOf(key) === `${pkg.name}@${pkg.version}` && resolution.type === 'tarball'
83
63
  && resolution.path === undefined && !resolution.gitHosted && (resolution.tarball ?? tarballUrl(pkg.name, pkg.version)) === tarballUrl(pkg.name, pkg.version)
84
64
  if (!fromRegistry) throw new DeptreeError(`only packages from ${REGISTRY} are supported`, quote(key))
85
65
  if (!resolution.integrity?.startsWith('sha512-')) throw new DeptreeError('expected a sha512 integrity', quote(key))
86
66
  }
87
67
 
88
- // What a package's snapshots all have of it, and it is fetched and held to.
89
- const PACKAGE_FIELDS = ['resolution', 'os', 'cpu', 'libc', 'hasBin', 'bundledDependencies']
90
- const packageFields = (pkg) => JSON.stringify(PACKAGE_FIELDS.map((field) => pkg[field]))
91
-
92
- // Each package's files and package.json, by its name and version: a
93
- // package is fetched once however many snapshots it has, a few at a time,
94
- // and the first failure stops the rest from starting.
95
- async function fetchAll(nodes) {
96
- const packages = new Map()
97
- for (const { key, pkg } of nodes.values()) {
98
- const id = packageKeyOf(key)
99
- if (!packages.has(id)) packages.set(id, pkg)
100
- else if (packageFields(packages.get(id)) !== packageFields(pkg)) throw new DeptreeError(`its snapshots differ on what the package is: ${PACKAGE_FIELDS.join(', ')}`, quote(id))
101
- }
102
- const queue = [...packages]
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, fetching) {
71
+ const packages = new Map([...nodes.values()].map(({ key, pkg }) => [packageKeyOf(key), pkg]))
103
72
  const fetched = new Map()
104
- let failed = false
105
- const worker = async () => {
106
- while (queue.length > 0 && !failed) {
107
- const [id, pkg] = queue.shift()
108
- try {
109
- fetched.set(id, await fetchPackage(pkg, quote(id)))
110
- } catch (error) {
111
- failed = true
112
- throw error instanceof DeptreeError ? error : new DeptreeError(error.message, quote(id), { cause: error })
113
- }
114
- }
115
- }
116
- await Promise.all(Array.from({ length: Math.min(CONCURRENCY, queue.length) }, worker))
73
+ await eachConcurrently(packages, async ([id, pkg]) => {
74
+ fetched.set(id, pkg.resolution.type === 'directory' ? readDirectoryPackage(project, pkg, quote(id), host) : await fetchPackage(pkg, quote(id), host.major, fetching))
75
+ }, ([id]) => quote(id))
117
76
  return fetched
118
77
  }
119
78
 
120
- // Each node with its package's files and package.json, by its directory:
121
- // its dependencies held to the package.json, as `hook` reads it once for
122
- // each package.
123
- async function fetchNodes(nodes, hook) {
124
- const fetched = await fetchAll(nodes)
79
+ async function fetchNodes(nodes, lockfile, hook, project, host, fetching) {
80
+ const fetched = await fetchAll(nodes, project, host, fetching)
81
+ const fresh = createFreshnessCheck(lockfile, host.major)
125
82
  const byDir = new Map()
126
83
  for (const node of nodes.values()) {
127
84
  const id = packageKeyOf(node.key)
128
85
  const got = fetched.get(id)
129
86
  got.read ??= hook(got.manifest, `${quote(id)}: package.json`)
130
- checkDependencies(got.manifest, got.read, node.pkg, quote(node.key))
131
- byDir.set(node.dir, { ...node, files: got.files, manifest: got.manifest })
87
+ checkDependencies(got.manifest, got.read, node.pkg, lockfile.packages, quote(node.key))
88
+ fresh?.(node, got.read)
89
+ byDir.set(node.dir, { ...node, files: got.files, manifest: got.manifest, about: got.about ?? NO_ABOUT })
132
90
  }
133
- return { byDir, tarballs: fetched.size }
91
+ return { byDir, tarballs: [...fetched.values()].filter((got) => !got.local).length }
92
+ }
93
+
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.
98
+ function executableElsewhere(byDir, targets, packageImportMethod, major) {
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) => {
103
+ const own = targets.get(node.dir) ?? new Set()
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
134
114
  }
135
115
 
136
- // A snapshot's files as pnpm leaves them: its package's, the patch the
137
- // snapshot names applied, and what linking bins does to them. `context`
138
- // is the host and settings.
139
- function compose(node, patches, targets, context) {
116
+ function compose(node, patches, { targets, executable }, { major, checkPatched }) {
140
117
  const where = quote(node.key)
141
118
  let files = node.files
142
119
  const { patchHash } = node.pkg
143
120
  if (patchHash !== undefined) {
144
- if (!patches.has(patchHash)) throw new DeptreeError(`the patch ${patchHash} is not given`, where)
145
- const patch = patches.get(patchHash)
146
- patch.parsed ??= parsePatch(patch.text, patch.path)
147
- files = applyPatch(files, patch.parsed)
148
- checkPatchedEngines(checkPatchOfBins(node, files, targets, where, context.host.major), where, context)
121
+ const patch = parsedPatch(patches, patchHash)
122
+ patch.applied ??= new WeakMap()
123
+ if (!patch.applied.has(files)) patch.applied.set(files, applyPatch(files, patch.parsed, { createdMode: major >= 12 ? 0o644 : undefined }))
124
+ files = patch.applied.get(files)
125
+ const manifest = checkPatchOfBins(node, files, targets, where, major)
126
+ checkPatched?.(manifest, where)
149
127
  }
150
- if (targets.size === 0) return files
128
+ if (targets.size === 0 && executable.size === 0) return files
151
129
  files = new Map(files)
152
- for (const path of targets) files.set(path, fixBin(files.get(path), `${where}: ${quote(path)}`))
130
+ for (const path of targets) files.set(path, fixBin(files.get(path), `${where}: ${quote(path)}`, major))
131
+ for (const path of executable) files.set(path, { ...files.get(path), mode: executableMode(files.get(path).mode, major) })
153
132
  return files
154
133
  }
155
134
 
156
- const sameBytes = (a, b) => a.length === b.length && a.every((byte, i) => byte === b[i])
135
+ function addMade(made, dir) {
136
+ for (let at = dir; !made.has(at) && at !== '/'; at = dirname(at)) made.add(at)
137
+ }
157
138
 
158
- // Writes a file where nothing is, or the same file is: a write never
159
- // replaces anything else.
160
- function writeOnce(vfs, path, { data, mode }) {
161
- if (vfs.isFile(path)) {
162
- if (vfs.lstat(path).mode === mode && sameBytes(vfs.readFile(path), data)) return false
163
- } else if (!vfs.isSymlink(path) && !vfs.isDirectory(path)) {
164
- vfs.mkdir(dirname(path), { recursive: true })
165
- vfs.writeFile(path, data, { mode })
166
- return true
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
167
165
  }
168
- throw new DeptreeError('would be written over with something else', quote(path.slice(1)))
169
166
  }
170
167
 
171
- // A link's target spelled from the directory the link is in, as pnpm's
172
- // symlink-dir spells it; a target may climb out of the tree, so both are
173
- // 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.
174
170
  function linkTarget(path, target) {
175
- const climbs = target.split('/').filter((segment) => segment === '..').length
176
- const root = '/_'.repeat(climbs)
171
+ const root = '/_'.repeat(target.split('/').filter((segment) => segment === '..').length)
177
172
  return relative(`${root}/${dirname(path)}`, `${root}/${target}`) || '.'
178
173
  }
179
174
 
180
- // Every link in the tree, by its path: each node's children beside it and
181
- // itself inside it where it depends on itself, then what is hoisted, then
182
- // each project's direct dependencies, which win over a hoisted alias.
183
- function linksOf(nodes, direct, settings, projects, major) {
184
- const byDir = new Map([...nodes.values()].map((node) => [node.dir, node]))
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, about, 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
+ ...about,
197
+ dev,
198
+ optional,
199
+ patch: patchHash === undefined ? undefined : { hash: patchHash, path: patches.get(patchHash).path },
200
+ }
201
+ }
202
+
203
+ // Later links win: each node's children, then what is hoisted, then each
204
+ // project's direct dependencies.
205
+ function linksOf(byDir, direct, settings, projects, major, hoisting) {
185
206
  const links = new Map()
186
- for (const node of nodes.values()) {
207
+ for (const node of byDir.values()) {
187
208
  for (const [alias, dir] of node.children) if (alias !== node.name) links.set(`${node.modules}/${alias}`, dir)
188
209
  const self = node.children.get(node.name)
189
- if (byDir.has(self)) links.set(`${node.dir}/node_modules/${node.name}`, self)
210
+ if (major < 12 && byDir.has(self)) links.set(`${node.dir}/node_modules/${node.name}`, self)
190
211
  }
191
- for (const [path, dir] of hoist(byDir, direct, settings, projects, major)) links.set(path, dir)
212
+ for (const [path, dir] of hoist(byDir, direct, settings, projects, major, hoisting)) links.set(path, dir)
192
213
  for (const [id, children] of direct) {
193
214
  for (const [alias, dir] of children) links.set(`${id === '.' ? '' : `${id}/`}node_modules/${alias}`, dir)
194
215
  }
195
216
  return links
196
217
  }
197
218
 
198
- // pnpm-workspace.yaml as parsed; one of comments alone, or nothing, sets
199
- // nothing, as pnpm reads it.
200
- const readWorkspace = (text) => (text === undefined || /^(?:[\t ]*(?:#.*)?(?:\r?\n|$))*$/u.test(text) ? undefined : parseYaml(text))
219
+ // The import methods with which each copy of a package is its own.
220
+ const COPYING = new Set(['copy', 'clone', 'clone-or-copy'])
201
221
 
202
- function readPatchesGiven(patches) {
203
- const entries = patches instanceof Map ? [...patches] : Object.entries(patches ?? {})
204
- for (const [path, text] of entries) {
205
- if (typeof text !== 'string') throw new TypeError(`patches[${quote(path)}] must be a string`)
222
+ // The hoisted layout of pnpm 10 and 11 (hoisted.js): nothing but the packages
223
+ // and links, each copy a parent before what lands in its node_modules, as
224
+ // pnpm keeps only its state in node_modules/.pnpm.
225
+ async function buildHoisted({ lockfile, settings, host, project, hook, installed, manifests, names, patched, skipped, fetching }) {
226
+ const { major } = host
227
+ const since = (version) => compareVersions(host.pnpm, version) >= 0
228
+ if (!COPYING.has(settings.packageImportMethod)) {
229
+ 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')
206
230
  }
207
- return entries
231
+ const directories = since('11.24.0')
232
+ const { placed, links, projects } = hoistedLayout(lockfile, { autoInstallPeers: settings.autoInstallPeers, skipped, directories, rootLinks: since('11.28.1') })
233
+ if (since('11.28.0')) for (const [path, id] of workspaceHoists(placed, lockfile, settings, names)) links.set(path, id)
234
+ for (const node of placed.values()) checkSource(node, installed)
235
+ const { byDir, tarballs } = await fetchNodes(placed, lockfile, hook, project, host, fetching)
236
+ const linked = readLinked(links, byDir, manifests, project)
237
+ // pnpm builds where any patch is configured, though scripts are ignored.
238
+ const building = Object.keys(settings.patchedDependencies ?? {}).length > 0
239
+ const hardlinks = since('10.21.0')
240
+ const keepsModules = since('11.25.0')
241
+ const idOf = since('11.23.0') ? (key) => packageIdOf(key, lockfile.packages[key], directories) : (key) => key
242
+ const changesOf = (node) => parsedPatch(patched, node.pkg.patchHash).parsed
243
+ 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 }) : []
244
+ const targets = hoistedBinTargets({ nodes: byDir, projects: new Map([...manifests, ...linked]), modules: hoistedModules(byDir, links, projects, manifests, lockfile), builds, hardlinks, keepsModules, idOf, major })
245
+ const prod = prodPackages(lockfile, skipped, directories)
246
+ return { byDir, links, targets, executable: new Map(), tarballs, dev: (node) => !prod.has(packageIdOf(node.key, node.pkg, directories)) }
208
247
  }
209
248
 
210
- export async function buildPnpmTree(options) {
211
- const { lockfile: text, manifests: manifestTexts, workspace, npmrc, patches, host: machine, vfs: into } = options ?? {}
212
- if (typeof text !== 'string') throw new TypeError('lockfile must be the text of pnpm-lock.yaml')
213
- if (into !== undefined && !(into instanceof Vfs)) throw new TypeError('vfs must be a Vfs, or left out')
214
- for (const [name, value] of [['workspace', workspace], ['npmrc', npmrc]]) {
215
- if (value !== undefined && typeof value !== 'string') throw new TypeError(`${name} must be a string, or left out`)
216
- }
217
- const host = checkHost(machine)
218
- // Refused before anything is fetched; mount checks again.
219
- if (into !== undefined) checkNoModules(into, host.os === 'darwin')
220
- const { lockfile, env } = parsePnpmLockfile(text)
221
- // pnpm 11 locks config dependencies there, which are refused, and the
222
- // pnpm a project pins, which leaves the tree as it is.
223
- if (env !== undefined && host.major < 11) throw new DeptreeError('the env document pnpm 11 writes is not supported', 'env')
224
- if (env !== undefined && Object.keys(env.importers['.'].configDependencies).length > 0) throw new DeptreeError('config dependencies are not supported', 'env.importers["."].configDependencies')
225
- if (!('.' in lockfile.importers)) throw new DeptreeError('expected the root project, whose package.json holds settings', 'importers')
226
- const manifests = readManifests(manifestTexts, lockfile)
227
- const settings = readSettings({ workspace: readWorkspace(workspace), npmrc, manifest: manifests.get('.'), os: host.os, major: host.major })
228
- checkLockfile(lockfile)
229
- checkWorkspace(Object.keys(lockfile.importers), settings.packages, host.major)
230
- const overrides = listOverrides(settings.overrides, settings.catalogs, host.major)
231
- checkLocalOverrides(overrides, into)
232
- const given = await checkUpToDate(lockfile, settings, overrides, readPatchesGiven(patches), host.major)
233
- const hook = createHook({ overrides, ignored: settings.ignoredOptionalDependencies, major: host.major })
234
- checkProjects(lockfile, manifests, { hook, host, settings })
235
- checkOptional(lockfile)
236
- const projects = settings.hoistWorkspacePackages ? workspaceNames(manifests) : new Map()
237
- const check = createCheck({ host, settings })
238
- const { skipped, incompatible } = skippedSnapshots(lockfile, check, { major: host.major, engineStrict: settings.engineStrict })
239
- const { nodes, direct } = await buildGraph(lockfile, skipped, settings.virtualStoreDirMaxLength, host.major)
240
- for (const node of nodes.values()) checkRegistry(node)
241
-
242
- const { byDir, tarballs } = await fetchNodes(nodes, hook)
243
- const links = linksOf(nodes, direct, settings, projects, host.major)
244
- const linked = readLinked(links, byDir, manifests, into)
249
+ // The isolated layout: each package in node_modules/.pnpm, linked from what
250
+ // needs it and where it is hoisted.
251
+ async function buildIsolated({ lockfile, settings, host, project, hook, installed, manifests, names, skipped, fetching }) {
252
+ const { major } = host
253
+ const { nodes, direct, hoisting } = await buildGraph(lockfile, skipped, settings.virtualStoreDirMaxLength, major)
254
+ for (const node of nodes.values()) checkSource(node, installed)
255
+ const { byDir, tarballs } = await fetchNodes(nodes, lockfile, hook, project, host, fetching)
256
+ const links = linksOf(byDir, direct, settings, names, major, hoisting)
257
+ const linked = readLinked(links, byDir, manifests, project)
245
258
  const targets = binTargets({
246
259
  nodes: byDir,
247
- projects: linked.size === 0 ? manifests : new Map([...manifests, ...linked]),
260
+ projects: new Map([...manifests, ...linked]),
248
261
  direct,
249
262
  links,
250
263
  publicHoist: settings.publicHoistPattern?.length > 0,
251
264
  building: Object.keys(settings.patchedDependencies ?? {}).length > 0,
252
265
  peers: settings.autoInstallPeers,
253
- major: host.major,
266
+ major,
254
267
  })
268
+ const prod = reachedInProd(lockfile.importers, nodes, byDir)
269
+ return { byDir, links, targets, executable: executableElsewhere(byDir, targets, settings.packageImportMethod, major), tarballs, dev: (node) => !prod.has(node.dir) }
270
+ }
271
+
272
+ export async function buildPnpmTree(options) {
273
+ const { project, host: given, vfs: into } = options ?? {}
274
+ if (into !== undefined && !(into instanceof Vfs)) throw new TypeError('vfs must be a Vfs, or left out')
275
+ const fetching = fetchingOf(options ?? {})
276
+ if (project !== undefined) checkProject(project)
277
+ const machine = checkHost(given)
278
+ const folded = machine.os === 'darwin'
279
+ // Refused before anything is fetched; mount checks again.
280
+ if (into !== undefined) checkNoModules(into, folded)
281
+ const inputs = inputsOf(options)
282
+ const { lockfile, env } = readLockfile(inputs.lockfile)
283
+ if (!('.' in lockfile.importers)) throw new DeptreeError('expected the root project, whose package.json holds settings', 'importers')
284
+ // Before the project is read for any importer: none leads out of it.
285
+ checkLockfile(lockfile, folded)
286
+ const { manifests, pnpm, major, workspace } = manifestsOf(inputs, lockfile, given.pnpm)
287
+ // Again with the projects given that the lockfile has no importer for.
288
+ checkProjectsOutside(Object.keys(lockfile.importers), folded)
289
+ const host = { pnpm, major, ...machine }
290
+ // The env document locks config dependencies, refused, and the pnpm a project
291
+ // pins, which leaves the tree as it is.
292
+ if (env !== undefined && major < 11) throw new DeptreeError('the env document pnpm 11 writes is not supported', 'env')
293
+ if (env !== undefined && Object.keys(env.importers['.'].configDependencies).length > 0) throw new DeptreeError('config dependencies are not supported', 'env.importers["."].configDependencies')
294
+ // As pnpm 9, 10 and 11 write the lockfile's own directory.
295
+ const empty = major >= 12 ? Object.keys(lockfile.packages).find((key) => packageKeyOf(key).endsWith('@file:')) : undefined
296
+ if (empty !== undefined) throw new DeptreeError('pnpm 12 refuses as broken a lockfile with `file:` and an empty path', quote(empty))
297
+ const settings = readSettings({ workspace, npmrc: inputs.npmrc, manifest: manifests.get('.'), major, pinned: pinsPnpm(manifests.get('.'), host.pnpm) })
298
+ checkWorkspace(Object.keys(lockfile.importers), settings.packages, major)
299
+ const overrides = listOverrides(settings.overrides, settings.catalogs, major)
300
+ const installed = checkLocalOverrides(overrides, project)
301
+ const patched = await checkUpToDate(lockfile, settings, overrides, patchesOf(inputs, settings.patchedDependencies), major)
302
+ const hook = createHook({ overrides, ignored: settings.ignoredOptionalDependencies, major })
303
+ checkProjects(lockfile, manifests, { hook, host, settings, env })
304
+ checkOptional(lockfile)
305
+ const names = settings.hoistWorkspacePackages ? workspaceNames(manifests) : new Map()
306
+ const { skipped, incompatible } = skippedSnapshots(lockfile, { host, settings })
307
+ const hoisted = settings.nodeLinker === 'hoisted'
308
+ const { byDir, links, targets, executable, tarballs, dev } = await (hoisted ? buildHoisted : buildIsolated)({ lockfile, settings, host, project, hook, installed, manifests, names, patched, skipped, fetching })
255
309
 
256
310
  const vfs = new Vfs()
257
- vfs.mkdir('/node_modules/.pnpm', { recursive: true })
258
- 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 }
311
+ if (!hoisted) makeDirs(vfs, 'node_modules/.pnpm')
312
+ 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 }
313
+ const listed = []
314
+ const composing = { major, checkPatched: createPatchedCheck({ host, settings }) }
315
+ // Each node is let go once written, and a package's files with its last.
259
316
  for (const node of byDir.values()) {
260
- if (node.pkg.patchHash !== undefined) stats.patched++
317
+ byDir.delete(node.dir)
261
318
  try {
262
- vfs.mkdir(`/${node.dir}`, { recursive: true })
263
- for (const [path, file] of compose(node, given, targets.get(node.dir) ?? new Set(), { host, settings })) {
264
- if (file.directory) vfs.mkdir(`/${node.dir}/${path}`, { recursive: true })
265
- else if (writeOnce(vfs, `/${node.dir}/${path}`, file)) {
266
- stats.files++
267
- stats.bytes += file.data.length
268
- }
269
- }
319
+ writeNode(vfs, node.dir, compose(node, patched, { targets: targets.get(node.dir) ?? new Set(), executable: executable.get(node.dir) ?? new Set() }, composing), stats)
270
320
  } catch (error) {
271
- if (error instanceof DeptreeError) throw error
272
- throw new DeptreeError(error.message, quote(node.key), { cause: error })
321
+ throw refusalOf(error, quote(node.key))
273
322
  }
323
+ listed.push(installedOf(node, dev(node), patched))
274
324
  }
275
325
  for (const [path, target] of links) {
276
326
  try {
277
- vfs.mkdir(dirname(`/${path}`), { recursive: true })
278
- vfs.symlink(linkTarget(path, target), `/${path}`)
327
+ writeLink(vfs, path, linkTarget(path, target))
279
328
  } catch (error) {
280
329
  throw new DeptreeError(`cannot be linked: ${error.message}`, quote(path), { cause: error })
281
330
  }
282
331
  }
283
332
  checkLinks(vfs, links)
284
- if (host.os === 'darwin') checkCollisions(vfs)
285
- if (into === undefined) return { vfs, stats }
286
- mount(vfs, into, host.os === 'darwin')
287
- return { vfs: into, stats }
333
+ return { vfs: mount(vfs, into, folded), stats, installed: listed }
288
334
  }
@@ -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
- export async function checkUpToDate(lockfile, settings, overrides, given, major = 10) {
65
- const { hashes, byHash } = await hashPatches(settings.patchedDependencies, given)
66
- for (const [name, catalog] of Object.entries(lockfile.catalogs)) {
52
+ export async function checkUpToDate(lockfile, settings, overrides, given, major) {
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
  }