@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/src/pnpm/tree.js CHANGED
@@ -21,38 +21,45 @@
21
21
 
22
22
  import { packageKeyOf, parsePnpmLockfile } from '@preventive/lockfile/pnpm.js'
23
23
  import { parseYaml } from '@preventive/lockfile/yaml.js'
24
- import { Vfs } from '@preventive/vfs'
24
+ import { Vfs, VfsError } from '@preventive/vfs'
25
25
  import { dirname, relative } from '@preventive/vfs/path.js'
26
26
  import { valid } from '@preventive/upstream/semver.js'
27
27
  import { DeptreeError, quote } from '../error.js'
28
28
  import { checkNoModules, mount } from '../mount.js'
29
29
  import { applyPatch, parsePatch } from '../patch.js'
30
- import { REGISTRY, checkDependencies, fetchPackage, tarballUrl } from '../tarball.js'
30
+ import { REGISTRY, checkDependencies, checkManifest, fetchPackage, sameBytes, tarballUrl } from '../tarball.js'
31
31
  import { binTargets, checkPatchOfBins, fixBin } from './bins.js'
32
32
  import { buildGraph } from './graph.js'
33
33
  import { hoist } from './hoist.js'
34
- import { checkLocalOverrides, readLinked } from './local.js'
35
- import { checkPatchedEngines, createCheck, skippedSnapshots } from './install.js'
34
+ import { checkLocalOverrides, readDirectoryPackage, readLinked } from './local.js'
35
+ import { createPatchedCheck, skippedSnapshots } from './install.js'
36
36
  import { checkCollisions, checkLinks, checkOptional } from './checks.js'
37
37
  import { createHook } from './hook.js'
38
38
  import { listOverrides } from './overrides.js'
39
39
  import { checkProjects, readManifests, workspaceNames } from './projects.js'
40
+ import { readers } from './readers.js'
40
41
  import { readSettings } from './settings.js'
41
42
  import { checkUpToDate } from './uptodate.js'
42
- import { checkWorkspace } from './workspace.js'
43
+ import { checkWorkspace, findProjects } from './workspace.js'
43
44
 
44
45
  const CONCURRENCY = 8
45
46
  const LIBC = new Set(['glibc', 'musl', 'unknown'])
46
47
 
48
+ // The major version of `pnpm`, 10 or 11: what pnpm 11 does differently is
49
+ // read by it, where it is.
50
+ function majorOf(pnpm) {
51
+ const major = Number(valid(pnpm)?.split('.')[0])
52
+ if (major !== 10 && major !== 11) throw new DeptreeError(`pnpm ${quote(pnpm)} is not supported: only pnpm 10 and 11 are`, 'host.pnpm')
53
+ return major
54
+ }
55
+
47
56
  function checkHost(host) {
48
57
  if (host === null || typeof host !== 'object') throw new TypeError('host must be an object with pnpm, node, os, cpu and libc')
49
58
  for (const key of ['pnpm', 'node', 'os', 'cpu', 'libc']) {
50
59
  if (typeof host[key] !== 'string' || host[key] === '') throw new TypeError(`host.${key} must be a non-empty string`)
51
60
  }
52
61
  const { pnpm, node, os, libc } = host
53
- const major = Number(valid(pnpm)?.split('.')[0])
54
- // What pnpm 11 does differently is read below, by `major`, where it is.
55
- if (major !== 10 && major !== 11) throw new DeptreeError(`pnpm ${quote(pnpm)} is not supported: only pnpm 10 and 11 are`, 'host.pnpm')
62
+ const major = majorOf(pnpm)
56
63
  if (valid(node) === null) throw new DeptreeError(`${quote(node)} is not an exact version`, 'host.node')
57
64
  if (os === 'win32') throw new DeptreeError('Windows is not supported: pnpm links there with junctions to absolute paths', 'host.os')
58
65
  if (!LIBC.has(libc)) throw new DeptreeError(`expected "glibc", "musl" or "unknown", found ${quote(libc)}`, 'host.libc')
@@ -75,10 +82,18 @@ function checkLockfile(lockfile) {
75
82
 
76
83
  // A package fetched here comes from the public registry, as upstream
77
84
  // fetches it: its key is its name and version, and its resolution a
78
- // tarball there with a sha512.
79
- function checkRegistry(node) {
85
+ // tarball there with a sha512. One pnpm installs from a directory is one
86
+ // a `file:` override names, in `installed`, as local.js reads it, and is
87
+ // not patched: pnpm installs its files by hardlinks, so a patch would be
88
+ // applied to the directory's own.
89
+ function checkSource(node, installed) {
80
90
  const { key, pkg } = node
81
91
  const { resolution } = pkg
92
+ if (resolution.type === 'directory') {
93
+ if (packageKeyOf(key) !== `${pkg.name}@file:${resolution.directory}` || !installed.has(resolution.directory)) throw new DeptreeError('a dependency on a local directory is supported only where a file: override names it', quote(key))
94
+ if (pkg.patchHash !== undefined) throw new DeptreeError('a patch to a package pnpm installs from a directory is not supported: it would be applied to the directory\'s own files, which pnpm hardlinks', quote(key))
95
+ return
96
+ }
82
97
  const fromRegistry = pkg.version !== undefined && packageKeyOf(key) === `${pkg.name}@${pkg.version}` && resolution.type === 'tarball'
83
98
  && resolution.path === undefined && !resolution.gitHosted && (resolution.tarball ?? tarballUrl(pkg.name, pkg.version)) === tarballUrl(pkg.name, pkg.version)
84
99
  if (!fromRegistry) throw new DeptreeError(`only packages from ${REGISTRY} are supported`, quote(key))
@@ -91,8 +106,9 @@ const packageFields = (pkg) => JSON.stringify(PACKAGE_FIELDS.map((field) => pkg[
91
106
 
92
107
  // Each package's files and package.json, by its name and version: a
93
108
  // package is fetched once however many snapshots it has, a few at a time,
94
- // and the first failure stops the rest from starting.
95
- async function fetchAll(nodes) {
109
+ // and the first failure stops the rest from starting. One installed from
110
+ // a directory is read from `vfs`, as npm-packlist picks its files.
111
+ async function fetchAll(nodes, vfs, major) {
96
112
  const packages = new Map()
97
113
  for (const { key, pkg } of nodes.values()) {
98
114
  const id = packageKeyOf(key)
@@ -106,7 +122,11 @@ async function fetchAll(nodes) {
106
122
  while (queue.length > 0 && !failed) {
107
123
  const [id, pkg] = queue.shift()
108
124
  try {
109
- fetched.set(id, await fetchPackage(pkg, quote(id)))
125
+ if (pkg.resolution.type === 'directory') {
126
+ const got = readDirectoryPackage(vfs, pkg, quote(id), major)
127
+ checkManifest(got.manifest, pkg, quote(id))
128
+ fetched.set(id, { ...got, local: true })
129
+ } else fetched.set(id, await fetchPackage(pkg, quote(id)))
110
130
  } catch (error) {
111
131
  failed = true
112
132
  throw error instanceof DeptreeError ? error : new DeptreeError(error.message, quote(id), { cause: error })
@@ -119,9 +139,9 @@ async function fetchAll(nodes) {
119
139
 
120
140
  // Each node with its package's files and package.json, by its directory:
121
141
  // its dependencies held to the package.json, as `hook` reads it once for
122
- // each package.
123
- async function fetchNodes(nodes, hook) {
124
- const fetched = await fetchAll(nodes)
142
+ // each package; and the number of tarballs fetched.
143
+ async function fetchNodes(nodes, hook, vfs, major) {
144
+ const fetched = await fetchAll(nodes, vfs, major)
125
145
  const byDir = new Map()
126
146
  for (const node of nodes.values()) {
127
147
  const id = packageKeyOf(node.key)
@@ -130,13 +150,36 @@ async function fetchNodes(nodes, hook) {
130
150
  checkDependencies(got.manifest, got.read, node.pkg, quote(node.key))
131
151
  byDir.set(node.dir, { ...node, files: got.files, manifest: got.manifest })
132
152
  }
133
- return { byDir, tarballs: fetched.size }
153
+ return { byDir, tarballs: [...fetched.values()].filter((got) => !got.local).length }
154
+ }
155
+
156
+ // A package installed from a directory has one file for each of its
157
+ // files, hardlinked into each of its snapshots: fixBin makes it
158
+ // executable in all of them, though a CRLF `#!` line it rewrites is
159
+ // written as a file of that snapshot's own. By directory, the files a
160
+ // snapshot has made executable by another's: `targets` is binTargets's.
161
+ function executableElsewhere(byDir, targets) {
162
+ const byPackage = new Map()
163
+ for (const node of byDir.values()) {
164
+ if (node.pkg.resolution.type !== 'directory') continue
165
+ const id = packageKeyOf(node.key)
166
+ if (!byPackage.has(id)) byPackage.set(id, new Set())
167
+ for (const path of targets.get(node.dir) ?? []) byPackage.get(id).add(path)
168
+ }
169
+ const executable = new Map()
170
+ for (const node of byDir.values()) {
171
+ if (node.pkg.resolution.type !== 'directory') continue
172
+ const own = targets.get(node.dir) ?? new Set()
173
+ executable.set(node.dir, new Set([...byPackage.get(packageKeyOf(node.key))].filter((path) => !own.has(path))))
174
+ }
175
+ return executable
134
176
  }
135
177
 
136
178
  // A snapshot's files as pnpm leaves them: its package's, the patch the
137
- // snapshot names applied, and what linking bins does to them. `context`
138
- // is the host and settings.
139
- function compose(node, patches, targets, context) {
179
+ // snapshot names applied, and what linking bins does to them: fixBin run
180
+ // on `targets`, and `executable` made so. `checkPatched` is
181
+ // createPatchedCheck's.
182
+ function compose(node, patches, { targets, executable }, { major, checkPatched }) {
140
183
  const where = quote(node.key)
141
184
  let files = node.files
142
185
  const { patchHash } = node.pkg
@@ -144,27 +187,33 @@ function compose(node, patches, targets, context) {
144
187
  if (!patches.has(patchHash)) throw new DeptreeError(`the patch ${patchHash} is not given`, where)
145
188
  const patch = patches.get(patchHash)
146
189
  patch.parsed ??= parsePatch(patch.text, patch.path)
147
- files = applyPatch(files, patch.parsed)
148
- checkPatchedEngines(checkPatchOfBins(node, files, targets, where, context.host.major), where, context)
190
+ // Once for each package, whatever its snapshots.
191
+ patch.applied ??= new WeakMap()
192
+ if (!patch.applied.has(files)) patch.applied.set(files, applyPatch(files, patch.parsed))
193
+ files = patch.applied.get(files)
194
+ const manifest = checkPatchOfBins(node, files, targets, where, major)
195
+ checkPatched?.(manifest, where)
149
196
  }
150
- if (targets.size === 0) return files
197
+ if (targets.size === 0 && executable.size === 0) return files
151
198
  files = new Map(files)
152
199
  for (const path of targets) files.set(path, fixBin(files.get(path), `${where}: ${quote(path)}`))
200
+ for (const path of executable) files.set(path, { ...files.get(path), mode: 0o755 })
153
201
  return files
154
202
  }
155
203
 
156
- const sameBytes = (a, b) => a.length === b.length && a.every((byte, i) => byte === b[i])
157
-
158
204
  // Writes a file where nothing is, or the same file is: a write never
159
- // replaces anything else.
205
+ // replaces anything else. The tree holds no links yet.
160
206
  function writeOnce(vfs, path, { data, mode }) {
161
- if (vfs.isFile(path)) {
162
- if (vfs.lstat(path).mode === mode && sameBytes(vfs.readFile(path), data)) return false
163
- } else if (!vfs.isSymlink(path) && !vfs.isDirectory(path)) {
207
+ let there
208
+ try {
209
+ there = vfs.lstat(path)
210
+ } catch (error) {
211
+ if (!(error instanceof VfsError)) throw error
164
212
  vfs.mkdir(dirname(path), { recursive: true })
165
213
  vfs.writeFile(path, data, { mode })
166
214
  return true
167
215
  }
216
+ if (there.type === 'file' && there.mode === mode && sameBytes(vfs.readFile(path), data)) return false
168
217
  throw new DeptreeError('would be written over with something else', quote(path.slice(1)))
169
218
  }
170
219
 
@@ -180,10 +229,10 @@ function linkTarget(path, target) {
180
229
  // Every link in the tree, by its path: each node's children beside it and
181
230
  // itself inside it where it depends on itself, then what is hoisted, then
182
231
  // each project's direct dependencies, which win over a hoisted alias.
183
- function linksOf(nodes, direct, settings, projects, major) {
184
- const byDir = new Map([...nodes.values()].map((node) => [node.dir, node]))
232
+ // `byDir` is the graph by directory.
233
+ function linksOf(byDir, direct, settings, projects, major) {
185
234
  const links = new Map()
186
- for (const node of nodes.values()) {
235
+ for (const node of byDir.values()) {
187
236
  for (const [alias, dir] of node.children) if (alias !== node.name) links.set(`${node.modules}/${alias}`, dir)
188
237
  const self = node.children.get(node.name)
189
238
  if (byDir.has(self)) links.set(`${node.dir}/node_modules/${node.name}`, self)
@@ -199,6 +248,20 @@ function linksOf(nodes, direct, settings, projects, major) {
199
248
  // nothing, as pnpm reads it.
200
249
  const readWorkspace = (text) => (text === undefined || /^(?:[\t ]*(?:#.*)?(?:\r?\n|$))*$/u.test(text) ? undefined : parseYaml(text))
201
250
 
251
+ // The directories of the projects pnpm finds for the workspace at the
252
+ // root of `vfs`, which buildPnpmTree takes the package.json of each of.
253
+ export function findPnpmProjects(options) {
254
+ const { workspace, host, vfs } = options ?? {}
255
+ if (workspace !== undefined && typeof workspace !== 'string') throw new TypeError('workspace must be a string, or left out')
256
+ if (typeof host?.pnpm !== 'string' || host.pnpm === '') throw new TypeError('host.pnpm must be a non-empty string')
257
+ if (['readdir', 'lstat', 'stat'].some((name) => typeof vfs?.[name] !== 'function')) throw new TypeError('vfs must be a Vfs, or have its readdir, lstat and stat')
258
+ const major = majorOf(host.pnpm)
259
+ const read = readWorkspace(workspace)
260
+ if (read !== undefined && (read === null || typeof read !== 'object' || Array.isArray(read))) throw new DeptreeError('expected a mapping', 'pnpm-workspace.yaml')
261
+ const packages = read?.packages === undefined ? undefined : readers.globs(read.packages, 'pnpm-workspace.yaml: packages')
262
+ return findProjects(vfs, packages, major)
263
+ }
264
+
202
265
  function readPatchesGiven(patches) {
203
266
  const entries = patches instanceof Map ? [...patches] : Object.entries(patches ?? {})
204
267
  for (const [path, text] of entries) {
@@ -215,8 +278,9 @@ export async function buildPnpmTree(options) {
215
278
  if (value !== undefined && typeof value !== 'string') throw new TypeError(`${name} must be a string, or left out`)
216
279
  }
217
280
  const host = checkHost(machine)
281
+ const folded = host.os === 'darwin'
218
282
  // Refused before anything is fetched; mount checks again.
219
- if (into !== undefined) checkNoModules(into, host.os === 'darwin')
283
+ if (into !== undefined) checkNoModules(into, folded)
220
284
  const { lockfile, env } = parsePnpmLockfile(text)
221
285
  // pnpm 11 locks config dependencies there, which are refused, and the
222
286
  // pnpm a project pins, which leaves the tree as it is.
@@ -224,27 +288,26 @@ export async function buildPnpmTree(options) {
224
288
  if (env !== undefined && Object.keys(env.importers['.'].configDependencies).length > 0) throw new DeptreeError('config dependencies are not supported', 'env.importers["."].configDependencies')
225
289
  if (!('.' in lockfile.importers)) throw new DeptreeError('expected the root project, whose package.json holds settings', 'importers')
226
290
  const manifests = readManifests(manifestTexts, lockfile)
227
- const settings = readSettings({ workspace: readWorkspace(workspace), npmrc, manifest: manifests.get('.'), os: host.os, major: host.major })
291
+ const settings = readSettings({ workspace: readWorkspace(workspace), npmrc, manifest: manifests.get('.'), major: host.major })
228
292
  checkLockfile(lockfile)
229
293
  checkWorkspace(Object.keys(lockfile.importers), settings.packages, host.major)
230
294
  const overrides = listOverrides(settings.overrides, settings.catalogs, host.major)
231
- checkLocalOverrides(overrides, into)
295
+ const installed = checkLocalOverrides(overrides, into)
232
296
  const given = await checkUpToDate(lockfile, settings, overrides, readPatchesGiven(patches), host.major)
233
297
  const hook = createHook({ overrides, ignored: settings.ignoredOptionalDependencies, major: host.major })
234
298
  checkProjects(lockfile, manifests, { hook, host, settings })
235
299
  checkOptional(lockfile)
236
300
  const projects = settings.hoistWorkspacePackages ? workspaceNames(manifests) : new Map()
237
- const check = createCheck({ host, settings })
238
- const { skipped, incompatible } = skippedSnapshots(lockfile, check, { major: host.major, engineStrict: settings.engineStrict })
301
+ const { skipped, incompatible } = skippedSnapshots(lockfile, { host, settings })
239
302
  const { nodes, direct } = await buildGraph(lockfile, skipped, settings.virtualStoreDirMaxLength, host.major)
240
- for (const node of nodes.values()) checkRegistry(node)
303
+ for (const node of nodes.values()) checkSource(node, installed)
241
304
 
242
- const { byDir, tarballs } = await fetchNodes(nodes, hook)
243
- const links = linksOf(nodes, direct, settings, projects, host.major)
305
+ const { byDir, tarballs } = await fetchNodes(nodes, hook, into, host.major)
306
+ const links = linksOf(byDir, direct, settings, projects, host.major)
244
307
  const linked = readLinked(links, byDir, manifests, into)
245
308
  const targets = binTargets({
246
309
  nodes: byDir,
247
- projects: linked.size === 0 ? manifests : new Map([...manifests, ...linked]),
310
+ projects: new Map([...manifests, ...linked]),
248
311
  direct,
249
312
  links,
250
313
  publicHoist: settings.publicHoistPattern?.length > 0,
@@ -252,15 +315,19 @@ export async function buildPnpmTree(options) {
252
315
  peers: settings.autoInstallPeers,
253
316
  major: host.major,
254
317
  })
318
+ const executable = executableElsewhere(byDir, targets)
255
319
 
256
320
  const vfs = new Vfs()
257
321
  vfs.mkdir('/node_modules/.pnpm', { recursive: true })
258
322
  const stats = { projects: manifests.size, snapshots: Object.keys(lockfile.packages).length, installed: nodes.size, skipped: skipped.size, incompatible: incompatible.size, tarballs, patched: 0, files: 0, bytes: 0, links: links.size }
323
+ const composing = { major: host.major, checkPatched: createPatchedCheck({ host, settings }) }
324
+ // Each node is let go once written, and a package's files with its last.
259
325
  for (const node of byDir.values()) {
326
+ byDir.delete(node.dir)
260
327
  if (node.pkg.patchHash !== undefined) stats.patched++
261
328
  try {
262
329
  vfs.mkdir(`/${node.dir}`, { recursive: true })
263
- for (const [path, file] of compose(node, given, targets.get(node.dir) ?? new Set(), { host, settings })) {
330
+ for (const [path, file] of compose(node, given, { targets: targets.get(node.dir) ?? new Set(), executable: executable.get(node.dir) ?? new Set() }, composing)) {
264
331
  if (file.directory) vfs.mkdir(`/${node.dir}/${path}`, { recursive: true })
265
332
  else if (writeOnce(vfs, `/${node.dir}/${path}`, file)) {
266
333
  stats.files++
@@ -281,8 +348,8 @@ export async function buildPnpmTree(options) {
281
348
  }
282
349
  }
283
350
  checkLinks(vfs, links)
284
- if (host.os === 'darwin') checkCollisions(vfs)
351
+ if (folded) checkCollisions(vfs)
285
352
  if (into === undefined) return { vfs, stats }
286
- mount(vfs, into, host.os === 'darwin')
353
+ mount(vfs, into, folded)
287
354
  return { vfs: into, stats }
288
355
  }
@@ -61,7 +61,7 @@ function checkPatches(locked, hashes, major) {
61
61
  // Throws where pnpm would not install the lockfile as it is; hands back the
62
62
  // patches by hash, their text and path, to apply where a snapshot names one.
63
63
  // `overrides` is listOverrides's.
64
- export async function checkUpToDate(lockfile, settings, overrides, given, major = 10) {
64
+ export async function checkUpToDate(lockfile, settings, overrides, given, major) {
65
65
  const { hashes, byHash } = await hashPatches(settings.patchedDependencies, given)
66
66
  for (const [name, catalog] of Object.entries(lockfile.catalogs)) {
67
67
  for (const [alias, { specifier }] of Object.entries(catalog)) {
@@ -2,12 +2,11 @@
2
2
  // under one lockfile: the root, always, and each directory whose
3
3
  // package.json a glob of pnpm-workspace.yaml's `packages` takes, as
4
4
  // @pnpm/fs.find-packages globs for them with tinyglobby — `<glob>/
5
- // package.json`, less anything under node_modules or bower_components.
6
- // Without `packages`, or without pnpm-workspace.yaml, the root is the only
7
- // project. pnpm finds them on disk; here they are what is given, and each
8
- // has to be one pnpm would find. Those it would find and are not given
9
- // cannot be seen here, and have to be given: pnpm refuses a frozen install
10
- // for one the lockfile has no importer for, and installs every one.
5
+ // package.{json,yaml,json5}`, less anything under node_modules or
6
+ // bower_components. Without `packages`, or without pnpm-workspace.yaml,
7
+ // the root is the only project. pnpm finds them on disk: findProjects
8
+ // finds them so in the directories it is given, and checkWorkspace holds
9
+ // the lockfile's importers to them.
11
10
  //
12
11
  // A glob is read as tinyglobby reads it, normalized as a path first, as
13
12
  // far as `*` and `**` go: `*` any run of characters in one directory's
@@ -19,55 +18,187 @@
19
18
  // pnpm 11 leaves out what a `!` glob takes with micromatch too, a name
20
19
  // starting with a dot and all.
21
20
 
21
+ import { normalize } from '@preventive/vfs/path.js'
22
22
  import { DeptreeError, quote } from '../error.js'
23
23
  import { escape } from '../matcher.js'
24
24
 
25
25
  const UNSUPPORTED = /[?[\]{}()\\]/u
26
26
 
27
- // tinyglobby's path.posix.normalize of a glob: empty and `.` names
28
- // dropped, and `..` taking the name before it with it.
29
- function normalizeGlob(glob, where) {
30
- const names = []
31
- for (const name of glob.split('/')) {
32
- if (name === '' || name === '.') continue
33
- if (name !== '..') names.push(name)
34
- else if (names.length === 0) throw new DeptreeError(`${quote(glob)} reaches outside the workspace's directory, which is not supported`, where)
35
- else names.pop()
36
- }
37
- return names
38
- }
39
-
40
- // A name's pattern: `*` any run of characters, but not a leading dot
41
- // unless `dot`.
42
- const NAME = (name, dot) => `${name.startsWith('*') && !dot ? '(?!\\.)' : ''}${name.split('*').map(escape).join('[^/]*')}`
43
- // `**`: any number of names, none with a leading dot unless `dot`, each
44
- // with its `/`.
45
- const GLOBSTAR = (dot) => `(?:${dot ? '' : '(?!\\.)'}[^/]+/)*`
27
+ // A name's pattern: `*` any run of characters, line terminators among
28
+ // them, but not a leading dot unless `dot`.
29
+ const NAME = (name, dot) => new RegExp(`^${name.startsWith('*') && !dot ? '(?!\\.)' : ''}${name.split('*').map(escape).join('[^/]*')}$`, 'u')
46
30
 
31
+ // A glob as the names of the paths it takes, normalized as tinyglobby
32
+ // does: each `**`, or the pattern of one name; `dot` whether `**` takes a
33
+ // name with a leading dot.
47
34
  function compile(glob, where, dot) {
48
- const names = normalizeGlob(`${glob}/package.json`, where)
35
+ const path = normalize(`./${glob}/package.json`)
36
+ if (path.startsWith('../')) throw new DeptreeError(`${quote(glob)} reaches outside the workspace's directory, which is not supported`, where)
37
+ const names = path.split('/')
49
38
  if (glob === '' || glob.startsWith('/') || UNSUPPORTED.test(glob) || glob.includes('!') || names.some((name) => name !== '**' && name.includes('**'))) {
50
39
  throw new DeptreeError(`${quote(glob)} is not supported: only \`*\`, \`**\` as a whole name and a leading \`!\` are`, where)
51
40
  }
52
- // The last name is package.json, which a `/` never follows.
53
- const source = names.map((name, index) => (name === '**' ? GLOBSTAR(dot) : `${NAME(name, dot)}${index === names.length - 1 ? '' : '/'}`)).join('')
54
- return new RegExp(`^${source}$`, 'u')
41
+ return { names: names.map((name) => (name === '**' ? name : NAME(name, dot))), dot }
42
+ }
43
+
44
+ // Which places in a glob the path of `names` leads to: for each index,
45
+ // whether the glob's names before it take the path, a name at a time, in
46
+ // time the glob's length for each and with no recursion, however many
47
+ // `**` it has. A `**` may take no name, so reaching one reaches the next.
48
+ function reach({ names: glob, dot }, names) {
49
+ let here = Array.from({ length: glob.length + 1 }, (_, g) => g === 0)
50
+ let next = Array.from({ length: glob.length + 1 }, () => false)
51
+ const onward = (places) => {
52
+ for (let g = 0; g < glob.length; g++) if (places[g] && glob[g] === '**') places[g + 1] = true
53
+ }
54
+ onward(here)
55
+ for (const name of names) {
56
+ next.fill(false)
57
+ for (let g = 0; g < glob.length; g++) {
58
+ if (!here[g]) continue
59
+ if (glob[g] !== '**') next[g + 1] ||= glob[g].test(name)
60
+ else if (dot || !name.startsWith('.')) next[g] = true
61
+ }
62
+ onward(next)
63
+ ;[here, next] = [next, here]
64
+ }
65
+ return here
66
+ }
67
+
68
+ // Whether a glob takes the path of `names`.
69
+ const takes = (glob, names) => reach(glob, names)[glob.names.length]
70
+
71
+ // Whether tinyglobby walks into the directory at `names` for a glob, as
72
+ // its partial matcher has it: name by name, each has to be taken by the
73
+ // glob's name in the same place, until a `**` there takes one, which
74
+ // takes whatever is below it. A `**` that takes none is not tried, so a
75
+ // name with a leading dot a `**` stands before is never walked into.
76
+ function enters({ names: glob, dot }, names) {
77
+ for (const [i, name] of names.entries()) {
78
+ if (i === glob.length) return false
79
+ if (glob[i] === '**') return dot || !name.startsWith('.')
80
+ if (!glob[i].test(name)) return false
81
+ }
82
+ return true
83
+ }
84
+
85
+ // `packages`, the globs or undefined, as the globs that take and those
86
+ // that leave out; `major` pnpm's major version.
87
+ function compileAll(packages, major) {
88
+ const globs = { include: [], exclude: [] }
89
+ for (const glob of packages ?? []) {
90
+ const exclude = glob.startsWith('!')
91
+ globs[exclude ? 'exclude' : 'include'].push(compile(exclude ? glob.slice(1) : glob, 'pnpm-workspace.yaml: packages', exclude && major >= 11))
92
+ }
93
+ return globs
55
94
  }
56
95
 
96
+ // What find-packages leaves out, as tinyglobby reads it, which does not
97
+ // take a name with a leading dot for `**`: what is under node_modules or
98
+ // bower_components.
99
+ const IGNORED = ['node_modules', 'bower_components'].map((name) => ({ names: ['**', NAME(name, false), '**'], dot: false }))
100
+ const ignored = (names) => IGNORED.some((glob) => takes(glob, names))
101
+
102
+ // Whether the globs take the manifest at `names`. What find-packages
103
+ // ignores it is not ignored for, in a directory tinyglobby walks into.
104
+ const taken = ({ include, exclude }, names) => include.some((glob) => takes(glob, names)) && !exclude.some((glob) => takes(glob, names))
105
+
106
+ // Whether tinyglobby walks into the directory at `names`, which it does
107
+ // through a link to one too.
108
+ const walked = ({ include }, names) => include.some((glob) => enters(glob, names)) && !ignored(names)
109
+
57
110
  // `ids` are the projects' directories, `.` the root; `packages` the globs,
58
- // or undefined; `major` pnpm's major version.
111
+ // or undefined; `major` pnpm's major version. pnpm finds a project where
112
+ // tinyglobby walks into each directory down to it, and the globs take its
113
+ // manifest.
59
114
  export function checkWorkspace(ids, packages, major = 10) {
60
- const where = 'pnpm-workspace.yaml: packages'
61
- const globs = (packages ?? []).map((glob) => {
62
- const exclude = glob.startsWith('!')
63
- return { exclude, regexp: compile(exclude ? glob.slice(1) : glob, where, exclude && major >= 11) }
64
- })
115
+ const globs = compileAll(packages, major)
65
116
  for (const id of ids) {
66
117
  if (id === '.') continue
67
- const path = `${id}/package.json`
68
- const taken = globs.some(({ exclude, regexp }) => !exclude && regexp.test(path)) && !globs.some(({ exclude, regexp }) => exclude && regexp.test(path))
69
- if (!taken || id.split('/').includes('bower_components')) {
118
+ const names = id.split('/')
119
+ if (!names.every((_, i) => walked(globs, names.slice(0, i + 1))) || !taken(globs, [...names, 'package.json'])) {
70
120
  throw new DeptreeError(`pnpm-workspace.yaml's packages ${packages === undefined ? 'are not set' : 'do not take this directory'}, so pnpm would not install it as a project`, `importers[${quote(id)}]`)
71
121
  }
72
122
  }
73
123
  }
124
+
125
+ // Of what @preventive/lockfile holds an importer's key to, what a project
126
+ // under the lockfile's directory has to be: its path from there, in normal
127
+ // form, with no drive letter, and no control, bidirectional or backslash
128
+ // character, which the lockfile could not name it by.
129
+ const UNSAFE = /[\p{Cc}\p{Zl}\p{Zp}\p{Bidi_Control}\\]/u
130
+ export function checkProjectId(id, where) {
131
+ if (id.split('/').some((name) => name === '' || name === '.' || name === '..' || UNSAFE.test(name)) || /^[A-Za-z]:/u.test(id)) {
132
+ throw new DeptreeError('expected a directory under the lockfile\'s, by its path from there in normal form, as a lockfile can key an importer', where)
133
+ }
134
+ }
135
+
136
+ // The names pnpm reads a project's manifest by, the first of them there
137
+ // winning.
138
+ const MANIFESTS = ['package.json', 'package.json5', 'package.yaml']
139
+
140
+ // The directories of the projects pnpm `major` finds by the globs of
141
+ // `packages` in the workspace at the root of `vfs`: `.`, the root, then
142
+ // the rest in order. Every directory tinyglobby walks into is read, and no
143
+ // other, a link to one followed as it follows it. A manifest is a file, or
144
+ // a link to one; a link that leads nowhere, or to a directory, is none.
145
+ // Refused, as not read here: a root with no manifest, which pnpm takes
146
+ // for no project; a project, the root among them, whose manifest is
147
+ // package.json5, package.yaml or a link; a project found
148
+ // through a link, and a link to a directory in one followed, which is not
149
+ // followed; a project in a directory a lockfile could not key its
150
+ // importer by; and a node_modules tinyglobby walks into, which it does
151
+ // only under a directory with a leading dot, as what is installed there
152
+ // is no project buildPnpmTree builds.
153
+ export function findProjects(vfs, packages, major = 10) {
154
+ const globs = compileAll(packages, major)
155
+ const ids = []
156
+ // The directories left to read, by their names, and the link each is
157
+ // reached through, if any: a stack, not recursion, however deep the tree.
158
+ const pending = [{ names: [] }]
159
+ while (pending.length > 0) {
160
+ const { names, link } = pending.pop()
161
+ const dir = names.join('/')
162
+ const entries = vfs.readdir(`/${dir}`)
163
+ const found = names.length === 0 || taken(globs, [...names, 'package.json'])
164
+ ? MANIFESTS.find((name) => entries.includes(name) && typeOf(vfs, `/${[...names, name].join('/')}`) === 'file')
165
+ : undefined
166
+ if (names.length === 0 && found === undefined) throw new DeptreeError('pnpm takes a workspace with no manifest at its root for one with no root project, which is not supported', quote('package.json'))
167
+ if (found !== undefined) {
168
+ const file = [...names, found].join('/')
169
+ if (vfs.lstat(`/${file}`).type === 'symlink') throw new DeptreeError('a link pnpm would read a project\'s manifest through is not supported', quote(file))
170
+ if (found !== 'package.json') throw new DeptreeError(`pnpm reads this project's ${found}, which is not supported`, quote(file))
171
+ if (link !== undefined) throw new DeptreeError(`pnpm finds a project through this link, ${quote(dir)}, which is not supported`, quote(link))
172
+ if (names.length > 0) {
173
+ checkProjectId(dir, quote(dir))
174
+ ids.push(dir)
175
+ }
176
+ }
177
+ for (const entry of entries) {
178
+ const at = [...names, entry]
179
+ if (!walked(globs, at)) continue
180
+ const path = at.join('/')
181
+ const { type } = vfs.lstat(`/${path}`)
182
+ const linked = type === 'symlink' && typeOf(vfs, `/${path}`) === 'directory'
183
+ if (type !== 'directory' && !linked) continue
184
+ if (entry === 'node_modules') throw new DeptreeError('pnpm-workspace.yaml\'s packages walk into this node_modules, which is not supported', quote(path))
185
+ if (!linked) pending.push({ names: at, link })
186
+ else if (link === undefined) pending.push({ names: at, link: path })
187
+ else throw new DeptreeError(`a link to a directory in one tinyglobby follows, ${quote(path)}, is not supported`, quote(link))
188
+ }
189
+ }
190
+ return ['.', ...ids.sort()]
191
+ }
192
+
193
+ // What `path` leads to, links followed; nothing, where it leads nowhere:
194
+ // to no entry, through a file, or round a loop of links. Any other
195
+ // failure is thrown.
196
+ const NOWHERE = new Set(['ENOENT', 'ENOTDIR', 'ELOOP'])
197
+ function typeOf(vfs, path) {
198
+ try {
199
+ return vfs.stat(path).type
200
+ } catch (error) {
201
+ if (NOWHERE.has(error?.code)) return undefined
202
+ throw error
203
+ }
204
+ }
package/src/tarball.js CHANGED
@@ -26,6 +26,7 @@
26
26
  import { decompress } from '@preventive/archive/compression.js'
27
27
  import { unpack } from '@preventive/archive/tar.js'
28
28
  import { normalize } from '@preventive/vfs/path.js'
29
+ import { packageKeyOf } from '@preventive/lockfile/pnpm.js'
29
30
  import { getTarball } from '@preventive/upstream/npm.js'
30
31
  import { DeptreeError, quote } from './error.js'
31
32
  import { localOf } from './pnpm/overrides.js'
@@ -47,10 +48,11 @@ function nameOf(stored) {
47
48
  return name.replaceAll('//', '/')
48
49
  }
49
50
 
50
- const sameFile = (a, b) => a.mode === b.mode && a.data.length === b.data.length && a.data.every((byte, i) => byte === b.data[i])
51
+ export const sameBytes = (a, b) => a.length === b.length && a.every((byte, i) => byte === b[i])
52
+ const sameFile = (a, b) => a.mode === b.mode && sameBytes(a.data, b.data)
51
53
 
52
54
  // A Map of each file's path in the package to its bytes and mode.
53
- export function filesOf(entries, where) {
55
+ function filesOf(entries, where) {
54
56
  const files = new Map()
55
57
  const tops = new Set()
56
58
  for (const entry of entries) {
@@ -100,17 +102,21 @@ function readManifest(files, pkg, where) {
100
102
  }
101
103
 
102
104
  // What the lockfile recorded of the package against the package.json.
103
- function checkManifest(manifest, pkg, where) {
105
+ export function checkManifest(manifest, pkg, where) {
104
106
  for (const field of ['os', 'cpu', 'libc']) {
105
107
  if (!same(manifest[field], pkg[field])) throw new DeptreeError(`package.json's ${field} is not the lockfile's`, where)
106
108
  }
107
109
  const has = hasBin(manifest)
108
110
  if (has !== undefined && has !== pkg.hasBin) throw new DeptreeError(`package.json ${pkg.hasBin ? 'has no bins, and the lockfile says it has' : 'has bins, and the lockfile says it has none'}`, where)
109
- if (!same(bundledOf(manifest), pkg.bundledDependencies)) throw new DeptreeError('package.json bundles other than the lockfile says', where)
111
+ if (!same(listed(bundledOf(manifest)), listed(pkg.bundledDependencies))) throw new DeptreeError('package.json bundles other than the lockfile says', where)
110
112
  }
111
113
 
112
114
  const bundledOf = (manifest) => manifest.bundleDependencies ?? manifest.bundledDependencies
113
115
 
116
+ // Bundled dependencies as the lockfile records them, where pnpm 10 writes
117
+ // an empty list and pnpm 11 leaves it out.
118
+ const listed = (bundled) => (Array.isArray(bundled) && bundled.length === 0 ? undefined : bundled)
119
+
114
120
  // A snapshot's dependencies against the package.json of its package, as
115
121
  // fetchPackage read it and `read` as hook.js's hook has it. One the
116
122
  // package.json, as overridden, names a directory for is linked there,
@@ -126,7 +132,7 @@ export function checkDependencies(manifest, read, pkg, where) {
126
132
  const target = pkg.dependencies[name] ?? pkg.optionalDependencies[name]
127
133
  if (target === undefined) continue
128
134
  const local = localOf(spec, `${where}: package.json`)
129
- if (local === undefined || target === `link:${local.dir}`) continue
135
+ if (local === undefined || target === `link:${local.dir}` || (local.protocol === 'file:' && packageKeyOf(target).endsWith(`@file:${local.dir}`))) continue
130
136
  throw new DeptreeError(`the lockfile gives it ${quote(name)} as ${quote(target)}, and its package.json, overridden, names ${quote(local.dir)}`, where)
131
137
  }
132
138
  // A peer resolved is filed as optional where it is optional; pnpm's