@preventive/deptree 1.0.0-alpha.6 → 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.
@@ -0,0 +1,149 @@
1
+ // The hoist of @yarnpkg/nm 4.0.5, which pnpm 9 and 10 bundle for the hoisted
2
+ // linker: each package is moved as near the root as it can go without
3
+ // shadowing a different one of its name for a package that needs that one.
4
+ // Step for step as it runs, with its recursions on stacks of their own, and
5
+ // its debug output and checks left out, which change nothing. pnpm sets no
6
+ // hoisting limits, hoist priorities or external soft links, which are left
7
+ // out too: the root alone is a hoist border, and nothing depends on it.
8
+
9
+ import { DeptreeError } from '../error.js'
10
+ import { REGULAR, WORKSPACE, buildPreferenceMap, depthFirst, getHoistIdentMap, getUsedDependencies, getZeroRoundUsedDependencies, hoistGraph, regularDependencies, walk } from './nm-hoist-graph.js'
11
+
12
+ export { REGULAR, WORKSPACE, depthFirst, reachable } from './nm-hoist-graph.js'
13
+
14
+ const makeLocator = (name, reference) => `${name}@${reference}`
15
+ const makeIdent = (name, reference) => {
16
+ const hash = reference.indexOf('#')
17
+ return makeLocator(name, hash >= 0 ? reference.slice(hash + 1) : reference)
18
+ }
19
+ const getIdentName = (locator) => locator.slice(0, locator.indexOf('@', 1))
20
+
21
+ // The steps hoisting may take, and the nodes of the tree it gives, past
22
+ // which it is refused: on a graph made to defeat it, the hoist walks each
23
+ // path through what it cannot hoist, and the tree has a copy of a package
24
+ // for each, of which there can be more than there is time or memory for.
25
+ const MAX_STEPS = 50_000_000
26
+ const MAX_NODES = 100_000
27
+
28
+ function counter(limit, what, stats) {
29
+ let steps = 0
30
+ return (count = 1) => {
31
+ steps += count
32
+ if (stats !== undefined) stats[what] = steps
33
+ if (steps > limit) throw new DeptreeError(`hoisting it ${what}, which is not supported`, 'lockfile')
34
+ }
35
+ }
36
+
37
+ // hoistTo of one node: its hoisting, until no name has another ident to try.
38
+ function hoistToNode(rootNodePath, parentShadowedNodes, options, flags, step) {
39
+ const rootNode = rootNodePath.at(-1)
40
+ step(rootNodePath.length)
41
+ const preferenceMap = buildPreferenceMap(rootNode, step)
42
+ step(preferenceMap.size)
43
+ const hoistIdentMap = getHoistIdentMap(rootNode, preferenceMap)
44
+ const usedDependencies = rootNodePath.length === 1 ? new Map() : options.fastLookupPossible ? getZeroRoundUsedDependencies(rootNodePath, step) : getUsedDependencies(rootNodePath, step)
45
+ const hoistIdents = new Map([...hoistIdentMap].map(([name, idents]) => [name, idents[0]]))
46
+ const shadowedNodes = new Map()
47
+ let wasStateChanged
48
+ do {
49
+ const state = { rootNode, rootNodePath, usedDependencies, hoistIdents, parentShadowedNodes, shadowedNodes, options, step, seenNodes: new Set(), isGraphChanged: false, anotherRoundNeeded: false }
50
+ hoistGraph(state)
51
+ if (state.isGraphChanged) flags.isGraphChanged = true
52
+ if (state.anotherRoundNeeded) flags.anotherRoundNeeded = true
53
+ wasStateChanged = false
54
+ step(hoistIdentMap.size)
55
+ for (const [name, idents] of hoistIdentMap) {
56
+ if (idents.length > 1 && !rootNode.dependencies.has(name)) {
57
+ hoistIdents.delete(name)
58
+ idents.shift()
59
+ hoistIdents.set(name, idents[0])
60
+ wasStateChanged = true
61
+ }
62
+ }
63
+ } while (wasStateChanged)
64
+ return shadowedNodes
65
+ }
66
+
67
+ // hoistTo: each node of the tree in turn becomes the root hoisted to, depth
68
+ // first along every path that does not come back to a package on it. The
69
+ // locators on the path are read by nothing else but the debug output.
70
+ function hoistTo(tree, options, step) {
71
+ const flags = { anotherRoundNeeded: false, isGraphChanged: false }
72
+ const locators = new Set([tree.locator])
73
+ const enter = (path, parentShadowedNodes) => ({ path, shadowedNodes: hoistToNode(path, parentShadowedNodes, options, flags, step), items: regularDependencies(path.at(-1)) })
74
+ depthFirst(enter([tree], new Map()), (dependency, frame) => {
75
+ if (locators.has(dependency.locator)) return undefined
76
+ locators.add(dependency.locator)
77
+ return enter([...frame.path, dependency], frame.shadowedNodes)
78
+ }, ({ path }) => locators.delete(path.at(-1).locator))
79
+ return flags
80
+ }
81
+
82
+ // The working copy of the tree: a node per package node of the tree, shared
83
+ // where the tree shares it, and coupled then, so that hoisting copies it
84
+ // before it changes it.
85
+ function cloneTree(tree, step) {
86
+ const workNodeOf = (node, dependencyKind) => ({
87
+ name: node.name,
88
+ references: new Set([node.reference]),
89
+ locator: makeLocator(node.identName, node.reference),
90
+ ident: makeIdent(node.identName, node.reference),
91
+ dependencies: new Map(),
92
+ originalDependencies: new Map(),
93
+ hoistedDependencies: new Map(),
94
+ peerNames: new Set(node.peerNames),
95
+ decoupled: true,
96
+ dependencyKind,
97
+ })
98
+ const treeCopy = workNodeOf(tree, WORKSPACE)
99
+ const seenNodes = new Map([[tree, treeCopy]])
100
+ const markNodeCoupled = (start) => walk(start, undefined, function* (node) {
101
+ node.decoupled = false
102
+ for (const dep of regularDependencies(node)) yield [dep]
103
+ }, step)
104
+ depthFirst({ workNode: treeCopy, items: tree.dependencies.values() }, (node, { workNode: parentNode }) => {
105
+ step()
106
+ const isSeen = seenNodes.has(node)
107
+ if (!isSeen) seenNodes.set(node, workNodeOf(node, node.dependencyKind || REGULAR))
108
+ const workNode = seenNodes.get(node)
109
+ parentNode.dependencies.set(node.name, workNode)
110
+ parentNode.originalDependencies.set(node.name, workNode)
111
+ if (!isSeen) return { workNode, items: node.dependencies.values() }
112
+ markNodeCoupled(workNode)
113
+ return undefined
114
+ })
115
+ return treeCopy
116
+ }
117
+
118
+ // The hoisted tree, unfolded along each path into one of nodes with a name,
119
+ // an identName, references and dependencies, a node's peers left out.
120
+ function shrinkTree(tree, maxNodes, stats) {
121
+ const step = counter(maxNodes, `makes a tree of more than ${maxNodes} packages`, stats)
122
+ const treeCopy = { name: tree.name, identName: getIdentName(tree.locator), references: new Set(tree.references), dependencies: new Set() }
123
+ const onPath = new Set([tree])
124
+ depthFirst({ node: tree, result: treeCopy, items: regularDependencies(tree) }, (node, { node: parentWorkNode, result: parentNode }) => {
125
+ step()
126
+ const resultNode = parentWorkNode === node ? parentNode : { name: node.name, identName: getIdentName(node.locator), references: node.references, dependencies: new Set() }
127
+ parentNode.dependencies.add(resultNode)
128
+ if (onPath.has(node)) return undefined
129
+ onPath.add(node)
130
+ return { node, result: resultNode, items: regularDependencies(node) }
131
+ }, ({ node }) => node !== tree && onPath.delete(node))
132
+ return treeCopy
133
+ }
134
+
135
+ // `tree` is a node of `name`, `identName`, `reference`, `peerNames`,
136
+ // `dependencyKind` and a Set of `dependencies`, as pnpm's real-hoist makes
137
+ // it.
138
+ export function hoist(tree, { maxSteps = MAX_STEPS, maxNodes = MAX_NODES, stats } = {}) {
139
+ const step = counter(maxSteps, `takes more than ${maxSteps} steps`, stats)
140
+ const treeCopy = cloneTree(tree, step)
141
+ const options = { fastLookupPossible: true }
142
+ let anotherRoundNeeded
143
+ do {
144
+ const result = hoistTo(treeCopy, options, step)
145
+ anotherRoundNeeded = result.anotherRoundNeeded || result.isGraphChanged
146
+ options.fastLookupPossible = false
147
+ } while (anotherRoundNeeded)
148
+ return shrinkTree(treeCopy, maxNodes, stats)
149
+ }
@@ -8,7 +8,7 @@
8
8
  import { basename, dirname, join, normalize } from '@preventive/vfs/path.js'
9
9
  import { quote } from '../error.js'
10
10
  import { glob } from './glob.js'
11
- import { caseless, fromParts, rulesOf } from './minimatch.js'
11
+ import { NO_TRAVERSAL_5, caseless, fromParts, rulesOf } from './minimatch.js'
12
12
 
13
13
  const DEFAULTS = ['.npmignore', '.gitignore', '**/.git', '**/.svn', '**/.hg', '**/CVS', '**/.git/**', '**/.svn/**', '**/.hg/**', '**/CVS/**', '/.lock-wscript', '/.wafpickle-*', '/build/config.gypi', 'npm-debug.log', '**/.npmrc', '.*.swp', '.DS_Store', '**/.DS_Store/**', '._*', '**/._*/**', '*.orig']
14
14
 
@@ -18,7 +18,6 @@ const STRICT = Symbol('strict rules')
18
18
 
19
19
  const MUST_HAVE_NAMES = ['readme', 'copying', 'license', 'licence']
20
20
  const MUST_HAVE_RE = caseless(String.raw`^(?:readme|copying|license|licence)(?:\..*[^~$])?$`)
21
- const NO_TRAVERSAL_5 = String.raw`(?!(?:^|\/)\.{1,2}(?:$|\/))`
22
21
 
23
22
  // npm-packlist 5's `@(readme|copying|license|licence){,.*[^~$]}`, as glob
24
23
  // and minimatch 5 read it: two patterns of one part.
@@ -29,7 +28,7 @@ const MUST_HAVES_10 = MUST_HAVE_NAMES.map((name) => fromParts(true, ['', String.
29
28
 
30
29
  const relOf = (walker, entry) => (walker.rel === '' ? entry : `${walker.rel}/${entry}`)
31
30
 
32
- export function readRules(view, rel, minimatch, where) {
31
+ function readRules(view, rel, minimatch, where) {
33
32
  const here = `${where}: ${quote(rel)}`
34
33
  return rulesOf([view.text(rel, here)], minimatch, here)
35
34
  }
@@ -83,8 +82,8 @@ function filter10(walker, entry, partial, base) {
83
82
  // A walk of one directory: its ignore files read, its entries filtered,
84
83
  // then each file kept and each directory walked. `entries` are its own, or,
85
84
  // for npm-packlist 5's root where package.json has `files`, what those take.
86
- function visit(view, walker, entries, engine, result) {
87
- if (entries.length === 0) return
85
+ function visit(view, walker, entries, engine, result = new Set()) {
86
+ if (entries.length === 0) return result
88
87
  for (const entry of entries) {
89
88
  if (walker.ignoreFiles.includes(entry)) engine.readIgnore(walker, entry)
90
89
  }
@@ -99,6 +98,7 @@ function visit(view, walker, entries, engine, result) {
99
98
  if (file) result.add(rel)
100
99
  } else if (dir) visit(view, engine.child(walker, entry, rel, file), view.entries(rel), engine, result)
101
100
  }
101
+ return result
102
102
  }
103
103
 
104
104
  // npm-normalize-package-bin 2's bin: an object, or nothing.
@@ -156,9 +156,7 @@ export function pack10(view, manifest, where, minimatch) {
156
156
  },
157
157
  child: (walker, entry, rel) => ({ rel, parent: walker, basename: basename(rel), isProject: false, rules: new Map(), ignoreFiles: walker.ignoreFiles }),
158
158
  }
159
- const result = new Set()
160
- visit(view, root, files && own.includes('package.json') ? filesEntries5(view, pkg, where) : own, engine, result)
161
- return result
159
+ return visit(view, root, files && own.includes('package.json') ? filesEntries5(view, pkg, where) : own, engine)
162
160
  }
163
161
 
164
162
  // npm-packlist 10's processPackage: package.json's rules, and the strict ones.
@@ -215,7 +213,5 @@ export function pack11(view, manifest, where, alternates) {
215
213
  requiredFiles: parent.requiredFiles.map(normalize).filter((path) => dirname(path) === entry).map((path) => basename(path)),
216
214
  }),
217
215
  }
218
- const result = new Set()
219
- visit(view, root, view.entries(''), engine, result)
220
- return result
216
+ return visit(view, root, view.entries(''), engine)
221
217
  }
@@ -30,8 +30,7 @@ const DELIMITER = /[^ @|]>/u
30
30
  export function parseSelector(selector, where) {
31
31
  if (!selector.isWellFormed()) throw new DeptreeError(`pnpm cannot parse the selector ${quote(selector)}`, where)
32
32
  const split = selector.search(DELIMITER)
33
- const parts = split === -1 ? [selector] : [selector.slice(0, split + 1), selector.slice(split + 2)]
34
- const parsed = parts.map(parseWanted)
33
+ const parsed = (split === -1 ? [selector] : [selector.slice(0, split + 1), selector.slice(split + 2)]).map(parseWanted)
35
34
  if (parsed.includes(undefined)) throw new DeptreeError(`pnpm cannot parse the selector ${quote(selector)}`, where)
36
35
  return parsed.length === 1 ? { target: parsed[0] } : { parent: parsed[0], target: parsed[1] }
37
36
  }
@@ -6,6 +6,7 @@
6
6
  import { normalize } from '@preventive/vfs/path.js'
7
7
  import { DeptreeError, quote } from '../error.js'
8
8
  import { checkNesting } from '../manifest.js'
9
+ import { isInside } from '../mount.js'
9
10
  import { fetchTarball, sameFile } from '../tarball.js'
10
11
  import { localOf } from './overrides.js'
11
12
 
@@ -30,7 +31,7 @@ function filesOf(entries, where) {
30
31
  tops.add(entry.storedName.slice(0, Math.max(entry.storedName.indexOf('/'), 0)))
31
32
  if (tops.size > 1 || tops.has('')) throw new DeptreeError('the tarball has files under more than one directory, or at its top', where)
32
33
  const name = nameOf(entry.storedName)
33
- if (name === '' || name.split('/').some((segment) => segment === '' || segment === '.' || segment === '..')) {
34
+ if (!isInside(name)) {
34
35
  throw new DeptreeError(`${quote(entry.storedName)} names no file in the package`, where)
35
36
  }
36
37
  const file = { data: entry.data, mode: (entry.mode & 0o111) === 0 ? 0o644 : 0o755 }
@@ -4,8 +4,7 @@
4
4
  // `bin`, the .npmignore and .gitignore files where they read them, and their
5
5
  // own rules. Of glob syntax only `*`, `?` and `**` are followed, which they
6
6
  // all read alike. Refused are a link the walk comes on, which they treat
7
- // differently, and a mode other than 0o644 or 0o755, which linking a bin
8
- // would change otherwise than fixBin does.
7
+ // differently, and a mode a checkout does not have under umask 022 or 002.
9
8
 
10
9
  import { compareVersions, valid } from '@preventive/upstream/semver.js'
11
10
  import { normalize } from '@preventive/vfs/path.js'
@@ -16,6 +15,8 @@ import { pack10, pack11 } from './npm-packlist.js'
16
15
 
17
16
  const decoder = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true })
18
17
 
18
+ const MODES = new Set([0o644, 0o664, 0o755, 0o775])
19
+
19
20
  // How deep a directory is walked: each entry is matched against the rules
20
21
  // of every directory above it, which takes time growing with the cube.
21
22
  const MAX_DEPTH = 100
@@ -129,7 +130,7 @@ function walk12(view, { globs }, where) {
129
130
  const path = rel === '' ? name : `${rel}/${name}`
130
131
  if ((rel === '' && name === 'node_modules') || VCS.has(name)) continue
131
132
  const isDir = view.type(path) === 'directory'
132
- const verdict = (key) => chain.map((level) => level[key] === undefined ? undefined : matched(level[key], level.dir === '' ? path : path.slice(level.dir.length + 1), isDir)).find(Boolean)
133
+ const verdict = (key) => chain.values().map((level) => level[key] === undefined ? undefined : matched(level[key], level.dir === '' ? path : path.slice(level.dir.length + 1), isDir)).find(Boolean)
133
134
  if ((verdict('custom') ?? verdict('git')) === 'ignore') continue
134
135
  if (isDir) visit(path, chain)
135
136
  else found.push(path)
@@ -186,7 +187,7 @@ export function packDirectory(project, dir, manifest, version, where) {
186
187
  const here = `${where}: ${quote(rel)}`
187
188
  if (rel.split('/').some((part) => part === '' || part === '.')) throw new DeptreeError('pnpm keeps it as a pattern spells it, which is not supported', here)
188
189
  const { mode } = view.lstat(rel)
189
- if (mode !== 0o644 && mode !== 0o755) throw new DeptreeError(`its mode, ${mode.toString(8)}, is not 644 or 755, which is not supported`, here)
190
+ if (!MODES.has(mode)) throw new DeptreeError(`its mode, ${mode.toString(8)}, is not 644, 664, 755 or 775, which is not supported`, here)
190
191
  files.set(rel, { data: view.bytes(rel), mode })
191
192
  }
192
193
  return files
@@ -12,43 +12,31 @@ const IMPORT_METHODS = new Set(['auto', 'hardlink', 'copy', 'clone', 'clone-or-c
12
12
 
13
13
  const show = (value) => (typeof value === 'string' ? quote(value) : Array.isArray(value) ? 'a list' : value === null ? 'null' : typeof value === 'object' ? 'a mapping' : String(value))
14
14
 
15
- const oneOf = (allowed) => (value, where) => {
16
- if (allowed.has(value)) return value
17
- throw new DeptreeError(`expected one of ${[...allowed].join(', ')}, found ${show(value)}`, where)
15
+ // `read` where `ok`, or else `value` refused as not `what`.
16
+ function checked(ok, value, what, where, read = value) {
17
+ if (ok) return read
18
+ throw new DeptreeError(`expected ${what}, found ${show(value)}`, where)
18
19
  }
19
20
 
21
+ const oneOf = (allowed) => (value, where) => checked(allowed.has(value), value, `one of ${[...allowed].join(', ')}`, where)
22
+
20
23
  export const readers = {
21
24
  boolean(value, where) {
22
- if (typeof value === 'boolean') return value
23
- if (value === 'true' || value === 'false') return value === 'true'
24
- throw new DeptreeError(`expected true or false, found ${show(value)}`, where)
25
+ return value === 'true' || value === 'false' ? value === 'true' : checked(typeof value === 'boolean', value, 'true or false', where)
25
26
  },
26
27
  count(value, where) {
27
28
  const number = typeof value === 'string' && /^\d{1,9}$/u.test(value) ? Number(value) : value
28
- if (Number.isSafeInteger(number) && number > 0) return number
29
- throw new DeptreeError(`expected a positive integer, found ${show(value)}`, where)
30
- },
31
- text(value, where) {
32
- if (typeof value === 'string') return value
33
- throw new DeptreeError(`expected a string, found ${show(value)}`, where)
29
+ return checked(Number.isSafeInteger(number) && number > 0, value, 'a positive integer', where, number)
34
30
  },
31
+ text: (value, where) => checked(typeof value === 'string', value, 'a string', where),
35
32
  // A string alone is a list of it, as pnpm reads a hoist pattern.
36
33
  texts(value, where) {
37
34
  return readers.list(typeof value === 'string' ? [value] : value, where, 'a string or a list of strings')
38
35
  },
39
36
  // Only a list: pnpm fails on a string alone where it sorts or maps it.
40
- list(value, where, expected = 'a list of strings') {
41
- if (!Array.isArray(value) || value.some((item) => typeof item !== 'string')) throw new DeptreeError(`expected ${expected}, found ${show(value)}`, where)
42
- return [...value]
43
- },
44
- globs(value, where) {
45
- if (!Array.isArray(value) || value.some((item) => typeof item !== 'string' || item === '')) throw new DeptreeError(`expected a list of non-empty strings, found ${show(value)}`, where)
46
- return [...value]
47
- },
48
- mapping(value, where) {
49
- if (value !== null && typeof value === 'object' && !Array.isArray(value)) return value
50
- throw new DeptreeError(`expected a mapping, found ${show(value)}`, where)
51
- },
37
+ list: (value, where, expected = 'a list of strings') => [...checked(Array.isArray(value) && value.every((item) => typeof item === 'string'), value, expected, where)],
38
+ globs: (value, where) => [...checked(Array.isArray(value) && value.every((item) => typeof item === 'string' && item !== ''), value, 'a list of non-empty strings', where)],
39
+ mapping: (value, where) => checked(value !== null && typeof value === 'object' && !Array.isArray(value), value, 'a mapping', where),
52
40
  importMethod: oneOf(IMPORT_METHODS),
53
41
  onFail: oneOf(ON_FAIL),
54
42
  linkWorkspacePackages(value, where) {
@@ -73,9 +61,7 @@ export const readers = {
73
61
  },
74
62
  }
75
63
 
76
- const only = (kind, wanted, why) => ({ kind, check: (value, where) => {
77
- if (value !== wanted) throw new DeptreeError(`${show(value)} is not supported: ${why}`, where)
78
- } })
64
+ const only = (kind, wanted, why) => ({ kind, check: (value, where) => value === wanted || never(why)(value, where) })
79
65
 
80
66
  const never = (why) => (value, where) => {
81
67
  throw new DeptreeError(`${show(value)} is not supported: ${why}`, where)
@@ -83,7 +69,8 @@ const never = (why) => (value, where) => {
83
69
 
84
70
  export const READ = {
85
71
  __proto__: null,
86
- nodeLinker: only('text', 'isolated', 'only the isolated node_modules layout is built'),
72
+ // pnpm 10's hoisted layout too (hoisted.js).
73
+ nodeLinker: { kind: 'text', check: (value, where) => value === 'hoisted' || value === 'isolated' || never('only the isolated and hoisted node_modules layouts are built')(value, where) },
87
74
  symlink: only('boolean', true, 'a tree without its links is not built'),
88
75
  enableModulesDir: only('boolean', true, 'a tree without node_modules is not built'),
89
76
  modulesDir: only('text', 'node_modules', 'the modules directory is always node_modules'),
@@ -182,6 +169,7 @@ const notEnabled = (value, where) => {
182
169
  }
183
170
  const READ_12 = {
184
171
  __proto__: null,
172
+ nodeLinker: only('text', 'isolated', 'only the isolated node_modules layout is built for pnpm 12'),
185
173
  cargo: { kind: 'mapping', check: notEnabled },
186
174
  python: { kind: 'mapping', check: notEnabled },
187
175
  }
@@ -198,6 +186,7 @@ export const unrecognized12 = (where) => new DeptreeError('pnpm 12 does not know
198
186
  // package.json's packageManager to the pnpm that runs (projects.js).
199
187
  const READ_9 = {
200
188
  __proto__: null,
189
+ nodeLinker: only('text', 'isolated', 'only the isolated node_modules layout is built for pnpm 9'),
201
190
  managePackageManagerVersions: { kind: 'boolean' },
202
191
  packageManagerStrict: { kind: 'boolean' },
203
192
  packageManagerStrictVersion: { kind: 'boolean' },
@@ -39,6 +39,10 @@ function checkNpmrcRegistries(text) {
39
39
  }
40
40
  }
41
41
 
42
+ // The registry's token as a project's .npmrc commonly gives it is taken to
43
+ // be set, as @preventive/upstream reads it too: pnpm reads the file then.
44
+ const isNpmToken = (key, value) => key === '//registry.npmjs.org/:_authToken' && value === '${NPM_TOKEN}'
45
+
42
46
  function fromNpmrc(text, major) {
43
47
  const settings = new Map()
44
48
  let environment = false
@@ -51,7 +55,7 @@ function fromNpmrc(text, major) {
51
55
  const name = KEBAB.test(key) ? camelCase(key) : undefined
52
56
  const read = name === undefined ? undefined : npmrcReader(name, major)
53
57
  if (read === undefined) {
54
- environment ||= fromEnvironment(key) || fromEnvironment(value)
58
+ if (!isNpmToken(key, value)) environment ||= fromEnvironment(key) || fromEnvironment(value)
55
59
  continue
56
60
  }
57
61
  noEnvironment(value, where)
@@ -77,9 +81,8 @@ function fromManifest(manifest, major) {
77
81
  }
78
82
  const { resolutions } = manifest
79
83
  if (resolutions !== undefined || Object.hasOwn(pnpm, 'overrides')) {
80
- const where = 'package.json: resolutions and pnpm.overrides'
81
84
  const value = { ...(resolutions === undefined ? {} : readers.mapping(resolutions, 'package.json: resolutions')), ...(Object.hasOwn(pnpm, 'overrides') ? readers.mapping(pnpm.overrides, 'package.json: pnpm.overrides') : {}) }
82
- settings.set('overrides', { value, where, read: READ.overrides })
85
+ settings.set('overrides', { value, where: 'package.json: resolutions and pnpm.overrides', read: READ.overrides })
83
86
  }
84
87
  return settings
85
88
  }
@@ -108,11 +111,8 @@ function fromWorkspace(workspace, major, pinned) {
108
111
  // among it.
109
112
  function fromWorkspace9(workspace) {
110
113
  readers.mapping(workspace, 'pnpm-workspace.yaml')
111
- const settings = new Map()
112
- for (const name of ['packages', 'catalog', 'catalogs']) {
113
- if (workspace[name] != null) settings.set(name, { value: workspace[name], where: `pnpm-workspace.yaml: ${name}`, read: READ[name] })
114
- }
115
- return settings
114
+ const names = ['packages', 'catalog', 'catalogs'].filter((name) => workspace[name] != null)
115
+ return new Map(names.map((name) => [name, { value: workspace[name], where: `pnpm-workspace.yaml: ${name}`, read: READ[name] }]))
116
116
  }
117
117
 
118
118
  const PUBLIC_9 = ['*eslint*', '*prettier*']
@@ -146,6 +146,7 @@ function derive(get, major) {
146
146
  pmOnFail: get('pmOnFail'),
147
147
  runtimeOnFail: get('runtimeOnFail'),
148
148
  packageImportMethod: get('packageImportMethod') ?? 'auto',
149
+ nodeLinker: get('nodeLinker') ?? 'isolated',
149
150
  ...major < 10 ? {
150
151
  packageManagerChecks: {
151
152
  manage: get('managePackageManagerVersions') ?? false,
package/src/pnpm/tree.js CHANGED
@@ -4,6 +4,7 @@
4
4
  // not linked, though what linking does to their files is (bins.js).
5
5
 
6
6
  import { packageKeyOf } from '@preventive/lockfile/pnpm.js'
7
+ import { compareVersions } from '@preventive/upstream/semver.js'
7
8
  import { Vfs } from '@preventive/vfs'
8
9
  import { dirname, relative } from '@preventive/vfs/path.js'
9
10
  import { eachConcurrently } from '../concurrent.js'
@@ -12,9 +13,10 @@ import { checkNoModules, checkWrite, fold, isInside, makeDirs, mount, writeLink
12
13
  import { applyPatch, parsePatch } from '../patch.js'
13
14
  import { checkProject, typeOf } from '../project.js'
14
15
  import { REGISTRY, tarballUrl } from '../tarball.js'
15
- import { binTargets, checkPatchOfBins, fixBin, requiresBuild } from './bins.js'
16
+ import { binTargets, checkPatchOfBins, executableMode, fixBin, hoistedBinTargets, requiresBuild } from './bins.js'
16
17
  import { buildGraph } from './graph.js'
17
18
  import { hoist } from './hoist.js'
19
+ import { hoistedBuilds, hoistedLayout, hoistedModules, packageIdOf, prodPackages, workspaceHoists } from './hoisted.js'
18
20
  import { checkLocalOverrides, createFreshnessCheck, readDirectoryPackage, readLinked } from './local.js'
19
21
  import { createPatchedCheck, skippedSnapshots } from './install.js'
20
22
  import { checkDependencies, fetchPackage } from './package.js'
@@ -104,13 +106,19 @@ function executableElsewhere(byDir, targets, packageImportMethod, major) {
104
106
  }))
105
107
  }
106
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
114
+ }
115
+
107
116
  function compose(node, patches, { targets, executable }, { major, checkPatched }) {
108
117
  const where = quote(node.key)
109
118
  let files = node.files
110
119
  const { patchHash } = node.pkg
111
120
  if (patchHash !== undefined) {
112
- const patch = patches.get(patchHash)
113
- patch.parsed ??= parsePatch(patch.text, patch.path)
121
+ const patch = parsedPatch(patches, patchHash)
114
122
  patch.applied ??= new WeakMap()
115
123
  if (!patch.applied.has(files)) patch.applied.set(files, applyPatch(files, patch.parsed, { createdMode: major >= 12 ? 0o644 : undefined }))
116
124
  files = patch.applied.get(files)
@@ -120,7 +128,7 @@ function compose(node, patches, { targets, executable }, { major, checkPatched }
120
128
  if (targets.size === 0 && executable.size === 0) return files
121
129
  files = new Map(files)
122
130
  for (const path of targets) files.set(path, fixBin(files.get(path), `${where}: ${quote(path)}`, major))
123
- 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) })
124
132
  return files
125
133
  }
126
134
 
@@ -160,8 +168,7 @@ function writeNode(vfs, dir, files, stats) {
160
168
  // As pnpm's symlink-dir spells it. A target may climb out of the tree, so both
161
169
  // are resolved under as many dummy directories as it climbs.
162
170
  function linkTarget(path, target) {
163
- const climbs = target.split('/').filter((segment) => segment === '..').length
164
- const root = '/_'.repeat(climbs)
171
+ const root = '/_'.repeat(target.split('/').filter((segment) => segment === '..').length)
165
172
  return relative(`${root}/${dirname(path)}`, `${root}/${target}`) || '.'
166
173
  }
167
174
 
@@ -208,6 +215,59 @@ function linksOf(byDir, direct, settings, projects, major, hoisting) {
208
215
  return links
209
216
  }
210
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
+
211
271
  export async function buildPnpmTree(options) {
212
272
  const { project, host: given, vfs: into } = options ?? {}
213
273
  if (into !== undefined && !(into instanceof Vfs)) throw new TypeError('vfs must be a Vfs, or left out')
@@ -236,35 +296,18 @@ export async function buildPnpmTree(options) {
236
296
  checkWorkspace(Object.keys(lockfile.importers), settings.packages, major)
237
297
  const overrides = listOverrides(settings.overrides, settings.catalogs, major)
238
298
  const installed = checkLocalOverrides(overrides, project)
239
- const patches = patchesOf(inputs, settings.patchedDependencies)
240
- const patched = await checkUpToDate(lockfile, settings, overrides, patches, major)
299
+ const patched = await checkUpToDate(lockfile, settings, overrides, patchesOf(inputs, settings.patchedDependencies), major)
241
300
  const hook = createHook({ overrides, ignored: settings.ignoredOptionalDependencies, major })
242
301
  checkProjects(lockfile, manifests, { hook, host, settings, env })
243
302
  checkOptional(lockfile)
244
- const projects = settings.hoistWorkspacePackages ? workspaceNames(manifests) : new Map()
303
+ const names = settings.hoistWorkspacePackages ? workspaceNames(manifests) : new Map()
245
304
  const { skipped, incompatible } = skippedSnapshots(lockfile, { host, settings })
246
- const { nodes, direct, hoisting } = await buildGraph(lockfile, skipped, settings.virtualStoreDirMaxLength, major)
247
- for (const node of nodes.values()) checkSource(node, installed)
248
-
249
- const { byDir, tarballs } = await fetchNodes(nodes, lockfile, hook, project, host)
250
- const links = linksOf(byDir, direct, settings, projects, major, hoisting)
251
- const linked = readLinked(links, byDir, manifests, project)
252
- const targets = binTargets({
253
- nodes: byDir,
254
- projects: new Map([...manifests, ...linked]),
255
- direct,
256
- links,
257
- publicHoist: settings.publicHoistPattern?.length > 0,
258
- building: Object.keys(settings.patchedDependencies ?? {}).length > 0,
259
- peers: settings.autoInstallPeers,
260
- major,
261
- })
262
- const executable = executableElsewhere(byDir, targets, settings.packageImportMethod, major)
263
- const prod = reachedInProd(lockfile.importers, nodes, byDir)
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 })
264
307
 
265
308
  const vfs = new Vfs()
266
- makeDirs(vfs, 'node_modules/.pnpm')
267
- const stats = { projects: manifests.size, snapshots: Object.keys(lockfile.packages).length, installed: nodes.size, skipped: skipped.size, incompatible: incompatible.size, tarballs, patched: [...nodes.values()].filter((node) => node.pkg.patchHash !== undefined).length, files: 0, bytes: 0, links: links.size }
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 }
268
311
  const listed = []
269
312
  const composing = { major, checkPatched: createPatchedCheck({ host, settings }) }
270
313
  // Each node is let go once written, and a package's files with its last.
@@ -275,7 +318,7 @@ export async function buildPnpmTree(options) {
275
318
  } catch (error) {
276
319
  throw refusalOf(error, quote(node.key))
277
320
  }
278
- listed.push(installedOf(node, !prod.has(node.dir), patched))
321
+ listed.push(installedOf(node, dev(node), patched))
279
322
  }
280
323
  for (const [path, target] of links) {
281
324
  try {
@@ -7,6 +7,7 @@
7
7
  import { compareNames, normalize } from '@preventive/vfs/path.js'
8
8
  import { DeptreeError, quote } from '../error.js'
9
9
  import { reach, wildcard } from '../matcher.js'
10
+ import { UNSAFE, isInside } from '../mount.js'
10
11
  import { typeOf } from '../project.js'
11
12
 
12
13
  const UNSUPPORTED = /[?[\]{}()\\]/u
@@ -172,9 +173,8 @@ export function checkWorkspace(ids, packages, major = 10) {
172
173
  }
173
174
 
174
175
  // The importer keys @preventive/lockfile takes for a project.
175
- const UNSAFE = /[\p{Cc}\p{Zl}\p{Zp}\p{Bidi_Control}\\]/u
176
176
  export function checkProjectId(id, where) {
177
- if (id.split('/').some((name) => name === '' || name === '.' || name === '..' || UNSAFE.test(name)) || /^[A-Za-z]:/u.test(id)) {
177
+ if (!isInside(id) || UNSAFE.test(id) || /^[A-Za-z]:/u.test(id)) {
178
178
  throw new DeptreeError('expected a directory under the lockfile\'s, by its path from there in normal form, as a lockfile can key an importer', where)
179
179
  }
180
180
  }