@preventive/deptree 1.0.0-alpha.6 → 1.0.0-alpha.8

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.
Files changed (48) hide show
  1. package/npm.d.ts +9 -8
  2. package/package.json +11 -7
  3. package/pnpm.d.ts +66 -18
  4. package/soldeer.d.ts +74 -21
  5. package/src/hash.js +2 -6
  6. package/src/matcher.js +3 -2
  7. package/src/mount.js +22 -2
  8. package/src/npm/bins.js +2 -19
  9. package/src/npm/compat.js +11 -6
  10. package/src/npm/inputs.js +4 -9
  11. package/src/npm/manifests.js +4 -12
  12. package/src/npmrc.js +1 -2
  13. package/src/patch.js +4 -13
  14. package/src/pnpm/bins.js +129 -37
  15. package/src/pnpm/commands.js +4 -10
  16. package/src/pnpm/frozen.js +3 -6
  17. package/src/pnpm/gitignore.js +3 -1
  18. package/src/pnpm/glob.js +3 -3
  19. package/src/pnpm/hoist.js +3 -6
  20. package/src/pnpm/hoisted.js +234 -0
  21. package/src/pnpm/inputs.js +24 -34
  22. package/src/pnpm/install.js +17 -20
  23. package/src/pnpm/local.js +15 -3
  24. package/src/pnpm/minimatch.js +6 -15
  25. package/src/pnpm/nm-hoist-graph.js +299 -0
  26. package/src/pnpm/nm-hoist.js +149 -0
  27. package/src/pnpm/npm-packlist.js +7 -11
  28. package/src/pnpm/overrides.js +1 -2
  29. package/src/pnpm/package.js +6 -3
  30. package/src/pnpm/packlist.js +5 -4
  31. package/src/pnpm/readers.js +26 -29
  32. package/src/pnpm/settings.js +9 -8
  33. package/src/pnpm/tree.js +73 -30
  34. package/src/pnpm/workspace.js +2 -2
  35. package/src/project.js +22 -6
  36. package/src/soldeer/git.js +52 -0
  37. package/src/soldeer/inputs.js +4 -11
  38. package/src/soldeer/tree.js +36 -22
  39. package/src/soldeer/zip.js +4 -5
  40. package/src/tarball.js +68 -11
  41. package/src/yarn1/bins.js +1 -1
  42. package/src/yarn1/inputs.js +4 -11
  43. package/src/yarn1/package.js +61 -9
  44. package/src/yarn1/requests.js +7 -5
  45. package/src/yarn1/resolve.js +62 -13
  46. package/src/yarn1/settings.js +1 -2
  47. package/src/yarn1/tree.js +29 -9
  48. package/yarn1.d.ts +62 -29
@@ -7,6 +7,7 @@
7
7
  import { compareNames, normalize } from '@preventive/vfs/path.js'
8
8
  import { DeptreeError, quote } from '../error.js'
9
9
  import { reach, wildcard } from '../matcher.js'
10
+ import { UNSAFE, isInside } from '../mount.js'
10
11
  import { typeOf } from '../project.js'
11
12
 
12
13
  const UNSUPPORTED = /[?[\]{}()\\]/u
@@ -172,9 +173,8 @@ export function checkWorkspace(ids, packages, major = 10) {
172
173
  }
173
174
 
174
175
  // The importer keys @preventive/lockfile takes for a project.
175
- const UNSAFE = /[\p{Cc}\p{Zl}\p{Zp}\p{Bidi_Control}\\]/u
176
176
  export function checkProjectId(id, where) {
177
- if (id.split('/').some((name) => name === '' || name === '.' || name === '..' || UNSAFE.test(name)) || /^[A-Za-z]:/u.test(id)) {
177
+ if (!isInside(id) || UNSAFE.test(id) || /^[A-Za-z]:/u.test(id)) {
178
178
  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)
179
179
  }
180
180
  }
package/src/project.js CHANGED
@@ -22,6 +22,15 @@ export function typeOf(project, path, follow = true) {
22
22
  // A BOM is kept, as in text handed in, for the reader to drop as pnpm does.
23
23
  const decoder = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true })
24
24
 
25
+ // `bytes` as text, refused with `detail` where they are not UTF-8.
26
+ export function decodeUtf8(bytes, detail, where) {
27
+ try {
28
+ return decoder.decode(bytes)
29
+ } catch {
30
+ throw new DeptreeError(detail, where)
31
+ }
32
+ }
33
+
25
34
  export function readBytes(project, path) {
26
35
  const bytes = project.readFile(path)
27
36
  if (!(bytes instanceof Uint8Array)) throw new TypeError('project.readFile must give back bytes')
@@ -32,10 +41,17 @@ export function readText(project, path, where) {
32
41
  const type = typeOf(project, path)
33
42
  if (type === undefined) return undefined
34
43
  if (type !== 'file') throw new DeptreeError(`${quote(path.slice(1))} is a ${type}, not a file`, where)
35
- const bytes = readBytes(project, path)
36
- try {
37
- return decoder.decode(bytes)
38
- } catch {
39
- throw new DeptreeError(`${quote(path.slice(1))} is not UTF-8`, where)
40
- }
44
+ return decodeUtf8(readBytes(project, path), `${quote(path.slice(1))} is not UTF-8`, where)
45
+ }
46
+
47
+ // The checks each manager's checkHost and inputsOf make alike.
48
+ export function checkHostKeys(host, keys, wanted) {
49
+ if (host === null || typeof host !== 'object') throw new TypeError(`host must be an object with ${wanted}`)
50
+ for (const key of keys) if (typeof host[key] !== 'string' || host[key] === '') throw new TypeError(`host.${key} must be a non-empty string`)
51
+ }
52
+ export function checkLeftOut(values, all = 'both') {
53
+ for (const [name, value] of Object.entries(values)) if (value !== undefined) throw new TypeError(`${name} must be left out where lockfile is: ${all} are read from project`)
54
+ }
55
+ export function checkTexts(values) {
56
+ for (const [name, value] of Object.entries(values)) if (value !== undefined && typeof value !== 'string') throw new TypeError(`${name} must be a string, or left out`)
41
57
  }
@@ -0,0 +1,52 @@
1
+ // A git dependency as Soldeer 0.12 installs it, `git clone` and then `git
2
+ // checkout` of the lockfile's rev, from GitHub's tarball of that commit's
3
+ // tree instead: the files a checkout writes, without the .git it clones.
4
+
5
+ import { decompress } from '@preventive/archive/compression.js'
6
+ import { ArchiveError, unpack } from '@preventive/archive/tar.js'
7
+ import { DeptreeError, quote } from '../error.js'
8
+ import { MAX_BYTES } from '../tarball.js'
9
+ import { isGit } from './zip.js'
10
+
11
+ // A GitHub repository as git takes its URL over the protocols Soldeer has
12
+ // it allow, https and ssh, `.git` after it or not, the scheme and host in
13
+ // any case: https://github.com/<repo>, ssh://git@github.com/<repo> and
14
+ // git@github.com:<repo>. The owner and name are as GitHub takes them.
15
+ const REPO = String.raw`(?<repo>(?=[\dA-Za-z-]{1,39}\/)[\dA-Za-z](?:-?[\dA-Za-z])*\/[\w.-]{1,100}?)(?:\.git)?`
16
+ const URL_FORM = new RegExp(String.raw`^(?:(?i:https):\/\/|(?i:ssh):\/\/git@)(?i:github\.com)\/${REPO}\/?$`, 'u')
17
+ const SCP_FORM = new RegExp(String.raw`^git@(?i:github\.com):${REPO}$`, 'u')
18
+
19
+ export function githubRepoOf(url) {
20
+ const repo = (URL_FORM.exec(url) ?? SCP_FORM.exec(url))?.groups.repo
21
+ return repo === undefined || /\/\.\.?$/u.test(repo) ? undefined : repo
22
+ }
23
+
24
+ // GitHub's tarball, which upstream holds to the tree GitHub names for the
25
+ // commit, files, symlinks and the submodules it shows as empty directories
26
+ // alike. Unpacked as a checkout with umask 0o022 writes it: directories
27
+ // 0o755, files 0o644 or 0o755 by the bit git keeps, symlinks as symlinks.
28
+ export async function checkoutOf(github, repo, rev, where) {
29
+ const bytes = await github.getRepoTarball({ repo, sha: rev })
30
+ let entries
31
+ try {
32
+ entries = unpack(await decompress(bytes, 'gzip', { limit: MAX_BYTES }))
33
+ } catch (error) {
34
+ if (error instanceof ArchiveError) throw new DeptreeError(`its tarball from GitHub cannot be read: ${error.message}`, where, { cause: error })
35
+ throw error
36
+ }
37
+ const top = entries[0]?.name.split('/')[0]
38
+ const dirs = new Set()
39
+ const files = new Map()
40
+ const links = new Map()
41
+ for (const entry of entries) {
42
+ if (entry.name === top) continue
43
+ if (!entry.name.startsWith(`${top}/`)) throw new Error('unreachable: an entry outside the one top directory upstream holds the tarball to')
44
+ const path = entry.name.slice(top.length + 1)
45
+ if (path.split('/').some(isGit)) throw new DeptreeError('a path with a .git in it, which git refuses to check out', `${where}: ${quote(path)}`)
46
+ if (entry.type === 'directory') dirs.add(path)
47
+ else if (entry.type === 'symlink') links.set(path, entry.linkname)
48
+ else if (entry.type === 'file') files.set(path, { data: entry.data, mode: entry.mode & 0o100 ? 0o755 : 0o644 })
49
+ else throw new Error(`unreachable: a ${entry.type} in a tarball of a git tree`)
50
+ }
51
+ return { dirs, files, links }
52
+ }
@@ -1,13 +1,10 @@
1
1
  // What buildSoldeerTree takes, as text or read from the project's root.
2
2
 
3
3
  import { DeptreeError, quote } from '../error.js'
4
- import { checkProject, readText } from '../project.js'
4
+ import { checkHostKeys, checkLeftOut, checkProject, checkTexts, readText } from '../project.js'
5
5
 
6
6
  export function checkHost(host) {
7
- if (host === null || typeof host !== 'object') throw new TypeError('host must be an object with soldeer and os')
8
- for (const key of ['soldeer', 'os']) {
9
- if (typeof host[key] !== 'string' || host[key] === '') throw new TypeError(`host.${key} must be a non-empty string`)
10
- }
7
+ checkHostKeys(host, ['soldeer', 'os'], 'soldeer and os')
11
8
  if (host.soldeer !== '0.12.0') throw new DeptreeError(`Soldeer ${quote(host.soldeer)} is not supported: only Soldeer 0.12.0 is`, 'host.soldeer')
12
9
  if (host.os === 'win32') throw new DeptreeError('Windows is not supported: Soldeer names folders otherwise there', 'host.os')
13
10
  return { soldeer: host.soldeer, os: host.os }
@@ -20,9 +17,7 @@ export function inputsOf(options) {
20
17
  if (lockfile === undefined) {
21
18
  if (project === undefined) throw new TypeError(LOCKFILE)
22
19
  checkProject(project)
23
- for (const [name, value] of Object.entries({ foundry, soldeer })) {
24
- if (value !== undefined) throw new TypeError(`${name} must be left out where lockfile is: all are read from project`)
25
- }
20
+ checkLeftOut({ foundry, soldeer }, 'all')
26
21
  const lock = readText(project, '/soldeer.lock', 'soldeer.lock')
27
22
  if (lock === undefined) throw new DeptreeError('the project has no soldeer.lock, without which Soldeer resolves each dependency anew')
28
23
  const foundryText = readText(project, '/foundry.toml', 'foundry.toml')
@@ -30,8 +25,6 @@ export function inputsOf(options) {
30
25
  }
31
26
  if (typeof lockfile !== 'string') throw new TypeError(LOCKFILE)
32
27
  if (project !== undefined) throw new TypeError('project must be left out where lockfile is given')
33
- for (const [name, value] of Object.entries({ foundry, soldeer })) {
34
- if (value !== undefined && typeof value !== 'string') throw new TypeError(`${name} must be a string, or left out`)
35
- }
28
+ checkTexts({ foundry, soldeer })
36
29
  return { lockfile, foundry, soldeer }
37
30
  }
@@ -7,6 +7,7 @@ import { eachConcurrently } from '../concurrent.js'
7
7
  import { DeptreeError, quote } from '../error.js'
8
8
  import { fold, makeDirs, mount, writeFiles } from '../mount.js'
9
9
  import { configOf } from './config.js'
10
+ import { checkoutOf, githubRepoOf } from './git.js'
10
11
  import { checkHost, inputsOf } from './inputs.js'
11
12
  import { extractZip } from './zip.js'
12
13
 
@@ -14,6 +15,12 @@ import { extractZip } from './zip.js'
14
15
  // and version, which Soldeer's sanitize_filename leaves as they are on Unix.
15
16
  const NAME = /^(?=.{3,100}$)[@\da-z][\da-z-]*[\da-z]$/u
16
17
  const VERSION = /^(?=.{1,128}$)[\dA-Za-z][\w.+-]*$/u
18
+ // A folder sanitize_filename leaves as it is on Unix: none of the characters
19
+ // it replaces, and at most 255 bytes, past which it cuts the name short.
20
+ const encoder = new TextEncoder()
21
+ const isKept = (folder) => !/[/?<>\\:*|"\p{Cc}]/u.test(folder) && encoder.encode(folder).length <= 255
22
+
23
+ const GITHUB = 'github must be a GitHub client from createClient, which a git dependency is fetched through'
17
24
 
18
25
  function checkNoDependencies(vfs, folded) {
19
26
  for (const name of vfs.readdir('/')) {
@@ -25,51 +32,58 @@ function checkNoDependencies(vfs, folded) {
25
32
 
26
33
  const about = (name) => `dependencies[${quote(name)}]`
27
34
 
28
- function registryDependencies(lock, config, folded) {
35
+ function checkDependency({ type, name, version, git, folder }, config) {
36
+ const where = about(name)
37
+ if (type === 'private') throw new DeptreeError('a private dependency, which the registry hands out to those signed in alone, is not supported', where)
38
+ if (type === 'git') {
39
+ if (githubRepoOf(git) === undefined) throw new DeptreeError(`a git dependency from ${quote(git)}, not a GitHub repository over https or ssh, is not supported`, where)
40
+ if (!isKept(folder)) throw new DeptreeError(`its folder, ${quote(folder)}, is one Soldeer names otherwise, which is not supported`, where)
41
+ return
42
+ }
43
+ if (config.dependencies?.[name]?.url !== undefined) throw new DeptreeError('a dependency from a URL of its own, rather than the registry, is not supported', where)
44
+ if (!NAME.test(name)) throw new DeptreeError('a name the registry does not take', where)
45
+ if (!VERSION.test(version)) throw new DeptreeError(`${quote(version)} is a version the registry does not take`, where)
46
+ }
47
+
48
+ function dependenciesOf(lock, config, folded) {
29
49
  const dependencies = Object.values(lock.dependencies).map((dependency) => ({ ...dependency, folder: `${dependency.name}-${dependency.version}` }))
50
+ for (const dependency of dependencies) checkDependency(dependency, config)
30
51
  const key = (folder) => (folded ? fold(folder) : folder)
31
52
  const folders = new Set(dependencies.map(({ folder }) => key(folder)))
32
- for (const { type, name, version } of dependencies) {
33
- const where = about(name)
34
- if (type === 'git') throw new DeptreeError('a git dependency, which Soldeer clones with its history, is not supported', where)
35
- if (type === 'private') throw new DeptreeError('a private dependency, which the registry hands out to those signed in alone, is not supported', where)
36
- if (config.dependencies?.[name]?.url !== undefined) throw new DeptreeError('a dependency from a URL of its own, rather than the registry, is not supported', where)
37
- if (!NAME.test(name)) throw new DeptreeError('a name the registry does not take', where)
38
- if (!VERSION.test(version)) throw new DeptreeError(`${quote(version)} is a version the registry does not take`, where)
39
- }
40
- for (const { name, folder } of dependencies) {
41
- if (folders.has(key(`${folder}.zip`))) throw new DeptreeError(`its zip is downloaded as ${quote(`${folder}.zip`)}, a folder Soldeer installs another dependency in`, about(name))
53
+ for (const { type, name, folder } of dependencies) {
54
+ if (type === 'http' && folders.has(key(`${folder}.zip`))) throw new DeptreeError(`its zip is downloaded as ${quote(`${folder}.zip`)}, a folder Soldeer installs another dependency in`, about(name))
42
55
  }
43
56
  return dependencies
44
57
  }
45
58
 
46
- async function fetchAll(dependencies) {
59
+ async function fetchAll(dependencies, github) {
47
60
  const extracted = new Map()
48
- await eachConcurrently(dependencies, async ({ name, version, checksum, folder }) => {
49
- extracted.set(folder, await extractZip(await getZip(name, version, checksum), checksum, about(name)))
61
+ await eachConcurrently(dependencies, async ({ type, name, version, checksum, git, rev, folder }) => {
62
+ const where = about(name)
63
+ extracted.set(folder, type === 'git' ? await checkoutOf(github, githubRepoOf(git), rev, where) : await extractZip(await getZip(name, version, checksum), checksum, where))
50
64
  }, ({ name }) => about(name))
51
65
  return extracted
52
66
  }
53
67
 
54
68
  export async function buildSoldeerTree(options) {
55
- const { host: given, vfs: into } = options ?? {}
69
+ const { host: given, vfs: into, github } = options ?? {}
56
70
  if (into !== undefined && !(into instanceof Vfs)) throw new TypeError('vfs must be a Vfs, or left out')
71
+ if (github !== undefined && typeof github?.getRepoTarball !== 'function') throw new TypeError(GITHUB)
57
72
  const inputs = inputsOf(options ?? {})
58
- const host = checkHost(given)
59
- const folded = host.os === 'darwin'
73
+ const folded = checkHost(given).os === 'darwin'
60
74
  // Refused before anything is fetched; mount checks again.
61
75
  if (into !== undefined) checkNoDependencies(into, folded)
62
76
  const config = configOf(inputs)
63
- const lock = parseSoldeerLockfile(inputs.lockfile, { config })
64
- const dependencies = registryDependencies(lock, config, folded)
65
- const extracted = await fetchAll(dependencies)
77
+ const dependencies = dependenciesOf(parseSoldeerLockfile(inputs.lockfile, { config }), config, folded)
78
+ if (github === undefined && dependencies.some(({ type }) => type === 'git')) throw new TypeError(GITHUB)
79
+ const extracted = await fetchAll(dependencies, github)
66
80
  const vfs = new Vfs()
67
81
  makeDirs(vfs, 'dependencies')
68
- const stats = { dependencies: dependencies.length, files: 0, bytes: 0 }
82
+ const stats = { dependencies: dependencies.length, files: 0, bytes: 0, links: 0 }
69
83
  // In the lockfile's order, whatever order the fetches finished in.
70
84
  for (const { folder } of dependencies) {
71
85
  writeFiles(vfs, `dependencies/${folder}`, extracted.get(folder), stats)
72
86
  }
73
- const installed = dependencies.map(({ name, version, checksum, folder }) => ({ path: `dependencies/${folder}`, name, version, checksum }))
87
+ const installed = dependencies.map(({ type, name, version, checksum, git, rev, folder }) => ({ path: `dependencies/${folder}`, name, version, ...(type === 'git' ? { git, rev } : { checksum }) }))
74
88
  return { vfs: mount(vfs, into, folded, checkNoDependencies), stats, installed }
75
89
  }
@@ -7,6 +7,7 @@
7
7
  import { ArchiveError, unzip } from '@preventive/archive/zip.js'
8
8
  import { DeptreeError, quote } from '../error.js'
9
9
  import { bytesSha256Hex } from '../hash.js'
10
+ import { MAX_BYTES } from '../tarball.js'
10
11
 
11
12
  const END = 0x06054b50
12
13
  const CENTRAL = 0x02014b50
@@ -14,9 +15,6 @@ const UTF8 = 0x0800
14
15
  const S_IFLNK = 0o120000
15
16
  const [NTFS, TIMESTAMP, UNICODE_COMMENT, AES] = [0x000a, 0x5455, 0x6375, 0x9901]
16
17
 
17
- // As in ../tarball.js: the archive reader makes room for what entries declare.
18
- const MAX_BYTES = 512 * 1024 * 1024
19
-
20
18
  // As the archive reader decodes a name: a leading U+FEFF is part of it.
21
19
  const decoder = new TextDecoder('utf-8', { ignoreBOM: true })
22
20
  const encoder = new TextEncoder()
@@ -74,8 +72,9 @@ function unixMode({ system, attributes }) {
74
72
  }
75
73
 
76
74
  // What str::trim_end_matches(['.', ' ']) and eq_ignore_ascii_case make of
77
- // a component Soldeer holds to `.git`.
78
- const isGit = (component) => component.replace(/[. ]+$/u, '').replace(/[A-Z]/gu, (char) => char.toLowerCase()) === '.git'
75
+ // a component Soldeer holds to `.git`; git's verify_path refuses to check
76
+ // one out, with core.protectNTFS, on by default.
77
+ export const isGit = (component) => component.replace(/[. ]+$/u, '').replace(/[A-Z]/gu, (char) => char.toLowerCase()) === '.git'
79
78
 
80
79
  // getZip has held the zip to its checksum; it is held to it again where it
81
80
  // is unpacked.
package/src/tarball.js CHANGED
@@ -1,15 +1,17 @@
1
1
  // A registry tarball, fetched through @preventive/upstream, which checks the
2
2
  // integrity it is given, and checked again here, as that is the lockfile's.
3
3
 
4
- import { decompress } from '@preventive/archive/compression.js'
4
+ import { CompressionError, decompress } from '@preventive/archive/compression.js'
5
5
  import { unpack } from '@preventive/archive/tar.js'
6
- import { getTarball } from '@preventive/upstream/npm.js'
6
+ import { getMeta, getTarball } from '@preventive/upstream/npm.js'
7
7
  import { DeptreeError, quote } from './error.js'
8
8
  import { matchesIntegrity } from './hash.js'
9
9
  import { fold } from './mount.js'
10
+ import { decodeUtf8 } from './project.js'
10
11
 
11
- // What a tarball may unpack to, as upstream bounds what it downloads.
12
- const MAX_BYTES = 512 * 1024 * 1024
12
+ // What a tarball or a zip may unpack to, as upstream bounds what it
13
+ // downloads: the archive reader makes room for what entries declare.
14
+ export const MAX_BYTES = 512 * 1024 * 1024
13
15
  export const REGISTRY = 'https://registry.npmjs.org/'
14
16
 
15
17
  // The registry's own URL for a version's tarball, as npm and pnpm spell it.
@@ -26,13 +28,15 @@ function checkId(name, version, where) {
26
28
  if (!NAME.test(name) || !VERSION.test(version)) throw new DeptreeError(`${quote(`${name}@${version}`)} is no package the registry's URL names as it is`, where)
27
29
  }
28
30
 
29
- // The registry's own tarball, by its sha512 alone, as fetchTarball takes it.
30
- export function ownTarball(url, name, version, integrity, where) {
31
+ // The registry's own tarball, by its sha512 alone, as fetchTarball takes it;
32
+ // where `unpinned`, with none where the lockfile records none, for
33
+ // fetchTarball to take the registry's.
34
+ export function ownTarball(url, name, version, integrity, where, unpinned = false) {
31
35
  checkId(name, version, where)
32
36
  const expected = tarballUrl(name, version)
33
37
  if (url !== expected) throw new DeptreeError(`only the registry's own tarball of ${name}@${version}, ${expected}, is supported`, where)
34
38
  const sha512 = integrity?.split(' ').find((part) => part.startsWith('sha512-'))
35
- if (sha512 === undefined) throw new DeptreeError('a tarball with no sha512 integrity is not supported', where)
39
+ if (sha512 === undefined && !(unpinned && integrity === undefined)) throw new DeptreeError('a tarball with no sha512 integrity is not supported', where)
36
40
  return { name, version, integrity: sha512 }
37
41
  }
38
42
 
@@ -40,12 +44,30 @@ export function ownTarball(url, name, version, integrity, where) {
40
44
  const YARNPKG = 'https://registry.yarnpkg.com/'
41
45
  export const fromMirror = (url) => (url.startsWith(YARNPKG) ? `${REGISTRY}${url.slice(YARNPKG.length)}` : url)
42
46
 
43
- const sameBytes = (a, b) => a.length === b.length && a.every((byte, i) => byte === b[i])
44
47
  // The name of a package's own node_modules, where npm and yarn install its
45
48
  // dependencies, in any case: macOS takes `Node_Modules` for it.
46
49
  export const isModules = (name) => fold(name) === 'node_modules'
47
50
 
48
- export const sameFile = (a, b) => a.mode === b.mode && sameBytes(a.data, b.data)
51
+ export const sameFile = (a, b) => a.mode === b.mode && a.data.length === b.data.length && a.data.every((byte, i) => byte === b.data[i])
52
+
53
+ // Where a file's first line is a `#!` one ending in a CRLF within its first
54
+ // 2048 bytes, as bin-links' fixBin tells it, the index of its LF; else -1.
55
+ export function crlfShebang(data) {
56
+ if (data[0] !== 0x23 || data[1] !== 0x21) return -1
57
+ const newline = data.subarray(0, 2048).indexOf(0x0a)
58
+ return newline >= 4 && data[newline - 1] === 0x0d ? newline : -1
59
+ }
60
+
61
+ // `data` less such a line's CR; the file is rewritten as UTF-8, else refused with `detail`.
62
+ export function fixShebang(data, detail, where) {
63
+ const newline = crlfShebang(data)
64
+ if (newline === -1) return data
65
+ decodeUtf8(data, detail, where)
66
+ const copy = new Uint8Array(data.length - 1)
67
+ copy.set(data.subarray(0, newline - 1))
68
+ copy.set(data.subarray(newline), newline - 1)
69
+ return copy
70
+ }
49
71
 
50
72
  // Adds to `dirs` each one `files` are in, refusing one that is a file too.
51
73
  export function withDirs(files, where, dirs = new Set()) {
@@ -57,12 +79,47 @@ export function withDirs(files, where, dirs = new Set()) {
57
79
  return { files, dirs }
58
80
  }
59
81
 
82
+ // Old tarballs, as npm 1.0 packed them through the system's tar, may run on
83
+ // in zeros past their gzip stream, to a whole 10240-byte record. Node's
84
+ // zlib, which npm, pnpm and yarn unpack through, stops at a zero byte after
85
+ // the stream; the platform's stream refuses anything there, so the zeros are
86
+ // cut off. The stream's last four bytes are the length its last member
87
+ // inflates to, under 2^32 as MAX_BYTES is, so it ends within three bytes
88
+ // past the last that is not zero; or, where that member is empty, as zlib
89
+ // writes one, `03 00` and eight zeros, within nine. It ends at the one place
90
+ // it decompresses whole. Each place tried inflates it all again, which only
91
+ // a padded tarball pays for.
92
+ async function gunzip(bytes) {
93
+ const inflate = (end) => decompress(bytes.subarray(0, end), 'gzip', { limit: MAX_BYTES })
94
+ try {
95
+ return await inflate(bytes.length)
96
+ } catch (error) {
97
+ if (!(error instanceof CompressionError) || error.limited || bytes.at(-1) !== 0) throw error
98
+ const last = bytes.findLastIndex((byte) => byte !== 0)
99
+ for (let end = last + 1; end <= Math.min(last + 10, bytes.length - 1); end++) {
100
+ try {
101
+ return await inflate(end)
102
+ } catch {
103
+ // Not where the stream ends: the next byte may be.
104
+ }
105
+ }
106
+ throw error
107
+ }
108
+ }
109
+
110
+ // The registry's sha512 of a version, for a tarball ownTarball let through
111
+ // unpinned.
112
+ export async function registryIntegrity(name, version, where) {
113
+ checkId(name, version, where)
114
+ return (await getMeta(name, version)).dist.integrity
115
+ }
116
+
60
117
  export async function fetchTarball(name, version, integrity, where) {
61
118
  checkId(name, version, where)
62
119
  if (!/^sha512-[\d+/A-Za-z]{86}==$/u.test(integrity)) throw new DeptreeError('a tarball with no sha512 integrity is not supported', where)
63
120
  const bytes = await getTarball(name, version, { tarball: tarballUrl(name, version), integrity })
64
121
  if (!await matchesIntegrity(bytes, integrity)) throw new DeptreeError(`the tarball is not ${integrity}`, where)
65
122
  if (bytes[0] !== 0x1f || bytes[1] !== 0x8b || bytes[2] !== 0x08) throw new DeptreeError('the tarball is not gzipped', where)
66
- const tar = await decompress(bytes, 'gzip', { limit: MAX_BYTES })
67
- return { bytes, entries: unpack(tar), inflated: tar.length }
123
+ const tar = await gunzip(bytes)
124
+ return { bytes, entries: unpack(tar), inflated: tar.length, integrity }
68
125
  }
package/src/yarn1/bins.js CHANGED
@@ -20,7 +20,7 @@ export function checkBinLinks({ placed, patterns, locations, realOf }) {
20
20
  const realBinLoc = realOf(binLoc)
21
21
  for (const pattern of info.ref.dependencies) {
22
22
  const dep = patterns.get(pattern)
23
- if (dep.kind !== 'registry' || !locations.has(dep) || !dep.hasBins) continue
23
+ if (dep.kind === 'workspace' || !locations.has(dep) || !dep.hasBins) continue
24
24
  const found = locations.get(dep).some((at) => finds(dep.name, at, binLoc) || finds(dep.name, at, realBinLoc))
25
25
  if (!found) throw new DeptreeError(`yarn finds no copy of ${quote(dep.name)} to link the bins of`, quote(loc))
26
26
  }
@@ -3,7 +3,7 @@
3
3
  import { valid } from '@preventive/upstream/semver.js'
4
4
  import { DeptreeError, quote } from '../error.js'
5
5
  import { readManifest, readManifests } from '../manifest.js'
6
- import { checkProject, readText, typeOf } from '../project.js'
6
+ import { checkHostKeys, checkLeftOut, checkProject, checkTexts, readText, typeOf } from '../project.js'
7
7
  import { walkWorkspaces } from '../glob.js'
8
8
  import { globsOf } from './manifest.js'
9
9
  import { readSettings } from './settings.js'
@@ -25,10 +25,7 @@ function yarnOf(yarn, root) {
25
25
  }
26
26
 
27
27
  export function checkHost(host, root) {
28
- if (host === null || typeof host !== 'object') throw new TypeError('host must be an object with node, os and cpu, and yarn where it is not pinned')
29
- for (const key of ['node', 'os', 'cpu']) {
30
- if (typeof host[key] !== 'string' || host[key] === '') throw new TypeError(`host.${key} must be a non-empty string`)
31
- }
28
+ checkHostKeys(host, ['node', 'os', 'cpu'], 'node, os and cpu, and yarn where it is not pinned')
32
29
  if (valid(host.node) !== host.node) throw new DeptreeError(`${quote(host.node)} is not an exact version`, 'host.node')
33
30
  if (host.os === 'win32') throw new DeptreeError('Windows is not supported: yarn links bins there with shims, and workspaces with junctions', 'host.os')
34
31
  return { yarn: yarnOf(host.yarn, root), node: host.node, os: host.os, cpu: host.cpu }
@@ -68,9 +65,7 @@ export function inputsOf(options) {
68
65
  if (project !== undefined) checkProject(project)
69
66
  if (lockfile === undefined) {
70
67
  if (project === undefined) throw new TypeError(LOCKFILE)
71
- for (const [name, value] of Object.entries({ manifests, yarnrc, npmrc })) {
72
- if (value !== undefined) throw new TypeError(`${name} must be left out where lockfile is: both are read from project`)
73
- }
68
+ checkLeftOut({ manifests, yarnrc, npmrc })
74
69
  const text = readText(project, '/yarn.lock')
75
70
  if (text === undefined) throw new DeptreeError('the project has no yarn.lock, which a frozen install cannot do without')
76
71
  const read = new Map([['.', readRoot(project)]])
@@ -82,9 +77,7 @@ export function inputsOf(options) {
82
77
  }
83
78
  if (typeof lockfile !== 'string') throw new TypeError(LOCKFILE)
84
79
  if (manifests === null || typeof manifests !== 'object') throw new TypeError('manifests must map each project\'s directory to its package.json')
85
- for (const [name, value] of Object.entries({ yarnrc, npmrc })) {
86
- if (value !== undefined && typeof value !== 'string') throw new TypeError(`${name} must be a string, or left out`)
87
- }
80
+ checkTexts({ yarnrc, npmrc })
88
81
  const settings = readSettings({ yarnrc, npmrc })
89
82
  return { lockfile, manifests: readManifests(manifests), settings, project }
90
83
  }
@@ -3,12 +3,16 @@
3
3
  // than yarn holds it to: what npm packs, every entry under one directory,
4
4
  // none in its own node_modules (npm packs those only for bundled
5
5
  // dependencies), and a package.json of the lockfile's name and version.
6
+ // And a directory by `file:`, as yarn's copy fetcher installs it.
6
7
 
7
8
  import { normalize } from '@preventive/vfs/path.js'
8
9
  import { DeptreeError, quote } from '../error.js'
9
10
  import { sha1Hex } from '../hash.js'
10
11
  import { readManifest } from '../manifest.js'
11
- import { fetchTarball, fromMirror, isModules, ownTarball, sameFile, withDirs } from '../tarball.js'
12
+ import { decodeUtf8, readBytes, typeOf } from '../project.js'
13
+ import { fetchTarball, fromMirror, isModules, ownTarball, registryIntegrity, sameFile, withDirs } from '../tarball.js'
14
+ import { fixLists } from './manifest.js'
15
+ import { kindOf, splitPattern } from './resolve.js'
12
16
 
13
17
  const UMASK = 0o022
14
18
 
@@ -40,18 +44,21 @@ function entriesOf(entries, where) {
40
44
 
41
45
  const decoder = new TextDecoder('utf-8', { fatal: true })
42
46
 
43
- // `name` is the one fetched, as an `npm:` alias asks for it.
47
+ // `name` is the one fetched, as an `npm:` alias asks for it. yarn writes no
48
+ // integrity for a pattern that names the tarball's URL, but the sha1 after
49
+ // its `#`: the tarball is held to that, and to the registry's sha512.
44
50
  export function registryTarball(entry, name, where) {
45
51
  const { resolution } = entry
46
52
  if (resolution === undefined) throw new DeptreeError('a directory, by file: or link:, is not supported', where)
47
53
  const url = resolution.type === 'tarball' ? fromMirror(resolution.tarball) : resolution.tarball
48
- return ownTarball(url, name, entry.version, resolution.integrity, where)
54
+ const byUrl = entry.patterns.some((pattern) => kindOf(splitPattern(pattern).range, where) === 'tarball')
55
+ return ownTarball(url, name, entry.version, resolution.integrity, where, byUrl && resolution.sha1 !== undefined)
49
56
  }
50
57
 
51
58
  export async function fetchYarnPackage({ name, version, integrity }, where) {
52
- const { bytes, entries } = await fetchTarball(name, version, integrity, where)
53
- const sha1 = await sha1Hex(bytes)
54
- const { files, dirs } = entriesOf(entries, where)
59
+ const fetched = await fetchTarball(name, version, integrity ?? await registryIntegrity(name, version, where), where)
60
+ const sha1 = await sha1Hex(fetched.bytes)
61
+ const { files, dirs } = entriesOf(fetched.entries, where)
55
62
  const file = files.get('package.json')
56
63
  if (file === undefined) throw new DeptreeError('the tarball has no package.json', where)
57
64
  let text
@@ -62,8 +69,53 @@ export async function fetchYarnPackage({ name, version, integrity }, where) {
62
69
  }
63
70
  const manifest = readManifest(text, `${where}: package.json`)
64
71
  if (manifest.name !== name || manifest.version !== version) throw new DeptreeError(`package.json is for ${quote(`${manifest.name}@${manifest.version}`)}`, where)
65
- // As yarn's fetcher leaves the package in its cache (base-fetcher.js): each
66
- // bin's target chmod 755, and a .bin made for the links.
72
+ return { ...withBins({ files, dirs }, manifest, where), sha1, integrity: fetched.integrity }
73
+ }
74
+
75
+ // A directory by `file:`, as yarn's copy fetcher installs it: all in it, each
76
+ // file's mode as it is, but what yarn's copy passes over (tree.js); read from
77
+ // the project, as yarn reads it again at every install. Held to more than
78
+ // yarn holds it to: no link, device or node_modules of its own in it, and a
79
+ // package.json of the name, version and lists its lockfile entry has, which
80
+ // yarn reads anew, installing whatever they are.
81
+ export function readYarnDirectory(project, { name, version, entry, dir }, where) {
82
+ if (typeOf(project, `/${dir}`, false) !== 'directory') throw new DeptreeError(`${quote(dir)} is not a directory of the project`, where)
83
+ const files = new Map()
84
+ const dirs = new Set()
85
+ const walk = (at) => {
86
+ for (const base of project.readdir(`/${dir}${at && `/${at}`}`)) {
87
+ const path = at ? `${at}/${base}` : base
88
+ const { type, mode } = project.lstat(`/${dir}/${path}`)
89
+ if (at === '' && isModules(base)) throw new DeptreeError(`${quote(`${dir}/${path}`)} is its own node_modules, which yarn copies beside what it installs there, and which is not supported`, where)
90
+ if (type === 'directory') {
91
+ dirs.add(path)
92
+ walk(path)
93
+ continue
94
+ }
95
+ if (type !== 'file') throw new DeptreeError(`${quote(`${dir}/${path}`)} is a ${type}, which is not supported`, where)
96
+ if (!Number.isInteger(mode)) throw new TypeError(`project.lstat must give a file's mode, and gives ${String(mode)} for ${quote(`/${dir}/${path}`)}`)
97
+ if ((mode & ~0o777) !== 0) throw new DeptreeError(`${quote(`${dir}/${path}`)} has the mode ${mode.toString(8)}, which is not supported`, where)
98
+ files.set(path, { data: readBytes(project, `/${dir}/${path}`), mode })
99
+ }
100
+ }
101
+ walk('')
102
+ const file = files.get('package.json')
103
+ if (file === undefined) throw new DeptreeError(`${quote(dir)} has no package.json, where yarn makes one up`, where)
104
+ const manifest = readManifest(decodeUtf8(file.data, 'package.json is not UTF-8', where), `${where}: package.json`)
105
+ const why = 'which yarn reads anew, installing what it says'
106
+ if (manifest.name !== name || manifest.version !== version) throw new DeptreeError(`package.json is for ${quote(`${manifest.name}@${manifest.version}`)}, not the lockfile's ${quote(`${name}@${version}`)}, ${why}`, where)
107
+ const fixed = fixLists(manifest)
108
+ for (const kind of ['dependencies', 'optionalDependencies']) {
109
+ const listed = Object.entries(fixed[kind] ?? {}).map(([dep, range]) => `${dep}@${range}`).sort()
110
+ const locked = Object.values(entry[kind] ?? {}).sort()
111
+ if (listed.join('\n') !== locked.join('\n')) throw new DeptreeError(`package.json's ${kind} are not the lockfile's, ${why}`, where)
112
+ }
113
+ return withBins(withDirs(files, where, dirs), manifest, where)
114
+ }
115
+
116
+ // As yarn's fetcher leaves a package in its cache (base-fetcher.js): each
117
+ // bin's target chmod 755, and a .bin made for the links.
118
+ function withBins({ files, dirs }, manifest, where) {
67
119
  const bins = binsOf(manifest, { files, dirs })
68
120
  if (bins.size > 0 && files.has('.bin')) throw new DeptreeError('.bin is a file, where yarn fails to make a directory for the bins', where)
69
121
  for (const target of bins.values()) {
@@ -71,7 +123,7 @@ export async function fetchYarnPackage({ name, version, integrity }, where) {
71
123
  const script = files.get(target.replace(/\/$/u, ''))
72
124
  if (script !== undefined) script.mode = 0o755
73
125
  }
74
- return { files, dirs, manifest, sha1, hasBins: bins.size > 0 }
126
+ return { files, dirs, manifest, hasBins: bins.size > 0 }
75
127
  }
76
128
 
77
129
  // Bins as yarn's normalize-manifest reads them, targets normalized as Node's
@@ -1,9 +1,10 @@
1
1
  // What yarn 1 asks for at the top (install.js's fetchRequestFromCwd).
2
2
 
3
- import { clean, validRange } from '@preventive/upstream/semver.js'
4
- import { DeptreeError, quote } from '../error.js'
3
+ import { clean } from '@preventive/upstream/semver.js'
4
+ import { quote } from '../error.js'
5
5
  import { matchesGlob } from '../glob.js'
6
6
  import { cleanDependencies, globsOf } from './manifest.js'
7
+ import { kindOf } from './resolve.js'
7
8
 
8
9
  // yarn names the workspace aggregator at random; this stands for it, and
9
10
  // sorts where a name starting so sorts.
@@ -38,13 +39,14 @@ export function aggregatorOf(root, workspaces) {
38
39
  return { name: AGGREGATOR, dir: '.', version: '1.0.0', manifest: cleanDependencies(manifest), aggregator: true }
39
40
  }
40
41
 
41
- // The resolutions as resolution-map.js reads them. One to neither a range
42
- // nor another source, which yarn passes over, the lockfile reader refuses.
42
+ // The resolutions as resolution-map.js reads them: to a semver range, or to a
43
+ // source, as kindOf takes one. One to neither a range nor a source, which
44
+ // yarn passes over, the lockfile reader refuses.
43
45
  export function rulesOf(root) {
44
46
  const rules = Object.entries(root.resolutions ?? {}).map(([path, range]) => {
45
47
  const names = path.match(/(?:@[^/]+\/)?[^/]+/gu) ?? [path]
46
48
  const name = names.at(-1)
47
- if (validRange(range) === null) throw new DeptreeError(`a resolution to ${quote(range)}, no semver range, is not supported`, `manifests["."].resolutions[${quote(path)}]`)
49
+ kindOf(range, `manifests["."].resolutions[${quote(path)}]`)
48
50
  return { path, name, glob: names.length === 1 ? `**/${path}` : path, pattern: `${name}@${range}` }
49
51
  })
50
52
  return [...Map.groupBy(rules, ({ name }) => name).values()].flat()