@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,125 @@
1
+ // The vendor directory `cargo vendor` makes from a Cargo.lock.
2
+
3
+ import { linkCargo, parseCargoConfig, parseCargoLock, parseCargoManifest, readCargoVendor } from '@preventive/lockfile/cargo.js'
4
+ import { parseToml } from '@preventive/lockfile/toml.js'
5
+ import { Vfs } from '@preventive/vfs'
6
+ import { DeptreeError, quote } from '../error.js'
7
+ import { own } from '../manifest.js'
8
+ import { checkNoDir, mount, writeFiles } from '../mount.js'
9
+ import { decodeUtf8 } from '../project.js'
10
+ import { checkHost, inputsOf } from './inputs.js'
11
+ import { about, fetchCrates, vendoredPackages } from './registry.js'
12
+ import { fileOf, findWorkspace, parseAs } from './workspace.js'
13
+
14
+ const checkNoVendor = checkNoDir('vendor', 'a vendor directory')
15
+
16
+ // Of the config, [patch] is read, as cargo resolves with it; `paths`, which
17
+ // overrides where packages come from, and `include`, which reads more
18
+ // files, are refused; the rest bears on no package vendored.
19
+ function configOf({ text, file }) {
20
+ if (text === undefined) return { patch: parseCargoConfig([]).patch, file }
21
+ const doc = parseAs(file, () => parseToml(text))
22
+ for (const key of ['paths', 'include']) if (doc[key] !== undefined) throw new DeptreeError('not supported', `${file}: ${key}`)
23
+ return { patch: parseAs(file, () => parseCargoConfig([text])).patch, file }
24
+ }
25
+
26
+ // Each path package by the key the lockfile gives it, `name version`: every
27
+ // one of the lockfile's has to be one cargo reads, and every member there.
28
+ function pathKeys(lock, packages) {
29
+ const keys = new Map()
30
+ const dirs = new Map()
31
+ for (const [dir, { manifest, member }] of packages) {
32
+ if (manifest.package === undefined) continue
33
+ const key = `${manifest.package.name} ${manifest.package.version}`
34
+ if (dirs.has(key)) throw new DeptreeError(`it and ${quote(fileOf(dirs.get(key)))} are both ${quote(key)}, which the lockfile names one package`, fileOf(dir))
35
+ if (member && lock.packages[key] === undefined) throw new DeptreeError(`the lockfile has no member ${quote(key)}: is it out of date?`, fileOf(dir))
36
+ keys.set(dir, key)
37
+ dirs.set(key, dir)
38
+ }
39
+ for (const [key, pkg] of Object.entries(lock.packages)) {
40
+ if (pkg.source === undefined && !dirs.has(key)) throw new DeptreeError('a path package that no manifest cargo reads here is: is the lockfile out of date?', about(key))
41
+ }
42
+ return keys
43
+ }
44
+
45
+ // linkCargo ties a path dependency to a path package by name and version;
46
+ // it has to be the one in the directory the path leads to.
47
+ function checkPaths(graph, packages, keys) {
48
+ for (const [dir, { links }] of packages) {
49
+ const linked = graph.packages[keys.get(dir)]
50
+ if (linked === undefined) continue
51
+ for (const { index, dir: to, where } of links) {
52
+ const { resolved } = linked.dependencies[index]
53
+ if (resolved !== undefined && resolved !== keys.get(to)) throw new DeptreeError(`the lockfile resolves it to ${quote(resolved)}, not ${quote(keys.get(to))}, which its path leads to`, where)
54
+ }
55
+ }
56
+ }
57
+
58
+ // `links` are the repository and homepage the Cargo.toml cargo packed gives
59
+ // in [package], or [project] as cargo reads it too: strings, as
60
+ // parseCargoManifest holds them to, or undefined.
61
+ function manifestOf(crate, vendored) {
62
+ const where = `${about(crate.key)}: Cargo.toml`
63
+ const file = vendored.files.get('Cargo.toml')
64
+ if (file === undefined) throw new DeptreeError('its .crate has no Cargo.toml', about(crate.key))
65
+ const text = decodeUtf8(file.data, 'not UTF-8, which cargo fails on', where)
66
+ const manifest = parseAs(where, () => parseCargoManifest(text))
67
+ const doc = parseToml(text)
68
+ const pkg = own(doc, 'package') ?? own(doc, 'project')
69
+ return { text, manifest, links: { repository: own(pkg, 'repository'), homepage: own(pkg, 'homepage') } }
70
+ }
71
+
72
+ // The lockfile laid over every manifest, as linkCargo holds it to them; then
73
+ // the vendored copies read back as cargo's directory source reads them.
74
+ // Gives back each crate's links, by its key.
75
+ function checkLock(lock, inputs, crates, vendored) {
76
+ const { keys } = inputs
77
+ const manifests = Object.create(null)
78
+ for (const [dir, key] of keys) if (key in lock.packages) manifests[key] = inputs.packages.get(dir).manifest
79
+ const texts = new Map(crates.map((crate) => [crate.key, manifestOf(crate, vendored.get(crate.key))]))
80
+ for (const [key, { manifest }] of texts) manifests[key] = manifest
81
+ const members = [...inputs.packages].filter(([dir, { member }]) => member && keys.has(dir)).map(([dir]) => keys.get(dir))
82
+ checkPaths(linkCargo(lock, manifests, { workspace: inputs.root, members, config: inputs.config }), inputs.packages, keys)
83
+ const read = readCargoVendor(lock, Object.fromEntries(crates.map((crate) => [crate.directory, { manifest: texts.get(crate.key).text, checksum: vendored.get(crate.key).checksumText }])))
84
+ for (const crate of crates) if (read[crate.key].directory !== crate.directory) throw new Error(`unreachable: ${crate.key} read back from ${read[crate.key].directory}`)
85
+ return new Map([...texts].map(([key, { links }]) => [key, links]))
86
+ }
87
+
88
+ // Each crate's bytes are let go once its files are written, which copies them.
89
+ function writeTree(crates, vendored, stats) {
90
+ const vfs = new Vfs()
91
+ for (const { key, directory } of crates) {
92
+ const { root, dirs, files } = vendored.get(key)
93
+ const path = `vendor/${directory}`
94
+ writeFiles(vfs, path, { dirs: dirs.keys(), files }, stats)
95
+ for (const [dir, mode] of dirs) vfs.chmod(`/${path}/${dir}`, mode)
96
+ vfs.chmod(`/${path}`, root)
97
+ vendored.delete(key)
98
+ }
99
+ return vfs
100
+ }
101
+
102
+ export async function buildCargoTree(options) {
103
+ const { host: given, vfs: into } = options ?? {}
104
+ if (into !== undefined && !(into instanceof Vfs)) throw new TypeError('vfs must be a Vfs, or left out')
105
+ const inputs = inputsOf(options ?? {})
106
+ const host = checkHost(given)
107
+ const folded = host.os === 'darwin'
108
+ // Refused before anything is fetched; mount checks again.
109
+ if (into !== undefined) checkNoVendor(into, folded)
110
+ const lock = parseCargoLock(inputs.lockfile)
111
+ const config = configOf(inputs.config)
112
+ const { root, packages, read } = findWorkspace(inputs.project, config, folded)
113
+ for (const dir of inputs.given ?? []) {
114
+ if (read.get(dir) === undefined) throw new DeptreeError('given, but no manifest cargo reads', `manifests[${quote(dir)}]`)
115
+ }
116
+ const crates = vendoredPackages(lock)
117
+ const keys = pathKeys(lock, packages)
118
+ const vendored = await fetchCrates(crates, host.comment)
119
+ const links = checkLock(lock, { root, packages, config, keys }, crates, vendored)
120
+ const stats = { packages: Object.keys(lock.packages).length, vendored: crates.length, files: 0, bytes: 0 }
121
+ // Before writeTree lets each crate go.
122
+ const installed = crates.map(({ key, directory, name, version, checksum }) => ({ path: `vendor/${directory}`, name, version, source: lock.packages[key].source, checksum, commit: vendored.get(key).commit, ...links.get(key) }))
123
+ const vfs = writeTree(crates, vendored, stats)
124
+ return { vfs: mount(vfs, into, folded, checkNoVendor), stats, installed }
125
+ }
@@ -0,0 +1,177 @@
1
+ // The workspace as cargo finds it from the project's root, which is taken to
2
+ // be its root: the members, each path dependency of one that is in the root
3
+ // and not excluded a member too, and every other path package cargo reads,
4
+ // each manifest parsed as cargo reads it, inheriting from the root's
5
+ // [workspace] where cargo has it inherit.
6
+
7
+ import { LockfileError, parseCargoManifest } from '@preventive/lockfile/cargo.js'
8
+ import { TomlError, parseToml } from '@preventive/lockfile/toml.js'
9
+ import { dirname } from '@preventive/vfs/path.js'
10
+ import { DeptreeError, quote } from '../error.js'
11
+ import { UNSAFE } from '../mount.js'
12
+ import { readUnlinked } from './inputs.js'
13
+ import { checkDefaultMembers, checkLists, explicitMembers, isExcluded, parts } from './members.js'
14
+
15
+ export const fileOf = (dir) => (dir === '.' ? 'Cargo.toml' : `${dir}/Cargo.toml`)
16
+ const manifestPath = (dir) => [...parts(dir), 'Cargo.toml']
17
+ // Whether the root's [workspace] takes `dir` in: there is one, and it does
18
+ // not exclude it.
19
+ const inRoot = (workspace, dir) => workspace !== undefined && !isExcluded(workspace, manifestPath(dir))
20
+
21
+ // A path as a manifest writes it, from the directory `base`: `..` only ahead
22
+ // of every name, which the filesystem would otherwise walk through a name
23
+ // that cargo's normalize_path drops unread.
24
+ function resolvePath(base, path, where) {
25
+ if (path.startsWith('/') || UNSAFE.test(path) || /^[A-Za-z]:/u.test(path)) throw new DeptreeError(`${quote(path)} is not a relative path within the project, which is all that is read`, where)
26
+ const segments = parts(base)
27
+ let named = false
28
+ for (const segment of parts(path)) {
29
+ if (segment !== '..') {
30
+ named = true
31
+ segments.push(segment)
32
+ } else if (named) {
33
+ throw new DeptreeError(`${quote(path)} has a \`..\` after a name, which is not supported`, where)
34
+ } else if (segments.pop() === undefined) {
35
+ throw new DeptreeError(`${quote(path)} leads out of the project, which is not read`, where)
36
+ }
37
+ }
38
+ return segments.length === 0 ? '.' : segments.join('/')
39
+ }
40
+
41
+ export function parseAs(file, parse) {
42
+ try {
43
+ return parse()
44
+ } catch (error) {
45
+ if (error instanceof LockfileError || error instanceof TomlError) throw new DeptreeError(error.message, file, { cause: error })
46
+ throw error
47
+ }
48
+ }
49
+
50
+ // A Cargo.toml's text and TOML, or undefined where there is none.
51
+ function readRaw(project, dir) {
52
+ const file = fileOf(dir)
53
+ const text = readUnlinked(project, file, 'a manifest')
54
+ return text === undefined ? undefined : { text, doc: parseAs(file, () => parseToml(text)) }
55
+ }
56
+
57
+ const pointerOf = (doc) => (doc.package ?? doc.project)?.workspace
58
+
59
+ const DEP_KEYS = { normal: 'dependencies', dev: 'dev-dependencies', build: 'build-dependencies' }
60
+ const depWhere = (dir, dep) => `${fileOf(dir)}: ${dep.target === undefined ? '' : `target.${quote(dep.target)}.`}${DEP_KEYS[dep.kind]}.${dep.name}`
61
+
62
+ // The context the steps below share: the root's manifest and [workspace],
63
+ // each Cargo.toml read, and each path package loaded.
64
+ function contextOf(project, folded) {
65
+ const read = new Map()
66
+ const raw = (dir) => {
67
+ if (!read.has(dir)) read.set(dir, readRaw(project, dir))
68
+ return read.get(dir)
69
+ }
70
+ const top = raw('.')
71
+ if (top === undefined) throw new DeptreeError('the project has no Cargo.toml')
72
+ if (pointerOf(top.doc) !== undefined) throw new DeptreeError('a root that points to a workspace above it, which is not read, is not supported', 'Cargo.toml: package.workspace')
73
+ const root = parseAs('Cargo.toml', () => parseCargoManifest(top.text))
74
+ if (root.workspace !== undefined) checkLists(root.workspace)
75
+ return { project, folded, read, raw, root, workspace: root.workspace, packages: new Map() }
76
+ }
77
+
78
+ // Where cargo finds the workspace of the package in `dir`, below the root:
79
+ // its own [workspace], the root's, or none. A package.workspace pointing
80
+ // elsewhere than the root, and a [workspace] between the two, are refused.
81
+ function workspaceOf({ raw, workspace }, dir) {
82
+ if (raw(dir).doc.workspace !== undefined) return 'own'
83
+ for (let here = dir; here !== '.'; here = dirname(here)) {
84
+ const doc = raw(here)?.doc
85
+ if (doc === undefined) continue
86
+ if (doc.workspace !== undefined) throw new DeptreeError('a [workspace] between a package and the root, one workspace in another, is not supported', fileOf(here))
87
+ const pointer = pointerOf(doc)
88
+ if (pointer === undefined) continue
89
+ const where = `${fileOf(here)}: package.workspace`
90
+ if (typeof pointer !== 'string' || resolvePath(here, pointer, where) !== '.' || workspace === undefined) throw new DeptreeError('a package.workspace pointing elsewhere than the root is not supported', where)
91
+ return 'root'
92
+ }
93
+ return inRoot(workspace, dir) ? 'root' : 'none'
94
+ }
95
+
96
+ // A path package's manifest, and where its path dependencies lead: of a
97
+ // member every kind, of another package all but dev-dependencies, which
98
+ // cargo resolves for members alone. An inherited dependency's path is from
99
+ // the root of the workspace it is inherited from.
100
+ function load(context, dir, member, where) {
101
+ const { raw, root, packages } = context
102
+ if (raw(dir) === undefined) throw new DeptreeError(`${quote(fileOf(dir))} is not there, which cargo fails on`, where)
103
+ const inherits = dir === '.' ? 'own' : workspaceOf(context, dir)
104
+ if (member && dir !== '.' && inherits !== 'root') throw new DeptreeError('a member with a [workspace] of its own, which cargo refuses', fileOf(dir))
105
+ const manifest = dir === '.' ? root : parseAs(fileOf(dir), () => parseCargoManifest(raw(dir).text, inherits === 'root' ? root : undefined))
106
+ if (manifest.package === undefined && dir !== '.') throw new DeptreeError('a manifest with no [package], which cargo fails on as a path dependency', fileOf(dir))
107
+ const links = []
108
+ for (const [index, dep] of (manifest.package?.dependencies ?? []).entries()) {
109
+ if (dep.source.type !== 'path' || (!member && dep.kind === 'dev')) continue
110
+ const here = depWhere(dir, dep)
111
+ links.push({ index, dir: resolvePath(dep.inherited && inherits === 'root' ? '.' : dir, dep.source.path, here), where: here })
112
+ }
113
+ packages.set(dir, { manifest, member, links })
114
+ return links
115
+ }
116
+
117
+ // Those `members` takes and the root, then each path dependency of one that
118
+ // is in the root and not excluded, of any kind. What else they lead to is
119
+ // given back, for the packages that are not members.
120
+ function loadMembers(context) {
121
+ const { project, folded, workspace } = context
122
+ const members = new Set()
123
+ const pending = []
124
+ const others = []
125
+ const join = ({ dir, where }) => {
126
+ if (members.has(dir)) return
127
+ members.add(dir)
128
+ pending.push({ dir, where })
129
+ }
130
+ const listed = workspace === undefined ? [] : explicitMembers(project, workspace, folded)
131
+ if (workspace !== undefined) {
132
+ for (const dir of listed) if (inRoot(workspace, dir)) join({ dir, where: 'Cargo.toml: workspace.members' })
133
+ if (isExcluded(workspace, ['Cargo.toml'])) throw new DeptreeError('the root is excluded from its own workspace, which cargo refuses', 'Cargo.toml: workspace.exclude')
134
+ }
135
+ join({ dir: '.', where: 'Cargo.toml' })
136
+ while (pending.length > 0) {
137
+ const { dir, where } = pending.shift()
138
+ for (const link of load(context, dir, true, where)) {
139
+ if (inRoot(workspace, link.dir)) join(link)
140
+ else others.push(link)
141
+ }
142
+ }
143
+ if (workspace !== undefined) checkDefaultMembers(project, workspace, members, new Set(listed), folded)
144
+ return others
145
+ }
146
+
147
+ // Each [patch] from a path, the root's from the root and the config's from
148
+ // the directory its .cargo is in, which is the root too.
149
+ function patchesOf(root, config) {
150
+ const tables = [
151
+ ...Object.entries(root.patch).map(([table, specs]) => ({ table, specs, file: 'Cargo.toml' })),
152
+ ...Object.entries(config.patch).map(([table, specs]) => ({ table, specs, file: config.file })),
153
+ ]
154
+ return tables.flatMap(({ table, specs, file }) => Object.entries(specs).filter(([, spec]) => spec.source.type === 'path').map(([name, spec]) => {
155
+ const where = `${file}: patch.${quote(table)}.${name}`
156
+ return { dir: resolvePath('.', spec.source.path, where), name: spec.package, where }
157
+ }))
158
+ }
159
+
160
+ // `config` is what parseCargoConfig gives, with the `file` it was read from.
161
+ // `read` is each Cargo.toml read, by its directory: undefined where there is
162
+ // none.
163
+ export function findWorkspace(project, config, folded) {
164
+ const context = contextOf(project, folded)
165
+ const others = loadMembers(context)
166
+ const patches = patchesOf(context.root, config)
167
+ others.push(...patches)
168
+ while (others.length > 0) {
169
+ const { dir, where } = others.shift()
170
+ if (!context.packages.has(dir)) others.push(...load(context, dir, false, where))
171
+ }
172
+ for (const { dir, name, where } of patches) {
173
+ const found = context.packages.get(dir).manifest.package.name
174
+ if (found !== name) throw new DeptreeError(`${quote(fileOf(dir))} is of ${quote(found)}, not ${quote(name)}, which cargo fails on`, where)
175
+ }
176
+ return { root: context.root, packages: context.packages, read: context.read }
177
+ }
@@ -0,0 +1,32 @@
1
+ import { Queue } from '@chalker/queue'
2
+ import { refusalOf } from './error.js'
3
+
4
+ const CONCURRENCY = 8
5
+
6
+ // A few at a time, so a large lockfile does not start every request at once.
7
+ // The first failure is thrown once every started job has ended, so that none
8
+ // goes on fetching or writing a cache after the call returns.
9
+ export async function eachConcurrently(items, job, whereOf) {
10
+ const queue = new Queue(CONCURRENCY)
11
+ let failure
12
+ await Promise.all([...items].map(async (item) => {
13
+ await queue.claim()
14
+ try {
15
+ if (failure === undefined) await job(item)
16
+ } catch (error) {
17
+ failure ??= { error: whereOf === undefined ? error : refusalOf(error, whereOf(item)) }
18
+ } finally {
19
+ queue.release()
20
+ }
21
+ }))
22
+ if (failure !== undefined) throw failure.error
23
+ }
24
+
25
+ // Each of `values` awaited at once, the first failure by position thrown once
26
+ // all have ended, as eachConcurrently throws one.
27
+ export async function settled(values) {
28
+ const results = await Promise.allSettled(values)
29
+ const failed = results.find(({ status }) => status === 'rejected')
30
+ if (failed !== undefined) throw failed.reason
31
+ return results.map(({ value }) => value)
32
+ }
package/src/error.js CHANGED
@@ -1,7 +1,5 @@
1
- // `where` is what a refusal is about — a file and the setting or key in
2
- // it, `pnpm-workspace.yaml: nodeLinker`, or a package and the file in it —
3
- // or undefined for the call as a whole; the message leads with it. What a
4
- // package below refused with is kept as the `cause`.
1
+ // `where` is what is refused, such as `pnpm-workspace.yaml: nodeLinker`, or
2
+ // undefined for the call as a whole; the message leads with it.
5
3
  export class DeptreeError extends Error {
6
4
  constructor(detail, where, options) {
7
5
  super(where === undefined ? detail : `${where}: ${detail}`, options)
@@ -10,17 +8,17 @@ export class DeptreeError extends Error {
10
8
  }
11
9
  }
12
10
 
13
- // A piece of an input for a message: quoted, cut short where it runs long,
14
- // and with every control, line separator and bidirectional control
15
- // escaped, so a name cannot act on a terminal or reorder what is shown.
11
+ export const refusalOf = (error, where) => (error instanceof DeptreeError ? error : new DeptreeError(error.message, where, { cause: error }))
12
+
13
+ // Escaped so that a name cannot act on a terminal or reorder what is shown.
16
14
  const UNSHOWN = /[\p{Cc}\p{Zl}\p{Zp}\p{Bidi_Control}]/gu
15
+ export const escaped = (text) => text.replaceAll(UNSHOWN, (char) => `\\u${char.codePointAt(0).toString(16).padStart(4, '0')}`)
16
+
17
17
  export function quote(text) {
18
18
  const cut = text.length > 200 ? `${text.slice(0, text.codePointAt(199) > 0xFFFF ? 199 : 200)}…` : text
19
- return JSON.stringify(cut).replaceAll(UNSHOWN, (char) => `\\u${char.codePointAt(0).toString(16).padStart(4, '0')}`)
19
+ return escaped(JSON.stringify(cut))
20
20
  }
21
21
 
22
- // The first key two mappings of strings differ at, for a message: `sides`
23
- // names where each is from, and `same` tells two values alike.
24
22
  export function difference(a, b, [aSide, bSide], same = (x, y) => x === y) {
25
23
  for (const key of new Set([...Object.keys(a), ...Object.keys(b)])) {
26
24
  const inA = Object.hasOwn(a, key)
package/src/glob.js ADDED
@@ -0,0 +1,55 @@
1
+ // Workspace globs as yarn and npm match and walk them, by minimatch's
2
+ // defaults as far as the lockfile reader lets them through: no wildcard
3
+ // takes a leading dot.
4
+
5
+ import { DeptreeError, quote } from './error.js'
6
+ import { reach, wildcard } from './matcher.js'
7
+ import { typeOf } from './project.js'
8
+
9
+ const compiled = new Map()
10
+
11
+ function compile(glob) {
12
+ return glob.split('/').map((segment) => {
13
+ if (segment === '**') return segment
14
+ const dot = !segment.startsWith('.') && /[*?]/u.test(segment)
15
+ const matches = wildcard(segment, { one: true })
16
+ return { test: (name) => !(dot && name.startsWith('.')) && matches(name) }
17
+ })
18
+ }
19
+
20
+ function placesOf(glob, path) {
21
+ if (!compiled.has(glob)) compiled.set(glob, compile(glob))
22
+ return reach(compiled.get(glob), path === '' ? [] : path.split('/'))
23
+ }
24
+
25
+ export const matchesGlob = (glob, path) => placesOf(glob, path).at(-1)
26
+
27
+ // Whether `glob` may take a path below `dir`: some of it left to take.
28
+ const reachesBelow = (glob, dir) => placesOf(glob, dir).slice(0, -1).some(Boolean)
29
+
30
+ // The directories the globs take that have a package.json, as yarn and npm
31
+ // walk for them. glob follows a link or not by where it is, so one the
32
+ // globs reach is refused. `enter` refuses a directory, or says whether it
33
+ // is kept and walked into.
34
+ export function walkWorkspaces(project, globs, { manager, fold = (path) => path, skip = () => false, enter = () => true }) {
35
+ const folded = globs.map(fold)
36
+ const found = []
37
+ const pending = globs.length === 0 ? [] : ['']
38
+ while (pending.length > 0) {
39
+ const dir = pending.pop()
40
+ for (const name of project.readdir(`/${dir}`)) {
41
+ const path = dir === '' ? name : `${dir}/${name}`
42
+ const key = fold(path)
43
+ const taken = folded.some((glob) => matchesGlob(glob, key))
44
+ if (skip(name) || (!taken && !folded.some((glob) => reachesBelow(glob, key)))) continue
45
+ const { type } = project.lstat(`/${path}`)
46
+ if (type === 'symlink') throw new DeptreeError(`a link where ${manager} looks for workspaces is not supported`, quote(path))
47
+ if (type !== 'directory') continue
48
+ const manifest = taken && typeOf(project, `/${path}/package.json`) !== undefined
49
+ if (!enter(path, name, taken, manifest)) continue
50
+ if (manifest) found.push(path)
51
+ pending.push(path)
52
+ }
53
+ }
54
+ return found.sort()
55
+ }
package/src/hash.js CHANGED
@@ -1,23 +1,58 @@
1
- // Digests on the platform's Web Crypto, which every runtime this runs on
2
- // has: the integrity a lockfile pins a tarball to, and the hex digests
3
- // pnpm names a patch and a long directory by.
4
-
1
+ import { toBase32 } from '@exodus/bytes/base32.js'
2
+ import { toBase64 } from '@exodus/bytes/base64.js'
3
+ import { toHex } from '@exodus/bytes/hex.js'
4
+ import { utf8fromString } from '@exodus/bytes/utf8.js'
5
5
  import { DeptreeError } from './error.js'
6
6
 
7
- const encoder = new TextEncoder()
8
-
9
7
  const digest = async (algorithm, bytes) => new Uint8Array(await crypto.subtle.digest(algorithm, bytes))
10
- const hex = (bytes) => Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('')
11
- const base64 = (bytes) => btoa(String.fromCodePoint(...bytes))
12
8
 
13
- // Text is hashed as its UTF-8, and only text that has one: TextEncoder
14
- // writes a lone surrogate as U+FFFD, so two different strings would hash
15
- // the same. `where` is what the text is, for the refusal.
16
- export async function sha256Hex(text, where) {
9
+ // Only well-formed text is hashed: a lone surrogate written as U+FFFD would
10
+ // hash two different strings the same.
11
+ function utf8(text, where) {
17
12
  if (typeof text !== 'string' || !text.isWellFormed()) throw new DeptreeError('expected well-formed text to hash', where)
18
- return hex(await digest('SHA-256', encoder.encode(text)))
13
+ return utf8fromString(text)
14
+ }
15
+
16
+ export const sha256Hex = async (text, where) => toHex(await digest('SHA-256', utf8(text, where)))
17
+
18
+ // MD5, which Web Crypto has not, as RFC 1321 has it.
19
+ const SHIFTS = [7, 12, 17, 22, 5, 9, 14, 20, 4, 11, 16, 23, 6, 10, 15, 21]
20
+ const SINES = Array.from({ length: 64 }, (_, i) => Math.floor(Math.abs(Math.sin(i + 1)) * 2 ** 32) >>> 0)
21
+ function md5(input) {
22
+ const padded = new Uint8Array(Math.ceil((input.length + 9) / 64) * 64)
23
+ padded.set(input)
24
+ padded[input.length] = 0x80
25
+ const view = new DataView(padded.buffer)
26
+ view.setUint32(padded.length - 8, (input.length * 8) >>> 0, true)
27
+ view.setUint32(padded.length - 4, Math.floor(input.length / 2 ** 29), true)
28
+ const state = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476]
29
+ for (let block = 0; block < padded.length; block += 64) {
30
+ let [a, b, c, d] = state
31
+ for (let i = 0; i < 64; i++) {
32
+ const round = i >> 4
33
+ const f = round === 0 ? (b & c) | (~b & d) : round === 1 ? (d & b) | (~d & c) : round === 2 ? b ^ c ^ d : c ^ (b | ~d)
34
+ const g = round === 0 ? i : round === 1 ? (5 * i + 1) % 16 : round === 2 ? (3 * i + 5) % 16 : (7 * i) % 16
35
+ const shift = SHIFTS[round * 4 + (i % 4)]
36
+ const sum = (a + f + SINES[i] + view.getUint32(block + g * 4, true)) >>> 0
37
+ ;[a, d, c] = [d, c, b]
38
+ b = (b + ((sum << shift) | (sum >>> (32 - shift)))) >>> 0
39
+ }
40
+ for (const [i, word] of [a, b, c, d].entries()) state[i] = (state[i] + word) >>> 0
41
+ }
42
+ const bytes = new Uint8Array(16)
43
+ const out = new DataView(bytes.buffer)
44
+ state.forEach((word, i) => out.setUint32(i * 4, word, true))
45
+ return bytes
19
46
  }
20
47
 
21
- // Whether `bytes` are what a subresource integrity names: a sha512, the
22
- // only kind taken, in padded base64.
23
- export const matchesIntegrity = async (bytes, integrity) => integrity === `sha512-${base64(await digest('SHA-512', bytes))}`
48
+ // pnpm 9's createBase32Hash: the MD5 of the text's UTF-8, in RFC 4648's
49
+ // base32, lowercased and unpadded.
50
+ export const md5Base32 = (text, where) => toBase32(md5(utf8(text, where)), { padding: false }).toLowerCase()
51
+
52
+ export const matchesIntegrity = async (bytes, integrity) => integrity === `sha512-${toBase64(await digest('SHA-512', bytes))}`
53
+
54
+ // As yarn 1 records a tarball's after the `#` of its URL.
55
+ export const sha1Hex = async (bytes) => toHex(await digest('SHA-1', bytes))
56
+
57
+ // As soldeer.lock records a zip's checksum.
58
+ export const bytesSha256Hex = async (bytes) => toHex(await digest('SHA-256', bytes))
@@ -0,0 +1,52 @@
1
+ // A package.json as pnpm, yarn 1 and npm read one, a byte order mark dropped.
2
+
3
+ import { DeptreeError, quote } from './error.js'
4
+ import { isInside } from './mount.js'
5
+
6
+ // A package.json is a few levels deep. One far deeper is refused where it is
7
+ // read, and again where it is copied whole, as structuredClone, which
8
+ // recurses, runs out of stack on one some thousands deep.
9
+ const DEEPEST = 100
10
+
11
+ export function checkNesting(value, where) {
12
+ const pending = [[value, 0]]
13
+ while (pending.length > 0) {
14
+ const [item, depth] = pending.pop()
15
+ if (item === null || typeof item !== 'object') continue
16
+ if (depth === DEEPEST) throw new DeptreeError(`nested more than ${DEEPEST} deep, which is not supported`, where)
17
+ for (const child of Object.values(item)) pending.push([child, depth + 1])
18
+ }
19
+ return value
20
+ }
21
+
22
+ // What a package.json's mapping has under `key` of its own. JSON.parse makes
23
+ // plain objects, which have `constructor` and `toString` from
24
+ // Object.prototype under names a package may have.
25
+ export const own = (map, key) => (map != null && Object.hasOwn(map, key) ? map[key] : undefined)
26
+
27
+ export function readManifest(text, where) {
28
+ if (typeof text !== 'string') throw new TypeError(`${where} must be the text of a package.json`)
29
+ let manifest
30
+ try {
31
+ manifest = JSON.parse(text.replace(/^/u, ''))
32
+ } catch (error) {
33
+ throw new DeptreeError(`not JSON: ${error.message}`, where, { cause: error })
34
+ }
35
+ if (manifest === null || typeof manifest !== 'object' || Array.isArray(manifest)) throw new DeptreeError('expected an object', where)
36
+ return checkNesting(manifest, where)
37
+ }
38
+
39
+ // The package.json texts given by directory, in a Map or a Record: the
40
+ // project's, and its workspaces', each in a directory under it, as one
41
+ // found in a project is. A workspace's dependencies are written in its
42
+ // directory, and a link made to it.
43
+ export function readManifests(texts) {
44
+ const read = new Map()
45
+ for (const [dir, text] of texts instanceof Map ? texts : Object.entries(texts)) {
46
+ const where = `manifests[${quote(dir)}]`
47
+ if (dir !== '.' && !isInside(dir)) throw new DeptreeError('expected "." or a directory under the project\'s, by its path from there in normal form', where)
48
+ read.set(dir, readManifest(text, where))
49
+ }
50
+ if (!read.has('.')) throw new DeptreeError('the root package.json is not given', 'manifests["."]')
51
+ return read
52
+ }
package/src/matcher.js CHANGED
@@ -1,19 +1,69 @@
1
1
  // pnpm's name patterns (@pnpm/matcher), as `hoist-pattern` and
2
- // `public-hoist-pattern` read them: `*` for any run of characters and
3
- // nothing else special, `!` in front to exclude. One pattern is that
4
- // pattern or its negation; several are read in order, where an exclusion
5
- // cancels what matched before it and nothing after it matches again but a
6
- // later inclusion, and a list of exclusions alone matches what none of them
7
- // does.
2
+ // `public-hoist-pattern` read them; and the walk of a path through a glob,
3
+ // which pnpm's workspace globs and yarn's share.
8
4
 
9
- // Text as a regular expression that matches it alone.
10
- export const escape = (text) => text.replace(/[$()+.?[\\\]^{|}]/gu, '\\$&')
5
+ // Whether a text matches `pattern`, `*` any run of what `any` takes and,
6
+ // with `one`, `?` any one code point; anything else itself. The places of
7
+ // `pattern` a text reaches are kept a code point at a time, in O(n·m) for
8
+ // any pattern, where a regexp of k `*`s backtracks in O(n^k): a glob from a
9
+ // project's own files is no one's to stall.
10
+ export function wildcard(pattern, { one = false, any = () => true } = {}) {
11
+ const parts = [...pattern]
12
+ const end = parts.length
13
+ const onward = (places) => {
14
+ for (let i = 0; i < end; i++) if (places[i] === 1 && parts[i] === '*') places[i + 1] = 1
15
+ }
16
+ let here = new Uint8Array(end + 1)
17
+ let next = new Uint8Array(end + 1)
18
+ return (text) => {
19
+ here.fill(0)
20
+ here[0] = 1
21
+ onward(here)
22
+ for (const char of text) {
23
+ next.fill(0)
24
+ for (let i = 0; i < end; i++) {
25
+ if (here[i] === 0) continue
26
+ if (parts[i] === '*') {
27
+ if (any(char)) next[i] = 1
28
+ } else if (parts[i] === char || (one && parts[i] === '?')) next[i + 1] = 1
29
+ }
30
+ onward(next)
31
+ ;[here, next] = [next, here]
32
+ }
33
+ return here[end] === 1
34
+ }
35
+ }
36
+
37
+ // For each place in `glob`, a regexp per name or `**`, whether `names` reach
38
+ // it, the last being a full match; linear per name, with no recursion however
39
+ // many `**`. A `**` takes no name with a leading dot unless `dot`.
40
+ export function reach(glob, names, dot = false) {
41
+ let here = Array.from({ length: glob.length + 1 }, (_, g) => g === 0)
42
+ let next = Array.from({ length: glob.length + 1 }, () => false)
43
+ const onward = (places) => {
44
+ for (let g = 0; g < glob.length; g++) if (places[g] && glob[g] === '**') places[g + 1] = true
45
+ }
46
+ onward(here)
47
+ for (const name of names) {
48
+ next.fill(false)
49
+ for (let g = 0; g < glob.length; g++) {
50
+ if (!here[g]) continue
51
+ if (glob[g] !== '**') next[g + 1] ||= glob[g].test(name)
52
+ else if (dot || !name.startsWith('.')) next[g] = true
53
+ }
54
+ onward(next)
55
+ ;[here, next] = [next, here]
56
+ }
57
+ return here
58
+ }
59
+
60
+ // pnpm's `*` is a regexp's `.*`, which takes no line terminator.
61
+ const LINE = new Set(['\n', '\r', '\u2028', '\u2029'])
11
62
 
12
63
  function matcherOf(pattern) {
13
64
  if (pattern === '*') return () => true
14
65
  if (!pattern.includes('*')) return (input) => input === pattern
15
- const regexp = new RegExp(`^${pattern.split('*').map(escape).join('.*')}$`, 'u')
16
- return (input) => regexp.test(input)
66
+ return wildcard(pattern, { any: (char) => !LINE.has(char) })
17
67
  }
18
68
 
19
69
  export function createMatcher(patterns) {