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

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.
package/src/pnpm/hook.js CHANGED
@@ -16,6 +16,7 @@
16
16
  // peerDependenciesMeta with the peer.
17
17
 
18
18
  import { intersects, satisfies, validRange } from '@preventive/upstream/semver.js'
19
+ import { relative } from '@preventive/vfs/path.js'
19
20
  import { DeptreeError } from '../error.js'
20
21
  import { createMatcher } from '../matcher.js'
21
22
 
@@ -31,20 +32,10 @@ const mostSpecific = (overrides) => overrides.sort((a, b) => (meets(b.target.ran
31
32
 
32
33
  const isPeerRange = (spec) => validRange(spec) !== null || spec.includes('workspace:') || spec.includes('catalog:')
33
34
 
34
- // A path from one directory under the lockfile's to another, both in
35
- // their normal form.
36
- function pathBetween(from, to) {
37
- const a = from === '.' ? [] : from.split('/')
38
- const b = to === '.' ? [] : to.split('/')
39
- let shared = 0
40
- while (shared < a.length && shared < b.length && a[shared] === b[shared]) shared++
41
- return [...a.slice(shared).map(() => '..'), ...b.slice(shared)].join('/') || '.'
42
- }
43
-
44
35
  // An override to a directory, `local` as listOverrides has it, as pnpm
45
36
  // writes it into the project at `dir`: relative to it.
46
37
  function localSpec({ protocol, dir: to }, dir) {
47
- const path = pathBetween(dir, to)
38
+ const path = relative(dir, to) || '.'
48
39
  return protocol === '' && !path.startsWith('.') ? `./${path}` : `${protocol}${path}`
49
40
  }
50
41
 
@@ -64,19 +55,21 @@ function checkFields(manifest, where) {
64
55
  // override to a path is written into it as pnpm writes it, and undefined
65
56
  // for a package's, whose specifiers are not read.
66
57
  export function createHook({ overrides, ignored, major = 10 }) {
58
+ // Each list by the name it overrides, in order.
59
+ const byName = (list) => Map.groupBy(list, ({ target }) => target.name)
67
60
  const withParent = overrides.filter(({ parent }) => parent !== undefined)
68
- const generic = overrides.filter(({ parent, converge }) => parent === undefined && !converge)
61
+ const generic = byName(overrides.filter(({ parent, converge }) => parent === undefined && !converge))
69
62
  const converging = new Map(overrides.filter(({ converge }) => converge).map(({ target, spec }) => [target.name, spec]))
70
- const isIgnored = ignored.length > 0 ? createMatcher(ignored) : undefined
63
+ const isIgnored = createMatcher(ignored)
71
64
  return (manifest, where, { dir } = {}) => {
72
65
  checkFields(manifest, where)
73
66
  const copy = structuredClone(manifest)
74
67
  if (overrides.length > 0) {
75
- const scoped = withParent.filter(({ parent }) => parent.name === copy.name && (!parent.range || satisfies(copy.version, parent.range)))
68
+ const scoped = byName(withParent.filter(({ parent }) => parent.name === copy.name && (!parent.range || satisfies(copy.version, parent.range))))
69
+ const pick = (list, spec) => mostSpecific((list ?? []).filter(({ target }) => meets(target.range, spec)))
76
70
  const override = (deps, peers) => {
77
71
  for (const [name, spec] of Object.entries(peers ?? deps)) {
78
- const chosen = mostSpecific(scoped.filter(({ target }) => target.name === name && meets(target.range, spec)))
79
- ?? mostSpecific(generic.filter(({ target }) => target.name === name && meets(target.range, spec)))
72
+ const chosen = pick(scoped.get(name), spec) ?? pick(generic.get(name), spec)
80
73
  const version = converging.get(name)
81
74
  if (chosen === undefined && version !== undefined && validRange(spec, { loose: true }) !== null && satisfies(version, spec, { loose: true })) (peers ?? deps)[name] = version
82
75
  if (chosen === undefined) continue
@@ -94,12 +87,10 @@ export function createHook({ overrides, ignored, major = 10 }) {
94
87
  for (const kind of KINDS) if (copy[kind] !== undefined) override(copy[kind])
95
88
  if (copy.peerDependencies !== undefined) override(copy.dependencies ??= {}, copy.peerDependencies)
96
89
  }
97
- if (isIgnored !== undefined) {
98
- for (const name of Object.keys(copy.optionalDependencies ?? {})) {
99
- if (!isIgnored(name)) continue
100
- delete copy.optionalDependencies[name]
101
- delete copy.dependencies?.[name]
102
- }
90
+ for (const name of Object.keys(copy.optionalDependencies ?? {})) {
91
+ if (!isIgnored(name)) continue
92
+ delete copy.optionalDependencies[name]
93
+ delete copy.dependencies?.[name]
103
94
  }
104
95
  return copy
105
96
  }
@@ -0,0 +1,125 @@
1
+ // What buildPnpmTree and findPnpmProjects take, checked: the host pnpm
2
+ // would install on, and the files an install reads — given as text, or
3
+ // read from the project (project.js) as pnpm reads them from disk.
4
+
5
+ import { parseYaml } from '@preventive/lockfile/yaml.js'
6
+ import { valid } from '@preventive/upstream/semver.js'
7
+ import { DeptreeError, quote } from '../error.js'
8
+ import { checkProject, readManifestTexts, readPatches, readRootFiles, readText, readWorkspaceText, typeOf } from './project.js'
9
+ import { pinnedPnpm, readManifest, readManifests } from './projects.js'
10
+ import { readers } from './readers.js'
11
+ import { checkWorkspace, findProjects, linkedManifest } from './workspace.js'
12
+
13
+ const LIBC = new Set(['glibc', 'musl', 'unknown'])
14
+
15
+ // The major version of `pnpm`, 10 or 11: what pnpm 11 does differently is
16
+ // read by it, where it is.
17
+ function majorOf(pnpm) {
18
+ const major = Number(valid(pnpm)?.split('.')[0])
19
+ if (major !== 10 && major !== 11) throw new DeptreeError(`pnpm ${quote(pnpm)} is not supported: only pnpm 10 and 11 are`, 'host.pnpm')
20
+ return major
21
+ }
22
+
23
+ // The pnpm that installs, and its major version: `pnpm`, host.pnpm, or
24
+ // where that is left out, the one the root package.json pins by its
25
+ // packageManager, which is the only one it takes; `root` gives that
26
+ // package.json as parsed, and is called only then.
27
+ function pnpmOf(pnpm, root) {
28
+ if (pnpm !== undefined && (typeof pnpm !== 'string' || pnpm === '')) throw new TypeError('host.pnpm must be a non-empty string, or left out')
29
+ const version = pnpm ?? pinnedPnpm(root()?.packageManager)
30
+ if (version === undefined) throw new TypeError('host.pnpm must be given where the root package.json\'s packageManager pins no pnpm')
31
+ return { pnpm: version, major: majorOf(version) }
32
+ }
33
+
34
+ // All of host but its pnpm, which pnpmOf reads.
35
+ export function checkHost(host) {
36
+ if (host === null || typeof host !== 'object') throw new TypeError('host must be an object with node, os, cpu and libc, and pnpm where it is not pinned')
37
+ for (const key of ['node', 'os', 'cpu', 'libc']) {
38
+ if (typeof host[key] !== 'string' || host[key] === '') throw new TypeError(`host.${key} must be a non-empty string`)
39
+ }
40
+ const { node, os, libc } = host
41
+ if (valid(node) === null) throw new DeptreeError(`${quote(node)} is not an exact version`, 'host.node')
42
+ if (os === 'win32') throw new DeptreeError('Windows is not supported: pnpm links there with junctions to absolute paths', 'host.os')
43
+ if (!LIBC.has(libc)) throw new DeptreeError(`expected "glibc", "musl" or "unknown", found ${quote(libc)}`, 'host.libc')
44
+ return { node, os, cpu: host.cpu, libc }
45
+ }
46
+
47
+ // pnpm-workspace.yaml as parsed; one of comments alone, or nothing, sets
48
+ // nothing, as pnpm reads it.
49
+ export const readWorkspace = (text) => (text === undefined || /^(?:[\t ]*(?:#.*)?(?:\r?\n|$))*$/u.test(text) ? undefined : parseYaml(text))
50
+
51
+ // The root package.json in `project`, as parsed, where there is one; one
52
+ // that is a link is refused unread, as findProjects refuses it.
53
+ const ROOT = 'manifests["."]'
54
+ function readRoot(project) {
55
+ if (typeOf(project, '/package.json', false) === 'symlink') throw linkedManifest('package.json')
56
+ const text = readText(project, '/package.json', ROOT)
57
+ return text === undefined ? undefined : readManifest(text, ROOT)
58
+ }
59
+
60
+ // The packages of `workspace`, pnpm-workspace.yaml as parsed, read here
61
+ // before the rest of it is, to find the projects by.
62
+ function packagesOf(workspace) {
63
+ if (workspace !== undefined && (workspace === null || typeof workspace !== 'object' || Array.isArray(workspace))) throw new DeptreeError('expected a mapping', 'pnpm-workspace.yaml')
64
+ return workspace?.packages === undefined ? undefined : readers.globs(workspace.packages, 'pnpm-workspace.yaml: packages')
65
+ }
66
+
67
+ // The directories of the projects pnpm finds in `project`, which
68
+ // buildPnpmTree takes the package.json of each of.
69
+ export function findPnpmProjects(options) {
70
+ const { project, host } = options ?? {}
71
+ checkProject(project)
72
+ if (host !== undefined && (host === null || typeof host !== 'object')) throw new TypeError('host must be an object, or left out')
73
+ const { major } = pnpmOf(host?.pnpm, () => readRoot(project))
74
+ return findProjects(project, packagesOf(readWorkspace(readWorkspaceText(project))), major)
75
+ }
76
+
77
+ const LOCKFILE = 'lockfile must be the text of pnpm-lock.yaml, or left out with a project given to read it from'
78
+
79
+ // The files an install reads but the package.json and the patches: given,
80
+ // with `lockfile`, or read from `project` without it.
81
+ export function inputsOf(options) {
82
+ const { lockfile, manifests, workspace, npmrc, patches, project } = options
83
+ if (lockfile === undefined) {
84
+ if (project === undefined) throw new TypeError(LOCKFILE)
85
+ for (const [name, value] of Object.entries({ manifests, workspace, npmrc, patches })) {
86
+ if (value !== undefined) throw new TypeError(`${name} must be left out where lockfile is: both are read from project`)
87
+ }
88
+ return { reading: true, project, ...readRootFiles(project) }
89
+ }
90
+ if (typeof lockfile !== 'string') throw new TypeError(LOCKFILE)
91
+ for (const [name, value] of Object.entries({ workspace, npmrc })) {
92
+ if (value !== undefined && typeof value !== 'string') throw new TypeError(`${name} must be a string, or left out`)
93
+ }
94
+ return { reading: false, lockfile, manifests, workspace, npmrc, patches }
95
+ }
96
+
97
+ // The package.json of every project, and the pnpm that installs as pnpmOf
98
+ // reads it from the root one: as given, or read from the project for
99
+ // each project pnpm finds there, and no other, as pnpm reads them: an
100
+ // importer the globs do not take is refused first, and one they take that
101
+ // pnpm does not find has none. `workspace` is pnpm-workspace.yaml as
102
+ // parsed; `pnpm` host.pnpm.
103
+ export function manifestsOf(inputs, workspace, lockfile, pnpm) {
104
+ if (!inputs.reading) {
105
+ const manifests = readManifests(inputs.manifests, lockfile)
106
+ return { manifests, ...pnpmOf(pnpm, () => manifests.get('.')) }
107
+ }
108
+ const { project } = inputs
109
+ const installs = pnpmOf(pnpm, () => readRoot(project))
110
+ const packages = packagesOf(workspace)
111
+ checkWorkspace(Object.keys(lockfile.importers), packages, installs.major)
112
+ const ids = findProjects(project, packages, installs.major)
113
+ return { manifests: readManifests(readManifestTexts(project, ids), lockfile), ...installs }
114
+ }
115
+
116
+ // The patch files, by path: as given, or read from the project, each that
117
+ // `configured`, patchedDependencies, names.
118
+ export function patchesOf(inputs, configured) {
119
+ if (inputs.reading) return readPatches(inputs.project, configured)
120
+ const entries = inputs.patches instanceof Map ? [...inputs.patches] : Object.entries(inputs.patches ?? {})
121
+ for (const [path, text] of entries) {
122
+ if (typeof text !== 'string') throw new TypeError(`patches[${quote(path)}] must be a string`)
123
+ }
124
+ return entries
125
+ }
@@ -70,12 +70,20 @@ function effectivePlatform(pkg) {
70
70
  // lists for each, `current` standing for itself.
71
71
  const current = (value, supported) => (supported ?? ['current']).map((item) => (item === 'current' ? value : item))
72
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))
73
+ const takesPlatform = (pkg, host, supported) => checkList(current(host.os, supported?.os), pkg.os ?? ['any'], host.major)
74
+ && checkList(current(host.cpu, supported?.cpu), pkg.cpu ?? ['any'], host.major)
75
+ && (host.libc === 'unknown' || checkList(current(host.libc, supported?.libc), pkg.libc ?? ['any'], host.major))
76
76
 
77
77
  const takesEngine = (engines, node) => !engines.node || satisfies(node, engines.node, { includePrerelease: true })
78
78
 
79
+ // The Node pnpm checks engines.node against.
80
+ const nodeOf = ({ host, settings }) => settings.nodeVersion ?? host.node
81
+
82
+ // With engineStrict, pnpm 11 passes over the engines the lockfile records
83
+ // of a patched snapshot, and holds those of its package.json, once
84
+ // patched, to the Node instead.
85
+ const patchedLater = ({ host, settings }) => host.major >= 11 && settings.engineStrict === true
86
+
79
87
  // A package.json's os, cpu or libc as pnpm's checkList reads one: a string
80
88
  // is a list of it, and what is not a string in a list is passed over.
81
89
  function platformList(value, where) {
@@ -92,10 +100,10 @@ function platformList(value, where) {
92
100
  // not match is found first, and the engines are then not looked at.
93
101
  export function checkProject(manifest, where, { host, settings }) {
94
102
  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
103
+ if (!takesPlatform(platform, host, settings.supportedArchitectures)) return
96
104
  const engines = manifest.engines
97
105
  if (engines === undefined || engines === null) return
98
- const node = settings.nodeVersion ?? host.node
106
+ const node = nodeOf({ host, settings })
99
107
  if (engines.pnpm && !satisfies(host.pnpm, engines.pnpm, { includePrerelease: true })) {
100
108
  throw new DeptreeError(`its engines.pnpm, ${quote(String(engines.pnpm))}, does not take pnpm ${host.pnpm}, which pnpm refuses`, where)
101
109
  }
@@ -104,32 +112,34 @@ export function checkProject(manifest, where, { host, settings }) {
104
112
 
105
113
  // A check of one snapshot: true where the host can run it, false where it
106
114
  // 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
115
+ // is installed anyway. With `engineStrict` that last is refused, where the
116
+ // lockfile does not mark the snapshot optional. pnpm 10 takes a snapshot
117
+ // to be optional as the lockfile marks it; pnpm 11 as the edge it is
118
+ // reached by.
119
+ function createCheck(context) {
120
+ const { host, settings } = context
121
+ const node = nodeOf(context)
122
+ const later = patchedLater(context)
123
+ return (key, pkg, optional = pkg.optional) => {
124
+ const platform = takesPlatform(host.major >= 11 && optional ? effectivePlatform(pkg) : pkg, host, settings.supportedArchitectures)
125
+ if (platform && takesEngine(later && pkg.patchHash !== undefined ? {} : pkg.engines, node)) return true
119
126
  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))
127
+ if (settings.engineStrict && !pkg.optional) throw new DeptreeError(`the host does not take its ${platform ? 'engines.node' : 'os, cpu or libc'}, which engineStrict refuses`, quote(key))
121
128
  return null
122
129
  }
123
130
  }
124
131
 
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
132
+ // A check of a patched package's package.json, once patched, where pnpm
133
+ // makes one (patchedLater): it fails where the Node is not taken; where
127
134
  // the package is optional, it removes it from the tree it has linked,
128
135
  // 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)
136
+ export function createPatchedCheck(context) {
137
+ if (!patchedLater(context)) return undefined
138
+ const node = nodeOf(context)
139
+ return (manifest, where) => {
140
+ if (manifest.engines === undefined || manifest.engines === null || takesEngine(manifest.engines, node)) return
141
+ 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)
142
+ }
133
143
  }
134
144
 
135
145
  // A reference's key, or the project a `link:` leads to, if it is one.
@@ -159,7 +169,7 @@ function projectKeys(lockfile, ids, walked) {
159
169
 
160
170
  // pnpm 11's filterLockfileByImportersAndEngine: the snapshots left out,
161
171
  // and those installed although the host cannot run them.
162
- function skippedSnapshots11(lockfile, check, strict) {
172
+ function skippedSnapshots11(lockfile, check) {
163
173
  const edgesOf = (deps, optional) => Object.values(deps).filter((target) => !target.startsWith('link:')).map((key) => ({ key, optional }))
164
174
  const queue = Object.values(lockfile.importers).flatMap((importer) => [...edgesOf(importer.dependencies, false), ...edgesOf(importer.devDependencies, false), ...edgesOf(importer.optionalDependencies, true)])
165
175
  const starts = queue.map(({ key }) => key)
@@ -180,7 +190,7 @@ function skippedSnapshots11(lockfile, check, strict) {
180
190
  const warned = new Set()
181
191
  for (const key of incompatible.keys()) {
182
192
  const pkg = lockfile.packages[key]
183
- const ok = check(key, pkg, !installed.has(key) || !required.has(key), strict && !pkg.optional)
193
+ const ok = check(key, pkg, !installed.has(key) || !required.has(key))
184
194
  if (ok === false) skipped.add(key)
185
195
  if (ok === null) warned.add(key)
186
196
  }
@@ -197,9 +207,10 @@ function skippedSnapshots11(lockfile, check, strict) {
197
207
  }
198
208
 
199
209
  // 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)
210
+ // host cannot run them, the host and settings being `context`'s.
211
+ export function skippedSnapshots(lockfile, context) {
212
+ const check = createCheck(context)
213
+ if (context.host.major >= 11) return skippedSnapshots11(lockfile, check)
203
214
  const ids = Object.keys(lockfile.importers)
204
215
  const walked = new Set(ids)
205
216
  const picked = new Set()
package/src/pnpm/local.js CHANGED
@@ -1,49 +1,57 @@
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.
1
+ // Directories outside node_modules the tree links to or installs, read
2
+ // from the project (project.js) where one is given: those local overrides
3
+ // name, and every other a `link:` leads to that is no project and is under
4
+ // the lockfile's directory. Each has to hold a package.json there, whose
5
+ // bins take their names as pnpm links them. An override to a directory is
6
+ // read only from a project given. One by `file:` has pnpm install the
7
+ // directory as a package, of the files npm-packlist picks (packlist.js);
8
+ // one to a tarball is refused.
9
9
 
10
10
  import { DeptreeError, quote } from '../error.js'
11
+ import { packDirectory } from './packlist.js'
12
+ import { readText, typeOf } from './project.js'
11
13
  import { readManifest } from './projects.js'
12
14
 
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
- }
15
+ function manifestAt(project, dir, where) {
16
+ const text = readText(project, `/${dir}/package.json`, where)
17
+ if (text === undefined) throw new DeptreeError(`${quote(dir)} holds no package.json in the project given`, where)
24
18
  return readManifest(text, where)
25
19
  }
26
20
 
27
- // `overrides` is listOverrides's.
28
- export function checkLocalOverrides(overrides, vfs) {
21
+ // `overrides` is listOverrides's. It gives back the directories `file:`
22
+ // overrides have pnpm install.
23
+ export function checkLocalOverrides(overrides, project) {
24
+ const installed = new Set()
29
25
  for (const { selector, local } of overrides) {
30
26
  if (local === undefined) continue
31
27
  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)
28
+ if (project === undefined) throw new DeptreeError(`an override to a directory, ${quote(local.dir)}, is read only from a project given`, where)
29
+ if (local.protocol === 'file:' && typeOf(project, `/${local.dir}`) === 'file') throw new DeptreeError(`${quote(local.dir)} is a file in the project given, and an override to a tarball is not supported`, where)
30
+ manifestAt(project, local.dir, where)
31
+ if (local.protocol === 'file:') installed.add(local.dir)
35
32
  }
33
+ return installed
34
+ }
35
+
36
+ // The package at the directory a `file:` dependency names, from `project`:
37
+ // its files as npm-packlist picks them, and its package.json, which has
38
+ // to be for the name the lockfile has; the lockfile has no version.
39
+ export function readDirectoryPackage(project, pkg, where, major) {
40
+ const { directory } = pkg.resolution
41
+ const manifest = manifestAt(project, directory, where)
42
+ if (manifest.name !== pkg.name) throw new DeptreeError(`its package.json is for ${quote(String(manifest.name))}`, where)
43
+ return { files: packDirectory(project, directory, manifest, major, where), manifest }
36
44
  }
37
45
 
38
46
  // By directory, the package.json of each directory the tree links to that
39
47
  // 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) {
48
+ // lockfile's directory, read from `project`; none without one.
49
+ export function readLinked(links, nodes, projects, project) {
42
50
  const linked = new Map()
43
- if (vfs === undefined) return linked
51
+ if (project === undefined) return linked
44
52
  for (const [path, target] of links) {
45
53
  if (nodes.has(target) || projects.has(target) || linked.has(target) || target === '..' || target.startsWith('../')) continue
46
- linked.set(target, manifestAt(vfs, target, quote(path)))
54
+ linked.set(target, manifestAt(project, target, quote(path)))
47
55
  }
48
56
  return linked
49
57
  }
@@ -30,7 +30,7 @@
30
30
  // with a parent and an empty range, and one whose version is not exact.
31
31
 
32
32
  import { valid } from '@preventive/upstream/semver.js'
33
- import { join, normalize } from '@preventive/vfs/path.js'
33
+ import { join } from '@preventive/vfs/path.js'
34
34
  import { DeptreeError, quote } from '../error.js'
35
35
 
36
36
  // validate-npm-package-name 5's validForOldPackages, which pnpm reads a
@@ -82,12 +82,19 @@ export function replaceReferences(overrides, manifest, where) {
82
82
 
83
83
  const CATALOG = 'catalog:'
84
84
 
85
+ // The catalog a `catalog:` specifier names, `default` where it names none,
86
+ // or undefined for another specifier.
87
+ export const catalogOf = (spec) => (spec.startsWith(CATALOG) ? spec.slice(CATALOG.length).trim() || 'default' : undefined)
88
+
89
+ // The entry catalog `catalog` of `catalogs` has for `name`, if any.
90
+ export const catalogEntry = (catalogs, catalog, name) => (Object.hasOwn(catalogs, catalog) && Object.hasOwn(catalogs[catalog], name) ? catalogs[catalog][name] : undefined)
91
+
85
92
  // @pnpm/catalogs.resolver's resolveFromCatalog: the specifier a catalog
86
93
  // gives `name`, where `spec` asks for one.
87
94
  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
95
+ const catalog = catalogOf(spec)
96
+ if (catalog === undefined) return spec
97
+ const found = catalogEntry(catalogs, catalog, name)
91
98
  const refused = found === undefined ? `catalog ${quote(catalog)} has no entry for ${quote(name)}`
92
99
  : found.startsWith(CATALOG) ? `the entry for ${quote(name)} in catalog ${quote(catalog)} is itself a catalog reference`
93
100
  : ['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`
@@ -102,7 +109,7 @@ export function localOf(spec, where) {
102
109
  const protocol = ['file:', 'link:'].find((prefix) => spec.startsWith(prefix)) ?? (/^(?:[./]|~\/)/u.test(spec) ? '' : undefined)
103
110
  if (protocol === undefined) return undefined
104
111
  const path = spec.slice(protocol.length).replace(/\/+$/u, '')
105
- const dir = /^(?:[/\\]|~[/\\]|[A-Za-z]:)/u.test(path) || path.includes('\\') ? '..' : normalize(join('.', path))
112
+ const dir = /^(?:[/\\]|~[/\\]|[A-Za-z]:)/u.test(path) || path.includes('\\') ? '..' : join('.', path)
106
113
  if (dir === '..' || dir.startsWith('../')) throw new DeptreeError(`${quote(spec)} is not a directory under the lockfile's, which is not supported`, where)
107
114
  return { protocol, dir }
108
115
  }
@@ -0,0 +1,100 @@
1
+ // The files pnpm installs of a directory a `file:` dependency names: its
2
+ // directory fetcher picks them with npm-packlist — 5.1.3 for pnpm 10,
3
+ // 10.0.4 for pnpm 11 — and hardlinks them into the tree. Only
4
+ // npm-packlist's built-in rules are followed here, which leave out, by
5
+ // name and whatever its case:
6
+ //
7
+ // - anywhere, `.git`, `.svn`, `.hg`, `CVS`, `.npmrc`, `.DS_Store`,
8
+ // `npm-debug.log`, `.npmignore`, `.gitignore`, and a name starting
9
+ // with `._`, or `.` and ending in `.swp`, or ending in `.orig`, with
10
+ // everything in it;
11
+ // - at the top, and with pnpm 11 in every directory, `.lock-wscript`,
12
+ // `.wafpickle-*`, `build/config.gypi` and what is in
13
+ // `archived-packages`;
14
+ // - at the top, `node_modules` and the lockfiles `package-lock.json`,
15
+ // `yarn.lock`, `pnpm-lock.yaml` and, with pnpm 11, `bun.lockb`;
16
+ //
17
+ // and every name with a `*` in it. A directory those do not describe is
18
+ // refused: one with a .npmignore or .gitignore in it, or a package.json
19
+ // with `files` or bundled dependencies, whose rules are not followed
20
+ // here; one with a link in it, which the two pass over differently; and
21
+ // one where a file those leave out is one npm-packlist would keep, a
22
+ // readme, copying, license or licence file, or one `main`, `browser` or
23
+ // `bin` names, as the two keep them differently. So is a file whose mode
24
+ // is not 0o644 or 0o755, which linking a bin would change otherwise than
25
+ // fixBin has it.
26
+
27
+ import { join } from '@preventive/vfs/path.js'
28
+ import { DeptreeError, quote } from '../error.js'
29
+ import { readBytes } from './project.js'
30
+
31
+ // The rules each name is held to, folded, wherever it is.
32
+ const ANYWHERE = /^(?:\.git|\.svn|\.hg|cvs|\.npmrc|\.ds_store|npm-debug\.log|\.npmignore|\.gitignore|\._.*|\..*\.swp|.*\.orig)$/u
33
+
34
+ // The rules held to the path, by its names folded, from the directory they
35
+ // are read in: the top for npm-packlist 5, and every directory for
36
+ // npm-packlist 10, which reads them again in each.
37
+ const anchored = (names, directory) => (names.length === 1 && (names[0] === '.lock-wscript' || names[0].startsWith('.wafpickle-') || (directory && names[0] === 'archived-packages')))
38
+ || (names.length === 2 && names[0] === 'build' && names[1] === 'config.gypi')
39
+
40
+ // The names left out at the top alone.
41
+ const TOP = ['node_modules', 'package-lock.json', 'yarn.lock', 'pnpm-lock.yaml']
42
+ const TOP_11 = [...TOP, 'bun.lockb']
43
+
44
+ // Whether the built-in rules leave out the entry at `names`, its path from
45
+ // the package's directory by name, which is a directory where `directory`.
46
+ function leftOut(names, directory, major) {
47
+ const folded = names.map((name) => name.toLowerCase())
48
+ const readIn = major >= 11 ? folded.map((_, i) => folded.slice(i)) : [folded]
49
+ return ANYWHERE.test(folded.at(-1)) || readIn.some((path) => anchored(path, directory))
50
+ || (folded.length === 1 && (major >= 11 ? TOP_11 : TOP).includes(folded[0]))
51
+ }
52
+
53
+ // npm-packlist's names it keeps, whatever else says.
54
+ const MUST_HAVE = /^(?:readme|copying|license|licence)(?:\..*[^~$])?$/iu
55
+
56
+ // The paths a package.json's main, browser and bin name, from its
57
+ // directory, whatever their case.
58
+ function namedByManifest(manifest) {
59
+ const { main, browser, bin } = manifest
60
+ const paths = [main, browser, ...typeof bin === 'string' ? [bin] : Object.values(bin ?? {})]
61
+ return paths.filter((path) => typeof path === 'string').map((path) => join('.', path).toLowerCase())
62
+ }
63
+
64
+ // Whether a package.json's list of bundled dependencies may name any: an
65
+ // empty one bundles none, with either npm-packlist.
66
+ const bundles = (list) => Boolean(list) && !(Array.isArray(list) && list.length === 0)
67
+
68
+ // The files of the package at `dir` of `project` npm-packlist picks, with
69
+ // their data and modes, by their paths from it; `manifest` is its
70
+ // package.json as parsed.
71
+ export function packDirectory(project, dir, manifest, major, where) {
72
+ if (manifest.files !== undefined) throw new DeptreeError('its package.json has `files`, which npm-packlist picks the files pnpm installs by, and which is not followed here', where)
73
+ if (bundles(manifest.bundleDependencies) || bundles(manifest.bundledDependencies)) throw new DeptreeError('a directory with bundled dependencies is not supported', where)
74
+ const named = namedByManifest(manifest)
75
+ const files = new Map()
76
+ const visit = (names) => {
77
+ for (const entry of project.readdir(['', dir, ...names].join('/'))) {
78
+ const at = [...names, entry]
79
+ const rel = at.join('/')
80
+ const here = `${where}: ${quote(rel)}`
81
+ const { type, mode } = project.lstat(`/${dir}/${rel}`)
82
+ if (type === 'symlink') throw new DeptreeError('a link in a directory pnpm installs a copy of is not supported', here)
83
+ if (entry === '.npmignore' || entry === '.gitignore') throw new DeptreeError(`${entry}'s rules, which npm-packlist picks the files pnpm installs by, are not followed here`, here)
84
+ if (names.length === 0 && entry !== 'node_modules' && entry.toLowerCase() === 'node_modules') throw new DeptreeError('a name that is node_modules but for its case is kept by pnpm 10 and left out by pnpm 11', here)
85
+ if (entry.includes('*')) continue
86
+ if (leftOut(at, type === 'directory', major)) {
87
+ const folded = rel.toLowerCase()
88
+ if (MUST_HAVE.test(entry) || named.some((kept) => kept === folded || kept.startsWith(`${folded}/`))) {
89
+ throw new DeptreeError('whether pnpm installs it turns on rules of npm-packlist not followed here', here)
90
+ }
91
+ continue
92
+ }
93
+ if (type === 'directory') visit(at)
94
+ else if (mode !== 0o644 && mode !== 0o755) throw new DeptreeError(`its mode, ${mode.toString(8)}, is not 644 or 755, which is not supported`, here)
95
+ else files.set(rel, { data: readBytes(project, `/${dir}/${rel}`), mode })
96
+ }
97
+ }
98
+ visit([])
99
+ return files
100
+ }
@@ -9,7 +9,7 @@
9
9
  // some snapshot.
10
10
 
11
11
  import { packageKeyOf } from '@preventive/lockfile/pnpm.js'
12
- import { satisfies, valid, validRange } from '@preventive/upstream/semver.js'
12
+ import { isExactVersion, satisfies, valid, validRange } from '@preventive/upstream/semver.js'
13
13
  import { DeptreeError, quote } from '../error.js'
14
14
 
15
15
  // dependency-path's parse of a selector: a name and an exact version, a
@@ -19,7 +19,7 @@ function parseSelector(selector) {
19
19
  const rest = at === -1 ? '' : packageKeyOf(selector).slice(at + 1)
20
20
  if (rest === '') return {}
21
21
  const name = selector.slice(0, at)
22
- return valid(rest) === rest ? { name, version: rest } : { name, range: rest }
22
+ return isExactVersion(rest) ? { name, version: rest } : { name, range: rest }
23
23
  }
24
24
 
25
25
  // groupPatchedDependencies: by package name, the selectors that can pick
@@ -117,7 +117,7 @@ export function checkPeerPatches(lockfile, hashes) {
117
117
  const known = lockfile.packages[key]?.version ?? version
118
118
  const found = groups.get(name)
119
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)
120
+ const selector = pick(groups, name, known ?? '', where)
121
121
  if ((selector === undefined ? undefined : hashes[selector].hash) !== hash) {
122
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
123
  }