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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,97 @@
1
+ // The project a tree is built for: a view of the lockfile's directory, by
2
+ // paths from `/` — a Vfs, or anything with its readdir, lstat, stat and
3
+ // readFile, such as one of a directory on disk. It is only read, and only
4
+ // where these say: the files pnpm reads at the root for an install, the
5
+ // package.json of each project and the patches the settings name, where
6
+ // buildPnpmTree is not handed them; the directories findProjects walks;
7
+ // and those a `link:` or `file:` leads to (local.js).
8
+
9
+ import { normalize } from '@preventive/vfs/path.js'
10
+ import { DeptreeError, quote } from '../error.js'
11
+
12
+ export function checkProject(project) {
13
+ if (['readdir', 'lstat', 'stat', 'readFile'].some((name) => typeof project?.[name] !== 'function')) {
14
+ throw new TypeError('project must be a Vfs, or have its readdir, lstat, stat and readFile')
15
+ }
16
+ }
17
+
18
+ // What `path` leads to, links followed, or where `follow` is false, what
19
+ // it is; nothing, where it leads nowhere: to no entry, through a file, or
20
+ // round a loop of links. Any other failure is thrown.
21
+ const NOWHERE = new Set(['ENOENT', 'ENOTDIR', 'ELOOP'])
22
+ export function typeOf(project, path, follow = true) {
23
+ try {
24
+ return (follow ? project.stat(path) : project.lstat(path)).type
25
+ } catch (error) {
26
+ if (NOWHERE.has(error?.code)) return undefined
27
+ throw error
28
+ }
29
+ }
30
+
31
+ // As text handed in would be: a byte order mark kept, for what reads it
32
+ // to drop as pnpm does.
33
+ const decoder = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true })
34
+
35
+ // The bytes of the file at `path`, as a Vfs gives them back.
36
+ export function readBytes(project, path) {
37
+ const bytes = project.readFile(path)
38
+ if (!(bytes instanceof Uint8Array)) throw new TypeError('project.readFile must give back bytes')
39
+ return bytes
40
+ }
41
+
42
+ // The text of the file at `path`, or undefined where nothing is.
43
+ export function readText(project, path, where) {
44
+ const type = typeOf(project, path)
45
+ if (type === undefined) return undefined
46
+ if (type !== 'file') throw new DeptreeError(`${quote(path.slice(1))} is a ${type}, not a file`, where)
47
+ const bytes = readBytes(project, path)
48
+ try {
49
+ return decoder.decode(bytes)
50
+ } catch {
51
+ throw new DeptreeError(`${quote(path.slice(1))} is not UTF-8`, where)
52
+ }
53
+ }
54
+
55
+ // pnpm-workspace.yaml, where it is. pnpm looks for it under other names
56
+ // too, and refuses one it finds so.
57
+ const MISNAMED = ['pnpm-workspaces.yaml', 'pnpm-workspaces.yml', 'pnpm-workspace.yml', '.pnpm-workspace.yaml', '.pnpm-workspace.yml', '.pnpm-workspaces.yaml', '.pnpm-workspaces.yml']
58
+ export function readWorkspaceText(project) {
59
+ const text = readText(project, '/pnpm-workspace.yaml')
60
+ const misnamed = text === undefined ? MISNAMED.find((name) => typeOf(project, `/${name}`) === 'file') : undefined
61
+ if (misnamed !== undefined) throw new DeptreeError('pnpm refuses a workspace manifest not named pnpm-workspace.yaml', quote(misnamed))
62
+ return text
63
+ }
64
+
65
+ // What pnpm reads at the root for an install besides the package.json:
66
+ // pnpm-lock.yaml, which a frozen install cannot do without, and
67
+ // pnpm-workspace.yaml and the .npmrc, where they are.
68
+ export function readRootFiles(project) {
69
+ const lockfile = readText(project, '/pnpm-lock.yaml')
70
+ if (lockfile === undefined) throw new DeptreeError('the project has no pnpm-lock.yaml, which a frozen install cannot do without')
71
+ return { lockfile, workspace: readWorkspaceText(project), npmrc: readText(project, '/.npmrc') }
72
+ }
73
+
74
+ // The text of the package.json of each of `ids`, the projects'
75
+ // directories, by directory.
76
+ export function readManifestTexts(project, ids) {
77
+ const texts = new Map()
78
+ for (const id of ids) {
79
+ texts.set(id, readText(project, id === '.' ? '/package.json' : `/${id}/package.json`, `manifests[${quote(id)}]`))
80
+ }
81
+ return texts
82
+ }
83
+
84
+ // The text of each patch `configured`, patchedDependencies, names, by its
85
+ // path from the lockfile's directory; one that is not there left out.
86
+ // One outside that directory, or absolute, is not in the project, and is
87
+ // refused.
88
+ export function readPatches(project, configured) {
89
+ const texts = new Map()
90
+ for (const [selector, spec] of Object.entries(configured ?? {})) {
91
+ const path = normalize(spec)
92
+ if (path === '..' || path.startsWith('../') || path.startsWith('/')) throw new DeptreeError(`the patch ${quote(spec)} is not in the project: it is outside the lockfile's directory`, `patchedDependencies[${quote(selector)}]`)
93
+ const text = readText(project, `/${path}`, `patches[${quote(path)}]`)
94
+ if (text !== undefined) texts.set(path, text)
95
+ }
96
+ return texts
97
+ }
@@ -150,6 +150,13 @@ function devEnginesPackageManager(devEngines, where) {
150
150
  return { name: engine.name, onFail }
151
151
  }
152
152
 
153
+ // The version of pnpm packageManager names, as pnpm's parsePackageManager
154
+ // reads it, where it names pnpm at an exact version.
155
+ export function pinnedPnpm(packageManager) {
156
+ const version = typeof packageManager === 'string' ? /^pnpm@([^+:@]+)(?:\+.*)?$/u.exec(packageManager)?.[1] : undefined
157
+ return isExactVersion(version) ? version : undefined
158
+ }
159
+
153
160
  // packageManager as pnpm's parsePackageManager reads it, held to be this
154
161
  // pnpm, exactly: pnpm switches to the version it names, and one it cannot
155
162
  // switch to, or another package manager, is refused rather than run over.
@@ -167,8 +174,8 @@ function checkPackageManager(manifest, host, pmOnFail) {
167
174
  }
168
175
  if (packageManager === undefined) return
169
176
  const where = 'manifests["."].packageManager'
170
- const version = typeof packageManager === 'string' ? /^pnpm@([^+:@]+)(?:\+.*)?$/u.exec(packageManager)?.[1] : undefined
171
- if (!isExactVersion(version)) throw new DeptreeError(`${quote(String(packageManager))} is not pnpm at an exact version`, where)
177
+ const version = pinnedPnpm(packageManager)
178
+ if (version === undefined) throw new DeptreeError(`${quote(String(packageManager))} is not pnpm at an exact version`, where)
172
179
  if (version !== host.pnpm) throw new DeptreeError(`the project is installed by pnpm ${version}, which pnpm switches to, not ${host.pnpm}`, where)
173
180
  }
174
181
 
package/src/pnpm/tree.js CHANGED
@@ -20,10 +20,8 @@
20
20
  // memory — its package's, patched, bins fixed — before one write of each.
21
21
 
22
22
  import { packageKeyOf, parsePnpmLockfile } from '@preventive/lockfile/pnpm.js'
23
- import { parseYaml } from '@preventive/lockfile/yaml.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'
27
25
  import { DeptreeError, quote } from '../error.js'
28
26
  import { checkNoModules, mount } from '../mount.js'
29
27
  import { applyPatch, parsePatch } from '../patch.js'
@@ -36,35 +34,14 @@ import { createPatchedCheck, skippedSnapshots } from './install.js'
36
34
  import { checkCollisions, checkLinks, checkOptional } from './checks.js'
37
35
  import { createHook } from './hook.js'
38
36
  import { listOverrides } from './overrides.js'
39
- import { checkProjects, readManifests, workspaceNames } from './projects.js'
40
- import { readers } from './readers.js'
37
+ import { checkHost, inputsOf, manifestsOf, patchesOf, readWorkspace } from './inputs.js'
38
+ import { checkProject } from './project.js'
39
+ import { checkProjects, workspaceNames } from './projects.js'
41
40
  import { readSettings } from './settings.js'
42
41
  import { checkUpToDate } from './uptodate.js'
43
- import { checkWorkspace, findProjects } from './workspace.js'
42
+ import { checkWorkspace } from './workspace.js'
44
43
 
45
44
  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
- }
68
45
 
69
46
  // What the lockfile holds that no tree is built for here.
70
47
  function checkLockfile(lockfile) {
@@ -107,8 +84,8 @@ const packageFields = (pkg) => JSON.stringify(PACKAGE_FIELDS.map((field) => pkg[
107
84
  // Each package's files and package.json, by its name and version: a
108
85
  // package is fetched once however many snapshots it has, a few at a time,
109
86
  // 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) {
87
+ // a directory is read from `project`, as npm-packlist picks its files.
88
+ async function fetchAll(nodes, project, major) {
112
89
  const packages = new Map()
113
90
  for (const { key, pkg } of nodes.values()) {
114
91
  const id = packageKeyOf(key)
@@ -123,7 +100,7 @@ async function fetchAll(nodes, vfs, major) {
123
100
  const [id, pkg] = queue.shift()
124
101
  try {
125
102
  if (pkg.resolution.type === 'directory') {
126
- const got = readDirectoryPackage(vfs, pkg, quote(id), major)
103
+ const got = readDirectoryPackage(project, pkg, quote(id), major)
127
104
  checkManifest(got.manifest, pkg, quote(id))
128
105
  fetched.set(id, { ...got, local: true })
129
106
  } else fetched.set(id, await fetchPackage(pkg, quote(id)))
@@ -140,8 +117,8 @@ async function fetchAll(nodes, vfs, major) {
140
117
  // Each node with its package's files and package.json, by its directory:
141
118
  // its dependencies held to the package.json, as `hook` reads it once for
142
119
  // each package; and the number of tarballs fetched.
143
- async function fetchNodes(nodes, hook, vfs, major) {
144
- const fetched = await fetchAll(nodes, vfs, major)
120
+ async function fetchNodes(nodes, hook, project, major) {
121
+ const fetched = await fetchAll(nodes, project, major)
145
122
  const byDir = new Map()
146
123
  for (const node of nodes.values()) {
147
124
  const id = packageKeyOf(node.key)
@@ -244,56 +221,32 @@ function linksOf(byDir, direct, settings, projects, major) {
244
221
  return links
245
222
  }
246
223
 
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
224
  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')
225
+ const { project, host: given, vfs: into } = options ?? {}
276
226
  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'
227
+ if (project !== undefined) checkProject(project)
228
+ const machine = checkHost(given)
229
+ const folded = machine.os === 'darwin'
282
230
  // Refused before anything is fetched; mount checks again.
283
231
  if (into !== undefined) checkNoModules(into, folded)
284
- const { lockfile, env } = parsePnpmLockfile(text)
232
+ const inputs = inputsOf(options)
233
+ const { lockfile, env } = parsePnpmLockfile(inputs.lockfile)
234
+ if (!('.' in lockfile.importers)) throw new DeptreeError('expected the root project, whose package.json holds settings', 'importers')
235
+ // Before the project is read for any importer: none leads out of it.
236
+ checkLockfile(lockfile)
237
+ const workspace = readWorkspace(inputs.workspace)
238
+ const { manifests, pnpm, major } = manifestsOf(inputs, workspace, lockfile, given.pnpm)
239
+ const host = { pnpm, major, ...machine }
285
240
  // pnpm 11 locks config dependencies there, which are refused, and the
286
241
  // pnpm a project pins, which leaves the tree as it is.
287
242
  if (env !== undefined && host.major < 11) throw new DeptreeError('the env document pnpm 11 writes is not supported', 'env')
288
243
  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)
244
+ const settings = readSettings({ workspace, npmrc: inputs.npmrc, manifest: manifests.get('.'), major: host.major })
293
245
  checkWorkspace(Object.keys(lockfile.importers), settings.packages, host.major)
294
246
  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)
247
+ const installed = checkLocalOverrides(overrides, project)
248
+ const patches = patchesOf(inputs, settings.patchedDependencies)
249
+ const patched = await checkUpToDate(lockfile, settings, overrides, patches, host.major)
297
250
  const hook = createHook({ overrides, ignored: settings.ignoredOptionalDependencies, major: host.major })
298
251
  checkProjects(lockfile, manifests, { hook, host, settings })
299
252
  checkOptional(lockfile)
@@ -302,9 +255,9 @@ export async function buildPnpmTree(options) {
302
255
  const { nodes, direct } = await buildGraph(lockfile, skipped, settings.virtualStoreDirMaxLength, host.major)
303
256
  for (const node of nodes.values()) checkSource(node, installed)
304
257
 
305
- const { byDir, tarballs } = await fetchNodes(nodes, hook, into, host.major)
258
+ const { byDir, tarballs } = await fetchNodes(nodes, hook, project, host.major)
306
259
  const links = linksOf(byDir, direct, settings, projects, host.major)
307
- const linked = readLinked(links, byDir, manifests, into)
260
+ const linked = readLinked(links, byDir, manifests, project)
308
261
  const targets = binTargets({
309
262
  nodes: byDir,
310
263
  projects: new Map([...manifests, ...linked]),
@@ -327,7 +280,7 @@ export async function buildPnpmTree(options) {
327
280
  if (node.pkg.patchHash !== undefined) stats.patched++
328
281
  try {
329
282
  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)) {
283
+ for (const [path, file] of compose(node, patched, { targets: targets.get(node.dir) ?? new Set(), executable: executable.get(node.dir) ?? new Set() }, composing)) {
331
284
  if (file.directory) vfs.mkdir(`/${node.dir}/${path}`, { recursive: true })
332
285
  else if (writeOnce(vfs, `/${node.dir}/${path}`, file)) {
333
286
  stats.files++
@@ -21,6 +21,7 @@
21
21
  import { normalize } from '@preventive/vfs/path.js'
22
22
  import { DeptreeError, quote } from '../error.js'
23
23
  import { escape } from '../matcher.js'
24
+ import { typeOf } from './project.js'
24
25
 
25
26
  const UNSUPPORTED = /[?[\]{}()\\]/u
26
27
 
@@ -133,15 +134,19 @@ export function checkProjectId(id, where) {
133
134
  }
134
135
  }
135
136
 
137
+ // A manifest pnpm would read through a link, the root's among them, is
138
+ // refused before it is read.
139
+ export const linkedManifest = (file) => new DeptreeError('a link pnpm would read a project\'s manifest through is not supported', quote(file))
140
+
136
141
  // The names pnpm reads a project's manifest by, the first of them there
137
142
  // winning.
138
143
  const MANIFESTS = ['package.json', 'package.json5', 'package.yaml']
139
144
 
140
145
  // 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.
146
+ // `packages` in `project` (project.js): `.`, the root, then the rest in
147
+ // order. Every directory tinyglobby walks into is read, and no other, a
148
+ // link to one followed as it follows it. A manifest is a file, or a link
149
+ // to one; a link that leads nowhere, or to a directory, is none.
145
150
  // Refused, as not read here: a root with no manifest, which pnpm takes
146
151
  // for no project; a project, the root among them, whose manifest is
147
152
  // package.json5, package.yaml or a link; a project found
@@ -150,7 +155,7 @@ const MANIFESTS = ['package.json', 'package.json5', 'package.yaml']
150
155
  // importer by; and a node_modules tinyglobby walks into, which it does
151
156
  // only under a directory with a leading dot, as what is installed there
152
157
  // is no project buildPnpmTree builds.
153
- export function findProjects(vfs, packages, major = 10) {
158
+ export function findProjects(project, packages, major = 10) {
154
159
  const globs = compileAll(packages, major)
155
160
  const ids = []
156
161
  // The directories left to read, by their names, and the link each is
@@ -159,14 +164,14 @@ export function findProjects(vfs, packages, major = 10) {
159
164
  while (pending.length > 0) {
160
165
  const { names, link } = pending.pop()
161
166
  const dir = names.join('/')
162
- const entries = vfs.readdir(`/${dir}`)
167
+ const entries = project.readdir(`/${dir}`)
163
168
  const found = names.length === 0 || taken(globs, [...names, 'package.json'])
164
- ? MANIFESTS.find((name) => entries.includes(name) && typeOf(vfs, `/${[...names, name].join('/')}`) === 'file')
169
+ ? MANIFESTS.find((name) => entries.includes(name) && typeOf(project, `/${[...names, name].join('/')}`) === 'file')
165
170
  : undefined
166
171
  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
172
  if (found !== undefined) {
168
173
  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))
174
+ if (project.lstat(`/${file}`).type === 'symlink') throw linkedManifest(file)
170
175
  if (found !== 'package.json') throw new DeptreeError(`pnpm reads this project's ${found}, which is not supported`, quote(file))
171
176
  if (link !== undefined) throw new DeptreeError(`pnpm finds a project through this link, ${quote(dir)}, which is not supported`, quote(link))
172
177
  if (names.length > 0) {
@@ -178,8 +183,8 @@ export function findProjects(vfs, packages, major = 10) {
178
183
  const at = [...names, entry]
179
184
  if (!walked(globs, at)) continue
180
185
  const path = at.join('/')
181
- const { type } = vfs.lstat(`/${path}`)
182
- const linked = type === 'symlink' && typeOf(vfs, `/${path}`) === 'directory'
186
+ const { type } = project.lstat(`/${path}`)
187
+ const linked = type === 'symlink' && typeOf(project, `/${path}`) === 'directory'
183
188
  if (type !== 'directory' && !linked) continue
184
189
  if (entry === 'node_modules') throw new DeptreeError('pnpm-workspace.yaml\'s packages walk into this node_modules, which is not supported', quote(path))
185
190
  if (!linked) pending.push({ names: at, link })
@@ -189,16 +194,3 @@ export function findProjects(vfs, packages, major = 10) {
189
194
  }
190
195
  return ['.', ...ids.sort()]
191
196
  }
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
@@ -144,14 +144,20 @@ export function checkDependencies(manifest, read, pkg, where) {
144
144
  }
145
145
  }
146
146
 
147
+ // A version's tarball from the registry, through @preventive/upstream, held
148
+ // to `integrity` and to be gzipped: its bytes, and its entries unpacked.
149
+ export async function fetchTarball(name, version, integrity, where) {
150
+ const bytes = await getTarball(name, version, { tarball: tarballUrl(name, version), integrity })
151
+ if (!await matchesIntegrity(bytes, integrity)) throw new DeptreeError(`the tarball is not ${integrity}`, where)
152
+ if (bytes[0] !== 0x1f || bytes[1] !== 0x8b || bytes[2] !== 0x08) throw new DeptreeError('the tarball is not gzipped', where)
153
+ return { bytes, entries: unpack(await decompress(bytes, 'gzip', { limit: MAX_BYTES })) }
154
+ }
155
+
147
156
  // A package's files, and its package.json as parsed; the package has to be
148
157
  // from the registry.
149
158
  export async function fetchPackage(pkg, where) {
150
- const { integrity } = pkg.resolution
151
- const bytes = await getTarball(pkg.name, pkg.version, { tarball: tarballUrl(pkg.name, pkg.version), integrity })
152
- if (!await matchesIntegrity(bytes, integrity)) throw new DeptreeError(`the tarball is not ${integrity}`, where)
153
- if (bytes[0] !== 0x1f || bytes[1] !== 0x8b || bytes[2] !== 0x08) throw new DeptreeError('the tarball is not gzipped', where)
154
- const files = filesOf(unpack(await decompress(bytes, 'gzip', { limit: MAX_BYTES })), where)
159
+ const { entries } = await fetchTarball(pkg.name, pkg.version, pkg.resolution.integrity, where)
160
+ const files = filesOf(entries, where)
155
161
  const manifest = readManifest(files, pkg, where)
156
162
  checkManifest(manifest, pkg, where)
157
163
  return { files, manifest }
@@ -0,0 +1,38 @@
1
+ // Where yarn 1 fails as it links bins (package-linker.js): of each package
2
+ // in the tree, each dependency's bins are linked from its copy nearest the
3
+ // package's node_modules, as node would find it from there, and yarn fails
4
+ // where there is none. What linking does to the tree, each target made
5
+ // executable, yarn's fetcher has done already (package.js). A dependency
6
+ // with no copy of its own reference in the tree, as one deduplicated into
7
+ // another's has none, links none, as yarn has no location for it.
8
+
9
+ import { dirname, join } from '@preventive/vfs/path.js'
10
+ import { DeptreeError, quote } from '../error.js'
11
+ import { binsOf } from './package.js'
12
+
13
+ // Whether node finds the package at `loc` by its name from `dir`, a
14
+ // directory at a time up from it, as yarn's
15
+ // findNearestInstalledVersionOfPackage looks. Paths are from the
16
+ // lockfile's directory, `.` it.
17
+ function finds(name, loc, dir) {
18
+ for (;; dir = dirname(dir)) {
19
+ if (join(dir, name) === loc || join(dir, `node_modules/${name}`) === loc) return true
20
+ if (dir === '.') return false
21
+ }
22
+ }
23
+
24
+ // `placed` the flat tree, tree.js's; `patterns` resolve.js's; `fetched`
25
+ // each registry package's files, and `manifestOf` its package.json, as
26
+ // yarn has them; `locations` each reference's copies, where they really
27
+ // are, and `realOf` where a path in the tree really is.
28
+ export function checkBinLinks({ placed, patterns, fetched, manifestOf, locations, realOf }) {
29
+ for (const { loc, info } of placed) {
30
+ const binLoc = `${loc}/node_modules`
31
+ for (const pattern of info.ref.dependencies) {
32
+ const dep = patterns.get(pattern)
33
+ if (dep.kind !== 'registry' || !locations.has(dep) || binsOf(manifestOf.get(dep), fetched.get(dep)).size === 0) continue
34
+ const found = locations.get(dep).some((at) => finds(dep.name, at, binLoc) || finds(dep.name, at, realOf(binLoc)))
35
+ if (!found) throw new DeptreeError(`yarn finds no copy of ${quote(dep.name)} to link the bins of`, quote(loc))
36
+ }
37
+ }
38
+ }
@@ -0,0 +1,86 @@
1
+ // yarn 1's package-compatibility.js: a package whose os, cpu or engines
2
+ // the host does not take is left out where it is optional, and fails the
3
+ // install otherwise; so does the root project, checked as yarn checks it
4
+ // before anything is resolved. Engines are checked against the Node yarn
5
+ // runs on and yarn itself; any other engine Node reports a version of in
6
+ // process.versions — v8, uv, openssl and the rest — would be checked
7
+ // against the Node that runs yarn, which is not known here, and is
8
+ // refused. One yarn knows of no version for is passed over, as yarn
9
+ // passes over it.
10
+
11
+ import { compareVersions, major, satisfies, valid } from '@preventive/upstream/semver.js'
12
+ import { DeptreeError, quote } from '../error.js'
13
+ import { satisfiesWithPrereleases } from './peers.js'
14
+
15
+ // What Node reports in process.versions, but `node`, in any release or
16
+ // build of it from 12 on (src/node_metadata.h).
17
+ const REPORTED = new Set([
18
+ 'acorn', 'ada', 'amaro', 'ares', 'base64', 'brotli', 'cjs_module_lexer', 'cldr', 'http_parser', 'icu', 'libffi', 'lief',
19
+ 'llhttp', 'merve', 'modules', 'napi', 'nbytes', 'ncrypto', 'nghttp2', 'nghttp3', 'ngtcp2', 'openssl', 'simdjson', 'simdutf',
20
+ 'sqlite', 'tz', 'undici', 'unicode', 'uv', 'uvwasi', 'v8', 'zlib', 'zstd',
21
+ ])
22
+
23
+ // yarn's isValid: an os or cpu list of names, `!` before one to exclude.
24
+ function isValid(items, actual) {
25
+ let isNotWhitelist = true
26
+ let isBlacklist = false
27
+ for (const item of items) {
28
+ if (item[0] === '!') {
29
+ isBlacklist = true
30
+ if (actual === item.slice(1)) return false
31
+ } else {
32
+ isNotWhitelist = false
33
+ if (item === actual) return true
34
+ }
35
+ }
36
+ return isBlacklist && isNotWhitelist
37
+ }
38
+
39
+ const LOOSE = { loose: true }
40
+
41
+ // yarn's testEngine: yarn's own version taken with its prereleases, and
42
+ // Node's versions before 1.0.0 taken for its majors.
43
+ function testEngine(name, range, versions) {
44
+ const actual = versions[name]
45
+ if (!actual || !valid(actual, LOOSE)) return false
46
+ if (satisfies(actual, range, LOOSE)) return true
47
+ if (name === 'yarn' && satisfiesWithPrereleases(actual, range, true)) return true
48
+ if (name === 'node' && compareVersions(actual, '1.0.0', LOOSE) > 0) {
49
+ const of = major(actual, LOOSE)
50
+ return [`0.10.${of}`, `0.11.${of}`, `0.12.${of}`, `0.13.${of}`].some((fake) => satisfies(fake, range, LOOSE))
51
+ }
52
+ return false
53
+ }
54
+
55
+ // Why the host does not take `manifest`, or undefined where it does; its
56
+ // os and cpu not checked with ignorePlatform, and its engines not with
57
+ // ignoreEngines. A manifest's engines may be a list of `name range`
58
+ // strings, which yarn reads into a mapping first.
59
+ export function incompatibility(manifest, host, where, { ignoreEngines, ignorePlatform }) {
60
+ const { os, cpu } = manifest
61
+ let { engines } = manifest
62
+ if (!ignorePlatform && Array.isArray(os) && os.length > 0 && !isValid(os, host.os)) return `its os, ${JSON.stringify(os)}, does not take ${quote(host.os)}`
63
+ if (!ignorePlatform && Array.isArray(cpu) && cpu.length > 0 && !isValid(cpu, host.cpu)) return `its cpu, ${JSON.stringify(cpu)}, does not take ${quote(host.cpu)}`
64
+ if (ignoreEngines) return undefined
65
+ if (Array.isArray(engines)) {
66
+ const read = {}
67
+ for (const item of engines) {
68
+ if (typeof item !== 'string') continue
69
+ const [name, ...rest] = item.trim().split(/ +/gu)
70
+ read[name] = rest.join(' ')
71
+ }
72
+ engines = read
73
+ }
74
+ if (engines === null || typeof engines !== 'object') return undefined
75
+ const versions = { node: host.node, yarn: host.yarn }
76
+ for (let [name, range] of Object.entries(engines)) {
77
+ if (name === 'iojs') name = 'node'
78
+ if (typeof range !== 'string' && (Object.hasOwn(versions, name) || REPORTED.has(name))) throw new DeptreeError(`engines.${name} is not a string, which yarn fails on`, where)
79
+ if (Object.hasOwn(versions, name)) {
80
+ if (!testEngine(name, range, versions)) return `its engines.${name}, ${quote(String(range))}, does not take ${versions[name]}`
81
+ } else if (REPORTED.has(name)) {
82
+ throw new DeptreeError(`yarn checks engines.${name} against the Node it runs on, which is not known here`, where)
83
+ }
84
+ }
85
+ return undefined
86
+ }
@@ -0,0 +1,52 @@
1
+ // The globs yarn matches with minimatch's defaults, as far as the lockfile
2
+ // reader lets them through: a segment at a time, `**` as any number of
3
+ // whole segments, `*` and `?` within one, and no segment that starts with
4
+ // a dot taken by a wildcard.
5
+
6
+ import { escape } from '../matcher.js'
7
+
8
+ const compiled = new Map()
9
+
10
+ function compile(glob) {
11
+ return glob.split('/').map((segment) => {
12
+ if (segment === '**') return null
13
+ const dot = segment.startsWith('.') || !/[*?]/u.test(segment) ? '' : '(?!\\.)'
14
+ return new RegExp(`^${dot}${segment.split(/([*?])/u).map((part) => (part === '*' ? '[^/]*' : part === '?' ? '[^/]' : escape(part))).join('')}$`, 'u')
15
+ })
16
+ }
17
+
18
+ // The places in `glob` that `path` reaches, a name at a time, a `**`
19
+ // taking none or more, in time linear in both: a place is the index of the
20
+ // glob's next segment, its length where all are taken.
21
+ function placesOf(glob, path) {
22
+ if (!compiled.has(glob)) compiled.set(glob, compile(glob))
23
+ const tests = compiled.get(glob)
24
+ const close = (places) => {
25
+ for (let i = 0; i < tests.length; i++) if (places.has(i) && tests[i] === null) places.add(i + 1)
26
+ return places
27
+ }
28
+ let places = close(new Set([0]))
29
+ for (const segment of path === '' ? [] : path.split('/')) {
30
+ const next = new Set()
31
+ for (const i of places) {
32
+ if (i === tests.length) continue
33
+ if (tests[i] === null) {
34
+ if (!segment.startsWith('.')) next.add(i)
35
+ } else if (tests[i].test(segment)) next.add(i + 1)
36
+ }
37
+ places = close(next)
38
+ }
39
+ return { places, length: tests.length }
40
+ }
41
+
42
+ // Whether `glob` takes `path`.
43
+ export function matchesGlob(glob, path) {
44
+ const { places, length } = placesOf(glob, path)
45
+ return places.has(length)
46
+ }
47
+
48
+ // Whether `glob` may take a path below `dir`: some of it left to take.
49
+ export function reachesBelow(glob, dir) {
50
+ const { places, length } = placesOf(glob, dir)
51
+ return [...places].some((place) => place < length)
52
+ }