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

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
@@ -1,4 +1,4 @@
1
- // A node_modules tree as pnpm 10 or 11 installs it from a frozen lockfile
1
+ // A node_modules tree as pnpm 10, 11 or 12 installs it from a frozen lockfile
2
2
  // with the isolated linker, held in a Vfs rooted at the lockfile's directory:
3
3
  // each package's files at node_modules/.pnpm/<its directory>/node_modules/
4
4
  // <its name>, its dependencies linked beside it, the hoisted aliases in
@@ -19,52 +19,28 @@
19
19
  // Each package is fetched once, and each snapshot's files composed in
20
20
  // memory — its package's, patched, bins fixed — before one write of each.
21
21
 
22
- import { packageKeyOf, parsePnpmLockfile } from '@preventive/lockfile/pnpm.js'
23
- import { parseYaml } from '@preventive/lockfile/yaml.js'
22
+ import { packageKeyOf } from '@preventive/lockfile/pnpm.js'
24
23
  import { Vfs, VfsError } from '@preventive/vfs'
25
24
  import { dirname, relative } from '@preventive/vfs/path.js'
26
- import { valid } from '@preventive/upstream/semver.js'
25
+ import { eachConcurrently } from '../concurrent.js'
27
26
  import { DeptreeError, quote } from '../error.js'
28
27
  import { checkNoModules, mount } from '../mount.js'
29
28
  import { applyPatch, parsePatch } from '../patch.js'
30
29
  import { REGISTRY, checkDependencies, checkManifest, fetchPackage, sameBytes, tarballUrl } from '../tarball.js'
31
- import { binTargets, checkPatchOfBins, fixBin } from './bins.js'
30
+ import { binTargets, checkPatchOfBins, fixBin, requiresBuild } from './bins.js'
32
31
  import { buildGraph } from './graph.js'
33
32
  import { hoist } from './hoist.js'
34
- import { checkLocalOverrides, readDirectoryPackage, readLinked } from './local.js'
33
+ import { checkLocalOverrides, createFreshnessCheck, readDirectoryPackage, readLinked } from './local.js'
35
34
  import { createPatchedCheck, skippedSnapshots } from './install.js'
36
35
  import { checkCollisions, checkLinks, checkOptional } from './checks.js'
37
36
  import { createHook } from './hook.js'
38
37
  import { listOverrides } from './overrides.js'
39
- import { checkProjects, readManifests, workspaceNames } from './projects.js'
40
- import { readers } from './readers.js'
38
+ import { checkHost, inputsOf, manifestsOf, patchesOf, readLockfile } from './inputs.js'
39
+ import { checkProject } from './project.js'
40
+ import { checkProjects, pinsPnpm, workspaceNames } from './projects.js'
41
41
  import { readSettings } from './settings.js'
42
42
  import { checkUpToDate } from './uptodate.js'
43
- import { checkWorkspace, findProjects } from './workspace.js'
44
-
45
- const CONCURRENCY = 8
46
- const LIBC = new Set(['glibc', 'musl', 'unknown'])
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
-
56
- function checkHost(host) {
57
- if (host === null || typeof host !== 'object') throw new TypeError('host must be an object with pnpm, node, os, cpu and libc')
58
- for (const key of ['pnpm', 'node', 'os', 'cpu', 'libc']) {
59
- if (typeof host[key] !== 'string' || host[key] === '') throw new TypeError(`host.${key} must be a non-empty string`)
60
- }
61
- const { pnpm, node, os, libc } = host
62
- const major = majorOf(pnpm)
63
- if (valid(node) === null) throw new DeptreeError(`${quote(node)} is not an exact version`, 'host.node')
64
- if (os === 'win32') throw new DeptreeError('Windows is not supported: pnpm links there with junctions to absolute paths', 'host.os')
65
- if (!LIBC.has(libc)) throw new DeptreeError(`expected "glibc", "musl" or "unknown", found ${quote(libc)}`, 'host.libc')
66
- return { pnpm, major, node, os, cpu: host.cpu, libc }
67
- }
43
+ import { checkWorkspace } from './workspace.js'
68
44
 
69
45
  // What the lockfile holds that no tree is built for here.
70
46
  function checkLockfile(lockfile) {
@@ -105,49 +81,43 @@ const PACKAGE_FIELDS = ['resolution', 'os', 'cpu', 'libc', 'hasBin', 'bundledDep
105
81
  const packageFields = (pkg) => JSON.stringify(PACKAGE_FIELDS.map((field) => pkg[field]))
106
82
 
107
83
  // Each package's files and package.json, by its name and version: a
108
- // package is fetched once however many snapshots it has, a few at a time,
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) {
84
+ // package is fetched once however many snapshots it has, a few at a time.
85
+ // One installed from a directory is read from `project`, as npm-packlist
86
+ // picks its files.
87
+ async function fetchAll(nodes, project, major) {
112
88
  const packages = new Map()
113
89
  for (const { key, pkg } of nodes.values()) {
114
90
  const id = packageKeyOf(key)
115
91
  if (!packages.has(id)) packages.set(id, pkg)
116
92
  else if (packageFields(packages.get(id)) !== packageFields(pkg)) throw new DeptreeError(`its snapshots differ on what the package is: ${PACKAGE_FIELDS.join(', ')}`, quote(id))
117
93
  }
118
- const queue = [...packages]
119
94
  const fetched = new Map()
120
- let failed = false
121
- const worker = async () => {
122
- while (queue.length > 0 && !failed) {
123
- const [id, pkg] = queue.shift()
124
- try {
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)))
130
- } catch (error) {
131
- failed = true
132
- throw error instanceof DeptreeError ? error : new DeptreeError(error.message, quote(id), { cause: error })
133
- }
95
+ await eachConcurrently(packages, async ([id, pkg]) => {
96
+ try {
97
+ if (pkg.resolution.type === 'directory') {
98
+ const got = readDirectoryPackage(project, pkg, quote(id), major)
99
+ checkManifest(got.manifest, pkg, quote(id), major)
100
+ fetched.set(id, { ...got, local: true })
101
+ } else fetched.set(id, await fetchPackage(pkg, quote(id), major))
102
+ } catch (error) {
103
+ throw error instanceof DeptreeError ? error : new DeptreeError(error.message, quote(id), { cause: error })
134
104
  }
135
- }
136
- await Promise.all(Array.from({ length: Math.min(CONCURRENCY, queue.length) }, worker))
105
+ })
137
106
  return fetched
138
107
  }
139
108
 
140
109
  // Each node with its package's files and package.json, by its directory:
141
110
  // its dependencies held to the package.json, as `hook` reads it once for
142
111
  // each package; and the number of tarballs fetched.
143
- async function fetchNodes(nodes, hook, vfs, major) {
144
- const fetched = await fetchAll(nodes, vfs, major)
112
+ async function fetchNodes(nodes, hook, project, major, fresh) {
113
+ const fetched = await fetchAll(nodes, project, major)
145
114
  const byDir = new Map()
146
115
  for (const node of nodes.values()) {
147
116
  const id = packageKeyOf(node.key)
148
117
  const got = fetched.get(id)
149
118
  got.read ??= hook(got.manifest, `${quote(id)}: package.json`)
150
119
  checkDependencies(got.manifest, got.read, node.pkg, quote(node.key))
120
+ fresh?.(node, got.read)
151
121
  byDir.set(node.dir, { ...node, files: got.files, manifest: got.manifest })
152
122
  }
153
123
  return { byDir, tarballs: [...fetched.values()].filter((got) => !got.local).length }
@@ -156,19 +126,22 @@ async function fetchNodes(nodes, hook, vfs, major) {
156
126
  // A package installed from a directory has one file for each of its
157
127
  // files, hardlinked into each of its snapshots: fixBin makes it
158
128
  // 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) {
129
+ // written as a file of that snapshot's own. Each snapshot has its own
130
+ // copy instead where pnpm builds the package, or, with pnpm 11 and 12,
131
+ // where packageImportMethod is other than auto or hardlink. By
132
+ // directory, the files a snapshot has made executable by another's:
133
+ // `targets` is binTargets's.
134
+ function executableElsewhere(byDir, targets, packageImportMethod, major) {
135
+ const linked = major < 11 || packageImportMethod === 'auto' || packageImportMethod === 'hardlink'
136
+ const shared = [...byDir.values()].filter((node) => linked && node.pkg.resolution.type === 'directory' && !requiresBuild(node.manifest, node.files, major))
162
137
  const byPackage = new Map()
163
- for (const node of byDir.values()) {
164
- if (node.pkg.resolution.type !== 'directory') continue
138
+ for (const node of shared) {
165
139
  const id = packageKeyOf(node.key)
166
140
  if (!byPackage.has(id)) byPackage.set(id, new Set())
167
141
  for (const path of targets.get(node.dir) ?? []) byPackage.get(id).add(path)
168
142
  }
169
143
  const executable = new Map()
170
- for (const node of byDir.values()) {
171
- if (node.pkg.resolution.type !== 'directory') continue
144
+ for (const node of shared) {
172
145
  const own = targets.get(node.dir) ?? new Set()
173
146
  executable.set(node.dir, new Set([...byPackage.get(packageKeyOf(node.key))].filter((path) => !own.has(path))))
174
147
  }
@@ -189,14 +162,14 @@ function compose(node, patches, { targets, executable }, { major, checkPatched }
189
162
  patch.parsed ??= parsePatch(patch.text, patch.path)
190
163
  // Once for each package, whatever its snapshots.
191
164
  patch.applied ??= new WeakMap()
192
- if (!patch.applied.has(files)) patch.applied.set(files, applyPatch(files, patch.parsed))
165
+ if (!patch.applied.has(files)) patch.applied.set(files, applyPatch(files, patch.parsed, { createdMode: major >= 12 ? 0o644 : undefined }))
193
166
  files = patch.applied.get(files)
194
167
  const manifest = checkPatchOfBins(node, files, targets, where, major)
195
168
  checkPatched?.(manifest, where)
196
169
  }
197
170
  if (targets.size === 0 && executable.size === 0) return files
198
171
  files = new Map(files)
199
- for (const path of targets) files.set(path, fixBin(files.get(path), `${where}: ${quote(path)}`))
172
+ for (const path of targets) files.set(path, fixBin(files.get(path), `${where}: ${quote(path)}`, major))
200
173
  for (const path of executable) files.set(path, { ...files.get(path), mode: 0o755 })
201
174
  return files
202
175
  }
@@ -226,85 +199,61 @@ function linkTarget(path, target) {
226
199
  return relative(`${root}/${dirname(path)}`, `${root}/${target}`) || '.'
227
200
  }
228
201
 
229
- // Every link in the tree, by its path: each node's children beside it and
230
- // itself inside it where it depends on itself, then what is hoisted, then
231
- // each project's direct dependencies, which win over a hoisted alias.
232
- // `byDir` is the graph by directory.
233
- function linksOf(byDir, direct, settings, projects, major) {
202
+ // Every link in the tree, by its path: each node's children beside it and,
203
+ // but with pnpm 12, itself inside it where it depends on itself, then what
204
+ // is hoisted, then each project's direct dependencies, which win over a
205
+ // hoisted alias.
206
+ // `byDir` is the graph by directory, and `hoisting` graph.js's.
207
+ function linksOf(byDir, direct, settings, projects, major, hoisting) {
234
208
  const links = new Map()
235
209
  for (const node of byDir.values()) {
236
210
  for (const [alias, dir] of node.children) if (alias !== node.name) links.set(`${node.modules}/${alias}`, dir)
237
211
  const self = node.children.get(node.name)
238
- if (byDir.has(self)) links.set(`${node.dir}/node_modules/${node.name}`, self)
212
+ if (major < 12 && byDir.has(self)) links.set(`${node.dir}/node_modules/${node.name}`, self)
239
213
  }
240
- for (const [path, dir] of hoist(byDir, direct, settings, projects, major)) links.set(path, dir)
214
+ for (const [path, dir] of hoist(byDir, direct, settings, projects, major, hoisting)) links.set(path, dir)
241
215
  for (const [id, children] of direct) {
242
216
  for (const [alias, dir] of children) links.set(`${id === '.' ? '' : `${id}/`}node_modules/${alias}`, dir)
243
217
  }
244
218
  return links
245
219
  }
246
220
 
247
- // pnpm-workspace.yaml as parsed; one of comments alone, or nothing, sets
248
- // nothing, as pnpm reads it.
249
- const readWorkspace = (text) => (text === undefined || /^(?:[\t ]*(?:#.*)?(?:\r?\n|$))*$/u.test(text) ? undefined : parseYaml(text))
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
-
265
- function readPatchesGiven(patches) {
266
- const entries = patches instanceof Map ? [...patches] : Object.entries(patches ?? {})
267
- for (const [path, text] of entries) {
268
- if (typeof text !== 'string') throw new TypeError(`patches[${quote(path)}] must be a string`)
269
- }
270
- return entries
271
- }
272
-
273
221
  export async function buildPnpmTree(options) {
274
- const { lockfile: text, manifests: manifestTexts, workspace, npmrc, patches, host: machine, vfs: into } = options ?? {}
275
- if (typeof text !== 'string') throw new TypeError('lockfile must be the text of pnpm-lock.yaml')
222
+ const { project, host: given, vfs: into } = options ?? {}
276
223
  if (into !== undefined && !(into instanceof Vfs)) throw new TypeError('vfs must be a Vfs, or left out')
277
- for (const [name, value] of [['workspace', workspace], ['npmrc', npmrc]]) {
278
- if (value !== undefined && typeof value !== 'string') throw new TypeError(`${name} must be a string, or left out`)
279
- }
280
- const host = checkHost(machine)
281
- const folded = host.os === 'darwin'
224
+ if (project !== undefined) checkProject(project)
225
+ const machine = checkHost(given)
226
+ const folded = machine.os === 'darwin'
282
227
  // Refused before anything is fetched; mount checks again.
283
228
  if (into !== undefined) checkNoModules(into, folded)
284
- const { lockfile, env } = parsePnpmLockfile(text)
229
+ const inputs = inputsOf(options)
230
+ const { lockfile, env } = readLockfile(inputs.lockfile)
231
+ if (!('.' in lockfile.importers)) throw new DeptreeError('expected the root project, whose package.json holds settings', 'importers')
232
+ // Before the project is read for any importer: none leads out of it.
233
+ checkLockfile(lockfile)
234
+ const { manifests, pnpm, major, workspace } = manifestsOf(inputs, lockfile, given.pnpm)
235
+ const host = { pnpm, major, ...machine }
285
236
  // pnpm 11 locks config dependencies there, which are refused, and the
286
237
  // pnpm a project pins, which leaves the tree as it is.
287
238
  if (env !== undefined && host.major < 11) throw new DeptreeError('the env document pnpm 11 writes is not supported', 'env')
288
239
  if (env !== undefined && Object.keys(env.importers['.'].configDependencies).length > 0) throw new DeptreeError('config dependencies are not supported', 'env.importers["."].configDependencies')
289
- if (!('.' in lockfile.importers)) throw new DeptreeError('expected the root project, whose package.json holds settings', 'importers')
290
- const manifests = readManifests(manifestTexts, lockfile)
291
- const settings = readSettings({ workspace: readWorkspace(workspace), npmrc, manifest: manifests.get('.'), major: host.major })
292
- checkLockfile(lockfile)
240
+ const settings = readSettings({ workspace, npmrc: inputs.npmrc, manifest: manifests.get('.'), major: host.major, pinned: pinsPnpm(manifests.get('.'), host.pnpm) })
293
241
  checkWorkspace(Object.keys(lockfile.importers), settings.packages, host.major)
294
242
  const overrides = listOverrides(settings.overrides, settings.catalogs, host.major)
295
- const installed = checkLocalOverrides(overrides, into)
296
- const given = await checkUpToDate(lockfile, settings, overrides, readPatchesGiven(patches), host.major)
243
+ const installed = checkLocalOverrides(overrides, project)
244
+ const patches = patchesOf(inputs, settings.patchedDependencies)
245
+ const patched = await checkUpToDate(lockfile, settings, overrides, patches, host.major)
297
246
  const hook = createHook({ overrides, ignored: settings.ignoredOptionalDependencies, major: host.major })
298
- checkProjects(lockfile, manifests, { hook, host, settings })
247
+ checkProjects(lockfile, manifests, { hook, host, settings, env })
299
248
  checkOptional(lockfile)
300
249
  const projects = settings.hoistWorkspacePackages ? workspaceNames(manifests) : new Map()
301
250
  const { skipped, incompatible } = skippedSnapshots(lockfile, { host, settings })
302
- const { nodes, direct } = await buildGraph(lockfile, skipped, settings.virtualStoreDirMaxLength, host.major)
251
+ const { nodes, direct, hoisting } = await buildGraph(lockfile, skipped, settings.virtualStoreDirMaxLength, host.major)
303
252
  for (const node of nodes.values()) checkSource(node, installed)
304
253
 
305
- const { byDir, tarballs } = await fetchNodes(nodes, hook, into, host.major)
306
- const links = linksOf(byDir, direct, settings, projects, host.major)
307
- const linked = readLinked(links, byDir, manifests, into)
254
+ const { byDir, tarballs } = await fetchNodes(nodes, hook, project, host.major, createFreshnessCheck(lockfile, host.major))
255
+ const links = linksOf(byDir, direct, settings, projects, host.major, hoisting)
256
+ const linked = readLinked(links, byDir, manifests, project)
308
257
  const targets = binTargets({
309
258
  nodes: byDir,
310
259
  projects: new Map([...manifests, ...linked]),
@@ -315,7 +264,7 @@ export async function buildPnpmTree(options) {
315
264
  peers: settings.autoInstallPeers,
316
265
  major: host.major,
317
266
  })
318
- const executable = executableElsewhere(byDir, targets)
267
+ const executable = executableElsewhere(byDir, targets, settings.packageImportMethod, host.major)
319
268
 
320
269
  const vfs = new Vfs()
321
270
  vfs.mkdir('/node_modules/.pnpm', { recursive: true })
@@ -327,7 +276,7 @@ export async function buildPnpmTree(options) {
327
276
  if (node.pkg.patchHash !== undefined) stats.patched++
328
277
  try {
329
278
  vfs.mkdir(`/${node.dir}`, { recursive: true })
330
- for (const [path, file] of compose(node, given, { targets: targets.get(node.dir) ?? new Set(), executable: executable.get(node.dir) ?? new Set() }, composing)) {
279
+ for (const [path, file] of compose(node, patched, { targets: targets.get(node.dir) ?? new Set(), executable: executable.get(node.dir) ?? new Set() }, composing)) {
331
280
  if (file.directory) vfs.mkdir(`/${node.dir}/${path}`, { recursive: true })
332
281
  else if (writeOnce(vfs, `/${node.dir}/${path}`, file)) {
333
282
  stats.files++
@@ -17,10 +17,19 @@
17
17
  // refused, and so is a glob reaching outside the workspace's directory.
18
18
  // pnpm 11 leaves out what a `!` glob takes with micromatch too, a name
19
19
  // starting with a dot and all.
20
-
21
- import { normalize } from '@preventive/vfs/path.js'
20
+ //
21
+ // pnpm 12 finds them its own way (its projects walk, with wax), and the
22
+ // same but in four places: a `**` may take no name before one a glob
23
+ // spells with a leading dot; nothing under a node_modules or a
24
+ // bower_components is walked into or taken, wherever it is; where a glob
25
+ // with a `*` takes a directory, the first of its manifests that is there
26
+ // is read, which fails where it is not a file; and the projects come in
27
+ // the order of their paths by name.
28
+
29
+ import { compareNames, normalize } from '@preventive/vfs/path.js'
22
30
  import { DeptreeError, quote } from '../error.js'
23
31
  import { escape } from '../matcher.js'
32
+ import { typeOf } from './project.js'
24
33
 
25
34
  const UNSUPPORTED = /[?[\]{}()\\]/u
26
35
 
@@ -83,29 +92,66 @@ function enters({ names: glob, dot }, names) {
83
92
  }
84
93
 
85
94
  // `packages`, the globs or undefined, as the globs that take and those
86
- // that leave out; `major` pnpm's major version.
95
+ // that leave out, with how pnpm `major` walks for them: which directories
96
+ // it enters for a glob, which it ignores, and which manifests it drops
97
+ // whatever the globs say. pnpm 12 reads the manifest of a directory a
98
+ // glob with a `*` takes, which is `wild`, whatever it is.
87
99
  function compileAll(packages, major) {
88
- const globs = { include: [], exclude: [] }
100
+ const twelve = major >= 12
101
+ const globs = { include: [], exclude: [], enters: twelve ? enters12 : enters, ignored: twelve ? ignored12 : ignored, dropped: twelve ? ignored12 : () => false }
89
102
  for (const glob of packages ?? []) {
90
103
  const exclude = glob.startsWith('!')
91
- globs[exclude ? 'exclude' : 'include'].push(compile(exclude ? glob.slice(1) : glob, 'pnpm-workspace.yaml: packages', exclude && major >= 11))
104
+ const compiled = compile(exclude ? glob.slice(1) : glob, 'pnpm-workspace.yaml: packages', exclude && major >= 11)
105
+ globs[exclude ? 'exclude' : 'include'].push({ ...compiled, wild: twelve && glob.includes('*') })
92
106
  }
93
107
  return globs
94
108
  }
95
109
 
110
+ // The manifest pnpm reads of the directory at `names`, given the names in
111
+ // it: the first of them there that is a file, a link that leads nowhere
112
+ // passed over. pnpm 12 reads the first there, where a glob with a `*`
113
+ // takes the directory, and fails where that is not a file.
114
+ function manifestOf(project, globs, names, entries) {
115
+ const wild = () => globs.include.some((glob) => glob.wild && takes(glob, [...names, 'package.json']))
116
+ for (const name of MANIFESTS) {
117
+ if (!entries.includes(name)) continue
118
+ const type = typeOf(project, `/${[...names, name].join('/')}`)
119
+ if (type === 'file') return name
120
+ if (type !== undefined && wild()) throw new DeptreeError(`pnpm 12 reads this as a manifest, and fails on it as a ${type}`, quote([...names, name].join('/')))
121
+ }
122
+ return undefined
123
+ }
124
+
125
+ // Two paths in the order of their names, as pnpm 12 has them.
126
+ function byNames(a, b) {
127
+ const x = a.split('/')
128
+ const y = b.split('/')
129
+ for (let i = 0; i < Math.min(x.length, y.length); i++) if (x[i] !== y[i]) return compareNames(x[i], y[i])
130
+ return x.length - y.length
131
+ }
132
+
96
133
  // What find-packages leaves out, as tinyglobby reads it, which does not
97
134
  // take a name with a leading dot for `**`: what is under node_modules or
98
135
  // bower_components.
99
- const IGNORED = ['node_modules', 'bower_components'].map((name) => ({ names: ['**', NAME(name, false), '**'], dot: false }))
136
+ const LEFT_OUT = ['node_modules', 'bower_components']
137
+ const IGNORED = LEFT_OUT.map((name) => ({ names: ['**', NAME(name, false), '**'], dot: false }))
100
138
  const ignored = (names) => IGNORED.some((glob) => takes(glob, names))
101
139
 
140
+ // What pnpm 12 never walks into or takes: anything with one of those in
141
+ // its path.
142
+ const ignored12 = (names) => names.some((name) => LEFT_OUT.includes(name))
143
+
144
+ // Whether pnpm 12 walks into the directory at `names` for a glob: where
145
+ // the glob's names before its last may take it.
146
+ const enters12 = (glob, names) => reach(glob, names).slice(0, glob.names.length).some(Boolean)
147
+
102
148
  // Whether the globs take the manifest at `names`. What find-packages
103
149
  // 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))
150
+ const taken = ({ include, exclude, dropped }, names) => include.some((glob) => takes(glob, names)) && !exclude.some((glob) => takes(glob, names)) && !dropped(names)
105
151
 
106
152
  // 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)
153
+ // through a link to one too; or pnpm 12.
154
+ const walked = (globs, names) => globs.include.some((glob) => globs.enters(glob, names)) && !globs.ignored(names)
109
155
 
110
156
  // `ids` are the projects' directories, `.` the root; `packages` the globs,
111
157
  // or undefined; `major` pnpm's major version. pnpm finds a project where
@@ -133,15 +179,19 @@ export function checkProjectId(id, where) {
133
179
  }
134
180
  }
135
181
 
182
+ // A manifest pnpm would read through a link, the root's among them, is
183
+ // refused before it is read.
184
+ export const linkedManifest = (file) => new DeptreeError('a link pnpm would read a project\'s manifest through is not supported', quote(file))
185
+
136
186
  // The names pnpm reads a project's manifest by, the first of them there
137
187
  // winning.
138
188
  const MANIFESTS = ['package.json', 'package.json5', 'package.yaml']
139
189
 
140
190
  // 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.
191
+ // `packages` in `project` (project.js): `.`, the root, then the rest in
192
+ // order. Every directory tinyglobby walks into is read, and no other, a
193
+ // link to one followed as it follows it. A manifest is a file, or a link
194
+ // to one; a link that leads nowhere, or to a directory, is none.
145
195
  // Refused, as not read here: a root with no manifest, which pnpm takes
146
196
  // for no project; a project, the root among them, whose manifest is
147
197
  // package.json5, package.yaml or a link; a project found
@@ -150,7 +200,7 @@ const MANIFESTS = ['package.json', 'package.json5', 'package.yaml']
150
200
  // importer by; and a node_modules tinyglobby walks into, which it does
151
201
  // only under a directory with a leading dot, as what is installed there
152
202
  // is no project buildPnpmTree builds.
153
- export function findProjects(vfs, packages, major = 10) {
203
+ export function findProjects(project, packages, major = 10) {
154
204
  const globs = compileAll(packages, major)
155
205
  const ids = []
156
206
  // The directories left to read, by their names, and the link each is
@@ -159,14 +209,12 @@ export function findProjects(vfs, packages, major = 10) {
159
209
  while (pending.length > 0) {
160
210
  const { names, link } = pending.pop()
161
211
  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
212
+ const entries = project.readdir(`/${dir}`)
213
+ const found = names.length === 0 || taken(globs, [...names, 'package.json']) ? manifestOf(project, globs, names, entries) : undefined
166
214
  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
215
  if (found !== undefined) {
168
216
  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))
217
+ if (project.lstat(`/${file}`).type === 'symlink') throw linkedManifest(file)
170
218
  if (found !== 'package.json') throw new DeptreeError(`pnpm reads this project's ${found}, which is not supported`, quote(file))
171
219
  if (link !== undefined) throw new DeptreeError(`pnpm finds a project through this link, ${quote(dir)}, which is not supported`, quote(link))
172
220
  if (names.length > 0) {
@@ -178,8 +226,8 @@ export function findProjects(vfs, packages, major = 10) {
178
226
  const at = [...names, entry]
179
227
  if (!walked(globs, at)) continue
180
228
  const path = at.join('/')
181
- const { type } = vfs.lstat(`/${path}`)
182
- const linked = type === 'symlink' && typeOf(vfs, `/${path}`) === 'directory'
229
+ const { type } = project.lstat(`/${path}`)
230
+ const linked = type === 'symlink' && typeOf(project, `/${path}`) === 'directory'
183
231
  if (type !== 'directory' && !linked) continue
184
232
  if (entry === 'node_modules') throw new DeptreeError('pnpm-workspace.yaml\'s packages walk into this node_modules, which is not supported', quote(path))
185
233
  if (!linked) pending.push({ names: at, link })
@@ -187,18 +235,5 @@ export function findProjects(vfs, packages, major = 10) {
187
235
  else throw new DeptreeError(`a link to a directory in one tinyglobby follows, ${quote(path)}, is not supported`, quote(link))
188
236
  }
189
237
  }
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
- }
238
+ return ['.', ...major >= 12 ? ids.sort(byNames) : ids.sort()]
204
239
  }
@@ -0,0 +1,79 @@
1
+ // The config `soldeer install` reads, as Soldeer 0.12 finds and reads it:
2
+ // foundry.toml where it has a [dependencies] table; else soldeer.toml,
3
+ // where there is no foundry.toml. Where neither holds, Soldeer asks which
4
+ // one to make its config, which is refused. Of foundry.toml, what Soldeer
5
+ // would fail on as it adds `dependencies` to the default profile's libs is
6
+ // refused; of the config, its [soldeer] settings where Soldeer would fail
7
+ // on them, and recursive_deps.
8
+
9
+ import { TomlError, isInlineTable, parseToml } from '@preventive/lockfile/toml.js'
10
+ import { DeptreeError } from '../error.js'
11
+
12
+ const isTable = (value) => typeof value === 'object' && value !== null && Object.getPrototypeOf(value) === null
13
+ // A table toml_edit gives as one, as a header or a dotted key makes it:
14
+ // one written inline it gives as a value, which Soldeer reads no
15
+ // dependencies from, and fails on for a profile.
16
+ const isTableItem = (value) => isTable(value) && !isInlineTable(value)
17
+
18
+ function parse(text, file) {
19
+ try {
20
+ return parseToml(text)
21
+ } catch (error) {
22
+ if (error instanceof TomlError) throw new DeptreeError(`not TOML read here: ${error.message}`, file, { cause: error })
23
+ throw error
24
+ }
25
+ }
26
+
27
+ // update_config_libs, which expects each of these to be what it adds where
28
+ // it is not there, and panics on another.
29
+ function checkLibs(doc) {
30
+ const { profile } = doc
31
+ if (profile === undefined) return
32
+ if (!isTableItem(profile)) throw new DeptreeError('not a table, which Soldeer fails on', 'foundry.toml: profile')
33
+ const defaults = profile.default
34
+ if (defaults === undefined) return
35
+ if (!isTableItem(defaults)) throw new DeptreeError('not a table, which Soldeer fails on', 'foundry.toml: profile.default')
36
+ const { libs } = defaults
37
+ if (libs !== undefined && (!Array.isArray(libs) || isTableItem(libs[0]))) throw new DeptreeError('not an array, which Soldeer fails on', 'foundry.toml: profile.default.libs')
38
+ }
39
+
40
+ function checkDependencies(doc, file) {
41
+ if (doc.dependencies !== undefined && !isTableItem(doc.dependencies)) {
42
+ throw new DeptreeError('not a table, which Soldeer reads no dependencies from, is not supported', `${file}: dependencies`)
43
+ }
44
+ }
45
+
46
+ const BOOLEANS = ['remappings_generate', 'remappings_regenerate', 'remappings_version', 'recursive_deps']
47
+
48
+ // read_soldeer_config's SoldeerConfig, by serde: each field of its type,
49
+ // any other passed over.
50
+ function checkSettings(settings, file) {
51
+ if (settings === undefined) return
52
+ const where = `${file}: soldeer`
53
+ if (!isTable(settings)) throw new DeptreeError('not a table, which Soldeer fails on', where)
54
+ for (const key of BOOLEANS) {
55
+ if (settings[key] !== undefined && typeof settings[key] !== 'boolean') throw new DeptreeError('not true or false, which Soldeer fails on', `${where}.${key}`)
56
+ }
57
+ if (settings.remappings_prefix !== undefined && typeof settings.remappings_prefix !== 'string') throw new DeptreeError('not a string, which Soldeer fails on', `${where}.remappings_prefix`)
58
+ if (settings.remappings_location !== undefined && settings.remappings_location !== 'txt' && settings.remappings_location !== 'config') {
59
+ throw new DeptreeError('not "txt" or "config", which Soldeer fails on', `${where}.remappings_location`)
60
+ }
61
+ if (settings.recursive_deps === true) throw new DeptreeError('has Soldeer install what each dependency depends on too, which is not supported', `${where}.recursive_deps`)
62
+ }
63
+
64
+ const ASKS = 'Soldeer asks which file to make its config, which is not supported'
65
+
66
+ // The file Soldeer reads its config from, and that config, parsed.
67
+ export function configOf({ foundry, soldeer }) {
68
+ if (foundry === undefined && soldeer === undefined) throw new DeptreeError(`neither foundry.toml nor soldeer.toml is there, so ${ASKS}`)
69
+ const file = foundry === undefined ? 'soldeer.toml' : 'foundry.toml'
70
+ const config = parse(foundry ?? soldeer, file)
71
+ if (foundry === undefined) {
72
+ checkDependencies(config, file)
73
+ } else {
74
+ if (!isTableItem(config.dependencies)) throw new DeptreeError(`no [dependencies] table, so ${ASKS}`, file)
75
+ checkLibs(config)
76
+ }
77
+ checkSettings(config.soldeer, file)
78
+ return { file, config }
79
+ }
@@ -0,0 +1,40 @@
1
+ // What buildSoldeerTree takes, checked: the host Soldeer runs on, and the
2
+ // files `soldeer install` reads — given as text, or read from the project
3
+ // (../pnpm/project.js) as Soldeer reads them at the project's root.
4
+
5
+ import { DeptreeError, quote } from '../error.js'
6
+ import { checkProject, readText } from '../pnpm/project.js'
7
+
8
+ export function checkHost(host) {
9
+ if (host === null || typeof host !== 'object') throw new TypeError('host must be an object with soldeer and os')
10
+ for (const key of ['soldeer', 'os']) {
11
+ if (typeof host[key] !== 'string' || host[key] === '') throw new TypeError(`host.${key} must be a non-empty string`)
12
+ }
13
+ if (host.soldeer !== '0.12.0') throw new DeptreeError(`Soldeer ${quote(host.soldeer)} is not supported: only Soldeer 0.12.0 is`, 'host.soldeer')
14
+ if (host.os === 'win32') throw new DeptreeError('Windows is not supported: Soldeer names folders otherwise there', 'host.os')
15
+ return { soldeer: host.soldeer, os: host.os }
16
+ }
17
+
18
+ const LOCKFILE = 'lockfile must be the soldeer.lock text, or left out where project is given'
19
+
20
+ export function inputsOf(options) {
21
+ const { lockfile, foundry, soldeer, project } = options
22
+ if (lockfile === undefined) {
23
+ if (project === undefined) throw new TypeError(LOCKFILE)
24
+ checkProject(project)
25
+ for (const [name, value] of Object.entries({ foundry, soldeer })) {
26
+ if (value !== undefined) throw new TypeError(`${name} must be left out where lockfile is: all are read from project`)
27
+ }
28
+ const lock = readText(project, '/soldeer.lock', 'soldeer.lock')
29
+ if (lock === undefined) throw new DeptreeError('the project has no soldeer.lock, without which Soldeer resolves each dependency anew')
30
+ // Soldeer reads soldeer.toml only where it cannot read foundry.toml.
31
+ const foundryText = readText(project, '/foundry.toml', 'foundry.toml')
32
+ return { lockfile: lock, foundry: foundryText, soldeer: foundryText === undefined ? readText(project, '/soldeer.toml', 'soldeer.toml') : undefined }
33
+ }
34
+ if (typeof lockfile !== 'string') throw new TypeError(LOCKFILE)
35
+ if (project !== undefined) throw new TypeError('project must be left out where lockfile is given')
36
+ for (const [name, value] of Object.entries({ foundry, soldeer })) {
37
+ if (value !== undefined && typeof value !== 'string') throw new TypeError(`${name} must be a string, or left out`)
38
+ }
39
+ return { lockfile, foundry, soldeer }
40
+ }