@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,319 @@
1
+ // minimatch as npm-packlist runs it, with matchBase, dot, flipNegate and
2
+ // nocase, of patterns whose only glob syntax is `*`, `?` and `**`: 5.1.6 for
3
+ // pnpm 9 and for 10 before 10.31, 5.1.9 for 10 from 10.31, which matches
4
+ // `**` by other steps, and 10.2 for pnpm 11. Its regexps have no `u`, as
5
+ // minimatch's have none: they take UTF-16 code units, and fold case as such
6
+ // a regexp folds it.
7
+
8
+ import { DeptreeError, quote } from '../error.js'
9
+
10
+ export const GLOBSTAR = Symbol('**')
11
+
12
+ // Characters with a meaning to minimatch, glob or globset that is not
13
+ // followed here, and those a regexp's `.` does not take.
14
+ const UNFOLLOWED = /[()[\\\]{|}\p{Cc}\u2028\u2029]/u
15
+
16
+ // `body` is a pattern with its leading `!`s taken off. A `.` part, an
17
+ // empty one and `**` beside other characters are read by each as written,
18
+ // and so is a `..` part where `parent` says, which then reads nothing.
19
+ export function checkGlob(body, where, { parent = false } = {}) {
20
+ const odd = UNFOLLOWED.test(body) ? 'glob syntax' : !parent && body.split('/').includes('..') ? 'a .. part' : undefined
21
+ if (odd !== undefined) throw new DeptreeError(`${quote(body)} has ${odd}, which is not followed here: of glob syntax, only * and ? are`, where)
22
+ }
23
+
24
+ // A longer pattern minimatch may make too large a regexp of for V8, which
25
+ // pnpm 9, 10 and 11 then fail on, and globset one, which pnpm 12 then drops
26
+ // with the rest of its file; none does below several times this.
27
+ const MAX_LENGTH = 4096
28
+
29
+ export function checkLength(pattern, where) {
30
+ if (pattern.length > MAX_LENGTH) throw new DeptreeError(`a pattern of more than ${MAX_LENGTH} characters, which pnpm may make too large a regexp of, is not supported`, where)
31
+ }
32
+
33
+ // More `**` than this are not matched here, which matching each takes time
34
+ // for.
35
+ const MAX_GLOBSTARS = 100
36
+
37
+ export function checkParts(pattern, parts, where) {
38
+ if (parts.filter((part) => part === '**').length > MAX_GLOBSTARS) throw new DeptreeError(`${quote(pattern)} has more than ${MAX_GLOBSTARS} ** parts, which is not supported`, where)
39
+ }
40
+
41
+ // Of minimatch's own parts, only those of fixed text are regexps here,
42
+ // with no `u`, as its own.
43
+ // oxlint-disable-next-line require-unicode-regexp
44
+ export const caseless = (source) => new RegExp(source, 'i')
45
+
46
+ export const NO_TRAVERSAL_5 = String.raw`(?!(?:^|\/)\.{1,2}(?:$|\/))`
47
+ const NO_TRAVERSAL_10 = String.raw`(?!(?:^|/)\.\.?(?:$|/))`
48
+
49
+ // What a regexp with `i` and no `u` takes a code unit for: its upper case
50
+ // where that is one code unit, but not one below 128 for one above.
51
+ const canonicals = new Map()
52
+ function canonical(unit) {
53
+ let found = canonicals.get(unit)
54
+ if (found === undefined) {
55
+ const upper = String.fromCodePoint(unit).toUpperCase()
56
+ found = upper.length === 1 && !(unit >= 128 && upper.codePointAt(0) < 128) ? upper.codePointAt(0) : unit
57
+ canonicals.set(unit, found)
58
+ }
59
+ return found
60
+ }
61
+
62
+ // A text's UTF-16 code unit at `i`, which a regexp with no `u` takes one by
63
+ // one.
64
+ // oxlint-disable-next-line unicorn/prefer-code-point
65
+ const unitAt = (text, i) => text.charCodeAt(i)
66
+
67
+ const STAR = -1
68
+ const ANY = -2
69
+ const SLASH = 0x2F
70
+ const LINE_TERMINATORS = new Set([0x0A, 0x0D, 0x2028, 0x2029])
71
+
72
+ // A part as minimatch's regexp of it matches a name, in time linear in
73
+ // both: `*` any run of code units but `/`, `?` any one, each other one
74
+ // itself without case. `lookahead` is minimatch 5's `(?=.)`, which takes no
75
+ // name that is empty or starts with a line terminator; `traversal` its
76
+ // lookahead that takes no `.` or `..`.
77
+ function partOf(text, { lookahead = false, traversal = false, empty = true } = {}) {
78
+ const units = Array.from({ length: text.length }, (_, i) => {
79
+ const unit = unitAt(text, i)
80
+ return unit === 0x2A ? STAR : unit === 0x3F ? ANY : canonical(unit)
81
+ })
82
+ const wild = units.some((unit) => unit < 0)
83
+ const skip = (places) => {
84
+ for (let i = 0; i < units.length; i++) if (places[i] === 1 && units[i] === STAR) places[i + 1] = 1
85
+ }
86
+ let here = new Uint8Array(units.length + 1)
87
+ let next = new Uint8Array(units.length + 1)
88
+ const test = (name) => {
89
+ if ((traversal && (name === '.' || name === '..')) || (!empty && name === '')) return false
90
+ if (lookahead && (name === '' || LINE_TERMINATORS.has(name.codePointAt(0)))) return false
91
+ if (!wild && name.length !== units.length) return false
92
+ here.fill(0)
93
+ here[0] = 1
94
+ skip(here)
95
+ for (let k = 0; k < name.length; k++) {
96
+ const unit = unitAt(name, k)
97
+ next.fill(0)
98
+ for (let i = 0; i < units.length; i++) {
99
+ if (here[i] === 0) continue
100
+ if (units[i] === STAR) {
101
+ if (unit !== SLASH) next[i] = 1
102
+ } else if (units[i] === ANY ? unit !== SLASH : canonical(unit) === units[i]) next[i + 1] = 1
103
+ }
104
+ skip(next)
105
+ ;[here, next] = [next, here]
106
+ }
107
+ return here[units.length] === 1
108
+ }
109
+ return { test }
110
+ }
111
+
112
+ const foldless = (text) => text.toUpperCase() === text.toLowerCase()
113
+
114
+ // minimatch 10's own tests of a part, which it runs in place of its regexp.
115
+ const FAST = [
116
+ [/^\*+$/u, () => (f) => f.length !== 0 && f !== '.' && f !== '..'],
117
+ [/^\*+([^!(*+?@[]*)$/u, ([, ext]) => (f) => f.toLowerCase().endsWith(ext.toLowerCase())],
118
+ [/^\?+([^!(*+?@[]*)?$/u, ([whole, ext]) => (f) => f.length === whole.length && f !== '.' && f !== '..' && (!ext || f.toLowerCase().endsWith(ext.toLowerCase()))],
119
+ [/^\*+\.\*+$/u, () => (f) => f !== '.' && f !== '..' && f.includes('.')],
120
+ [/^\.\*+$/u, () => (f) => f !== '.' && f !== '..' && f.startsWith('.')],
121
+ ]
122
+
123
+ // A part as minimatch 5 reads it, or with `ten` minimatch 10.
124
+ export function readPart(text, ten = false) {
125
+ if (text === '**') return GLOBSTAR
126
+ if (!/[*?]/u.test(text)) return text === '' || foldless(text) ? text : partOf(text)
127
+ if (!ten) return partOf(text, { lookahead: true, traversal: /^[*?]/u.test(text) })
128
+ const fast = FAST.find(([re]) => re.test(text))
129
+ if (fast !== undefined) return { test: fast[1](text.match(fast[0])) }
130
+ return partOf(text, { traversal: /^\.{0,2}[*?]/u.test(text), empty: !/^\*+$/u.test(text) })
131
+ }
132
+
133
+ const hit = (part, name) => (typeof part === 'string' ? name === part : part.test(name))
134
+ const traversal = (name) => name === '.' || name === '..'
135
+
136
+ // How a match ends where file, as long as `end`, or pattern runs out at
137
+ // `fi` and `pi`.
138
+ function ended(file, pattern, fi, pi, partial, end = file.length) {
139
+ if (fi === end) return pi === pattern.length || partial
140
+ return pi === pattern.length && fi === end - 1 && file[fi] === ''
141
+ }
142
+
143
+ // minimatch's #matchOne, of `file` as if cut at `end`.
144
+ function matchFlat(file, pattern, partial, fileIndex = 0, end = file.length) {
145
+ let fi = fileIndex
146
+ let pi = 0
147
+ for (; fi < end && pi < pattern.length; fi++, pi++) {
148
+ if (pattern[pi] === GLOBSTAR || !hit(pattern[pi], file[fi])) return false
149
+ }
150
+ return ended(file, pattern, fi, pi, partial, end)
151
+ }
152
+
153
+ // minimatch 5.1.6's matchOne: a `**` swallows each count of parts in turn,
154
+ // each try of what is left matched once here, which minimatch tries anew.
155
+ function matchOld(file, pattern, partial) {
156
+ const memo = new Map()
157
+ const from = (start, patternStart) => {
158
+ const key = start * (pattern.length + 1) + patternStart
159
+ if (!memo.has(key)) memo.set(key, step(start, patternStart))
160
+ return memo.get(key)
161
+ }
162
+ const step = (start, patternStart) => {
163
+ let fi = start
164
+ let pi = patternStart
165
+ for (; fi < file.length && pi < pattern.length; fi++, pi++) {
166
+ if (pattern[pi] !== GLOBSTAR) {
167
+ if (!hit(pattern[pi], file[fi])) return false
168
+ continue
169
+ }
170
+ if (pi + 1 === pattern.length) return !file.slice(fi).some(traversal)
171
+ let fr = fi
172
+ for (; fr < file.length; fr++) {
173
+ if (from(fr, pi + 1)) return true
174
+ if (traversal(file[fr])) break
175
+ }
176
+ return partial && fr === file.length
177
+ }
178
+ return ended(file, pattern, fi, pi, partial)
179
+ }
180
+ return from(0, 0)
181
+ }
182
+
183
+ // minimatch 5.1.9's and 10's: a head, a tail, and the sections between `**`s.
184
+ function matchNew(file, pattern, partial) {
185
+ if (!pattern.includes(GLOBSTAR)) return matchFlat(file, pattern, partial)
186
+ const first = pattern.indexOf(GLOBSTAR)
187
+ const last = pattern.lastIndexOf(GLOBSTAR)
188
+ const head = pattern.slice(0, first)
189
+ const body = partial ? pattern.slice(first + 1) : pattern.slice(first + 1, last)
190
+ const tail = partial ? [] : pattern.slice(last + 1)
191
+ if (head.length && !matchFlat(file, head, partial, 0, Math.min(file.length, head.length))) return false
192
+ const fileIndex = head.length
193
+ let tailMatch = 0
194
+ if (tail.length) {
195
+ if (tail.length + fileIndex > file.length) return false
196
+ const tailStart = file.length - tail.length
197
+ if (matchFlat(file, tail, partial, tailStart)) tailMatch = tail.length
198
+ else {
199
+ if (file.at(-1) !== '' || fileIndex + tail.length === file.length) return false
200
+ if (!matchFlat(file, tail, partial, tailStart - 1)) return false
201
+ tailMatch = tail.length + 1
202
+ }
203
+ }
204
+ if (!body.length) {
205
+ const rest = file.slice(fileIndex, file.length - tailMatch)
206
+ return !rest.some(traversal) && (partial || tailMatch > 0 || rest.length > 0)
207
+ }
208
+ const sections = [[]]
209
+ for (const part of body) {
210
+ if (part === GLOBSTAR) sections.push([])
211
+ else sections.at(-1).push(part)
212
+ }
213
+ // Each section's last start, from the parts before the section that
214
+ // mirrors it, as minimatch reckons it.
215
+ const before = sections.map((_, i) => sections.slice(0, i).reduce((sum, section) => sum + section.length, 0))
216
+ const after = sections.map((section, i) => file.length - tailMatch - (before[sections.length - 1 - i] + section.length))
217
+ return Boolean(matchSections(file, { sections, after, partial, sawTail: tailMatch > 0, memo: new Map() }, fileIndex, 0))
218
+ }
219
+
220
+ // Whether the sections from `index` match from `fileIndex`: minimatch's
221
+ // answer, false, null where no later start can do, or true; each pair
222
+ // reckoned once here. minimatch gives up past 200 sections, which more
223
+ // than 100 `**` are refused before reaching.
224
+ function matchSections(file, walk, fileIndex, index) {
225
+ const { sections, after, partial, sawTail, memo } = walk
226
+ if (index === sections.length) {
227
+ const rest = file.slice(fileIndex)
228
+ return !rest.some(traversal) && (sawTail || rest.length > 0)
229
+ }
230
+ const key = fileIndex * (sections.length + 1) + index
231
+ if (memo.has(key)) return memo.get(key)
232
+ let found = partial || null
233
+ const section = sections[index]
234
+ for (let at = fileIndex; at <= after[index]; at++) {
235
+ if (matchFlat(file, section, partial, at, Math.min(file.length, at + section.length))) {
236
+ const sub = matchSections(file, walk, at + section.length, index + 1)
237
+ if (sub !== false) {
238
+ found = sub
239
+ break
240
+ }
241
+ }
242
+ if (traversal(file[at])) {
243
+ found = false
244
+ break
245
+ }
246
+ }
247
+ memo.set(key, found)
248
+ return found
249
+ }
250
+
251
+ // The part minimatch makes of `[object Object]`, the path npm-packlist has
252
+ // for a `browser` or `main` that is an object: one character of a class.
253
+ export const OBJECT_5 = caseless(`^${NO_TRAVERSAL_5}(?=.)[object Object]$`)
254
+ const OBJECT_10 = caseless(`^${NO_TRAVERSAL_10}[object Object]$`)
255
+
256
+ // minimatch 10's levelOneOptimize: `**`s in a row as one, and a part
257
+ // before `..` taken out with it.
258
+ function levelOne(parts) {
259
+ const out = []
260
+ for (const part of parts) {
261
+ const prev = out.at(-1)
262
+ if (part === '**' && prev === '**') continue
263
+ if (part === '..' && prev && prev !== '..' && prev !== '.' && prev !== '**') out.pop()
264
+ else out.push(part)
265
+ }
266
+ return out.length === 0 ? [''] : out
267
+ }
268
+
269
+ // A rule as ignore-walk reads one, or as npm-packlist makes one, by the
270
+ // minimatch pnpm bundles: `5.1.6`, `5.1.9` or `10.2`.
271
+ function compile(pattern, minimatch, where) {
272
+ if (pattern.startsWith('#')) return { negate: false, globParts: [], test: () => false }
273
+ checkLength(pattern, where)
274
+ const bangs = pattern.match(/^!*/u)[0].length
275
+ const body = pattern.slice(bangs)
276
+ const five = minimatch !== '10.2'
277
+ if (body.replace(/^\//u, '') === '[object Object]') return fromParts(bangs % 2 === 1, [[...body.startsWith('/') ? [''] : [], five ? OBJECT_5 : OBJECT_10]], minimatch)
278
+ checkGlob(body, where, { parent: true })
279
+ const split = body.split(/\/+/u)
280
+ const parts = five ? split : levelOne(split)
281
+ checkParts(pattern, parts, where)
282
+ return fromParts(bangs % 2 === 1, [parts], minimatch)
283
+ }
284
+
285
+ // The rules of lines as ignore-walk reads them, an ignore file's or those
286
+ // npm-packlist hands it: each line trimmed, and none of a blank one or a
287
+ // comment. A rule given made is kept as it is.
288
+ export function rulesOf(lines, minimatch, where) {
289
+ return lines.flatMap((line) => (typeof line === 'string' ? line.split(/\r?\n/u).map((rule) => rule.trim()).filter((rule) => rule !== '' && !rule.startsWith('#')).map((rule) => compile(rule, minimatch, where)) : [line]))
290
+ }
291
+
292
+ // A path's parts, as minimatch splits it, and its last one that is not
293
+ // empty, which matchBase matches a pattern of one part against. Every rule
294
+ // splits the same few paths, so the last ones are kept.
295
+ const splits = new Map()
296
+ function splitOf(path) {
297
+ let found = splits.get(path)
298
+ if (found === undefined) {
299
+ const file = path.split(/\/+/u)
300
+ found = { file, base: [file.findLast(Boolean) ?? file[0]] }
301
+ if (splits.size >= 1024) splits.clear()
302
+ splits.set(path, found)
303
+ }
304
+ return found
305
+ }
306
+
307
+ // `globParts` are the patterns' parts, as text but for those given parsed;
308
+ // ignore-walk 8 reads them. `test(path, partial)` is whether one matches,
309
+ // with matchBase.
310
+ export function fromParts(negate, globParts, minimatch) {
311
+ const set = globParts.map((parts) => parts.map((part) => (typeof part === 'string' ? readPart(part, minimatch === '10.2') : part)))
312
+ const matchOne = minimatch === '5.1.6' ? matchOld : matchNew
313
+ const test = (path, partial = false) => {
314
+ if (path === '/' && partial) return true
315
+ const { file, base } = splitOf(path)
316
+ return set.some((pattern) => matchOne(pattern.length === 1 ? base : file, pattern, partial))
317
+ }
318
+ return { negate, globParts, set, test }
319
+ }
@@ -0,0 +1,299 @@
1
+ // The hoisting of @yarnpkg/nm 4.0.5 to one root (nm-hoist.js): which of the
2
+ // packages below it move up to it, one pass at a time.
3
+
4
+ export const REGULAR = 0
5
+ export const WORKSPACE = 1
6
+
7
+ const YES = 0
8
+ const NO = 1
9
+ const DEPENDS = 2
10
+
11
+ const getAliasedLocator = (node) => `${node.name}@${node.locator}`
12
+
13
+ // Depth first, as pnpm recurses, on a stack: each item of a frame's `items`
14
+ // goes to `visit(item, frame)`, which gives the frame to go into, if any;
15
+ // each frame done goes to `leave`.
16
+ export function depthFirst(frame, visit, leave) {
17
+ const stack = [frame]
18
+ while (stack.length > 0) {
19
+ const top = stack.at(-1)
20
+ const { value, done } = top.items.next()
21
+ if (done) {
22
+ stack.pop()
23
+ leave?.(top)
24
+ } else {
25
+ const next = visit(value, top)
26
+ if (next !== undefined) stack.push(next)
27
+ }
28
+ }
29
+ }
30
+
31
+ // Depth first from `start`, each node once: `visit(node, extra)` runs as a
32
+ // node is reached, and yields the children to go on to and what each is
33
+ // reached with.
34
+ export function walk(start, extra, visit, step) {
35
+ const seen = new Set()
36
+ const enter = (node, given) => {
37
+ step()
38
+ if (seen.has(node)) return undefined
39
+ seen.add(node)
40
+ return { items: visit(node, given) }
41
+ }
42
+ depthFirst(enter(start, extra), (value) => enter(...value))
43
+ }
44
+
45
+ // What `starts` reach through `next`, but where `skip` says.
46
+ export function reachable(starts, next, skip = () => false) {
47
+ const reached = new Set()
48
+ const pending = [...starts]
49
+ while (pending.length > 0) {
50
+ const item = pending.pop()
51
+ if (reached.has(item) || skip(item)) continue
52
+ reached.add(item)
53
+ pending.push(...next(item))
54
+ }
55
+ return reached
56
+ }
57
+
58
+ // A node's dependencies but its peers.
59
+ export function* regularDependencies(node) {
60
+ for (const dep of node.dependencies.values()) if (!node.peerNames.has(dep.name)) yield dep
61
+ }
62
+
63
+ // The names used below the root: zero-round, each hoisted dependency's own;
64
+ // later, what each name a node had hoisted from it resolves to on the path.
65
+ export function getZeroRoundUsedDependencies(rootNodePath, step) {
66
+ const used = new Map()
67
+ walk(rootNodePath.at(-1), undefined, function* (node) {
68
+ for (const dep of node.hoistedDependencies.values()) used.set(dep.name, dep)
69
+ for (const dep of regularDependencies(node)) yield [dep]
70
+ }, step)
71
+ return used
72
+ }
73
+
74
+ export function getUsedDependencies(rootNodePath, step) {
75
+ const used = new Map()
76
+ walk(rootNodePath.at(-1), new Set(), function* (node, hidden) {
77
+ for (const dep of node.hoistedDependencies.values()) {
78
+ if (hidden.has(dep.name)) continue
79
+ step(rootNodePath.length)
80
+ for (const onPath of rootNodePath) {
81
+ const resolved = onPath.dependencies.get(dep.name)
82
+ if (resolved) used.set(resolved.name, resolved)
83
+ }
84
+ }
85
+ const childrenHidden = new Set(node.dependencies.keys())
86
+ for (const dep of regularDependencies(node)) yield [dep, childrenHidden]
87
+ }, step)
88
+ return used
89
+ }
90
+
91
+ function decoupleGraphNode(parent, node, step) {
92
+ if (node.decoupled) return node
93
+ step(node.dependencies.size + node.originalDependencies.size + node.hoistedDependencies.size + 1)
94
+ const clone = {
95
+ ...node,
96
+ references: new Set(node.references),
97
+ dependencies: new Map(node.dependencies),
98
+ originalDependencies: new Map(node.originalDependencies),
99
+ hoistedDependencies: new Map(node.hoistedDependencies),
100
+ peerNames: new Set(node.peerNames),
101
+ decoupled: true,
102
+ }
103
+ const selfDep = clone.dependencies.get(node.name)
104
+ if (selfDep && selfDep.ident === clone.ident) clone.dependencies.set(node.name, clone)
105
+ parent.dependencies.set(clone.name, clone)
106
+ return clone
107
+ }
108
+
109
+ // Each package below `rootNode` by name and ident, with who depends on it,
110
+ // and as a peer, but the root's peers. pnpm sets no hoist priority.
111
+ export function buildPreferenceMap(rootNode, step) {
112
+ const preferenceMap = new Map()
113
+ const entryOf = (node) => {
114
+ const key = `${node.name}@${node.ident}`
115
+ if (!preferenceMap.has(key)) preferenceMap.set(key, { dependents: new Set(), peerDependents: new Set() })
116
+ return preferenceMap.get(key)
117
+ }
118
+ walk(rootNode, undefined, function* (node) {
119
+ for (const dep of node.dependencies.values()) {
120
+ if (!node.peerNames.has(dep.name)) {
121
+ entryOf(dep).dependents.add(node.ident)
122
+ yield [dep]
123
+ } else if (node !== rootNode) {
124
+ entryOf(dep).peerDependents.add(node.ident)
125
+ }
126
+ }
127
+ }, step)
128
+ return preferenceMap
129
+ }
130
+
131
+ // By name, the idents to try at the root, the most wanted first.
132
+ export function getHoistIdentMap(rootNode, preferenceMap) {
133
+ const identMap = new Map([[rootNode.name, [rootNode.ident]]])
134
+ for (const dep of regularDependencies(rootNode)) identMap.set(dep.name, [dep.ident])
135
+ const wanted = (key) => preferenceMap.get(key).dependents.size + preferenceMap.get(key).peerDependents.size
136
+ const keyList = [...preferenceMap.keys()].sort((key1, key2) => wanted(key2) - wanted(key1))
137
+ for (const key of keyList) {
138
+ const name = key.slice(0, key.indexOf('@', 1))
139
+ const ident = key.slice(name.length + 1)
140
+ if (rootNode.peerNames.has(name)) continue
141
+ let idents = identMap.get(name)
142
+ if (!idents) {
143
+ idents = []
144
+ identMap.set(name, idents)
145
+ }
146
+ if (!idents.includes(ident)) idents.push(ident)
147
+ }
148
+ return identMap
149
+ }
150
+
151
+ // A node's dependencies but its peers, each after the peers it has among
152
+ // them.
153
+ function getSortedRegularDependencies(node, step) {
154
+ step(node.dependencies.size + 1)
155
+ const dependencies = new Set()
156
+ const frameOf = (dep) => ({ dep, items: dep.peerNames.values() })
157
+ for (const top of regularDependencies(node)) {
158
+ const seenDeps = new Set([top])
159
+ depthFirst(frameOf(top), (peerName) => {
160
+ const peerDep = node.peerNames.has(peerName) ? undefined : node.dependencies.get(peerName)
161
+ if (!peerDep || dependencies.has(peerDep) || seenDeps.has(peerDep)) return undefined
162
+ seenDeps.add(peerDep)
163
+ step()
164
+ return frameOf(peerDep)
165
+ }, ({ dep }) => dependencies.add(dep))
166
+ }
167
+ return dependencies
168
+ }
169
+
170
+ // Whether a node of `node`'s name on the path, other than it, shadows it,
171
+ // which the parent then records.
172
+ function isShadowed(nodePath, node, shadowedNodes) {
173
+ for (let idx = nodePath.length - 1; idx >= 1; idx--) {
174
+ const parentDep = nodePath[idx].dependencies.get(node.name)
175
+ if (!parentDep || parentDep.ident === node.ident) continue
176
+ const parentNode = nodePath.at(-1)
177
+ if (!shadowedNodes.has(parentNode)) shadowedNodes.set(parentNode, new Set())
178
+ shadowedNodes.get(parentNode).add(node.name)
179
+ return true
180
+ }
181
+ return false
182
+ }
183
+
184
+ // The parent's packages `node`'s peers are, which have to go to the root
185
+ // before it, or null where a peer up the path is not the root's.
186
+ function peersDependOn(rootNode, nodePath, node) {
187
+ const dependsOn = new Set()
188
+ const checkList = new Set(node.peerNames)
189
+ for (let idx = nodePath.length - 1; idx >= 1; idx--) {
190
+ const parent = nodePath[idx]
191
+ for (const name of checkList) {
192
+ if (parent.peerNames.has(name) && parent.originalDependencies.has(name)) continue
193
+ const parentDepNode = parent.dependencies.get(name)
194
+ if (parentDepNode && rootNode.dependencies.get(name) !== parentDepNode) {
195
+ if (idx !== nodePath.length - 1) return null
196
+ dependsOn.add(parentDepNode)
197
+ }
198
+ checkList.delete(name)
199
+ }
200
+ }
201
+ return dependsOn
202
+ }
203
+
204
+ // Whether `node` goes to the root, in the order the checks are made, as
205
+ // one shadowing it is recorded as it is found. One that waits for its peers
206
+ // to go first does so whatever its hoisted dependencies say.
207
+ function getNodeHoistInfo(rootNode, nodePath, node, usedDependencies, hoistIdents, shadowedNodes, fastLookupPossible) {
208
+ const no = { isHoistable: NO }
209
+ if (node.ident === nodePath.at(-1).ident || node.dependencyKind === WORKSPACE || rootNode.peerNames.has(node.name)) return no
210
+ const usedDep = usedDependencies.get(node.name)
211
+ if ((usedDep && usedDep.ident !== node.ident) || isShadowed(nodePath, node, shadowedNodes) || hoistIdents.get(node.name) !== node.ident) return no
212
+ const dependsOn = peersDependOn(rootNode, nodePath, node)
213
+ if (dependsOn === null) return no
214
+ if (dependsOn.size > 0) return { isHoistable: DEPENDS, dependsOn }
215
+ const used = (dep) => usedDependencies.get(dep.name) || rootNode.dependencies.get(dep.name)
216
+ if (!fastLookupPossible && node.hoistedDependencies.values().some((dep) => used(dep)?.ident !== dep.ident)) return no
217
+ return { isHoistable: YES }
218
+ }
219
+
220
+ // hoistGraph's hoistNodeDependencies, of one parent: what of its own it
221
+ // hoists to the root, and the children it could not hoist, to go on into.
222
+ function hoistNodeDependencies(state, nodePath, parentNode, newNodes) {
223
+ const { rootNode, usedDependencies, hoistIdents, parentShadowedNodes, shadowedNodes, options, step } = state
224
+ const fullPath = [rootNode, ...nodePath, parentNode]
225
+ const dependantTree = new Map()
226
+ const hoistInfos = new Map()
227
+ for (const subDependency of getSortedRegularDependencies(parentNode, step)) {
228
+ step(fullPath.length + subDependency.peerNames.size + subDependency.hoistedDependencies.size)
229
+ const hoistInfo = getNodeHoistInfo(rootNode, fullPath, subDependency, usedDependencies, hoistIdents, shadowedNodes, options.fastLookupPossible)
230
+ hoistInfos.set(subDependency, hoistInfo)
231
+ if (hoistInfo.isHoistable === DEPENDS) {
232
+ for (const node of hoistInfo.dependsOn) {
233
+ const dependants = dependantTree.get(node.name) || new Set()
234
+ dependants.add(subDependency.name)
235
+ dependantTree.set(node.name, dependants)
236
+ }
237
+ }
238
+ }
239
+ // What cannot go, and what waits for it to.
240
+ const unhoistable = [...hoistInfos].filter(([, hoistInfo]) => hoistInfo.isHoistable === NO).map(([node]) => node)
241
+ const unhoistableNodes = reachable(unhoistable, (node) => [...dependantTree.get(node.name) ?? []].map((name) => parentNode.dependencies.get(name)))
242
+ for (const node of hoistInfos.keys()) {
243
+ if (unhoistableNodes.has(node)) continue
244
+ state.isGraphChanged = true
245
+ if (parentShadowedNodes.get(parentNode)?.has(node.name)) state.anotherRoundNeeded = true
246
+ parentNode.dependencies.delete(node.name)
247
+ parentNode.hoistedDependencies.set(node.name, node)
248
+ const hoistedNode = rootNode.dependencies.get(node.name)
249
+ if (hoistedNode) {
250
+ for (const reference of node.references) hoistedNode.references.add(reference)
251
+ } else if (rootNode.ident !== node.ident) {
252
+ rootNode.dependencies.set(node.name, node)
253
+ newNodes.add(node)
254
+ }
255
+ }
256
+ return { unhoistableNodes, children: getSortedRegularDependencies(parentNode, step) }
257
+ }
258
+
259
+ // hoistNodeDependencies from `start` down, through what it cannot hoist,
260
+ // each parent seen while what is below it is.
261
+ function hoistFrom(state, start, aliasedRootNodePathLocators, newNodes) {
262
+ const { seenNodes, step } = state
263
+ const call = (nodePath, aliasedLocatorPath, parentNode) => {
264
+ if (seenNodes.has(parentNode)) return undefined
265
+ step(aliasedLocatorPath.length + 1)
266
+ const nextAliasedLocatorPath = [...aliasedLocatorPath, getAliasedLocator(parentNode)]
267
+ const { unhoistableNodes, children } = hoistNodeDependencies(state, nodePath, parentNode, newNodes)
268
+ return { nodePath, nextAliasedLocatorPath, parentNode, unhoistableNodes, items: children.values() }
269
+ }
270
+ const into = (node, frame) => {
271
+ step(frame.nextAliasedLocatorPath.length)
272
+ if (!frame.unhoistableNodes.has(node) || frame.nextAliasedLocatorPath.includes(getAliasedLocator(node))) return undefined
273
+ seenNodes.add(frame.parentNode)
274
+ const next = call([...frame.nodePath, frame.parentNode], frame.nextAliasedLocatorPath, decoupleGraphNode(frame.parentNode, node, step))
275
+ if (next === undefined) seenNodes.delete(frame.parentNode)
276
+ return next
277
+ }
278
+ const first = call([], aliasedRootNodePathLocators, start)
279
+ if (first === undefined) return
280
+ depthFirst(first, into, ({ nodePath }) => {
281
+ if (nodePath.length > 0) seenNodes.delete(nodePath.at(-1))
282
+ })
283
+ }
284
+
285
+ // One pass of hoisting to the root of `rootNodePath`, from each package that
286
+ // newly reached it, down through what stays where it is.
287
+ export function hoistGraph(state) {
288
+ const { rootNode, rootNodePath, step } = state
289
+ let nextNewNodes = new Set(getSortedRegularDependencies(rootNode, step))
290
+ const aliasedRootNodePathLocators = rootNodePath.map(getAliasedLocator)
291
+ do {
292
+ const newNodes = nextNewNodes
293
+ nextNewNodes = new Set()
294
+ for (const dep of newNodes) {
295
+ if (dep.locator === rootNode.locator) continue
296
+ hoistFrom(state, decoupleGraphNode(rootNode, dep, step), aliasedRootNodePathLocators, nextNewNodes)
297
+ }
298
+ } while (nextNewNodes.size > 0)
299
+ }