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

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 +325 -0
  8. package/npm.js +7 -0
  9. package/package.json +92 -11
  10. package/pnpm.d.ts +401 -81
  11. package/pnpm.js +4 -9
  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 +124 -42
  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 +96 -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 +202 -322
  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 +29 -73
  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 +96 -59
  49. package/src/pnpm/hoisted.js +234 -0
  50. package/src/pnpm/hook.js +26 -31
  51. package/src/pnpm/inputs.js +177 -0
  52. package/src/pnpm/install.js +123 -124
  53. package/src/pnpm/local.js +95 -40
  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 +11 -51
  59. package/src/pnpm/package.js +123 -0
  60. package/src/pnpm/packlist.js +176 -81
  61. package/src/pnpm/patches.js +18 -25
  62. package/src/pnpm/projects.js +132 -89
  63. package/src/pnpm/readers.js +122 -77
  64. package/src/pnpm/settings.js +74 -95
  65. package/src/pnpm/tree.js +216 -237
  66. package/src/pnpm/uptodate.js +16 -28
  67. package/src/pnpm/workspace.js +152 -126
  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 -131
  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,130 @@
1
+ // The project's package.json files, which npm ci reads from disk in place
2
+ // of the lockfile's entries, held to ask for exactly what those entries do.
3
+
4
+ import { join } from '@preventive/vfs/path.js'
5
+ import { DeptreeError, quote } from '../error.js'
6
+ import { own } from '../manifest.js'
7
+ import { checkRuns } from './compat.js'
8
+ import { checkDevEngines } from './dev-engines.js'
9
+
10
+ const where = (dir) => `manifests[${quote(dir)}]`
11
+
12
+ function specsOf(manifest, list, at) {
13
+ const specs = manifest[list] ?? {}
14
+ if (typeof specs !== 'object' || Array.isArray(specs) || Object.values(specs).some((spec) => typeof spec !== 'string')) {
15
+ throw new DeptreeError('expected a mapping of names to specs, which npm fails without', `${at}.${list}`)
16
+ }
17
+ return specs
18
+ }
19
+
20
+ // Node#loadDeps: a name's edge is of the last list that has it, but a
21
+ // workspace's, which none takes over.
22
+ function edgesOf(manifest, at, workspaces, legacyPeerDeps) {
23
+ const edges = new Map()
24
+ const add = (name, type, spec) => {
25
+ if (edges.get(name)?.type === 'workspace') return
26
+ edges.delete(name)
27
+ edges.set(name, { type, spec })
28
+ }
29
+ for (const [name, dir] of workspaces) add(name, 'workspace', `file:${dir}`)
30
+ const peers = Object.entries(specsOf(manifest, 'peerDependencies', at))
31
+ const meta = manifest.peerDependenciesMeta || {}
32
+ if (!legacyPeerDeps) {
33
+ for (const [name, spec] of peers) if (!own(meta, name)?.optional) add(name, 'peer', spec)
34
+ for (const [name, spec] of peers) if (own(meta, name)?.optional) add(name, 'peerOptional', spec)
35
+ }
36
+ for (const [list, type] of [['dependencies', 'prod'], ['optionalDependencies', 'optional'], ['devDependencies', 'dev']]) {
37
+ for (const [name, spec] of Object.entries(specsOf(manifest, list, at))) add(name, type, spec)
38
+ }
39
+ return edges
40
+ }
41
+
42
+ const describe = (edge) => (edge === undefined ? 'nothing' : `${edge.type} ${quote(edge.spec)}`)
43
+
44
+ function compareEdges(edges, importer, at) {
45
+ for (const name of new Set([...edges.keys(), ...Object.keys(importer.edges)])) {
46
+ const ours = edges.get(name)
47
+ const theirs = importer.edges[name]
48
+ if (ours?.type === theirs?.type && ours?.spec === theirs?.spec) continue
49
+ throw new DeptreeError(`asks for ${quote(name)} as ${describe(ours)}, and the lockfile as ${describe(theirs)}, which npm ci refuses or resolves again`, at)
50
+ }
51
+ }
52
+
53
+ // npm 10's #checkRootEdges: unless the root's edges are its lockfile lists
54
+ // to the letter (no name in two lists, no peer under legacy-peer-deps, no
55
+ // workspace asked for by name too), npm 10 works every flag out again.
56
+ export function recalculates(lists, edges) {
57
+ const { dependencies = {}, devDependencies = {}, optionalDependencies = {}, peerDependencies = {}, peerDependenciesMeta = {} } = lists
58
+ const byType = { dev: devDependencies, optional: optionalDependencies, peer: { ...peerDependencies }, peerOptional: {}, prod: { ...dependencies } }
59
+ for (const [name, meta] of Object.entries(peerDependenciesMeta)) {
60
+ if (meta?.optional && own(byType.peer, name) !== undefined) {
61
+ byType.peerOptional[name] = byType.peer[name]
62
+ delete byType.peer[name]
63
+ }
64
+ }
65
+ for (const name of Object.keys(optionalDependencies)) delete byType.prod[name]
66
+ const left = new Set([...edges].filter(([, edge]) => edge.type !== 'workspace').map(([name]) => name))
67
+ for (const [type, specs] of Object.entries(byType)) {
68
+ for (const [name, spec] of Object.entries(specs)) {
69
+ if (edges.get(name)?.type !== type || edges.get(name).spec !== spec) return true
70
+ left.delete(name)
71
+ }
72
+ }
73
+ return left.size > 0
74
+ }
75
+
76
+ // map-workspaces names a workspace by its package.json, or its folder.
77
+ function workspacesOf(manifests) {
78
+ const workspaces = new Map()
79
+ for (const [dir, manifest] of manifests) {
80
+ if (dir === '.') continue
81
+ const segments = dir.split('/')
82
+ const name = manifest.name || (segments.at(-2)?.startsWith('@') ? segments.slice(-2).join('/') : segments.at(-1))
83
+ if (workspaces.has(name)) throw new DeptreeError(`the name of the workspace ${quote(workspaces.get(name))} too, which npm fails on`, where(dir))
84
+ workspaces.set(name, dir)
85
+ }
86
+ return workspaces
87
+ }
88
+
89
+ export const rootEdgesOf = (manifests, settings) => edgesOf(manifests.get('.'), where('.'), workspacesOf(manifests), settings.legacyPeerDeps)
90
+
91
+ // A workspace's name is held to the lockfile's by the root's edge to it.
92
+ // npm links its bins after every package's, so only one into its own
93
+ // node_modules changes the tree.
94
+ function checkWorkspace(dir, manifest, importer) {
95
+ if (/[#%]/u.test(dir)) throw new DeptreeError('a workspace whose directory has a "#" or "%", which npm escapes in one place and not another, is not supported', where(dir))
96
+ if (manifest.version !== importer.version) throw new DeptreeError(`is ${quote(String(manifest.version))}, and the lockfile has ${quote(String(importer.version))}, which npm ci refuses`, `${where(dir)}.version`)
97
+ if (manifest.directories?.bin !== undefined) throw new DeptreeError('directories.bin, which npm reads otherwise across its releases, is not supported', `${where(dir)}.directories.bin`)
98
+ const { bin } = manifest
99
+ const targets = typeof bin === 'string' ? [bin] : bin !== null && typeof bin === 'object' ? Object.values(bin) : []
100
+ if (targets.some((target) => typeof target === 'string' && /^node_modules(?:\/|$)/u.test(join('/', target.replace(/\\/gu, '/')).slice(1)))) {
101
+ throw new DeptreeError('a bin in its own node_modules, which is another package\'s, is not supported', `${where(dir)}.bin`)
102
+ }
103
+ }
104
+
105
+ export function checkManifests({ lockfile, manifests, settings, host, rootEdges }) {
106
+ const root = manifests.get('.')
107
+ if (root.overrides != null && (typeof root.overrides !== 'object' || Object.keys(root.overrides).length > 0)) {
108
+ throw new DeptreeError('overrides, which change what npm asks for, are not supported', `${where('.')}.overrides`)
109
+ }
110
+ if (host.allowScripts && root.allowScripts !== undefined) throw new DeptreeError('allowScripts, which npm reads for whose bins to link, is not supported', `${where('.')}.allowScripts`)
111
+ checkDevEngines(root.devEngines, host, `${where('.')}.devEngines`)
112
+ for (const [dir, importer] of Object.entries(lockfile.importers)) {
113
+ if (dir === '.') continue
114
+ if (!importer.workspace) throw new DeptreeError('a directory linked by file:, not a workspace, is not supported', `importers[${quote(dir)}]`)
115
+ if (!manifests.has(dir)) throw new DeptreeError('a workspace of the lockfile npm does not find', where(dir))
116
+ }
117
+ for (const [dir, manifest] of manifests) {
118
+ const importer = lockfile.importers[dir]
119
+ if (importer === undefined) throw new DeptreeError('a workspace the lockfile does not have, which npm ci refuses', where(dir))
120
+ if (dir !== '.') checkWorkspace(dir, manifest, importer)
121
+ if (manifest.acceptDependencies != null || Object.values(importer.edges).some((edge) => edge.accept !== undefined)) {
122
+ throw new DeptreeError('acceptDependencies, which npm reads otherwise for devDependencies, is not supported', `${where(dir)}.acceptDependencies`)
123
+ }
124
+ compareEdges(dir === '.' ? rootEdges : edgesOf(manifest, where(dir), [], settings.legacyPeerDeps), importer, where(dir))
125
+ if (host.reuse && dir !== '.' && manifest.scripts?.prepare) throw new DeptreeError('a workspace with a prepare script, which npm 10 runs even with --ignore-scripts, is not supported', `${where(dir)}.scripts.prepare`)
126
+ // The root and workspaces are never left out; npm skips the root's engines
127
+ // where it has devEngines.
128
+ checkRuns(manifest, host, where(dir), settings.engineStrict && !(dir === '.' && manifest.devEngines))
129
+ }
130
+ }
@@ -0,0 +1,96 @@
1
+ // A tarball unpacked as pacote has tar unpack it: files alone, so no empty
2
+ // directory; modes with read and write for all, less a 0o022 umask, and no
3
+ // execute bits added, as npm reads no packument for a resolved URL. Where a
4
+ // .npmignore follows a .gitignore renamed to it, tar writes the second's
5
+ // bytes into the first's file, keeping its mode. What tar's releases read
6
+ // otherwise, or npm never packs, is refused.
7
+
8
+ import { DeptreeError, quote } from '../error.js'
9
+ import { fetchTarball, fromMirror, isModules, ownTarball, withDirs } from '../tarball.js'
10
+
11
+ const UMASK = 0o022
12
+
13
+ // npm's URL, a scope's `/` as `/`, which npm may write `%2f`.
14
+ const asNpm = (url) => fromMirror(url).replace(/^(https:\/\/registry\.npmjs\.org\/@[^/]+)%2f/iu, '$1/')
15
+
16
+ export function registryTarball({ name, version, resolution }, where) {
17
+ if (resolution === undefined) throw new DeptreeError('a package bundled in another is not supported', where)
18
+ if (resolution.type === 'git') throw new DeptreeError('a git repository is not supported', where)
19
+ if (resolution.tarball === undefined) throw new DeptreeError('a package with no resolved URL, which npm fetches by the registry\'s packument, whose bins it makes executable, is not supported', where)
20
+ return ownTarball(asNpm(resolution.tarball), name, version, resolution.integrity, where)
21
+ }
22
+
23
+ const FILES = new Set(['file', 'contiguous-file'])
24
+
25
+ // The headers that stand ahead of an entry: pax, global, long name, long link.
26
+ const EXTENDED = new Set([0x78, 0x67, 0x4c, 0x4b])
27
+ const PAX = 0x78
28
+ const BLOCK = 512
29
+ const blocks = (size) => BLOCK * Math.ceil(size / BLOCK)
30
+
31
+ // An extended header's size as the archive reader read it, which held it to
32
+ // 1 MiB: base 256, or octal digits to a NUL, a blank field 0.
33
+ function extendedSize(tar, at) {
34
+ const field = tar.subarray(at + 124, at + 136)
35
+ if (field[0] === 0x80 || field[0] === 0xff) return field.subarray(1).reduce((size, byte) => size * 256 + byte, 0)
36
+ const digits = /^ *([0-7]*)/u.exec(String.fromCodePoint(...field).split('\0')[0])[1]
37
+ return digits === '' ? 0 : Number.parseInt(digits, 8)
38
+ }
39
+
40
+ // Every tar release takes a pax size over the header's. Up to 7.5.15, as
41
+ // npm 10.9.8 and 11.16 and before bundle it, tar reads it into each header
42
+ // after the pax one up to its entry too, so a long name, a long link or a
43
+ // global header between them is read by it, and all that follows otherwise
44
+ // than later releases read it. The archive reader has checked the layout
45
+ // whole, so each header is where the sizes it took say.
46
+ function checkPaxSizes(tar, entries, where) {
47
+ if (!entries.some(({ pax }) => pax.has('size'))) return
48
+ let at = 0
49
+ for (const { storedName, data, pax } of entries) {
50
+ let afterPax = false
51
+ let between = false
52
+ for (let flag = tar[at + 156]; EXTENDED.has(flag); flag = tar[at + 156]) {
53
+ between ||= afterPax
54
+ afterPax ||= flag === PAX
55
+ at += BLOCK + blocks(extendedSize(tar, at))
56
+ }
57
+ if (between && pax.has('size')) throw new DeptreeError(`${quote(storedName)} has a pax size ahead of another extended header, which tar's releases read otherwise`, where)
58
+ at += BLOCK + blocks(data.length)
59
+ }
60
+ if (tar.length < at + 2 * BLOCK || tar.subarray(at, at + 2 * BLOCK).some((byte) => byte !== 0)) throw new Error('unreachable: no end of the archive where the archive reader found one')
61
+ }
62
+
63
+ function unpack(entries, where) {
64
+ const files = new Map()
65
+ const ignores = new Set()
66
+ let top
67
+ for (const { storedName, storedLinkname, type, mode, data, globalPax } of entries) {
68
+ const segments = storedName.replace(/(?<=.)\/$/u, '').split('/')
69
+ if (segments.length > 1024 || /[\\\0]/u.test(storedName) || segments.some((segment) => segment === '' || segment === '.' || segment === '..')) {
70
+ throw new DeptreeError(`${quote(storedName)} is a name tar reads otherwise`, where)
71
+ }
72
+ if (globalPax.size > 0) throw new DeptreeError(`${quote(storedName)} has a pax header tar's releases read otherwise`, where)
73
+ if (top !== undefined && segments[0] !== top) throw new DeptreeError('the tarball has entries under more than one directory', where)
74
+ top = segments[0]
75
+ if (!FILES.has(type)) continue
76
+ if (storedLinkname !== '') throw new DeptreeError(`${quote(storedName)} is a file with a link name, which tar's releases read otherwise`, where)
77
+ if (segments.length === 1) throw new DeptreeError(`${quote(storedName)} is a file at the top of the tarball`, where)
78
+ if (isModules(segments[1])) throw new DeptreeError(`${quote(storedName)} is in the package's own node_modules, where npm installs its dependencies, which is not supported`, where)
79
+ if ((mode & 0o7000) !== 0) throw new DeptreeError(`${quote(storedName)} has a setuid, setgid or sticky bit, which is not supported`, where)
80
+ let path = segments.slice(1).join('/')
81
+ if (segments.at(-1) === '.npmignore') ignores.add(path)
82
+ else if (segments.at(-1) === '.gitignore') {
83
+ path = path.replace(/\.gitignore$/u, '.npmignore')
84
+ if (ignores.has(path)) continue
85
+ }
86
+ files.set(path, { data, mode: files.get(path)?.mode ?? ((mode | 0o666) & ~UMASK & 0o777) })
87
+ }
88
+ return withDirs(files, where)
89
+ }
90
+
91
+ export async function fetchNpmPackage({ name, version, integrity }, where, check, fetching) {
92
+ const { bytes, tar, entries, inflated, about } = await fetchTarball(name, version, integrity, where, fetching)
93
+ await check?.(bytes, inflated, where)
94
+ checkPaxSizes(tar, entries, where)
95
+ return { ...unpack(entries, where), about }
96
+ }
@@ -0,0 +1,34 @@
1
+ // tar 7.5.19 on gives up once what it has inflated is over 1000 times what
2
+ // it has read, checked at each piece of output, so where depends on how the
3
+ // bytes arrive: a tarball is refused if any prefix inflates 900 times. Such
4
+ // a prefix is no longer than 1/900 of what all of it, or any longer prefix,
5
+ // inflates to: a bound that shrinks each time it is taken again.
6
+
7
+ import { decompress } from '@preventive/archive/compression.js'
8
+ import { DeptreeError } from '../error.js'
9
+
10
+ const RATIO = 900
11
+ const STEPS = 32
12
+
13
+ async function inflatedFrom(bytes, length) {
14
+ try {
15
+ return (await decompress(bytes.subarray(0, length), 'gzip')).length
16
+ } catch (error) {
17
+ if (error?.bytes instanceof Uint8Array && !error.limited) return error.bytes.length
18
+ throw error
19
+ }
20
+ }
21
+
22
+ export async function checkRatio(bytes, inflated, where) {
23
+ const refuse = (detail) => {
24
+ throw new DeptreeError(`the tarball ${detail}, which npm's tar may give up at`, where)
25
+ }
26
+ if (inflated >= RATIO * bytes.length) refuse(`inflates ${Math.floor(inflated / bytes.length)} times its length`)
27
+ let bound = Math.min(Math.floor(inflated / RATIO), bytes.length - 1)
28
+ for (let step = 0; bound > 0; step++) {
29
+ if (step === STEPS) refuse('inflates close to as far from some prefix')
30
+ const out = await inflatedFrom(bytes, bound)
31
+ if (out >= RATIO * bound) refuse(`inflates ${Math.floor(out / bound)} times its first ${bound} bytes`)
32
+ bound = Math.min(Math.floor(out / RATIO), bound - 1)
33
+ }
34
+ }
@@ -0,0 +1,67 @@
1
+ // The project's .npmrc. npm hands the install its settings as ini reads
2
+ // them, before validating them (`bin-links=0` links bins, "0" being
3
+ // truthy), so one that can change the tree is read only in a form with one
4
+ // reading. The rest only change where and how npm fetches, which the
5
+ // lockfile's integrities make moot, or what it prints.
6
+
7
+ import { DeptreeError, quote } from '../error.js'
8
+ import { parseNpmrc } from '../npmrc.js'
9
+
10
+ const FOLLOWED = { __proto__: null, 'legacy-peer-deps': 'legacyPeerDeps', 'engine-strict': 'engineStrict', 'bin-links': 'binLinks' }
11
+
12
+ const DEFAULTS = {
13
+ __proto__: null,
14
+ 'allow-git': ['all'],
15
+ 'allow-directory': ['all'],
16
+ 'allow-file': ['all'],
17
+ 'allow-remote': ['all'],
18
+ 'install-strategy': ['hoisted'],
19
+ 'install-links': ['false'],
20
+ force: ['false'],
21
+ 'dry-run': ['false'],
22
+ global: ['false'],
23
+ 'package-lock-only': ['false'],
24
+ usage: ['false'],
25
+ 'include-workspace-root': ['false'],
26
+ // Any other version npm fails on.
27
+ 'lockfile-version': ['1', '2', '3'],
28
+ }
29
+
30
+ // A credential not scoped to a registry fails npm ci; allow-scripts fails
31
+ // npm 11.16 on, or picks whose bins it links.
32
+ const REFUSED = new Set([
33
+ 'omit', 'include', 'production', 'dev', 'only', 'also', 'optional', 'os', 'cpu', 'libc', 'workspace', 'workspaces',
34
+ 'location', 'umask', 'prefix', 'globalconfig', 'userconfig', '_auth', '_authToken', '_authtoken', '-authtoken', 'username',
35
+ '_password', 'allow-scripts',
36
+ ])
37
+
38
+ // Pairs npm fails on, both set.
39
+ const SAVES = ['save-dev', 'save-optional', 'save-peer', 'save-prod']
40
+ const EXCLUSIVE = [
41
+ ['before', 'min-release-age'], ['expect-results', 'expect-result-count'], ['provenance', 'provenance-file'], ['prefer-online', 'prefer-offline'],
42
+ ...SAVES.flatMap((save, i) => SAVES.slice(i + 1).map((other) => [save, other])),
43
+ ]
44
+
45
+ // ini unquotes, unescapes and cuts at `;` or `#` a key as it does a value,
46
+ // and npm fills a `${VAR}` in either from the environment.
47
+ const PLAIN = /^[^"'`;#\\]*$/u
48
+ const plain = (text) => PLAIN.test(text) && !text.includes('${')
49
+
50
+ export function readSettings(text) {
51
+ const settings = { legacyPeerDeps: false, engineStrict: false, binLinks: true }
52
+ const seen = new Set()
53
+ for (const { key, value, list, line } of text === undefined ? [] : parseNpmrc(text)) {
54
+ const where = `.npmrc:${line}`
55
+ if (!plain(key)) throw new DeptreeError(`${quote(key)} is quoted, escaped, commented or taken from the environment, which is not read here`, where)
56
+ seen.add(key)
57
+ if (REFUSED.has(key)) throw new DeptreeError(`${quote(key)} is a setting not supported here: it may change what npm installs`, where)
58
+ const accepted = key in FOLLOWED ? ['true', 'false'] : DEFAULTS[key]
59
+ if (accepted === undefined) continue
60
+ if (list || !accepted.includes(value)) throw new DeptreeError(`expected ${accepted.join(' or ')} for ${quote(key)}`, where)
61
+ if (key in FOLLOWED) settings[FOLLOWED[key]] = value === 'true'
62
+ }
63
+ for (const pair of EXCLUSIVE) {
64
+ if (pair.every((key) => seen.has(key))) throw new DeptreeError(`${quote(pair[0])} and ${quote(pair[1])} are both set, which npm fails on`, '.npmrc')
65
+ }
66
+ return settings
67
+ }
@@ -0,0 +1,139 @@
1
+ // The tree `npm ci --ignore-scripts` makes, but node_modules/.bin and npm's
2
+ // node_modules/.package-lock.json.
3
+
4
+ import { parseNpmLockfile } from '@preventive/lockfile/npm.js'
5
+ import { Vfs } from '@preventive/vfs'
6
+ import { dirname, relative } from '@preventive/vfs/path.js'
7
+ import { satisfies, valid, validRange } from '@preventive/upstream/semver.js'
8
+ import { eachConcurrently } from '../concurrent.js'
9
+ import { DeptreeError, quote } from '../error.js'
10
+ import { checkNoModules, isInside, makeDirs, mount, writeFiles, writeLink } from '../mount.js'
11
+ import { fetchingOf } from '../tarball.js'
12
+ import { fixBins } from './bins.js'
13
+ import { skippedOf } from './compat.js'
14
+ import { graphOf } from './graph.js'
15
+ import { checkHost, inputsOf } from './inputs.js'
16
+ import { checkManifests, recalculates, rootEdgesOf } from './manifests.js'
17
+ import { fetchNpmPackage, registryTarball } from './package.js'
18
+ import { checkRatio } from './ratio.js'
19
+
20
+ const whereOf = (node) => `packages[${quote(node.location)}]`
21
+
22
+ function checkLinks(lockfile) {
23
+ for (const [location, target] of Object.entries(lockfile.links)) {
24
+ const where = `packages[${quote(location)}]`
25
+ const importer = lockfile.importers[target]
26
+ if (!importer?.workspace) throw new DeptreeError(`a link to ${importer === undefined ? 'a package' : 'the project'} is not supported`, where)
27
+ if (location !== `node_modules/${importer.name}`) throw new DeptreeError(`a workspace linked other than as node_modules/${importer.name} is not supported`, where)
28
+ }
29
+ }
30
+
31
+ const LISTS = { prod: 'dependencies', optional: 'optionalDependencies', dev: 'devDependencies', peer: 'peerDependencies', peerOptional: 'peerDependencies', workspace: 'workspaces' }
32
+ const WILDCARD = /(?:^|[^\w-])[*Xx]\.\d/u
33
+
34
+ // semver 7.8.4 (npm 11.17 on) reads `1.x.0` otherwise; npm 10 resolves an
35
+ // unmet optional peer again, where npm 11 takes it as it is.
36
+ function checkSpecs(lockfile, host) {
37
+ for (const [location, pkg] of [...Object.entries(lockfile.importers), ...Object.entries(lockfile.packages)]) {
38
+ for (const [name, { type, spec, accept, target }] of Object.entries(pkg.edges)) {
39
+ const where = `packages[${quote(location === '.' ? '' : location)}].${LISTS[type]}[${quote(name)}]`
40
+ const ranges = [spec, accept].filter((range) => range !== undefined)
41
+ if (ranges.some((range) => WILDCARD.test(range))) throw new DeptreeError(`${quote(spec)} has a wildcard before a number, which npm's releases read otherwise`, where)
42
+ if (!host.reuse || type !== 'peerOptional' || target === undefined) continue
43
+ const { version } = target.startsWith('link:') ? lockfile.importers[target.slice(5)] : lockfile.packages[target]
44
+ if (!ranges.some((range) => validRange(range, true) !== null && satisfies(version ?? '', range, true))) {
45
+ throw new DeptreeError(`${quote(spec)} is an optional peer the lockfile does not meet, which npm 10 resolves again`, where)
46
+ }
47
+ }
48
+ }
49
+ }
50
+
51
+ // Every URL is checked before any is fetched.
52
+ async function fetchAll(nodes, host, fetching) {
53
+ const tarballs = new Map()
54
+ for (const node of nodes) {
55
+ const tarball = registryTarball(node.pkg, whereOf(node))
56
+ const key = `${tarball.name}@${tarball.version} ${tarball.integrity}`
57
+ if (!tarballs.has(key)) tarballs.set(key, { tarball, where: whereOf(node), nodes: [] })
58
+ tarballs.get(key).nodes.push(node)
59
+ }
60
+ const fetched = new Map()
61
+ await eachConcurrently(tarballs.values(), async ({ tarball, where, nodes: copies }) => {
62
+ const pkg = { ...await fetchNpmPackage(tarball, where, host.ratio ? checkRatio : undefined, fetching), integrity: tarball.integrity }
63
+ for (const node of copies) fetched.set(node, pkg)
64
+ }, ({ where }) => where)
65
+ return { fetched, tarballs: tarballs.size }
66
+ }
67
+
68
+ // npm 10 makes every package's directory before leaving out those the host
69
+ // cannot run, and leaves the directories they were in.
70
+ function residueOf(nodes, skipped) {
71
+ const removed = [...skipped].map((node) => node.location)
72
+ const inRemoved = (dir) => removed.some((location) => dir === location || dir.startsWith(`${location}/`))
73
+ const dirs = new Set()
74
+ for (const location of removed) {
75
+ for (let dir = dirname(location); dir !== '.' && !nodes.has(dir) && !inRemoved(dir); dir = dirname(dir)) dirs.add(dir)
76
+ }
77
+ return dirs
78
+ }
79
+
80
+ function writeTree({ lockfile, kept, fetched, changed, residue }) {
81
+ const vfs = new Vfs()
82
+ const stats = { files: 0, bytes: 0, links: 0 }
83
+ for (const node of kept) {
84
+ const { files, dirs } = fetched.get(node)
85
+ const fixed = changed.get(node.location)
86
+ writeFiles(vfs, node.location, { dirs, files: fixed === undefined ? files : new Map([...files].map(([path, file]) => [path, fixed.get(path) ?? file])) }, stats)
87
+ }
88
+ // checkLinks has each a workspace's, in the project.
89
+ for (const [location, target] of Object.entries(lockfile.links)) {
90
+ if (!isInside(target)) throw new DeptreeError('links out of the project', whereOf({ location }))
91
+ writeLink(vfs, location, relative(`/${dirname(location)}`, `/${target}`))
92
+ stats.links++
93
+ }
94
+ for (const dir of residue) makeDirs(vfs, dir)
95
+ return { vfs, stats }
96
+ }
97
+
98
+ // The lockfile reader refuses what does not parse.
99
+ function rootListsOf(text) {
100
+ try {
101
+ return JSON.parse(text)?.packages?.[''] ?? {}
102
+ } catch {
103
+ return {}
104
+ }
105
+ }
106
+
107
+ export async function buildNpmTree(options) {
108
+ const { host: given, vfs: into } = options ?? {}
109
+ if (into !== undefined && !(into instanceof Vfs)) throw new TypeError('vfs must be a Vfs, or left out')
110
+ const fetching = fetchingOf(options ?? {})
111
+ const host = checkHost(given)
112
+ const folded = host.os === 'darwin'
113
+ const inputs = inputsOf(options ?? {}, folded)
114
+ // Refused before anything is fetched; mount checks again.
115
+ if (into !== undefined) checkNoModules(into, folded)
116
+ const { settings, manifests } = inputs
117
+ const rootEdges = rootEdgesOf(manifests, settings)
118
+ // npm 10 takes the lockfile's flags as written, where it can.
119
+ const recalculated = !host.reuse || recalculates(rootListsOf(inputs.lockfile), rootEdges)
120
+ const lockfile = parseNpmLockfile(inputs.lockfile, { semver: { satisfies, valid, validRange }, legacyPeerDeps: settings.legacyPeerDeps, npm: recalculated ? host.npm : undefined })
121
+ checkManifests({ lockfile, manifests, settings, host, rootEdges })
122
+ checkLinks(lockfile)
123
+ checkSpecs(lockfile, host)
124
+ const nodes = graphOf(lockfile, manifests)
125
+ const skipped = skippedOf(nodes, host, settings)
126
+ const kept = [...nodes.values()].filter((node) => node.kind === 'package' && !skipped.has(node))
127
+ const { fetched, tarballs } = await fetchAll(kept, host, fetching)
128
+ const changed = settings.binLinks ? fixBins(kept, fetched) : new Map()
129
+ const residue = host.reuse ? residueOf(nodes, skipped) : new Set()
130
+ const { vfs, stats: written } = writeTree({ lockfile, kept, fetched, changed, residue })
131
+ const packages = Object.keys(lockfile.packages).length
132
+ const stats = { packages, installed: kept.length, skipped: packages - kept.length, tarballs, ...written }
133
+ const installed = kept.map((node) => {
134
+ const { name, version, dev, optional, devOptional, peer } = node.pkg
135
+ const { integrity, about } = fetched.get(node)
136
+ return { path: node.location, name, version, integrity, ...about, dev, optional, devOptional, peer }
137
+ })
138
+ return { vfs: mount(vfs, into, folded), stats, installed }
139
+ }
@@ -0,0 +1,20 @@
1
+ // What changes the tree between the npm releases supported. `reuse` is npm
2
+ // 10's ci, building on the tree it loaded the lockfile into: lockfile flags
3
+ // as written, optional packages left out after their directories are made,
4
+ // an unmet optional peer resolved again, a workspace's prepare script run.
5
+
6
+ import { DeptreeError, quote } from '../error.js'
7
+
8
+ const SUPPORTED = [[[10, 9, 3], [10, 9, 9]], [[11, 11, 1], [11, 21, 0]]]
9
+
10
+ const compare = (a, b) => a[0] - b[0] || a[1] - b[1] || a[2] - b[2]
11
+ const show = ([from, to]) => (compare(from, to) === 0 ? from.join('.') : `${from.join('.')} to ${to.join('.')}`)
12
+
13
+ export function profileOf(npm) {
14
+ const version = /^(\d+)\.(\d+)\.(\d+)$/u.exec(npm)?.slice(1).map(Number)
15
+ if (version === undefined || !SUPPORTED.some(([from, to]) => compare(version, from) >= 0 && compare(version, to) <= 0)) {
16
+ throw new DeptreeError(`npm ${quote(npm)} is not supported: only ${SUPPORTED.map(show).join(', and ')}`, 'host.npm')
17
+ }
18
+ const since = (bound) => compare(version, bound) >= 0
19
+ return { npm, reuse: version[0] === 10, ratio: version[0] === 10 ? since([10, 9, 9]) : since([11, 18, 0]), inert: since([11, 13, 0]), allowScripts: since([11, 16, 0]) }
20
+ }
package/src/npmrc.js ADDED
@@ -0,0 +1,24 @@
1
+ // An .npmrc as the `ini` package reads it for npm and pnpm, as far as a key
2
+ // and the text after its `=` go; each settings.js refuses a value ini would
3
+ // unquote, unescape, cut at a `;` or `#`, or fill in from the environment. A
4
+ // section, which npm reads under a prefix no setting here has, is refused.
5
+
6
+ import { DeptreeError } from './error.js'
7
+
8
+ export function parseNpmrc(text) {
9
+ const settings = []
10
+ for (const [index, raw] of text.split(/\r\n|\r|\n/u).entries()) {
11
+ const line = raw.trim()
12
+ const where = `.npmrc:${index + 1}`
13
+ if (line === '' || line.startsWith('#') || line.startsWith(';')) continue
14
+ if (line.startsWith('[')) throw new DeptreeError('a section is not supported', where)
15
+ const eq = line.indexOf('=')
16
+ let key = (eq === -1 ? line : line.slice(0, eq)).trim()
17
+ const value = eq === -1 ? 'true' : line.slice(eq + 1).trim()
18
+ const list = key.length > 2 && key.endsWith('[]')
19
+ if (list) key = key.slice(0, -2)
20
+ if (key === '') throw new DeptreeError('a setting has no name', where)
21
+ settings.push({ key, value, list, line: index + 1 })
22
+ }
23
+ return settings
24
+ }