@preventive/deptree 1.0.0-alpha.1 → 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 +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 +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 +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,57 @@
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
+ function unpack(entries, where) {
26
+ const files = new Map()
27
+ const ignores = new Set()
28
+ let top
29
+ for (const { storedName, storedLinkname, type, mode, data, pax, globalPax } of entries) {
30
+ const segments = storedName.replace(/(?<=.)\/$/u, '').split('/')
31
+ if (segments.length > 1024 || /[\\\0]/u.test(storedName) || segments.some((segment) => segment === '' || segment === '.' || segment === '..')) {
32
+ throw new DeptreeError(`${quote(storedName)} is a name tar reads otherwise`, where)
33
+ }
34
+ if (globalPax.size > 0 || pax.has('size')) throw new DeptreeError(`${quote(storedName)} has a pax header tar's releases read otherwise`, where)
35
+ if (top !== undefined && segments[0] !== top) throw new DeptreeError('the tarball has entries under more than one directory', where)
36
+ top = segments[0]
37
+ if (!FILES.has(type)) continue
38
+ if (storedLinkname !== '') throw new DeptreeError(`${quote(storedName)} is a file with a link name, which tar's releases read otherwise`, where)
39
+ if (segments.length === 1) throw new DeptreeError(`${quote(storedName)} is a file at the top of the tarball`, where)
40
+ 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)
41
+ if ((mode & 0o7000) !== 0) throw new DeptreeError(`${quote(storedName)} has a setuid, setgid or sticky bit, which is not supported`, where)
42
+ let path = segments.slice(1).join('/')
43
+ if (segments.at(-1) === '.npmignore') ignores.add(path)
44
+ else if (segments.at(-1) === '.gitignore') {
45
+ path = path.replace(/\.gitignore$/u, '.npmignore')
46
+ if (ignores.has(path)) continue
47
+ }
48
+ files.set(path, { data, mode: files.get(path)?.mode ?? ((mode | 0o666) & ~UMASK & 0o777) })
49
+ }
50
+ return withDirs(files, where)
51
+ }
52
+
53
+ export async function fetchNpmPackage({ name, version, integrity }, where, check, fetching) {
54
+ const { bytes, entries, inflated, about } = await fetchTarball(name, version, integrity, where, fetching)
55
+ await check?.(bytes, inflated, where)
56
+ return { ...unpack(entries, where), about }
57
+ }
@@ -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
+ }
package/src/patch.js CHANGED
@@ -1,42 +1,40 @@
1
- // A patch applied to a package's files, as `pnpm patch-commit`
2
- // writes one: a git diff, a `diff --git a/<path> b/<path>` header for each
3
- // file, and unified hunks, a path relative to the package's directory. A
4
- // file is changed, created from /dev/null or deleted; a rename, a copy, a
5
- // change of mode and a binary patch are refused, as is anything else
6
- // between one file's hunks and the next header.
7
- //
8
- // A hunk applies where it says and nowhere else, every line of context and
9
- // every line it removes the same, byte for byte, as the file has there.
10
- // pnpm (@pnpm/patch-package) would also look up to twenty lines away and
11
- // compare lines with their trailing whitespace dropped; a patch that needs
12
- // either is refused here, so a patch applied here leaves the file as pnpm
13
- // would. So is a hunk that inserts after a line and keeps no context,
14
- // which pnpm puts a line early.
1
+ // A patch as `pnpm patch-commit` writes one: a git diff of files changed,
2
+ // created or deleted. A hunk applies where it says, its context and removed
3
+ // lines the same byte for byte. pnpm (@pnpm/patch-package) would also look
4
+ // up to twenty lines away and drop trailing whitespace, and puts a hunk that
5
+ // inserts after a line with no context a line early; a patch that needs any
6
+ // of that is refused, so one applied here leaves the file as pnpm would.
15
7
 
8
+ import { utf8fromString } from '@exodus/bytes/utf8.js'
16
9
  import { applyChangeSet, parseDiff } from '@preventive/diff'
17
10
  import { DeptreeError, quote } from './error.js'
11
+ import { UNSAFE, isInside } from './mount.js'
12
+ import { decodeUtf8 } from './project.js'
18
13
 
19
14
  const HEADER = 'diff --git a/'
20
15
  const MODE = /^(?:new|deleted) file mode (100644|100755)$/u
21
16
  const INDEX = /^index [\da-f]+\.\.[\da-f]+(?: 100644| 100755)?$/u
22
17
  const HUNK_LINE = /^(?:@@ |[ +\\-]|$)/u
23
18
 
24
- // The path a header names on both sides, or undefined where the two differ.
25
19
  function pathOf(header) {
26
20
  const rest = header.slice(HEADER.length)
27
21
  const path = rest.slice(0, (rest.length - 3) / 2)
28
22
  return rest === `${path} b/${path}` ? path : undefined
29
23
  }
30
24
 
25
+ // git quotes a path with a control character, and by default one with any
26
+ // other non-ASCII one. Of what it may leave unquoted, a backslash, a
27
+ // separator on Windows, and what reads otherwise than it is written (a line
28
+ // or paragraph separator, a bidirectional control) are refused, as the
29
+ // lockfile reader refuses them in a path.
31
30
  function checkPath(path, where) {
32
- if (path === undefined || path.startsWith('"') || path.split('/').some((segment) => segment === '' || segment === '.' || segment === '..')) {
31
+ if (path === undefined || path.startsWith('"') || UNSAFE.test(path) || !isInside(path)) {
33
32
  throw new DeptreeError('expected a header naming one relative path on both sides', where)
34
33
  }
35
34
  return path
36
35
  }
37
36
 
38
- // One file's header: what happens to the file, and the `---`/`+++` pair
39
- // naming it, which a patch without hunks may leave out.
37
+ // The `---`/`+++` pair may be left out where the file has no hunks.
40
38
  function readHeader(lines, path, where) {
41
39
  let change = 'modify'
42
40
  let mode = 0o644
@@ -57,9 +55,8 @@ function readHeader(lines, path, where) {
57
55
  return { change, mode, body: i }
58
56
  }
59
57
 
60
- // The hunks of one file, each line of them read: parseDiff passes over
61
- // what it does not read, so every line has to be one a hunk holds, and
62
- // every one of those in a hunk.
58
+ // parseDiff passes over what it does not read, so every line is checked to
59
+ // be one a hunk holds, and every one of those to be in a hunk.
63
60
  function readHunks(lines, where) {
64
61
  if (lines.length === 0) return { hunks: [], blocks: [] }
65
62
  if (!lines.every((line) => HUNK_LINE.test(line))) throw new DeptreeError('expected only hunks after the header', where)
@@ -76,8 +73,7 @@ function readHunks(lines, where) {
76
73
  export function parsePatch(text, where) {
77
74
  if (text.includes('\r')) throw new DeptreeError('a carriage return is not supported', where)
78
75
  if (!text.startsWith(HEADER)) throw new DeptreeError(`expected ${quote(HEADER)} first`, where)
79
- const sections = text.split(/\n(?=diff --git )/u)
80
- return sections.map((section) => {
76
+ return text.split(/\n(?=diff --git )/u).map((section) => {
81
77
  const lines = section.split('\n')
82
78
  if (lines.at(-1) === '') lines.pop()
83
79
  const path = checkPath(pathOf(lines[0]), `${where}: ${quote(lines[0])}`)
@@ -87,8 +83,6 @@ export function parsePatch(text, where) {
87
83
  })
88
84
  }
89
85
 
90
- // Holds each hunk to the lines it names in `text`, and hands back what
91
- // applying them makes of it.
92
86
  function applyTo(text, { hunks, blocks, where }) {
93
87
  const records = text.split(/(?<=\n)/u)
94
88
  let end = 0
@@ -103,43 +97,30 @@ function applyTo(text, { hunks, blocks, where }) {
103
97
  return applyChangeSet(text, blocks)
104
98
  }
105
99
 
106
- const decoder = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true })
107
- const encoder = new TextEncoder()
108
-
109
- function textOf(file, where) {
110
- try {
111
- return decoder.decode(file.data)
112
- } catch {
113
- throw new DeptreeError('changes a file that is not UTF-8', where)
114
- }
115
- }
116
-
117
100
  function bytesOf(text, where) {
118
101
  if (!text.isWellFormed()) throw new DeptreeError('makes a file that is not well-formed text', where)
119
- return encoder.encode(text)
102
+ return utf8fromString(text)
120
103
  }
121
104
 
122
105
  const parentsOf = (path) => path.split('/').slice(0, -1).map((_, index, names) => names.slice(0, index + 1).join('/'))
123
106
 
124
- // Applies a parsed patch to a package's files: a Map of each path in the
125
- // package to a file, `{ data, mode }`, or to `{ directory: true }` for a
126
- // directory. A changed file keeps its mode, and a deleted one leaves its
127
- // directory, empty or not, as pnpm leaves them. Hands back a new Map; the
128
- // one given is left as it is.
129
- export function applyPatch(files, patch) {
107
+ // `files` maps each path to `{ data, mode }` or `{ directory: true }`. A
108
+ // deleted file leaves its directory, empty or not, as pnpm does; a created
109
+ // one has `createdMode` where given, as pnpm 12 writes one plain.
110
+ export function applyPatch(files, patch, { createdMode } = {}) {
130
111
  const next = new Map(files)
131
112
  for (const file of patch) {
132
113
  const current = next.get(file.path)
133
114
  if (file.change === 'create') {
134
115
  const taken = current !== undefined || [...next.keys()].some((path) => path.startsWith(`${file.path}/`)) || parentsOf(file.path).some((dir) => next.get(dir)?.data !== undefined)
135
116
  if (taken) throw new DeptreeError('creates a file that is there', file.where)
136
- next.set(file.path, { data: bytesOf(applyTo('', file), file.where), mode: file.mode })
117
+ next.set(file.path, { data: bytesOf(applyTo('', file), file.where), mode: createdMode ?? file.mode })
137
118
  continue
138
119
  }
139
120
  if (current?.data === undefined) throw new DeptreeError('changes a file that is not there', file.where)
140
121
  // A deletion git writes with --irreversible-delete has no hunks, and
141
122
  // says nothing of what it deletes.
142
- const result = file.change === 'delete' && file.hunks.length === 0 ? '' : applyTo(textOf(current, file.where), file)
123
+ const result = file.change === 'delete' && file.hunks.length === 0 ? '' : applyTo(decodeUtf8(current.data, 'changes a file that is not UTF-8', file.where), file)
143
124
  if (file.change === 'delete') {
144
125
  if (result !== '') throw new DeptreeError('deletes a file it does not remove all of', file.where)
145
126
  next.delete(file.path)