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

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@preventive/deptree",
3
- "version": "1.0.0-alpha.0",
3
+ "version": "1.0.0-alpha.1",
4
4
  "description": "A node_modules tree in memory, as a package manager would install it: pnpm 10 or 11 from its lockfile, tarballs fetched and checked, patches applied",
5
5
  "type": "module",
6
6
  "exports": {
@@ -28,6 +28,7 @@
28
28
  "src/pnpm/local.js",
29
29
  "src/pnpm/npmrc.js",
30
30
  "src/pnpm/overrides.js",
31
+ "src/pnpm/packlist.js",
31
32
  "src/pnpm/patches.js",
32
33
  "src/pnpm/projects.js",
33
34
  "src/pnpm/readers.js",
package/pnpm.d.ts CHANGED
@@ -43,7 +43,12 @@ export interface PnpmHost {
43
43
  // and no other glob syntax. Without `packages` the root is the only
44
44
  // project. Every importer has to have its package.json given, and be a
45
45
  // project those globs take; and every project pnpm would find has to be
46
- // given, which cannot be checked here, as the directories are not.
46
+ // given, which buildPnpmTree cannot check, as it is not given the
47
+ // directories: findPnpmProjects finds them in those. A project the
48
+ // lockfile has no importer for is held to an empty one, as pnpm holds it:
49
+ // with no dependencies it is installed, and hoisted by its name, and with
50
+ // any it is refused as not up to date. Its directory has to be given as
51
+ // pnpm would key its importer: from the lockfile's, in normal form.
47
52
  //
48
53
  // Each project is held to its importer as --frozen-lockfile holds it: its
49
54
  // dependencies, devDependencies, optionalDependencies and, with
@@ -59,11 +64,18 @@ export interface PnpmHost {
59
64
  // those name none are pnpm-workspace.yaml's `overrides` read. `$name` in
60
65
  // one is the root package.json's own specifier for `name`, and
61
66
  // `catalog:` what the workspace's catalog gives the package. One to a
62
- // directory — a path alone, such as `./vendor/foo`, or by `link:` — is
63
- // read only with `vfs` given, and only where the directory is under the
64
- // lockfile's and holds a package.json there; pnpm links it. One to a copy
65
- // of a directory, by `file:`, is refused: pnpm picks the files it copies
66
- // with npm-packlist.
67
+ // directory — a path alone, such as `./vendor/foo`, `link:` or `file:` —
68
+ // is read only with `vfs` given, and only where the directory is under
69
+ // the lockfile's and holds a package.json there. pnpm links to it by a
70
+ // path alone or `link:`. By `file:` it installs it as a package, of the
71
+ // files npm-packlist's built-in rules keep, which are followed here alone:
72
+ // a directory with a .npmignore or .gitignore, a package.json with `files`
73
+ // or bundled dependencies, or a link in it, is refused. pnpm hardlinks
74
+ // those files from the directory into each snapshot of the package, so a
75
+ // file linking a bin makes executable is made so in every snapshot and in
76
+ // the directory, which is not written here; a CRLF `#!` line it rewrites
77
+ // is rewritten as a file of that snapshot's own. One by `file:` to a
78
+ // tarball is refused, and so is a `file:` dependency no override names.
67
79
  //
68
80
  // Of the .npmrc, only what pnpm reads for an install is read: its settings
69
81
  // by their kebab-case names, those that can change the tree held to what
@@ -217,6 +229,36 @@ export interface PnpmTree {
217
229
  // TypeError is thrown for options of the wrong type.
218
230
  export function buildPnpmTree(options: PnpmTreeOptions): Promise<PnpmTree>
219
231
 
232
+ // The directories of the projects pnpm finds for the workspace at the
233
+ // root of `vfs`, by which buildPnpmTree takes their package.json: `.`, the
234
+ // root, first, then in order each directory whose package.json a glob of
235
+ // `workspace`'s `packages` takes, as pnpm `host.pnpm` finds them.
236
+ //
237
+ // `vfs` is a Vfs, or anything with its readdir, lstat and stat, such as a
238
+ // view of a directory on disk, by paths from `/`; nothing is written. Of
239
+ // it, only the directories pnpm walks into are read: none under
240
+ // node_modules or bower_components, and none whose name starts with a dot
241
+ // unless a glob spells it there. A manifest is a file, or a link to one; a
242
+ // link that leads nowhere, or to a directory, is none, as pnpm has it.
243
+ //
244
+ // Refused: a root with no manifest, which pnpm takes for no project; a
245
+ // project, the root among them, whose manifest is package.json5 or
246
+ // package.yaml, which pnpm reads where there is no package.json, or is a
247
+ // link; a project pnpm finds through a link to a directory, which it
248
+ // follows, and a link to a directory in one followed, which is not; a
249
+ // project in a directory a lockfile could not key its importer by, with a
250
+ // control, bidirectional or backslash character in its path, or a drive
251
+ // letter; a node_modules pnpm walks into, which it does only under a
252
+ // directory with a leading dot that a glob spells; and a glob
253
+ // buildPnpmTree refuses, or a pnpm not 10.x or 11.x.
254
+ export interface PnpmProjectsOptions {
255
+ workspace?: string
256
+ host: Pick<PnpmHost, 'pnpm'>
257
+ vfs: Pick<Vfs, 'readdir' | 'lstat' | 'stat'>
258
+ }
259
+
260
+ export function findPnpmProjects(options: PnpmProjectsOptions): string[]
261
+
220
262
  // `where` is what a refusal is about — `pnpm-workspace.yaml: nodeLinker`,
221
263
  // `.npmrc:3: node-linker`, a package's key — or undefined for the call as
222
264
  // a whole; the message leads with it. `cause` is what a package beneath
package/pnpm.js CHANGED
@@ -2,7 +2,7 @@
2
2
  // 11 installs it with the isolated linker: pnpm.d.ts says what it takes and
3
3
  // what comes back. Nothing here touches a filesystem; tarballs come
4
4
  // through @preventive/upstream, and whatever cache it keeps is its own.
5
- export { buildPnpmTree } from './src/pnpm/tree.js'
5
+ export { buildPnpmTree, findPnpmProjects } from './src/pnpm/tree.js'
6
6
  export { DeptreeError } from './src/error.js'
7
7
  // Where @preventive/upstream caches what it fetches, tarballs among it;
8
8
  // unset, nothing is cached and nothing is written.
package/src/mount.js CHANGED
@@ -39,20 +39,27 @@ function typeAt(vfs, path) {
39
39
  // Each file is taken out of `tree` as it is written.
40
40
  export function mount(tree, target, folded) {
41
41
  checkNoModules(target, folded)
42
- const entries = [...tree.walk('/')].filter(({ path }) => path !== '/')
43
- for (const { path, type } of entries) {
44
- const existing = typeAt(target, path)
42
+ // The tree's entries, parents first, each with what is there already;
43
+ // under a directory that is not there, nothing is.
44
+ const absent = new Set()
45
+ const entries = []
46
+ for (const { path, type } of tree.walk('/')) {
47
+ if (path === '/') continue
48
+ const parent = dirname(path)
49
+ const existing = absent.has(parent) ? undefined : typeAt(target, path)
50
+ if (existing === undefined && type === 'directory') absent.add(path)
51
+ entries.push({ path, type, existing })
45
52
  if (existing !== undefined && (type !== 'directory' || existing !== 'directory')) {
46
53
  throw new DeptreeError(`a ${existing} is there already, where the tree has a ${type}`, where(path))
47
54
  }
48
- if (!folded || existing !== undefined || typeAt(target, dirname(path)) !== 'directory') continue
55
+ if (!folded || existing !== undefined || absent.has(parent)) continue
49
56
  const name = basename(path)
50
- const clash = target.readdir(dirname(path)).find((other) => fold(other) === fold(name))
57
+ const clash = target.readdir(parent).find((other) => fold(other) === fold(name))
51
58
  if (clash !== undefined) throw new DeptreeError(`${quote(clash)} is there already, which is one name with ${quote(name)} on macOS`, where(path))
52
59
  }
53
- for (const { path, type } of entries) {
60
+ for (const { path, type, existing } of entries) {
54
61
  if (type === 'directory') {
55
- if (typeAt(target, path) === undefined) target.mkdir(path)
62
+ if (existing === undefined) target.mkdir(path)
56
63
  } else if (type === 'symlink') {
57
64
  target.symlink(tree.readlink(path), path)
58
65
  } else {
package/src/pnpm/bins.js CHANGED
@@ -197,7 +197,7 @@ function bundledIn(files) {
197
197
 
198
198
  function parseManifest(file, where) {
199
199
  try {
200
- const manifest = JSON.parse(decoder.decode(file.data).replace(/^/u, ''))
200
+ const manifest = JSON.parse(decoder.decode(file.data))
201
201
  if (manifest === null || typeof manifest !== 'object' || Array.isArray(manifest)) throw new Error('not an object')
202
202
  return manifest
203
203
  } catch {
@@ -248,7 +248,7 @@ function peersOf(children, nodes) {
248
248
  // Whether pnpm builds a package, as its pkgRequiresBuild tells: an
249
249
  // install script, a binding.gyp or a .hooks directory.
250
250
  const hasInstallScript = (manifest, files) => Boolean((manifest.scripts != null && (manifest.scripts.preinstall || manifest.scripts.install || manifest.scripts.postinstall))
251
- || files.has('binding.gyp') || [...files.keys()].some((path) => /^\.hooks[\\/]/u.test(path)))
251
+ || files.has('binding.gyp') || files.keys().some((path) => /^\.hooks[\\/]/u.test(path)))
252
252
 
253
253
  // The files pnpm runs fixBin on, by the directory of the package they
254
254
  // are in: `nodes` is the graph by directory, each node with its package's
@@ -259,7 +259,7 @@ const hasInstallScript = (manifest, files) => Boolean((manifest.scripts != null
259
259
  // installed automatically, and `major` pnpm's major version.
260
260
  export function binTargets({ nodes, projects, direct, links, publicHoist, building, peers, major }) {
261
261
  const commandCache = new Map()
262
- const commandsOfDir = (dir, { raw = false } = {}) => {
262
+ const commandsOfDir = (dir, { normalize = false } = {}) => {
263
263
  const node = nodes.get(dir)
264
264
  if (node !== undefined) {
265
265
  if (!commandCache.has(dir)) commandCache.set(dir, commandsOf(dir, node.manifest, node.files, dir, quote(node.key), major))
@@ -271,7 +271,7 @@ export function binTargets({ nodes, projects, direct, links, publicHoist, buildi
271
271
  const manifest = projects.get(dir)
272
272
  if (manifest === undefined) return [UNKNOWN]
273
273
  const where = `manifests[${quote(dir)}]`
274
- return commandsOf(dir, raw ? manifest : normalized(manifest, where), undefined, undefined, where, major)
274
+ return commandsOf(dir, normalize ? normalized(manifest, where) : manifest, undefined, undefined, where, major)
275
275
  }
276
276
 
277
277
  // By each file's path in the tree, the package it is in; and of those
@@ -279,11 +279,10 @@ export function binTargets({ nodes, projects, direct, links, publicHoist, buildi
279
279
  const fixed = new Map()
280
280
  const contested = new Map()
281
281
  // One linking of commands into a directory: `ordered` says whether the
282
- // order they come in is one pnpm always has, and `blind` whether a
283
- // command not known here may be among them. It gives back the names
282
+ // order they come in is one pnpm always has. It gives back the names
284
283
  // linked, and whether others may be.
285
- const link = (commands, { ordered, blind = false, where }) => {
286
- const unknown = blind || commands.some((command) => command.unknown)
284
+ const link = (commands, { ordered, where }) => {
285
+ const unknown = commands.some((command) => command.unknown)
287
286
  const best = new Map()
288
287
  for (const command of commands) {
289
288
  if (command.unknown) continue
@@ -309,7 +308,7 @@ export function binTargets({ nodes, projects, direct, links, publicHoist, buildi
309
308
  const children = [...node.children.values()]
310
309
  const withBins = children.filter((dir) => nodes.get(dir)?.pkg.hasBin).flatMap((dir) => commandsOfDir(dir))
311
310
  if (children.every((dir) => nodes.has(dir))) link(withBins, { ordered: true, where })
312
- else link(children.flatMap((dir) => commandsOfDir(dir)), { ordered: false, where })
311
+ else link(children.flatMap((dir) => commandsOfDir(dir, { normalize: true })), { ordered: false, where })
313
312
  if (node.pkg.bundledDependencies !== undefined) link(bundledCommands(node, where, major), { ordered: false, where })
314
313
  if (building && (node.pkg.patchHash !== undefined || hasInstallScript(node.manifest, node.files))) {
315
314
  link([...withBins, ...commandsOfDir(node.dir)], { ordered: true, where })
@@ -318,7 +317,7 @@ export function binTargets({ nodes, projects, direct, links, publicHoist, buildi
318
317
 
319
318
  const PRIVATE = 'node_modules/.pnpm/node_modules/'
320
319
  const hoisted = [...links].filter(([path, dir]) => path.startsWith(PRIVATE) && nodes.get(dir)?.pkg.hasBin)
321
- link(hoisted.flatMap(([, dir]) => commandsOfDir(dir, { raw: true })), { ordered: true, where: quote(PRIVATE.slice(0, -1)) })
320
+ link(hoisted.flatMap(([, dir]) => commandsOfDir(dir)), { ordered: true, where: quote(PRIVATE.slice(0, -1)) })
322
321
 
323
322
  for (const [id, children] of direct) {
324
323
  const where = `importers[${quote(id)}]`
@@ -327,17 +326,18 @@ export function binTargets({ nodes, projects, direct, links, publicHoist, buildi
327
326
  const manifest = projects.get('.')
328
327
  const own = new Set(Object.keys({ ...manifest.devDependencies, ...manifest.dependencies, ...manifest.optionalDependencies }))
329
328
  const entries = [...links].filter(([path]) => /^node_modules\/(?:@[^/]+\/)?[^/@.][^/]*$/u.test(path))
330
- const commands = entries.flatMap(([path, dir]) => commandsOfDir(dir, { raw: true }).map((command) => ({ ...command, direct: own.has(path.slice('node_modules/'.length)) })))
329
+ const commands = entries.flatMap(([path, dir]) => commandsOfDir(dir).map((command) => ({ ...command, direct: own.has(path.slice('node_modules/'.length)) })))
331
330
  const names = new Set(commands.filter((command) => command.direct).map(({ name }) => name))
332
331
  linked = link([...commands.filter((command) => command.direct), ...commands.filter((command) => !command.direct && !names.has(command.name))], { ordered: false, where })
333
332
  } else {
334
333
  // pnpm 11 reads the bins only of what the lockfile says has some.
335
334
  const dirs = [...children.values()].filter((dir) => major < 11 || (nodes.get(dir)?.pkg.hasBin ?? true))
336
- linked = link(dirs.flatMap((dir) => commandsOfDir(dir, { raw: true })), { ordered: true, where })
335
+ linked = link(dirs.flatMap((dir) => commandsOfDir(dir)), { ordered: true, where })
337
336
  }
338
337
  if (major >= 11 && peers) {
339
- const commands = peersOf(children, nodes).flatMap((dir) => commandsOfDir(dir, { raw: true }))
340
- link(commands.filter(({ name }) => !linked.names.has(name)), { ordered: true, blind: linked.unknown, where })
338
+ // Where the names linked are not all known, neither are those left.
339
+ const commands = peersOf(children, nodes).flatMap((dir) => commandsOfDir(dir))
340
+ link([...commands.filter(({ name }) => !linked.names.has(name)), ...linked.unknown ? [UNKNOWN] : []], { ordered: true, where })
341
341
  }
342
342
  }
343
343
 
@@ -8,8 +8,9 @@
8
8
 
9
9
  import { packageKeyOf } from '@preventive/lockfile/pnpm.js'
10
10
  import { satisfies, valid, validRange } from '@preventive/upstream/semver.js'
11
- import { join, normalize } from '@preventive/vfs/path.js'
11
+ import { join } from '@preventive/vfs/path.js'
12
12
  import { DeptreeError, quote } from '../error.js'
13
+ import { catalogEntry, catalogOf } from './overrides.js'
13
14
 
14
15
  const GIT_HOSTS = new Set(['github.com', 'gitlab.com', 'bitbucket.org'])
15
16
  const SHORTCUTS = [['github:', 'github.com'], ['gitlab:', 'gitlab.com'], ['bitbucket:', 'bitbucket.org']]
@@ -57,20 +58,21 @@ export function sameSpecifier(a, b, major) {
57
58
  }
58
59
 
59
60
  // The version an importer's target resolved to, as the lockfile spells
60
- // it: a key of the alias's own name is its version and peers.
61
- export const refOf = (alias, target) => (target.startsWith(`${alias}@`) ? target.slice(alias.length + 1) : target)
61
+ // it, peers and all left out: a key of the alias's own name is its
62
+ // version.
63
+ export const resolvedOf = (alias, target) => packageKeyOf(target.startsWith(`${alias}@`) ? target.slice(alias.length + 1) : target)
62
64
 
63
65
  const targetOf = (importer, alias) => importer.dependencies[alias] ?? importer.devDependencies[alias] ?? importer.optionalDependencies[alias]
64
66
 
65
67
  // catalogResolutionsAreUpToDate.
66
68
  export function checkCatalogResolutions(importer, catalogs, where) {
67
69
  for (const [alias, specifier] of Object.entries(importer.specifiers)) {
68
- if (!specifier.startsWith('catalog:')) continue
69
- const name = specifier.slice('catalog:'.length).trim() || 'default'
70
- const version = Object.hasOwn(catalogs, name) && Object.hasOwn(catalogs[name], alias) ? catalogs[name][alias].version : undefined
70
+ const name = catalogOf(specifier)
71
+ if (name === undefined) continue
72
+ const version = catalogEntry(catalogs, name, alias)?.version
71
73
  const target = targetOf(importer, alias)
72
74
  if (version === undefined || target === undefined) continue
73
- const resolved = packageKeyOf(refOf(alias, target))
75
+ const resolved = resolvedOf(alias, target)
74
76
  if (valid(resolved) !== null && resolved !== version) throw new DeptreeError(`${quote(alias)} resolved to ${quote(resolved)}, and the lockfile's catalog ${quote(name)} to ${quote(version)}, which pnpm 11 refuses a frozen install for`, where)
75
77
  }
76
78
  }
@@ -81,7 +83,7 @@ export function checkCatalogResolutions(importer, catalogs, where) {
81
83
  function specPath(dir, path, where) {
82
84
  const clean = path.startsWith('./') ? path.slice(2) : path
83
85
  if (/^(?:~[/\\]|[/\\]|[A-Za-z]:)/u.test(clean) || clean.includes('\\')) throw new DeptreeError(`${quote(path)} is not a path from the project, which is not supported`, where)
84
- return normalize(join(dir, clean.replace(/\/+$/u, '')))
86
+ return join(dir, clean.replace(/\/+$/u, ''))
85
87
  }
86
88
 
87
89
  const isWorkspacePath = (spec) => /^(?:[./\\]|~[/\\]|[A-Za-z]:)/u.test(spec)
@@ -124,7 +126,7 @@ const inRange = (version, range) => range === '*' || range === '^' || range ===
124
126
  // version-selector-type's tag: a name that is no version or range.
125
127
  const isTag = (range) => valid(range, { loose: true }) === null && validRange(range, { loose: true }) === null && encodeURIComponent(range) === range
126
128
 
127
- const KINDS = ['optionalDependencies', 'dependencies', 'devDependencies']
129
+ export const KINDS = ['optionalDependencies', 'dependencies', 'devDependencies']
128
130
 
129
131
  // The directory a specifier names, where it names one: by `link:`,
130
132
  // `file:`, a `workspace:` path, or a path alone, as pnpm reads one. One
@@ -133,8 +135,8 @@ const KINDS = ['optionalDependencies', 'dependencies', 'devDependencies']
133
135
  // links it.
134
136
  function pathOf(spec) {
135
137
  if (spec.startsWith('link:') || spec.startsWith('file:')) return spec.slice(5)
136
- if (spec.startsWith('workspace:')) return isWorkspacePath(spec.slice('workspace:'.length)) ? spec.slice('workspace:'.length) : undefined
137
- return /^(?:[./\\]|~[/\\]|[a-z]:)/iu.test(spec) ? spec : undefined
138
+ const path = spec.startsWith('workspace:') ? spec.slice('workspace:'.length) : spec
139
+ return isWorkspacePath(path) ? path : undefined
138
140
  }
139
141
 
140
142
  // A dependency the lockfile links has to be linked where the project's
@@ -157,24 +159,30 @@ export function checkLinkTargets({ id, manifest, importer }, where) {
157
159
  }
158
160
  }
159
161
 
160
- // checkLinkedPackagesAreUpToDate, for the project at `id`, less the
161
- // directories a package.json names, which checkLinkTargets holds links to:
162
- // `manifest` is its package.json as read through the read-package hook,
163
- // `projects` every project's by its directory, as given, and
164
- // `linkWorkspacePackages` the setting.
165
- export function checkLinkedPackages({ manifest, importer, projects, linkWorkspacePackages }, where) {
162
+ // Every project's package.json, as given, by its directory, and by where
163
+ // pnpm 11 links it from, its publishConfig.directory among them; and the
164
+ // directory of each by name and version, of which no two may be one.
165
+ export function indexProjects(projects) {
166
166
  const byName = new Map()
167
167
  const byDir = new Map()
168
168
  for (const [dir, project] of projects) {
169
169
  byDir.set(dir, project)
170
170
  const directory = project.publishConfig?.directory
171
- if (typeof directory === 'string' && project.publishConfig.linkDirectory !== false) byDir.set(normalize(join(dir, directory)), project)
171
+ if (typeof directory === 'string' && project.publishConfig.linkDirectory !== false) byDir.set(join(dir, directory), project)
172
172
  if (!project.name) continue
173
173
  if (!byName.has(project.name)) byName.set(project.name, new Map())
174
174
  const version = project.version ?? '0.0.0'
175
175
  if (byName.get(project.name).has(version)) throw new DeptreeError(`${quote(String(project.name))} at ${quote(String(version))} is another project's name and version too, which leaves which pnpm 11 checks a dependency against to the order it finds them in`, `manifests[${quote(dir)}]`)
176
176
  byName.get(project.name).set(version, dir)
177
177
  }
178
+ return { projects, byName, byDir }
179
+ }
180
+
181
+ // checkLinkedPackagesAreUpToDate, less the directories a package.json
182
+ // names, which checkLinkTargets holds links to: `manifest` is the
183
+ // project's package.json as read through the read-package hook, `index`
184
+ // indexProjects's, and `linkWorkspacePackages` the setting.
185
+ export function checkLinkedPackages({ manifest, importer, index: { projects, byName, byDir }, linkWorkspacePackages }, where) {
178
186
  const outdated = (detail) => new DeptreeError(`the lockfile is not up to date with this package.json, which pnpm 11 refuses a frozen install for: ${detail}`, where)
179
187
  for (const kind of KINDS) {
180
188
  const wanted = manifest[kind]
@@ -185,15 +193,17 @@ export function checkLinkedPackages({ manifest, importer, projects, linkWorkspac
185
193
  const here = `${where}.${kind}.${alias}`
186
194
  const workspaceRange = spec.startsWith('workspace:') && !isWorkspacePath(spec.slice('workspace:'.length))
187
195
  const linked = target.startsWith('link:')
196
+ // A local directory or tarball is up to date where the lockfile has
197
+ // it, as pnpm 11's frozen install skips its own dependencies; which
198
+ // is installed is held to tree.js's checkSource.
188
199
  const local = importer.specifiers[alias].startsWith('file:') || packageKeyOf(target).includes('@file:')
189
- if (local && !linked) throw new DeptreeError('a dependency on a local directory or tarball is not supported', here)
190
200
  if (local) continue
191
201
  if (linked && pathOf(spec) !== undefined) continue
192
202
  const name = targetName(spec, alias)
193
203
  const range = versionRange(spec)
194
204
  if (linked && isTag(range)) continue
195
205
  const named = byName.get(name)
196
- const dir = linked ? target.slice('link:'.length) : named?.get(packageKeyOf(refOf(alias, target)))
206
+ const dir = linked ? target.slice('link:'.length) : named?.get(resolvedOf(alias, target))
197
207
  if (dir === undefined) {
198
208
  const taking = workspaceRange && named !== undefined ? [...named.keys()].find((version) => inRange(projects.get(named.get(version)).version, range)) : undefined
199
209
  if (taking !== undefined) throw outdated(`the workspace package ${quote(name)} (${taking}) is in the range ${quote(spec)} and not linked`)
package/src/pnpm/hoist.js CHANGED
@@ -38,9 +38,10 @@ function walk(nodes, starts) {
38
38
  const lexCompare = (a, b) => (a > b ? 1 : a < b ? -1 : 0)
39
39
 
40
40
  // The aliases hoisted from the graph, walked from `starts`: a Map of each
41
- // link's path to its target. `taken` holds the names, folded, that none
42
- // may be hoisted by: the root project's own aliases, and, with pnpm 10,
43
- // with `projects` named among them at the top, hoisted last.
41
+ // link's path to its target. `taken` holds the names none may be hoisted
42
+ // by, each alias looked up in it folded: the root project's own aliases,
43
+ // and those hoisted, folded. With pnpm 10, `projects` are named among the
44
+ // top's, and hoisted last.
44
45
  function hoistGraph(nodes, starts, taken, typeOf, projects = new Map()) {
45
46
  const root = new Map([...projects].map(([id, name]) => [name, { project: id }]))
46
47
  const listed = new Set()
@@ -103,7 +104,7 @@ export function hoist(nodes, direct, { hoistPattern, publicHoistPattern }, proje
103
104
  const takenByDependencies = new Set(starts.map(([alias]) => alias.toLowerCase()))
104
105
  const hoistedProjects = [...projects].filter(([, name]) => typeOf(name) !== undefined && !takenByDependencies.has(name.toLowerCase()))
105
106
  const taken = new Set([...rootAliases, ...hoistedProjects.map(([, name]) => name)].map((alias) => alias.toLowerCase()))
106
- const links = nodes.size === 0 ? new Map() : hoistGraph(nodes, starts, taken, typeOf)
107
+ const links = hoistGraph(nodes, starts, taken, typeOf)
107
108
  for (const [id, name] of hoistedProjects) links.set(`${typeOf(name)}/${name}`, id)
108
109
  return links
109
110
  }
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
  }
@@ -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()