@preventive/deptree 1.0.0-alpha.0

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,229 @@
1
+ // Which snapshots a pnpm 10 install from a frozen lockfile leaves out: an
2
+ // optional one that the host cannot run — its `os`, `cpu` or `libc` do not
3
+ // take the host's, or its `engines.node` does not take the Node pnpm runs
4
+ // on — and an optional one first reached, depth first from the projects,
5
+ // through a snapshot that is not installed. That first reach decides it,
6
+ // as it does for pnpm (@pnpm/lockfile.filtering's pkgAllDeps, then
7
+ // @pnpm/deps.graph-builder checking every snapshot again), so a snapshot
8
+ // reached both ways is left out or not by which way is walked first.
9
+ // Anything else incompatible is installed, as pnpm installs it with a
10
+ // warning, or refused where `engineStrict` has pnpm refuse it.
11
+ //
12
+ // The projects are walked in the lockfile's order, which is the order of
13
+ // their directories; pnpm walks them in the order it finds them on disk,
14
+ // which only a snapshot reached both ways as above can tell apart.
15
+ //
16
+ // pnpm 11 walks breadth first, and by the kind of each edge rather than of
17
+ // each snapshot: an optional dependency the host cannot run is not taken,
18
+ // and what a taken package requires is taken whether the host can run it
19
+ // or not, with a warning; each reachable snapshot not taken is left out.
20
+ // Where a package of an optional edge names no os, cpu or libc, pnpm 11
21
+ // infers them from its name, as `@nx/nx-win32-arm64-msvc` names win32.
22
+
23
+ import { satisfies } from '@preventive/upstream/semver.js'
24
+ import { DeptreeError, quote } from '../error.js'
25
+
26
+ // pnpm's checkList: `any` alone is anything, `!x` excludes, and a list of
27
+ // exclusions alone takes what none of them names. pnpm 10 counts the
28
+ // exclusions over every value the host is taken to be, so a list of them
29
+ // takes nothing where the host is taken to be more than one thing; pnpm 11
30
+ // does not.
31
+ function checkList(values, list, major) {
32
+ if (list.length === 1 && list[0] === 'any') return true
33
+ let match = false
34
+ let excluded = 0
35
+ for (const value of values) {
36
+ for (const item of list) {
37
+ if (item.startsWith('!')) {
38
+ if (item.slice(1) === value) return false
39
+ excluded++
40
+ } else if (item === value) match = true
41
+ }
42
+ }
43
+ return match || (major >= 11 ? list.every((item) => item.startsWith('!')) : excluded === list.length)
44
+ }
45
+
46
+ // pnpm 11's inferPlatformFromPackageName: the os, cpu and libc the words
47
+ // of a package's name, less its scope, say it is for.
48
+ const OS_WORDS = { __proto__: null, aix: 'aix', android: 'android', darwin: 'darwin', macos: 'darwin', osx: 'darwin', freebsd: 'freebsd', linux: 'linux', netbsd: 'netbsd', openbsd: 'openbsd', openharmony: 'openharmony', sunos: 'sunos', win32: 'win32', windows: 'win32' }
49
+ const CPU_WORDS = { __proto__: null, arm: 'arm', armv6: 'arm', armv7: 'arm', arm64: 'arm64', aarch64: 'arm64', ia32: 'ia32', loong64: 'loong64', mips64el: 'mips64el', ppc64: 'ppc64', ppc64le: 'ppc64', riscv64: 'riscv64', s390x: 's390x', x64: 'x64', amd64: 'x64', wasm32: 'wasm32' }
50
+ const LIBC_WORDS = { __proto__: null, glibc: 'glibc', gnu: 'glibc', gnueabihf: 'glibc', musl: 'musl', musleabihf: 'musl' }
51
+ function inferPlatform(name) {
52
+ const words = name.slice(name.indexOf('/') + 1).toLowerCase().split(/[-_.]/u)
53
+ const pick = (table) => {
54
+ const values = [...new Set(words.map((word) => table[word]).filter((value) => value !== undefined))]
55
+ return values.length > 0 ? values : undefined
56
+ }
57
+ return { os: pick(OS_WORDS), cpu: pick(CPU_WORDS), libc: pick(LIBC_WORDS) }
58
+ }
59
+
60
+ // pnpm 11's effectivePlatform, for a package checked as optional.
61
+ function effectivePlatform(pkg) {
62
+ if (pkg.os !== undefined && pkg.cpu !== undefined && pkg.libc !== undefined) return pkg
63
+ const inferred = inferPlatform(pkg.name)
64
+ const declares = pkg.os !== undefined || pkg.cpu !== undefined || pkg.libc !== undefined
65
+ if (inferred.os === undefined && (!declares || (inferred.cpu === undefined && inferred.libc === undefined))) return pkg
66
+ return { ...pkg, os: pkg.os ?? inferred.os, cpu: pkg.cpu ?? inferred.cpu, libc: pkg.libc ?? inferred.libc }
67
+ }
68
+
69
+ // What the host is taken to be: itself, or what `supportedArchitectures`
70
+ // lists for each, `current` standing for itself.
71
+ const current = (value, supported) => (supported ?? ['current']).map((item) => (item === 'current' ? value : item))
72
+
73
+ const takesPlatform = (pkg, host, supported, major = 10) => checkList(current(host.os, supported?.os), pkg.os ?? ['any'], major)
74
+ && checkList(current(host.cpu, supported?.cpu), pkg.cpu ?? ['any'], major)
75
+ && (host.libc === 'unknown' || checkList(current(host.libc, supported?.libc), pkg.libc ?? ['any'], major))
76
+
77
+ const takesEngine = (engines, node) => !engines.node || satisfies(node, engines.node, { includePrerelease: true })
78
+
79
+ // A package.json's os, cpu or libc as pnpm's checkList reads one: a string
80
+ // is a list of it, and what is not a string in a list is passed over.
81
+ function platformList(value, where) {
82
+ if (value === undefined || value === null) return undefined
83
+ if (typeof value === 'string') return [value]
84
+ if (Array.isArray(value)) return value.filter((item) => typeof item === 'string')
85
+ throw new DeptreeError('expected a string or a list of them', where)
86
+ }
87
+
88
+ // A project as pnpm's packageIsInstallable holds it when it reads its
89
+ // package.json: a platform the host is not only warns, and so does an
90
+ // engines.node it does not take, unless engineStrict; an engines.pnpm it
91
+ // does not take is always refused. As pnpm has it, a platform that does
92
+ // not match is found first, and the engines are then not looked at.
93
+ export function checkProject(manifest, where, { host, settings }) {
94
+ const platform = { os: platformList(manifest.os, `${where}.os`), cpu: platformList(manifest.cpu, `${where}.cpu`), libc: platformList(manifest.libc, `${where}.libc`) }
95
+ if (!takesPlatform(platform, host, settings.supportedArchitectures, host.major)) return
96
+ const engines = manifest.engines
97
+ if (engines === undefined || engines === null) return
98
+ const node = settings.nodeVersion ?? host.node
99
+ if (engines.pnpm && !satisfies(host.pnpm, engines.pnpm, { includePrerelease: true })) {
100
+ throw new DeptreeError(`its engines.pnpm, ${quote(String(engines.pnpm))}, does not take pnpm ${host.pnpm}, which pnpm refuses`, where)
101
+ }
102
+ if (settings.engineStrict && !takesEngine(engines, node)) throw new DeptreeError(`its engines.node, ${quote(String(engines.node))}, does not take Node ${node}, which engineStrict refuses`, where)
103
+ }
104
+
105
+ // A check of one snapshot: true where the host can run it, false where it
106
+ // is optional and cannot, and null where it cannot but is not optional and
107
+ // is installed anyway. With `engineStrict` that last is refused. pnpm 10
108
+ // takes a snapshot to be optional as the lockfile marks it; pnpm 11 as the
109
+ // edge it is reached by, and holds only one the lockfile does not mark
110
+ // optional to engineStrict. With engineStrict, pnpm 11 passes over the
111
+ // engines of a snapshot that is patched, which checkPatchedEngines holds
112
+ // its package.json to once patched.
113
+ export function createCheck({ host, settings }) {
114
+ const node = settings.nodeVersion ?? host.node
115
+ const patchedLater = host.major >= 11 && settings.engineStrict
116
+ return (key, pkg, optional = pkg.optional, strict = settings.engineStrict) => {
117
+ const platform = takesPlatform(host.major >= 11 && optional ? effectivePlatform(pkg) : pkg, host, settings.supportedArchitectures, host.major)
118
+ if (platform && takesEngine(patchedLater && pkg.patchHash !== undefined ? {} : pkg.engines, node)) return true
119
+ if (optional) return false
120
+ if (strict) throw new DeptreeError(`the host does not take its ${platform ? 'engines.node' : 'os, cpu or libc'}, which engineStrict refuses`, quote(key))
121
+ return null
122
+ }
123
+ }
124
+
125
+ // pnpm 11, with engineStrict, holds a patched package's package.json,
126
+ // once patched, to the Node, and fails where it does not take it; where
127
+ // the package is optional, it removes it from the tree it has linked,
128
+ // which is refused too.
129
+ export function checkPatchedEngines(manifest, where, { host, settings }) {
130
+ if (host.major < 11 || !settings.engineStrict || manifest.engines === undefined || manifest.engines === null) return
131
+ const node = settings.nodeVersion ?? host.node
132
+ if (!takesEngine(manifest.engines, node)) throw new DeptreeError(`its package.json, patched, has an engines.node, ${quote(String(manifest.engines.node))}, that does not take Node ${node}, which pnpm 11 refuses with engineStrict, or removes the package for where it is optional`, where)
133
+ }
134
+
135
+ // A reference's key, or the project a `link:` leads to, if it is one.
136
+ function split(targets, lockfile) {
137
+ const keys = []
138
+ const projects = []
139
+ for (const target of targets) {
140
+ if (!target.startsWith('link:')) keys.push(target)
141
+ else if (target.slice(5) in lockfile.importers) projects.push(target.slice(5))
142
+ }
143
+ return { keys, projects }
144
+ }
145
+
146
+ // Every snapshot a project depends on, then those of the projects it
147
+ // links to that were not walked yet, as pnpm's toImporterDepPaths lists
148
+ // them: dependencies, devDependencies, optionalDependencies.
149
+ function projectKeys(lockfile, ids, walked) {
150
+ const targets = ids.flatMap((id) => {
151
+ const importer = lockfile.importers[id]
152
+ return Object.values({ ...importer.dependencies, ...importer.devDependencies, ...importer.optionalDependencies })
153
+ })
154
+ const { keys, projects } = split(targets, lockfile)
155
+ const more = projects.filter((id) => !walked.has(id))
156
+ for (const id of more) walked.add(id)
157
+ return more.length === 0 ? keys : [...keys, ...projectKeys(lockfile, more, walked)]
158
+ }
159
+
160
+ // pnpm 11's filterLockfileByImportersAndEngine: the snapshots left out,
161
+ // and those installed although the host cannot run them.
162
+ function skippedSnapshots11(lockfile, check, strict) {
163
+ const edgesOf = (deps, optional) => Object.values(deps).filter((target) => !target.startsWith('link:')).map((key) => ({ key, optional }))
164
+ const queue = Object.values(lockfile.importers).flatMap((importer) => [...edgesOf(importer.dependencies, false), ...edgesOf(importer.devDependencies, false), ...edgesOf(importer.optionalDependencies, true)])
165
+ const starts = queue.map(({ key }) => key)
166
+ const installed = new Set()
167
+ const required = new Set()
168
+ const incompatible = new Map()
169
+ for (let i = 0; i < queue.length; i++) {
170
+ const { key, optional } = queue[i]
171
+ if (!optional) required.add(key)
172
+ if (installed.has(key)) continue
173
+ const pkg = lockfile.packages[key]
174
+ if (!incompatible.has(key)) incompatible.set(key, check(key, pkg, true) === false)
175
+ if (optional && incompatible.get(key)) continue
176
+ installed.add(key)
177
+ queue.push(...edgesOf(pkg.dependencies, false), ...edgesOf(pkg.optionalDependencies, true))
178
+ }
179
+ const skipped = new Set()
180
+ const warned = new Set()
181
+ for (const key of incompatible.keys()) {
182
+ const pkg = lockfile.packages[key]
183
+ const ok = check(key, pkg, !installed.has(key) || !required.has(key), strict && !pkg.optional)
184
+ if (ok === false) skipped.add(key)
185
+ if (ok === null) warned.add(key)
186
+ }
187
+ const seen = new Set()
188
+ for (let i = 0; i < starts.length; i++) {
189
+ const key = starts[i]
190
+ if (seen.has(key)) continue
191
+ seen.add(key)
192
+ const pkg = lockfile.packages[key]
193
+ if (!installed.has(key) && pkg.optional) skipped.add(key)
194
+ starts.push(...[...edgesOf(pkg.dependencies), ...edgesOf(pkg.optionalDependencies)].map((edge) => edge.key))
195
+ }
196
+ return { skipped, incompatible: warned }
197
+ }
198
+
199
+ // The keys of the snapshots left out, and of those installed although the
200
+ // host cannot run them. `check` is createCheck's.
201
+ export function skippedSnapshots(lockfile, check, { major = 10, engineStrict = false } = {}) {
202
+ if (major >= 11) return skippedSnapshots11(lockfile, check, engineStrict)
203
+ const ids = Object.keys(lockfile.importers)
204
+ const walked = new Set(ids)
205
+ const picked = new Set()
206
+ const skipped = new Set()
207
+ const visit = (keys, parentInstallable) => {
208
+ for (const key of keys) {
209
+ if (picked.has(key)) continue
210
+ const pkg = lockfile.packages[key]
211
+ const installable = parentInstallable && check(key, pkg) !== false
212
+ if (!installable && pkg.optional) skipped.add(key)
213
+ picked.add(key)
214
+ const { keys: next, projects } = split(Object.values({ ...pkg.dependencies, ...pkg.optionalDependencies }), lockfile)
215
+ for (const id of projects) walked.add(id)
216
+ visit([...next, ...projectKeys(lockfile, projects, walked)], installable)
217
+ }
218
+ }
219
+ visit(projectKeys(lockfile, ids, walked), true)
220
+ // The graph is built of the rest, each checked again on its own.
221
+ const incompatible = new Set()
222
+ for (const key of picked) {
223
+ if (skipped.has(key)) continue
224
+ const ok = check(key, lockfile.packages[key])
225
+ if (ok === false) skipped.add(key)
226
+ if (ok === null) incompatible.add(key)
227
+ }
228
+ return { skipped, incompatible }
229
+ }
@@ -0,0 +1,49 @@
1
+ // Directories outside node_modules the tree links to, read from the Vfs
2
+ // given as `vfs` where there is one: those local overrides name, and
3
+ // every other a `link:` leads to that is no project and is under the
4
+ // lockfile's directory. Each has to hold a package.json there, whose bins
5
+ // take their names as pnpm links them. An override to a directory is
6
+ // read only from a Vfs given, and one to a copy of it, as `file:` has
7
+ // pnpm install it, is refused: pnpm picks the files it copies with
8
+ // npm-packlist, whose rules are not followed here.
9
+
10
+ import { DeptreeError, quote } from '../error.js'
11
+ import { readManifest } from './projects.js'
12
+
13
+ const decoder = new TextDecoder('utf-8', { fatal: true })
14
+
15
+ function manifestAt(vfs, dir, where) {
16
+ const path = `/${dir}/package.json`
17
+ if (!vfs.isFile(path)) throw new DeptreeError(`${quote(dir)} holds no package.json in the Vfs given`, where)
18
+ let text
19
+ try {
20
+ text = decoder.decode(vfs.readFile(path))
21
+ } catch {
22
+ throw new DeptreeError(`${quote(`${dir}/package.json`)} is not UTF-8`, where)
23
+ }
24
+ return readManifest(text, where)
25
+ }
26
+
27
+ // `overrides` is listOverrides's.
28
+ export function checkLocalOverrides(overrides, vfs) {
29
+ for (const { selector, local } of overrides) {
30
+ if (local === undefined) continue
31
+ const where = `overrides[${quote(selector)}]`
32
+ if (local.protocol === 'file:') throw new DeptreeError('an override to a copy of a directory, as file: has pnpm install it, is not supported: pnpm picks the files it copies with npm-packlist', where)
33
+ if (vfs === undefined) throw new DeptreeError(`an override to a directory, ${quote(local.dir)}, is read only from a Vfs given as vfs`, where)
34
+ manifestAt(vfs, local.dir, where)
35
+ }
36
+ }
37
+
38
+ // By directory, the package.json of each directory the tree links to that
39
+ // is no node of `nodes`, no project of `projects`, and under the
40
+ // lockfile's directory, read from `vfs`; none without one.
41
+ export function readLinked(links, nodes, projects, vfs) {
42
+ const linked = new Map()
43
+ if (vfs === undefined) return linked
44
+ for (const [path, target] of links) {
45
+ if (nodes.has(target) || projects.has(target) || linked.has(target) || target === '..' || target.startsWith('../')) continue
46
+ linked.set(target, manifestAt(vfs, target, quote(path)))
47
+ }
48
+ return linked
49
+ }
@@ -0,0 +1,31 @@
1
+ // An .npmrc read as the `ini` package reads it for npm and pnpm, as far as
2
+ // a key and the text after its `=` go: a line per setting, `#` or `;` in
3
+ // front for a comment, `key[]` to add to a list, and a key with no `=`
4
+ // set to true. What a value means is left to the setting that reads it,
5
+ // which takes it only in a form with one reading (settings.js); a value
6
+ // ini would unquote, unescape, cut at a `;` or `#`, or fill in from the
7
+ // environment is refused there rather than read two ways. A section, which
8
+ // npm reads under a prefix no setting here has, is refused outright.
9
+
10
+ import { DeptreeError } from '../error.js'
11
+
12
+ // Each setting in the order written: `line` counts from one, and `list`
13
+ // says the key was written with `[]`, which is dropped from it.
14
+ export function parseNpmrc(text) {
15
+ const settings = []
16
+ const lines = text.split(/\r\n|\r|\n/u)
17
+ for (const [index, raw] of lines.entries()) {
18
+ const line = raw.trim()
19
+ const where = `.npmrc:${index + 1}`
20
+ if (line === '' || line.startsWith('#') || line.startsWith(';')) continue
21
+ if (line.startsWith('[')) throw new DeptreeError('a section is not supported', where)
22
+ const eq = line.indexOf('=')
23
+ let key = (eq === -1 ? line : line.slice(0, eq)).trim()
24
+ const value = eq === -1 ? 'true' : line.slice(eq + 1).trim()
25
+ const list = key.length > 2 && key.endsWith('[]')
26
+ if (list) key = key.slice(0, -2)
27
+ if (key === '') throw new DeptreeError('a setting has no name', where)
28
+ settings.push({ key, value, list, line: index + 1 })
29
+ }
30
+ return settings
31
+ }
@@ -0,0 +1,128 @@
1
+ // Overrides as pnpm 10 reads them. The root package.json gives Yarn's
2
+ // `resolutions` and its own `pnpm.overrides`, the second winning a
3
+ // selector both name; where the two name any, they are the overrides,
4
+ // and pnpm-workspace.yaml's are passed over whole, as `pnpm install`
5
+ // spreads the package.json's settings over the rest. Only where the
6
+ // package.json names none are pnpm-workspace.yaml's `overrides` read. In
7
+ // each, a value of `$name` is the specifier
8
+ // the root package.json gives its own dependency `name` (optional over
9
+ // regular over dev), and one of `catalog:` or `catalog:<name>` is what
10
+ // that catalog gives the package the selector targets. A selector is a
11
+ // package, `name` or `name@range`, and may lead with its parent and a
12
+ // `>`: `bar@2>foo@1`. Anything pnpm cannot read — a selector it cannot
13
+ // parse, a `$name` with no such dependency, a catalog without the entry,
14
+ // or with one it refuses — is refused the same.
15
+ //
16
+ // The overrides are what the lockfile was resolved with, which is where
17
+ // they did their work: with a frozen lockfile pnpm only holds them to the
18
+ // lockfile's `overrides` (uptodate.js), and resolves anew where they
19
+ // differ.
20
+ //
21
+ // An override to a directory — `link:`, `file:` or a path alone, such as
22
+ // `./vendor/foo` — names it from the lockfile's directory, and is read
23
+ // only from a Vfs given that holds it (tree.js): one outside the lockfile's
24
+ // directory, or from the root or the home directory, is refused.
25
+ //
26
+ // pnpm 11 reads them from pnpm-workspace.yaml alone, trims each selector,
27
+ // takes a catalog's `workspace:` entry, and reads `name@` with an exact
28
+ // version as converging: a dependency on `name` whose range takes that
29
+ // version is given it, where no other override is chosen. It refuses one
30
+ // with a parent and an empty range, and one whose version is not exact.
31
+
32
+ import { valid } from '@preventive/upstream/semver.js'
33
+ import { join, normalize } from '@preventive/vfs/path.js'
34
+ import { DeptreeError, quote } from '../error.js'
35
+
36
+ // validate-npm-package-name 5's validForOldPackages, which pnpm reads a
37
+ // selector's name by: what npm ever took as a name.
38
+ const SCOPED = /^(?:@([^/]+?)\/)?([^/]+?)$/u
39
+ export function validForOldPackages(name) {
40
+ if (name === '' || name.startsWith('.') || name.startsWith('_') || name.trim() !== name) return false
41
+ if (name.toLowerCase() === 'node_modules' || name.toLowerCase() === 'favicon.ico') return false
42
+ if (encodeURIComponent(name) === name) return true
43
+ const m = SCOPED.exec(name)
44
+ return m !== null && encodeURIComponent(m[1]) === m[1] && encodeURIComponent(m[2]) === m[2]
45
+ }
46
+
47
+ // @pnpm/parse-wanted-dependency: a name, where what comes before the first
48
+ // `@` past the start is one, then what follows it.
49
+ function parseWanted(raw) {
50
+ const at = raw.indexOf('@', 1)
51
+ const name = at === -1 ? raw : raw.slice(0, at)
52
+ return validForOldPackages(name) ? { name, range: at === -1 ? undefined : raw.slice(at + 1) } : undefined
53
+ }
54
+
55
+ // A `>` after anything but a space, `|` or `@` splits the parent from the
56
+ // package, as pnpm's DELIMITER_REGEX has it; `foo@>1` is one package.
57
+ const DELIMITER = /[^ @|]>/u
58
+
59
+ export function parseSelector(selector, where) {
60
+ if (!selector.isWellFormed()) throw new DeptreeError(`pnpm cannot parse the selector ${quote(selector)}`, where)
61
+ const split = selector.search(DELIMITER)
62
+ const parts = split === -1 ? [selector] : [selector.slice(0, split + 1), selector.slice(split + 2)]
63
+ const parsed = parts.map(parseWanted)
64
+ if (parsed.includes(undefined)) throw new DeptreeError(`pnpm cannot parse the selector ${quote(selector)}`, where)
65
+ return parsed.length === 1 ? { target: parsed[0] } : { parent: parsed[0], target: parsed[1] }
66
+ }
67
+
68
+ // A layer's overrides with each `$name` replaced; `manifest` is the root
69
+ // package.json as parsed.
70
+ export function replaceReferences(overrides, manifest, where) {
71
+ const own = { ...manifest.devDependencies, ...manifest.dependencies, ...manifest.optionalDependencies }
72
+ const replaced = Object.create(null)
73
+ for (const [selector, spec] of Object.entries(overrides)) {
74
+ if (typeof spec !== 'string') throw new DeptreeError(`expected a string for ${quote(selector)}`, where)
75
+ if (!spec.startsWith('$')) { replaced[selector] = spec; continue }
76
+ const found = Object.hasOwn(own, spec.slice(1)) ? own[spec.slice(1)] : undefined
77
+ if (typeof found !== 'string' || found === '') throw new DeptreeError(`${quote(spec)} names no dependency of the root package.json`, where)
78
+ replaced[selector] = found
79
+ }
80
+ return replaced
81
+ }
82
+
83
+ const CATALOG = 'catalog:'
84
+
85
+ // @pnpm/catalogs.resolver's resolveFromCatalog: the specifier a catalog
86
+ // gives `name`, where `spec` asks for one.
87
+ function fromCatalog(catalogs, spec, name, where, major) {
88
+ if (!spec.startsWith(CATALOG)) return spec
89
+ const catalog = spec.slice(CATALOG.length).trim() || 'default'
90
+ const found = Object.hasOwn(catalogs, catalog) && Object.hasOwn(catalogs[catalog], name) ? catalogs[catalog][name] : undefined
91
+ const refused = found === undefined ? `catalog ${quote(catalog)} has no entry for ${quote(name)}`
92
+ : found.startsWith(CATALOG) ? `the entry for ${quote(name)} in catalog ${quote(catalog)} is itself a catalog reference`
93
+ : ['link', 'file', ...(major >= 11 ? [] : ['workspace'])].includes(found.split(':')[0]) ? `the entry for ${quote(name)} in catalog ${quote(catalog)} uses a protocol pnpm refuses in a catalog`
94
+ : undefined
95
+ if (refused !== undefined) throw new DeptreeError(`pnpm cannot resolve a catalog in the overrides: ${refused}`, where)
96
+ return found
97
+ }
98
+
99
+ // The directory an override names, as pnpm's local resolver reads a
100
+ // specifier, and by which protocol, or undefined for one that is none.
101
+ export function localOf(spec, where) {
102
+ const protocol = ['file:', 'link:'].find((prefix) => spec.startsWith(prefix)) ?? (/^(?:[./]|~\/)/u.test(spec) ? '' : undefined)
103
+ if (protocol === undefined) return undefined
104
+ const path = spec.slice(protocol.length).replace(/\/+$/u, '')
105
+ const dir = /^(?:[/\\]|~[/\\]|[A-Za-z]:)/u.test(path) || path.includes('\\') ? '..' : normalize(join('.', path))
106
+ if (dir === '..' || dir.startsWith('../')) throw new DeptreeError(`${quote(spec)} is not a directory under the lockfile's, which is not supported`, where)
107
+ return { protocol, dir }
108
+ }
109
+
110
+ // The overrides pnpm installs with, in order, as its parseOverrides has
111
+ // them: each selector parsed, and its specifier with any catalog resolved,
112
+ // and `local` the directory it names, where it names one. By selector,
113
+ // they are what the lockfile's `overrides` is held to.
114
+ export function listOverrides(overrides, catalogs, major = 10) {
115
+ const seen = new Set()
116
+ return Object.entries(overrides ?? {}).map(([raw, given]) => {
117
+ const where = `overrides[${quote(raw)}]`
118
+ const selector = major >= 11 ? raw.trim() : raw
119
+ if (seen.has(selector)) throw new DeptreeError(`${quote(selector)} is another selector's too, once pnpm 11 trims them`, where)
120
+ seen.add(selector)
121
+ const { parent, target } = parseSelector(selector, where)
122
+ const spec = fromCatalog(catalogs, given, target.name, where, major)
123
+ if (major < 11 || (target.range !== '' && parent?.range !== '')) return { selector, parent, target, spec, local: localOf(spec, where) }
124
+ if (parent !== undefined) throw new DeptreeError('an empty range with a parent is refused by pnpm 11', where)
125
+ if (valid(spec) === null) throw new DeptreeError(`${quote(spec)} is not the exact version pnpm 11 holds a converging override to`, where)
126
+ return { selector, target, spec, converge: true }
127
+ })
128
+ }
@@ -0,0 +1,142 @@
1
+ // Which patch pnpm 10 applies to a package: not the one its snapshot key
2
+ // names, but the one the settings' patchedDependencies pick for its name
3
+ // and version (@pnpm/patching.config's getPatchInfo): `name@version`
4
+ // exactly, else the one `name@range` whose range takes the version — two
5
+ // that do are refused — else `name@*` or `name` alone. Every snapshot is
6
+ // held to have the patch hash that pick has, so the patch applied here by
7
+ // the key is the one pnpm applies; and, stricter than pnpm, which checks
8
+ // this only when it resolves, every patch configured has to be the pick of
9
+ // some snapshot.
10
+
11
+ import { packageKeyOf } from '@preventive/lockfile/pnpm.js'
12
+ import { satisfies, valid, validRange } from '@preventive/upstream/semver.js'
13
+ import { DeptreeError, quote } from '../error.js'
14
+
15
+ // dependency-path's parse of a selector: a name and an exact version, a
16
+ // name and anything else after its `@`, or neither.
17
+ function parseSelector(selector) {
18
+ const at = selector.indexOf('@', 1)
19
+ const rest = at === -1 ? '' : packageKeyOf(selector).slice(at + 1)
20
+ if (rest === '') return {}
21
+ const name = selector.slice(0, at)
22
+ return valid(rest) === rest ? { name, version: rest } : { name, range: rest }
23
+ }
24
+
25
+ // groupPatchedDependencies: by package name, the selectors that can pick
26
+ // it; a later one of a kind over an earlier, as pnpm assigns them.
27
+ function group(selectors) {
28
+ const groups = new Map()
29
+ const of = (name) => {
30
+ if (!groups.has(name)) groups.set(name, { exact: new Map(), ranges: [], all: undefined })
31
+ return groups.get(name)
32
+ }
33
+ for (const selector of selectors) {
34
+ const { name, version, range } = parseSelector(selector)
35
+ if (version !== undefined) of(name).exact.set(version, selector)
36
+ else if (range === undefined) of(selector).all = selector
37
+ else if (validRange(range) === null) throw new DeptreeError(`${quote(range)} is not a version range, which pnpm refuses`, `patchedDependencies[${quote(selector)}]`)
38
+ else if (range.trim() === '*') of(name).all = selector
39
+ else of(name).ranges.push({ range, selector })
40
+ }
41
+ return groups
42
+ }
43
+
44
+ function pick(groups, name, version, where) {
45
+ const found = groups.get(name)
46
+ if (found === undefined) return undefined
47
+ if (found.exact.has(version)) return found.exact.get(version)
48
+ const taking = found.ranges.filter(({ range }) => satisfies(version, range))
49
+ if (taking.length > 1) throw new DeptreeError(`the patches ${taking.map(({ selector }) => quote(selector)).join(' and ')} both take it, which pnpm refuses`, where)
50
+ return taking[0]?.selector ?? found.all
51
+ }
52
+
53
+ // `hashes` is the configured patches' hashes and paths, by selector.
54
+ export function checkPatchUse(lockfile, hashes) {
55
+ const groups = group(Object.keys(hashes))
56
+ const used = new Set()
57
+ for (const [key, pkg] of Object.entries(lockfile.packages)) {
58
+ const selector = pick(groups, pkg.name, pkg.version, quote(key))
59
+ const wanted = selector === undefined ? undefined : hashes[selector].hash
60
+ if (wanted !== pkg.patchHash) {
61
+ throw new DeptreeError(`pnpm applies ${selector === undefined ? 'no patch' : `the patch of ${quote(selector)}`} to it, and the lockfile names ${pkg.patchHash === undefined ? 'none' : `the patch ${pkg.patchHash}`}`, quote(key))
62
+ }
63
+ if (selector !== undefined) used.add(selector)
64
+ }
65
+ for (const selector of Object.keys(hashes)) {
66
+ if (!used.has(selector)) throw new DeptreeError('patches no package in the lockfile', `patchedDependencies[${quote(selector)}]`)
67
+ }
68
+ }
69
+
70
+ const PATCH = '(patch_hash='
71
+
72
+ // A key's run of balanced groups at its end, each on its own, and what is
73
+ // before them; undefined where they do not balance.
74
+ function splitSuffix(key) {
75
+ const segments = []
76
+ let end = key.length
77
+ while (end > 0 && key[end - 1] === ')') {
78
+ let depth = 0
79
+ let start = end - 1
80
+ for (; start >= 0; start--) {
81
+ if (key[start] === ')') depth++
82
+ else if (key[start] === '(' && --depth === 0) break
83
+ }
84
+ if (start < 0) return undefined
85
+ segments.unshift(key.slice(start, end))
86
+ end = start
87
+ }
88
+ return { locator: key.slice(0, end), segments }
89
+ }
90
+
91
+ // dependency-path's parse, of what is read here: the name, the version
92
+ // where it is SemVer, and the patch hash.
93
+ function parseKey(key) {
94
+ const at = key.indexOf('@', 1)
95
+ if (at === -1 || at === key.length - 1) return {}
96
+ const rest = key.slice(at + 1)
97
+ const base = packageKeyOf(rest)
98
+ const hash = rest.startsWith(PATCH, base.length) ? rest.slice(base.length + PATCH.length, rest.indexOf(')', base.length)) : undefined
99
+ return { name: key.slice(0, at), version: valid(base) === null ? undefined : base, hash }
100
+ }
101
+
102
+ // pnpm 11 holds what a key names to their patches down through its peers
103
+ // (@pnpm/lockfile.fs's checkPatchedDepPaths), where pnpm 10 holds only the
104
+ // snapshot: a peer that names a patch hash, or, unless dedupePeers leaves
105
+ // them out, one of a version of a patched package, has to name the hash of
106
+ // the patch picked for it. One whose hash cannot be told is refused too.
107
+ export function checkPeerPatches(lockfile, hashes) {
108
+ const groups = group(Object.keys(hashes))
109
+ const carried = lockfile.settings.dedupePeers !== true
110
+ const uncheckable = (key, where) => new DeptreeError(`${quote(key)} is patched in a way pnpm 11 cannot check against patchedDependencies, which a frozen install refuses`, where)
111
+ const seen = new Set()
112
+ const judge = (key, where) => {
113
+ const suffix = splitSuffix(key)
114
+ if (key.includes(PATCH) && (suffix === undefined || suffix.locator.includes(PATCH) || suffix.segments.slice(1).some((segment) => segment.startsWith(PATCH)))) throw uncheckable(key, where)
115
+ const { name, version, hash } = parseKey(key)
116
+ if (name === undefined) throw uncheckable(key, where)
117
+ const known = lockfile.packages[key]?.version ?? version
118
+ const found = groups.get(name)
119
+ if (known === undefined && found !== undefined && (found.exact.size > 0 || found.ranges.length > 0)) throw uncheckable(key, where)
120
+ const selector = found === undefined ? undefined : pick(groups, name, known ?? '', where)
121
+ if ((selector === undefined ? undefined : hashes[selector].hash) !== hash) {
122
+ throw new DeptreeError(`the patch hash ${quote(key)} names is not the one of the patch pnpm picks for it, which pnpm 11 refuses a frozen install for`, where)
123
+ }
124
+ const peers = []
125
+ for (const segment of suffix?.segments ?? []) {
126
+ if (segment.startsWith(PATCH)) continue
127
+ const peer = segment.slice(1, -1)
128
+ const parsed = parseKey(peer)
129
+ if (segment.includes(PATCH) || (carried && version !== undefined && parsed.version !== undefined && groups.has(parsed.name))) peers.push(peer)
130
+ }
131
+ return peers
132
+ }
133
+ for (const key of Object.keys(lockfile.packages)) {
134
+ let level = [key]
135
+ while (level.length > 0) {
136
+ level = level.filter((peer) => !seen.has(peer)).flatMap((peer) => {
137
+ seen.add(peer)
138
+ return judge(peer, quote(key))
139
+ })
140
+ }
141
+ }
142
+ }