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

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 (89) hide show
  1. package/LICENSE-APACHE +202 -0
  2. package/bin/compare.js +132 -0
  3. package/bin/deptree.js +211 -0
  4. package/bin/npmrc.js +21 -0
  5. package/cargo.d.ts +223 -0
  6. package/cargo.js +6 -0
  7. package/npm.d.ts +321 -0
  8. package/npm.js +7 -0
  9. package/package.json +93 -11
  10. package/pnpm.d.ts +422 -60
  11. package/pnpm.js +3 -8
  12. package/soldeer.d.ts +235 -0
  13. package/soldeer.js +6 -0
  14. package/src/cargo/crate.js +183 -0
  15. package/src/cargo/inputs.js +81 -0
  16. package/src/cargo/members.js +90 -0
  17. package/src/cargo/registry.js +65 -0
  18. package/src/cargo/tree.js +125 -0
  19. package/src/cargo/workspace.js +177 -0
  20. package/src/concurrent.js +32 -0
  21. package/src/error.js +8 -10
  22. package/src/glob.js +55 -0
  23. package/src/hash.js +51 -16
  24. package/src/manifest.js +52 -0
  25. package/src/matcher.js +60 -10
  26. package/src/mount.js +128 -39
  27. package/src/npm/bins.js +54 -0
  28. package/src/npm/compat.js +97 -0
  29. package/src/npm/dev-engines.js +52 -0
  30. package/src/npm/graph.js +68 -0
  31. package/src/npm/inputs.js +75 -0
  32. package/src/npm/manifests.js +130 -0
  33. package/src/npm/package.js +57 -0
  34. package/src/npm/ratio.js +34 -0
  35. package/src/npm/settings.js +67 -0
  36. package/src/npm/tree.js +139 -0
  37. package/src/npm/versions.js +20 -0
  38. package/src/npmrc.js +24 -0
  39. package/src/patch.js +26 -45
  40. package/src/pnpm/bins.js +207 -327
  41. package/src/pnpm/checks.js +8 -35
  42. package/src/pnpm/commands.js +230 -0
  43. package/src/pnpm/filename.js +19 -16
  44. package/src/pnpm/frozen.js +47 -81
  45. package/src/pnpm/gitignore.js +138 -0
  46. package/src/pnpm/glob.js +65 -0
  47. package/src/pnpm/graph.js +26 -34
  48. package/src/pnpm/hoist.js +97 -59
  49. package/src/pnpm/hoisted.js +234 -0
  50. package/src/pnpm/hook.js +37 -51
  51. package/src/pnpm/inputs.js +177 -0
  52. package/src/pnpm/install.js +140 -130
  53. package/src/pnpm/local.js +105 -34
  54. package/src/pnpm/minimatch.js +319 -0
  55. package/src/pnpm/nm-hoist-graph.js +299 -0
  56. package/src/pnpm/nm-hoist.js +149 -0
  57. package/src/pnpm/npm-packlist.js +217 -0
  58. package/src/pnpm/overrides.js +20 -53
  59. package/src/pnpm/package.js +123 -0
  60. package/src/pnpm/packlist.js +194 -0
  61. package/src/pnpm/patches.js +21 -28
  62. package/src/pnpm/projects.js +150 -101
  63. package/src/pnpm/readers.js +122 -77
  64. package/src/pnpm/settings.js +85 -93
  65. package/src/pnpm/tree.js +234 -188
  66. package/src/pnpm/uptodate.js +17 -29
  67. package/src/pnpm/workspace.js +210 -53
  68. package/src/project.js +56 -0
  69. package/src/soldeer/config.js +63 -0
  70. package/src/soldeer/git.js +52 -0
  71. package/src/soldeer/inputs.js +30 -0
  72. package/src/soldeer/tree.js +83 -0
  73. package/src/soldeer/zip.js +121 -0
  74. package/src/tarball.js +123 -125
  75. package/src/yarn1/bins.js +28 -0
  76. package/src/yarn1/compat.js +67 -0
  77. package/src/yarn1/hoist.js +249 -0
  78. package/src/yarn1/inputs.js +83 -0
  79. package/src/yarn1/manifest.js +64 -0
  80. package/src/yarn1/package.js +206 -0
  81. package/src/yarn1/peers.js +51 -0
  82. package/src/yarn1/requests.js +74 -0
  83. package/src/yarn1/resolve.js +289 -0
  84. package/src/yarn1/settings.js +95 -0
  85. package/src/yarn1/tree.js +219 -0
  86. package/yarn1.d.ts +368 -0
  87. package/yarn1.js +7 -0
  88. package/src/pnpm/npmrc.js +0 -31
  89. /package/{LICENSE → LICENSE-MIT} +0 -0
@@ -0,0 +1,121 @@
1
+ // A registry zip as Soldeer 0.12 extracts it (download.rs's
2
+ // extract_dependency_archive, zip crate 8.6); what the archive reader takes
3
+ // and the two would read otherwise is refused. As a 0o022 umask leaves them,
4
+ // every directory is 0o755, and a file's mode its Unix mode as the zip crate
5
+ // reads it, or 0o644 where it reads none; a symlink is a file of its target.
6
+
7
+ import { utf8fromStringLoose, utf8toStringLoose } from '@exodus/bytes/utf8.js'
8
+ import { ArchiveError, unzip } from '@preventive/archive/zip.js'
9
+ import { DeptreeError, quote } from '../error.js'
10
+ import { bytesSha256Hex } from '../hash.js'
11
+ import { MAX_BYTES } from '../tarball.js'
12
+
13
+ const END = 0x06054b50
14
+ const CENTRAL = 0x02014b50
15
+ const UTF8 = 0x0800
16
+ const S_IFLNK = 0o120000
17
+ const [NTFS, TIMESTAMP, UNICODE_COMMENT, AES] = [0x000a, 0x5455, 0x6375, 0x9901]
18
+
19
+ // As the archive reader decodes a name: a leading U+FEFF is part of it.
20
+
21
+ const ones = (byte) => [...byte.toString(2)].filter((bit) => bit === '1').length
22
+
23
+ // Why the zip crate would fail on an entry's extra fields, or undefined; an
24
+ // AES or a Unicode comment field is refused here.
25
+ function extraRefusal(view, at, length) {
26
+ for (let pos = at; pos < at + length;) {
27
+ const id = view.getUint16(pos, true)
28
+ const size = view.getUint16(pos + 2, true)
29
+ const body = pos + 4
30
+ if (id === NTFS && (size !== 32 || view.getUint16(body + 4, true) !== 1 || view.getUint16(body + 6, true) !== 24)) return 'an NTFS extra field the zip crate does not read'
31
+ if (id === TIMESTAMP && (size === 0 || (size !== 5 && size !== 1 + 4 * ones(view.getUint8(body))))) return 'an extended timestamp the zip crate does not read'
32
+ if (id === AES) return 'an AES extra field, which has the zip crate decrypt the entry'
33
+ if (id === UNICODE_COMMENT) return 'a Unicode comment extra field, which the zip crate checks'
34
+ pos = body + size
35
+ }
36
+ return undefined
37
+ }
38
+
39
+ // What the zip crate reads of each entry that unzip does not hand out. unzip
40
+ // has checked the layout whole, so each record is where it says.
41
+ function centralRecords(bytes) {
42
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)
43
+ let end = bytes.length - 22
44
+ while (view.getUint32(end, true) !== END || end + 22 + view.getUint16(end + 20, true) !== bytes.length) end--
45
+ const records = []
46
+ let at = view.getUint32(end + 16, true)
47
+ for (let i = 0; i < view.getUint16(end + 10, true); i++) {
48
+ if (view.getUint32(at, true) !== CENTRAL) throw new Error('unreachable: a central record where unzip found none')
49
+ const [nameLength, extraLength, commentLength] = [at + 28, at + 30, at + 32].map((field) => view.getUint16(field, true))
50
+ records.push({
51
+ system: view.getUint8(at + 5),
52
+ flags: view.getUint16(at + 8, true),
53
+ attributes: view.getUint32(at + 38, true),
54
+ name: bytes.subarray(at + 46, at + 46 + nameLength),
55
+ extra: extraRefusal(view, at + 46 + nameLength, extraLength),
56
+ })
57
+ at += 46 + nameLength + extraLength + commentLength
58
+ }
59
+ return records
60
+ }
61
+
62
+ // The zip crate's ZipFileData::unix_mode; system 0 is MS-DOS, and 3 Unix.
63
+ function unixMode({ system, attributes }) {
64
+ if (attributes === 0) return undefined
65
+ const upper = attributes >>> 16
66
+ if (upper !== 0) return upper
67
+ if (system === 3) return 0
68
+ if (system !== 0) return undefined
69
+ const mode = attributes & 0x10 ? 0o040775 : 0o100664
70
+ return attributes & 0x01 ? mode & ~0o222 : mode
71
+ }
72
+
73
+ // What str::trim_end_matches(['.', ' ']) and eq_ignore_ascii_case make of
74
+ // a component Soldeer holds to `.git`; git's verify_path refuses to check
75
+ // one out, with core.protectNTFS, on by default.
76
+ export const isGit = (component) => component.replace(/[. ]+$/u, '').replace(/[A-Z]/gu, (char) => char.toLowerCase()) === '.git'
77
+
78
+ // getZip has held the zip to its checksum; it is held to it again where it
79
+ // is unpacked.
80
+ export async function extractZip(bytes, checksum, where) {
81
+ if (await bytesSha256Hex(bytes) !== checksum) throw new DeptreeError(`its zip's sha256 is not ${checksum}`, where)
82
+ let entries
83
+ try {
84
+ entries = await unzip(bytes, { limit: MAX_BYTES })
85
+ } catch (error) {
86
+ if (error instanceof ArchiveError) throw new DeptreeError(`its zip cannot be read: ${error.message}`, where, { cause: error })
87
+ throw error
88
+ }
89
+ const records = centralRecords(bytes)
90
+ // The zip crate keys entries by their names' bytes, here the stored names:
91
+ // of two of one name, the later is extracted where the first was.
92
+ const last = new Map()
93
+ for (const [index, entry] of entries.entries()) {
94
+ const record = records[index]
95
+ if (utf8toStringLoose(record.name) !== entry.storedName) throw new Error('unreachable: unzip lists entries out of the central directory\'s order')
96
+ const here = `${where}: ${quote(entry.storedName)}`
97
+ if (record.extra !== undefined) throw new DeptreeError(`${record.extra}, which Soldeer fails on`, here)
98
+ if (!(record.flags & UTF8) && record.name.some((byte) => byte >= 0x80)) throw new DeptreeError('a name not flagged UTF-8, which Soldeer reads as CP437, is not supported', here)
99
+ last.set(entry.storedName, index)
100
+ }
101
+ const dirs = new Set()
102
+ const files = new Map()
103
+ for (const index of last.values()) {
104
+ const entry = entries[index]
105
+ if (entry.name === '.') continue
106
+ const components = entry.name.split('/')
107
+ if (components.some((component) => component.includes(':'))) throw new DeptreeError('a name with a ":" in it, which Soldeer fails on', `${where}: ${quote(entry.storedName)}`)
108
+ if (components.some(isGit)) continue
109
+ for (let i = 1; i < components.length; i++) dirs.add(components.slice(0, i).join('/'))
110
+ if (entry.type === 'directory') {
111
+ dirs.add(entry.name)
112
+ continue
113
+ }
114
+ const mode = unixMode(records[index])
115
+ const data = entry.type === 'symlink' ? utf8fromStringLoose(entry.linkname) : entry.data
116
+ // A file written again keeps its mode where the zip crate reads none.
117
+ const kept = mode === undefined || (mode & S_IFLNK) === S_IFLNK ? files.get(entry.name)?.mode ?? 0o644 : mode & 0o777 & ~0o022
118
+ files.set(entry.name, { data, mode: kept })
119
+ }
120
+ return { dirs, files }
121
+ }
package/src/tarball.js CHANGED
@@ -1,152 +1,150 @@
1
- // A registry package's files, from its tarball: fetched through
2
- // @preventive/upstream, which reads a cache of its own and npm's before
3
- // the registry and holds what it gets to the integrity it is given, then
4
- // held to that integrity again here, since it is the lockfile's; gunzipped
5
- // and unpacked by @preventive/archive, with every rule of a name that
6
- // holds; and read into files the way pnpm reads them out of a tarball
7
- // (@pnpm/store.cafs): the first segment of each name dropped, whatever it
8
- // is, only files kept, as ones not executable or executable by anyone.
9
- //
10
- // Here it is held to more than pnpm holds it to, to what npm packs: a
11
- // gzipped tarball, every file under one directory, no link of either kind
12
- // or device, which pnpm would pass over or refuse, and no name twice as
13
- // two different files, of which pnpm would keep the later. It has to have
14
- // a package.json, for exactly the name and version the lockfile says, and
15
- // that package.json has to agree with what the lockfile recorded of the
16
- // package's: its os, cpu and libc, whether it has bins, what it bundles.
17
- // And every dependency it asks for, read through pnpm's read-package hook
18
- // as pnpm reads it (hook.js), has to be among each of its snapshots', bundled
19
- // or optional ones aside: a lockfile that leaves one out would leave the
20
- // package to find it wherever it is hoisted, if anywhere. A registry whose
21
- // metadata says other than its tarball does is caught at the same time.
22
- //
23
- // A package is fetched and read once however many snapshots it has, one
24
- // for each set of peers it is resolved with.
25
-
26
- import { decompress } from '@preventive/archive/compression.js'
1
+ // A registry tarball, fetched through @preventive/upstream, which checks the
2
+ // integrity it is given, and checked again here, as that is the lockfile's;
3
+ // and its version's document from the registry, where asked for, for what
4
+ // it says of where the package comes from.
5
+
6
+ import { CompressionError, decompress } from '@preventive/archive/compression.js'
27
7
  import { unpack } from '@preventive/archive/tar.js'
28
- import { normalize } from '@preventive/vfs/path.js'
29
- import { getTarball } from '@preventive/upstream/npm.js'
8
+ import { getMeta, getTarball } from '@preventive/upstream/npm.js'
9
+ import { settled } from './concurrent.js'
30
10
  import { DeptreeError, quote } from './error.js'
31
- import { localOf } from './pnpm/overrides.js'
32
11
  import { matchesIntegrity } from './hash.js'
12
+ import { fold } from './mount.js'
13
+ import { decodeUtf8 } from './project.js'
33
14
 
34
- // What a tarball may unpack to, as upstream bounds what it downloads.
35
- const MAX_BYTES = 512 * 1024 * 1024
15
+ // What a tarball or a zip may unpack to, as upstream bounds what it
16
+ // downloads: the archive reader makes room for what entries declare.
17
+ export const MAX_BYTES = 512 * 1024 * 1024
36
18
  export const REGISTRY = 'https://registry.npmjs.org/'
37
19
 
38
20
  // The registry's own URL for a version's tarball, as npm and pnpm spell it.
39
21
  export const tarballUrl = (name, version) => `${REGISTRY}${name}/-/${name.split('/').at(-1)}-${version}.tgz`
40
22
 
41
- // pnpm's name for an entry: past the first `/` of the name as stored,
42
- // folded where it has a `./` in it, a `//` made one.
43
- function nameOf(stored) {
44
- const slash = stored.indexOf('/')
45
- let name = slash === -1 ? stored : stored.slice(slash + 1)
46
- if (name.includes('./')) name = normalize(`/${name}`).slice(1)
47
- return name.replaceAll('//', '/')
23
+ // A name and a version that URL holds as they are: ASCII a URL takes
24
+ // unescaped, no part of the name `.` or `..`, and nothing that would end the
25
+ // path. The lockfile reader holds both to more; the URL fetched is held to
26
+ // this whatever reached here.
27
+ const NAME = /^(?:@[\w~-][\w.~-]*\/)?[\w~-][\w.~-]*$/u
28
+ const VERSION = /^[\dA-Za-z][\dA-Za-z.+-]*$/u
29
+
30
+ function checkId(name, version, where) {
31
+ 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)
48
32
  }
49
33
 
50
- const sameFile = (a, b) => a.mode === b.mode && a.data.length === b.data.length && a.data.every((byte, i) => byte === b.data[i])
51
-
52
- // A Map of each file's path in the package to its bytes and mode.
53
- export function filesOf(entries, where) {
54
- const files = new Map()
55
- const tops = new Set()
56
- for (const entry of entries) {
57
- if (entry.type === 'directory') continue
58
- if (entry.type !== 'file') throw new DeptreeError(`${quote(entry.name)} is a ${entry.type}, which is not supported`, where)
59
- tops.add(entry.storedName.slice(0, Math.max(entry.storedName.indexOf('/'), 0)))
60
- if (tops.size > 1 || tops.has('')) throw new DeptreeError('the tarball has files under more than one directory, or at its top', where)
61
- const name = nameOf(entry.storedName)
62
- if (name === '' || name.split('/').some((segment) => segment === '' || segment === '.' || segment === '..')) {
63
- throw new DeptreeError(`${quote(entry.storedName)} names no file in the package`, where)
64
- }
65
- const file = { data: entry.data, mode: (entry.mode & 0o111) === 0 ? 0o644 : 0o755 }
66
- const earlier = files.get(name)
67
- if (earlier !== undefined && !sameFile(earlier, file)) throw new DeptreeError(`${quote(name)} is in the tarball twice`, where)
68
- files.set(name, file)
69
- }
70
- return files
34
+ // The registry's own tarball, by its sha512 alone, as fetchTarball takes it;
35
+ // where `unpinned`, with none where the lockfile records none, for
36
+ // fetchTarball to take the registry's.
37
+ export function ownTarball(url, name, version, integrity, where, unpinned = false) {
38
+ checkId(name, version, where)
39
+ const expected = tarballUrl(name, version)
40
+ if (url !== expected) throw new DeptreeError(`only the registry's own tarball of ${name}@${version}, ${expected}, is supported`, where)
41
+ const sha512 = integrity?.split(' ').find((part) => part.startsWith('sha512-'))
42
+ if (sha512 === undefined && !(unpinned && integrity === undefined)) throw new DeptreeError('a tarball with no sha512 integrity is not supported', where)
43
+ return { name, version, integrity: sha512 }
71
44
  }
72
45
 
73
- const decoder = new TextDecoder('utf-8', { fatal: true })
74
- const same = (a, b) => JSON.stringify(a) === JSON.stringify(b)
75
- const names = (value) => Object.keys(value ?? {})
76
-
77
- // Whether a package.json has bins, as the lockfile's hasBin records it:
78
- // by a `bin` that names any, or with none, by a directories.bin. Where
79
- // `bin` is there and names none, and there is a directories.bin, pnpm
80
- // resolves it as having none and pnpm 11 rewrites a snapshot as having
81
- // some, so that is undefined: bins are linked as the lockfile has it.
82
- function hasBin({ bin, directories }) {
83
- if (bin === undefined || bin === null) return Boolean(directories?.bin)
84
- if (bin && Object.keys(bin).length > 0) return true
85
- return directories?.bin ? undefined : false
46
+ // yarn's mirror of npm's registry serves the same tarballs at the same paths.
47
+ const YARNPKG = 'https://registry.yarnpkg.com/'
48
+ export const fromMirror = (url) => (url.startsWith(YARNPKG) ? `${REGISTRY}${url.slice(YARNPKG.length)}` : url)
49
+
50
+ // The name of a package's own node_modules, where npm and yarn install its
51
+ // dependencies, in any case: macOS takes `Node_Modules` for it.
52
+ export const isModules = (name) => fold(name) === 'node_modules'
53
+
54
+ export const sameFile = (a, b) => a.mode === b.mode && a.data.length === b.data.length && a.data.every((byte, i) => byte === b.data[i])
55
+
56
+ // Where a file's first line is a `#!` one ending in a CRLF within its first
57
+ // 2048 bytes, as bin-links' fixBin tells it, the index of its LF; else -1.
58
+ export function crlfShebang(data) {
59
+ if (data[0] !== 0x23 || data[1] !== 0x21) return -1
60
+ const newline = data.subarray(0, 2048).indexOf(0x0a)
61
+ return newline >= 4 && data[newline - 1] === 0x0d ? newline : -1
86
62
  }
87
63
 
88
- function readManifest(files, pkg, where) {
89
- const file = files.get('package.json')
90
- if (file === undefined) throw new DeptreeError('the tarball has no package.json', where)
91
- let manifest
92
- try {
93
- manifest = JSON.parse(decoder.decode(file.data))
94
- } catch {
95
- throw new DeptreeError('package.json is not JSON', where)
96
- }
97
- if (manifest === null || typeof manifest !== 'object' || Array.isArray(manifest)) throw new DeptreeError('package.json is not an object', where)
98
- if (manifest.name !== pkg.name || manifest.version !== pkg.version) throw new DeptreeError(`package.json is for ${quote(`${manifest.name}@${manifest.version}`)}`, where)
99
- return manifest
64
+ // `data` less such a line's CR; the file is rewritten as UTF-8, else refused with `detail`.
65
+ export function fixShebang(data, detail, where) {
66
+ const newline = crlfShebang(data)
67
+ if (newline === -1) return data
68
+ decodeUtf8(data, detail, where)
69
+ const copy = new Uint8Array(data.length - 1)
70
+ copy.set(data.subarray(0, newline - 1))
71
+ copy.set(data.subarray(newline), newline - 1)
72
+ return copy
100
73
  }
101
74
 
102
- // What the lockfile recorded of the package against the package.json.
103
- function checkManifest(manifest, pkg, where) {
104
- for (const field of ['os', 'cpu', 'libc']) {
105
- if (!same(manifest[field], pkg[field])) throw new DeptreeError(`package.json's ${field} is not the lockfile's`, where)
75
+ // Adds to `dirs` each one `files` are in, refusing one that is a file too.
76
+ export function withDirs(files, where, dirs = new Set()) {
77
+ for (const path of files.keys()) {
78
+ const segments = path.split('/')
79
+ for (let i = 1; i < segments.length; i++) dirs.add(segments.slice(0, i).join('/'))
106
80
  }
107
- const has = hasBin(manifest)
108
- if (has !== undefined && has !== pkg.hasBin) throw new DeptreeError(`package.json ${pkg.hasBin ? 'has no bins, and the lockfile says it has' : 'has bins, and the lockfile says it has none'}`, where)
109
- if (!same(bundledOf(manifest), pkg.bundledDependencies)) throw new DeptreeError('package.json bundles other than the lockfile says', where)
81
+ for (const dir of dirs) if (files.has(dir)) throw new DeptreeError(`${quote(dir)} is both a file and a directory in the tarball`, where)
82
+ return { files, dirs }
110
83
  }
111
84
 
112
- const bundledOf = (manifest) => manifest.bundleDependencies ?? manifest.bundledDependencies
113
-
114
- // A snapshot's dependencies against the package.json of its package, as
115
- // fetchPackage read it and `read` as hook.js's hook has it. One the
116
- // package.json, as overridden, names a directory for is linked there,
117
- // from the lockfile's directory, as pnpm writes it.
118
- export function checkDependencies(manifest, read, pkg, where) {
119
- const bundled = bundledOf(manifest)
120
- const given = new Set([...names(pkg.dependencies), ...names(pkg.optionalDependencies)])
121
- for (const name of [...names(read.dependencies), ...names(read.optionalDependencies)]) {
122
- if (bundled === true || (Array.isArray(bundled) && bundled.includes(name)) || given.has(name)) continue
123
- throw new DeptreeError(`package.json asks for ${quote(name)}, which the lockfile does not give it`, where)
124
- }
125
- for (const [name, spec] of [...Object.entries(read.dependencies ?? {}), ...Object.entries(read.optionalDependencies ?? {})]) {
126
- const target = pkg.dependencies[name] ?? pkg.optionalDependencies[name]
127
- if (target === undefined) continue
128
- const local = localOf(spec, `${where}: package.json`)
129
- if (local === undefined || target === `link:${local.dir}`) continue
130
- throw new DeptreeError(`the lockfile gives it ${quote(name)} as ${quote(target)}, and its package.json, overridden, names ${quote(local.dir)}`, where)
85
+ // Old tarballs, as npm 1.0 packed them through the system's tar, may run on
86
+ // in zeros past their gzip stream, to a whole 10240-byte record. Node's
87
+ // zlib, which npm, pnpm and yarn unpack through, stops at a zero byte after
88
+ // the stream; the platform's stream refuses anything there, so the zeros are
89
+ // cut off. The stream's last four bytes are the length its last member
90
+ // inflates to, under 2^32 as MAX_BYTES is, so it ends within three bytes
91
+ // past the last that is not zero; or, where that member is empty, as zlib
92
+ // writes one, `03 00` and eight zeros, within nine. It ends at the one place
93
+ // it decompresses whole. Each place tried inflates it all again, which only
94
+ // a padded tarball pays for.
95
+ async function gunzip(bytes) {
96
+ const inflate = (end) => decompress(bytes.subarray(0, end), 'gzip', { limit: MAX_BYTES })
97
+ try {
98
+ return await inflate(bytes.length)
99
+ } catch (error) {
100
+ if (!(error instanceof CompressionError) || error.limited || bytes.at(-1) !== 0) throw error
101
+ const last = bytes.findLastIndex((byte) => byte !== 0)
102
+ for (let end = last + 1; end <= Math.min(last + 10, bytes.length - 1); end++) {
103
+ try {
104
+ return await inflate(end)
105
+ } catch {
106
+ // Not where the stream ends: the next byte may be.
107
+ }
108
+ }
109
+ throw error
131
110
  }
132
- // A peer resolved is filed as optional where it is optional; pnpm's
133
- // compatibility database adds peers to a few packages, which the
134
- // lockfile records among their peers and the package.json does not.
135
- const optional = new Set([...names(read.optionalDependencies), ...names(manifest.peerDependencies), ...names(manifest.peerDependenciesMeta), ...names(pkg.peerDependencies), ...names(pkg.peerDependenciesMeta)])
136
- for (const name of names(pkg.optionalDependencies)) {
137
- if (!optional.has(name)) throw new DeptreeError(`the lockfile gives it ${quote(name)} as optional, which its package.json does not`, where)
111
+ }
112
+
113
+ // What a version document says of where a package comes from, each
114
+ // undefined where it says nothing: `commit` is its gitHead.
115
+ const aboutOf = ({ gitHead, repository, homepage, bugs }) => ({ commit: gitHead, repository, homepage, bugs })
116
+ export const NO_ABOUT = Object.freeze(aboutOf({}))
117
+
118
+ // What a tree's options say of what it fetches from npm's registry:
119
+ // `metadata`, true unless given false, and `cache`, as upstream's
120
+ // CacheOptions take it, which keeps each version's document and tarball.
121
+ export function fetchingOf({ metadata = true, cache }) {
122
+ if (typeof metadata !== 'boolean') throw new TypeError('metadata must be a boolean, or left out')
123
+ if (cache !== undefined && cache !== false && (typeof cache?.read !== 'function' || typeof cache?.write !== 'function')) {
124
+ throw new TypeError('cache must be false, or a store with read and write, or left out')
138
125
  }
126
+ return { metadata, cache }
139
127
  }
140
128
 
141
- // A package's files, and its package.json as parsed; the package has to be
142
- // from the registry.
143
- export async function fetchPackage(pkg, where) {
144
- const { integrity } = pkg.resolution
145
- const bytes = await getTarball(pkg.name, pkg.version, { tarball: tarballUrl(pkg.name, pkg.version), integrity })
129
+ // Kept as `cache` says. Without a `given` integrity, as ownTarball lets one
130
+ // through unpinned, the registry's is taken from the version document, which
131
+ // getMeta holds to the registry's own tarball, and `about` is what that
132
+ // says, whatever `metadata` is. Else, with `metadata`, the document is asked
133
+ // for beside the tarball, given the dist the tarball is fetched by, which
134
+ // getMeta holds the document's to as text, the registry's being the one a
135
+ // lockfile copies, so nothing is hashed again. Else NO_ABOUT.
136
+ export async function fetchTarball(name, version, given, where, { metadata, cache }) {
137
+ checkId(name, version, where)
138
+ const meta = given === undefined ? await getMeta(name, version, { cache }) : undefined
139
+ const integrity = given ?? meta.dist.integrity
140
+ if (!/^sha512-[\d+/A-Za-z]{86}==$/u.test(integrity)) throw new DeptreeError('a tarball with no sha512 integrity is not supported', where)
141
+ const dist = { tarball: tarballUrl(name, version), integrity }
142
+ let about = NO_ABOUT
143
+ if (meta !== undefined) about = aboutOf(meta)
144
+ else if (metadata) about = getMeta(name, version, { dist, cache }).then(aboutOf)
145
+ const [bytes, said] = await settled([getTarball(name, version, dist, { cache }), about])
146
146
  if (!await matchesIntegrity(bytes, integrity)) throw new DeptreeError(`the tarball is not ${integrity}`, where)
147
147
  if (bytes[0] !== 0x1f || bytes[1] !== 0x8b || bytes[2] !== 0x08) throw new DeptreeError('the tarball is not gzipped', where)
148
- const files = filesOf(unpack(await decompress(bytes, 'gzip', { limit: MAX_BYTES })), where)
149
- const manifest = readManifest(files, pkg, where)
150
- checkManifest(manifest, pkg, where)
151
- return { files, manifest }
148
+ const tar = await gunzip(bytes)
149
+ return { bytes, entries: unpack(tar), inflated: tar.length, integrity, about: said }
152
150
  }
@@ -0,0 +1,28 @@
1
+ // Where yarn 1 fails as it links bins (package-linker.js). The one change
2
+ // linking makes to the tree, each target made executable, package.js has
3
+ // made. A dependency deduplicated into another's reference links no bins.
4
+
5
+ import { dirname, join } from '@preventive/vfs/path.js'
6
+ import { DeptreeError, quote } from '../error.js'
7
+
8
+ // As yarn's findNearestInstalledVersionOfPackage looks; paths are from the
9
+ // lockfile's directory, `.`.
10
+ function finds(name, loc, dir) {
11
+ for (;; dir = dirname(dir)) {
12
+ if (join(dir, name) === loc || join(dir, `node_modules/${name}`) === loc) return true
13
+ if (dir === '.') return false
14
+ }
15
+ }
16
+
17
+ export function checkBinLinks({ placed, patterns, locations, realOf }) {
18
+ for (const { loc, info } of placed) {
19
+ const binLoc = `${loc}/node_modules`
20
+ const realBinLoc = realOf(binLoc)
21
+ for (const pattern of info.ref.dependencies) {
22
+ const dep = patterns.get(pattern)
23
+ if (dep.kind === 'workspace' || !locations.has(dep) || !dep.hasBins) continue
24
+ const found = locations.get(dep).some((at) => finds(dep.name, at, binLoc) || finds(dep.name, at, realBinLoc))
25
+ if (!found) throw new DeptreeError(`yarn finds no copy of ${quote(dep.name)} to link the bins of`, quote(loc))
26
+ }
27
+ }
28
+ }
@@ -0,0 +1,67 @@
1
+ // yarn 1's package-compatibility.js, engines checked against host.node and
2
+ // host.yarn; one yarn knows no version of is passed over, as yarn does.
3
+
4
+ import { compareVersions, major, satisfies, valid } from '@preventive/upstream/semver.js'
5
+ import { DeptreeError, quote } from '../error.js'
6
+ import { satisfiesWithPrereleases } from './peers.js'
7
+
8
+ // What Node reports in process.versions, but `node`, in any release or
9
+ // build of it from 12 on (src/node_metadata.h).
10
+ const REPORTED = new Set([
11
+ 'acorn', 'ada', 'amaro', 'ares', 'base64', 'brotli', 'cjs_module_lexer', 'cldr', 'http_parser', 'icu', 'libffi', 'lief',
12
+ 'llhttp', 'merve', 'modules', 'napi', 'nbytes', 'ncrypto', 'nghttp2', 'nghttp3', 'ngtcp2', 'openssl', 'simdjson', 'simdutf',
13
+ 'sqlite', 'tz', 'undici', 'unicode', 'uv', 'uvwasi', 'v8', 'zlib', 'zstd',
14
+ ])
15
+
16
+ // yarn's isValid: an os or cpu list of names, `!` before one to exclude.
17
+ function isValid(items, actual) {
18
+ let isNotWhitelist = true
19
+ let isBlacklist = false
20
+ for (const item of items) {
21
+ if (item[0] === '!') {
22
+ isBlacklist = true
23
+ if (actual === item.slice(1)) return false
24
+ } else {
25
+ isNotWhitelist = false
26
+ if (item === actual) return true
27
+ }
28
+ }
29
+ return isBlacklist && isNotWhitelist
30
+ }
31
+
32
+ const LOOSE = { loose: true }
33
+
34
+ // yarn's testEngine: yarn's own version taken with its prereleases, and
35
+ // Node's versions before 1.0.0 taken for its majors.
36
+ function testEngine(name, range, versions) {
37
+ const actual = versions[name]
38
+ if (!actual || !valid(actual, LOOSE)) return false
39
+ if (satisfies(actual, range, LOOSE)) return true
40
+ if (name === 'yarn' && satisfiesWithPrereleases(actual, range, true)) return true
41
+ if (name === 'node' && compareVersions(actual, '1.0.0', LOOSE) > 0) {
42
+ const of = major(actual, LOOSE)
43
+ return [`0.10.${of}`, `0.11.${of}`, `0.12.${of}`, `0.13.${of}`].some((fake) => satisfies(fake, range, LOOSE))
44
+ }
45
+ return false
46
+ }
47
+
48
+ // engines may be a list of `name range` strings, which yarn reads as a map.
49
+ export function incompatibility(manifest, host, where, { ignoreEngines, ignorePlatform }) {
50
+ const { os, cpu } = manifest
51
+ let { engines } = manifest
52
+ if (!ignorePlatform && Array.isArray(os) && os.length > 0 && !isValid(os, host.os)) return `its os, ${JSON.stringify(os)}, does not take ${quote(host.os)}`
53
+ if (!ignorePlatform && Array.isArray(cpu) && cpu.length > 0 && !isValid(cpu, host.cpu)) return `its cpu, ${JSON.stringify(cpu)}, does not take ${quote(host.cpu)}`
54
+ if (ignoreEngines) return undefined
55
+ if (Array.isArray(engines)) engines = Object.fromEntries(engines.filter((item) => typeof item === 'string').map((item) => item.trim().split(/ +/gu)).map(([name, ...rest]) => [name, rest.join(' ')]))
56
+ if (engines === null || typeof engines !== 'object') return undefined
57
+ const versions = { node: host.node, yarn: host.yarn }
58
+ for (let [name, range] of Object.entries(engines)) {
59
+ if (name === 'iojs') name = 'node'
60
+ const known = Object.hasOwn(versions, name)
61
+ if (!known && !REPORTED.has(name)) continue
62
+ if (typeof range !== 'string') throw new DeptreeError(`engines.${name} is not a string, which yarn fails on`, where)
63
+ if (!known) throw new DeptreeError(`yarn checks engines.${name} against the Node it runs on, which is not known here`, where)
64
+ if (!testEngine(name, range, versions)) return `its engines.${name}, ${quote(range)}, does not take ${versions[name]}`
65
+ }
66
+ return undefined
67
+ }