@preventive/deptree 1.0.0-alpha.5 → 1.0.0-alpha.6

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 (75) hide show
  1. package/LICENSE-APACHE +202 -0
  2. package/npm.d.ts +288 -0
  3. package/npm.js +7 -0
  4. package/package.json +36 -10
  5. package/pnpm.d.ts +116 -22
  6. package/pnpm.js +2 -10
  7. package/soldeer.d.ts +13 -0
  8. package/soldeer.js +1 -7
  9. package/src/concurrent.js +16 -17
  10. package/src/error.js +5 -9
  11. package/src/glob.js +55 -0
  12. package/src/hash.js +64 -13
  13. package/src/manifest.js +52 -0
  14. package/src/matcher.js +59 -10
  15. package/src/mount.js +95 -44
  16. package/src/npm/bins.js +71 -0
  17. package/src/npm/compat.js +92 -0
  18. package/src/npm/dev-engines.js +52 -0
  19. package/src/npm/graph.js +68 -0
  20. package/src/npm/inputs.js +80 -0
  21. package/src/npm/manifests.js +138 -0
  22. package/src/npm/package.js +57 -0
  23. package/src/npm/ratio.js +34 -0
  24. package/src/npm/settings.js +67 -0
  25. package/src/npm/tree.js +136 -0
  26. package/src/npm/versions.js +20 -0
  27. package/src/{pnpm/npmrc.js → npmrc.js} +5 -11
  28. package/src/patch.js +21 -31
  29. package/src/pnpm/bins.js +32 -103
  30. package/src/pnpm/checks.js +8 -35
  31. package/src/pnpm/commands.js +49 -86
  32. package/src/pnpm/filename.js +10 -21
  33. package/src/pnpm/frozen.js +27 -70
  34. package/src/pnpm/gitignore.js +137 -0
  35. package/src/pnpm/glob.js +65 -0
  36. package/src/pnpm/graph.js +15 -43
  37. package/src/pnpm/hoist.js +65 -55
  38. package/src/pnpm/hook.js +26 -31
  39. package/src/pnpm/inputs.js +67 -40
  40. package/src/pnpm/install.js +72 -115
  41. package/src/pnpm/local.js +21 -40
  42. package/src/pnpm/minimatch.js +328 -0
  43. package/src/pnpm/npm-packlist.js +221 -0
  44. package/src/pnpm/overrides.js +10 -49
  45. package/src/pnpm/package.js +120 -0
  46. package/src/pnpm/packlist.js +168 -109
  47. package/src/pnpm/patches.js +18 -25
  48. package/src/pnpm/projects.js +63 -107
  49. package/src/pnpm/readers.js +46 -55
  50. package/src/pnpm/settings.js +60 -97
  51. package/src/pnpm/tree.js +134 -149
  52. package/src/pnpm/uptodate.js +16 -28
  53. package/src/pnpm/workspace.js +122 -131
  54. package/src/project.js +41 -0
  55. package/src/soldeer/config.js +8 -24
  56. package/src/soldeer/inputs.js +2 -5
  57. package/src/soldeer/tree.js +20 -56
  58. package/src/soldeer/zip.js +17 -36
  59. package/src/tarball.js +38 -142
  60. package/src/yarn1/bins.js +9 -19
  61. package/src/yarn1/compat.js +9 -28
  62. package/src/yarn1/hoist.js +53 -68
  63. package/src/yarn1/inputs.js +16 -51
  64. package/src/yarn1/manifest.js +8 -23
  65. package/src/yarn1/package.js +24 -63
  66. package/src/yarn1/peers.js +8 -15
  67. package/src/yarn1/requests.js +19 -37
  68. package/src/yarn1/resolve.js +35 -111
  69. package/src/yarn1/settings.js +14 -41
  70. package/src/yarn1/tree.js +67 -91
  71. package/yarn1.d.ts +30 -2
  72. package/yarn1.js +1 -8
  73. package/src/pnpm/project.js +0 -97
  74. package/src/yarn1/glob.js +0 -52
  75. /package/{LICENSE → LICENSE-MIT} +0 -0
package/src/pnpm/local.js CHANGED
@@ -1,20 +1,15 @@
1
- // Directories outside node_modules the tree links to or installs, read
2
- // from the project (project.js) where one is given: those local overrides
3
- // name, and every other a `link:` leads to that is no project and is under
4
- // the lockfile's directory. Each has to hold a package.json there, whose
5
- // bins take their names as pnpm links them. An override to a directory is
6
- // read only from a project given. One by `file:` has pnpm install the
7
- // directory as a package, of the files npm-packlist picks (packlist.js);
8
- // one to a tarball is refused. pnpm 12 holds one a project depends on to
9
- // the lockfile before it installs (createFreshnessCheck).
1
+ // Directories outside node_modules the tree links to or installs, read from the
2
+ // project given. Each must hold a package.json, whose bins take their names as
3
+ // pnpm links them.
10
4
 
11
5
  import { satisfies, valid, validRange } from '@preventive/upstream/semver.js'
12
6
  import { DeptreeError, difference, quote } from '../error.js'
13
- import { targetName, versionRange } from './frozen.js'
7
+ import { readManifest } from '../manifest.js'
8
+ import { readText, typeOf } from '../project.js'
9
+ import { parseSpec } from './frozen.js'
14
10
  import { localOf } from './overrides.js'
11
+ import { checkManifest } from './package.js'
15
12
  import { packDirectory } from './packlist.js'
16
- import { readText, typeOf } from './project.js'
17
- import { readManifest } from './projects.js'
18
13
 
19
14
  function manifestAt(project, dir, where) {
20
15
  const text = readText(project, `/${dir}/package.json`, where)
@@ -22,8 +17,7 @@ function manifestAt(project, dir, where) {
22
17
  return readManifest(text, where)
23
18
  }
24
19
 
25
- // `overrides` is listOverrides's. It gives back the directories `file:`
26
- // overrides have pnpm install.
20
+ // The directories `file:` overrides have pnpm install.
27
21
  export function checkLocalOverrides(overrides, project) {
28
22
  const installed = new Set()
29
23
  for (const { selector, local } of overrides) {
@@ -37,19 +31,16 @@ export function checkLocalOverrides(overrides, project) {
37
31
  return installed
38
32
  }
39
33
 
40
- // The package at the directory a `file:` dependency names, from `project`:
41
- // its files as npm-packlist picks them, and its package.json, which has
42
- // to be for the name the lockfile has; the lockfile has no version.
43
- export function readDirectoryPackage(project, pkg, where, major) {
34
+ // The lockfile records no version for a `file:` dependency's directory.
35
+ export function readDirectoryPackage(project, pkg, where, host) {
44
36
  const { directory } = pkg.resolution
45
37
  const manifest = manifestAt(project, directory, where)
46
38
  if (manifest.name !== pkg.name) throw new DeptreeError(`its package.json is for ${quote(String(manifest.name))}`, where)
47
- return { files: packDirectory(project, directory, manifest, major, where), manifest }
39
+ const files = packDirectory(project, directory, manifest, host.pnpm, where)
40
+ checkManifest(manifest, pkg, where, host.major)
41
+ return { files, manifest, local: true }
48
42
  }
49
43
 
50
- // By directory, the package.json of each directory the tree links to that
51
- // is no node of `nodes`, no project of `projects`, and under the
52
- // lockfile's directory, read from `project`; none without one.
53
44
  export function readLinked(links, nodes, projects, project) {
54
45
  const linked = new Map()
55
46
  if (project === undefined) return linked
@@ -60,29 +51,21 @@ export function readLinked(links, nodes, projects, project) {
60
51
  return linked
61
52
  }
62
53
 
63
- // Whether pnpm 12 takes a dependency on `name` by `spec`, a specifier not
64
- // to a directory, to be what the lockfile resolved it to, `target`: a
65
- // package of the name it asks for, `npm:` aliasing another, at a version
66
- // in its range, where it is a range and the version is one.
54
+ // Whether pnpm 12 takes `target` to be what `spec` asks for.
67
55
  function resolvesTo(name, spec, target, packages) {
68
56
  if (target.startsWith('link:')) return false
69
57
  const locked = packages[target]
70
- if (locked.name !== targetName(spec, name)) return false
71
- const range = versionRange(spec)
58
+ const { name: wanted, range } = parseSpec(spec, name)
59
+ if (locked.name !== wanted) return false
72
60
  const version = valid(locked.version ?? '')
73
61
  return validRange(range) === null || version === null || satisfies(version, range)
74
62
  }
75
63
 
76
64
  const optionalPeers = (meta) => Object.entries(meta ?? {}).filter(([, item]) => item?.optional === true).map(([name]) => name).sort()
77
65
 
78
- // pnpm 12 holds a directory a project depends on by `file:` to the
79
- // lockfile as it reads the directory's package.json, overridden, `read`:
80
- // each dependency the snapshot `pkg` has is one it asks for, a peer among
81
- // them, and each it asks for is there, resolved as it asks, an optional one
82
- // there or not; its peers are exactly what the lockfile records, and so is
83
- // which of them are optional. A `file:` or `link:` one is held to where it
84
- // leads by tarball.js's checkDependencies; a path alone, or `workspace:`,
85
- // is refused. `packages` is the lockfile's.
66
+ // `read` is the hooked package.json. A peer may be among the snapshot's
67
+ // dependencies and an optional one missing; a `file:` or `link:` one is left to
68
+ // package.js's checkDependencies.
86
69
  function checkFresh(read, pkg, packages, where) {
87
70
  const outdated = (why) => new DeptreeError(`the lockfile is not up to date with its package.json, which a frozen install of pnpm 12 refuses: ${why}`, where)
88
71
  const wanted = { dependencies: read.dependencies ?? {}, optionalDependencies: read.optionalDependencies ?? {} }
@@ -107,10 +90,8 @@ function checkFresh(read, pkg, packages, where) {
107
90
  if (JSON.stringify(optionalPeers(read.peerDependenciesMeta)) !== JSON.stringify(optionalPeers(pkg.peerDependenciesMeta))) throw outdated('which of its peers are optional is not the lockfile\'s')
108
91
  }
109
92
 
110
- // pnpm 12's check, before it installs, of each snapshot a project depends
111
- // on by a `file:` specifier to a directory: undefined for another pnpm.
112
- // It is given the node of a snapshot and its package.json as hook.js reads
113
- // it.
93
+ // pnpm 12's check, before it installs, of each snapshot a project depends on by
94
+ // a `file:` specifier to a directory.
114
95
  export function createFreshnessCheck(lockfile, major) {
115
96
  if (major < 12) return undefined
116
97
  const direct = new Set()
@@ -0,0 +1,328 @@
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
+ 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
+ export function part5(text) {
115
+ if (text === '**') return GLOBSTAR
116
+ if (!/[*?]/u.test(text)) return text === '' || foldless(text) ? text : partOf(text)
117
+ return partOf(text, { lookahead: true, traversal: /^[*?]/u.test(text) })
118
+ }
119
+
120
+ // minimatch 10's own tests of a part, which it runs in place of its regexp.
121
+ const FAST = [
122
+ [/^\*+$/u, () => (f) => f.length !== 0 && f !== '.' && f !== '..'],
123
+ [/^\*+([^!(*+?@[]*)$/u, ([, ext]) => (f) => f.toLowerCase().endsWith(ext.toLowerCase())],
124
+ [/^\?+([^!(*+?@[]*)?$/u, ([whole, ext]) => (f) => f.length === whole.length && f !== '.' && f !== '..' && (!ext || f.toLowerCase().endsWith(ext.toLowerCase()))],
125
+ [/^\*+\.\*+$/u, () => (f) => f !== '.' && f !== '..' && f.includes('.')],
126
+ [/^\.\*+$/u, () => (f) => f !== '.' && f !== '..' && f.startsWith('.')],
127
+ ]
128
+
129
+ function part10(text) {
130
+ if (text === '**') return GLOBSTAR
131
+ if (!/[*?]/u.test(text)) return text === '' || foldless(text) ? text : partOf(text)
132
+ const fast = FAST.find(([re]) => re.test(text))
133
+ if (fast !== undefined) return { test: fast[1](text.match(fast[0])) }
134
+ return partOf(text, { traversal: /^\.{0,2}[*?]/u.test(text), empty: !/^\*+$/u.test(text) })
135
+ }
136
+
137
+ const hit = (part, name) => (typeof part === 'string' ? name === part : part.test(name))
138
+ const traversal = (name) => name === '.' || name === '..'
139
+
140
+ function traversalFrom(file, start) {
141
+ for (let i = start; i < file.length; i++) if (traversal(file[i])) return true
142
+ return false
143
+ }
144
+
145
+ // How a match ends where file, as long as `end`, or pattern runs out at
146
+ // `fi` and `pi`.
147
+ function ended(file, pattern, fi, pi, partial, end = file.length) {
148
+ if (fi === end) return pi === pattern.length || partial
149
+ return pi === pattern.length && fi === end - 1 && file[fi] === ''
150
+ }
151
+
152
+ // minimatch's #matchOne, of `file` as if cut at `end`.
153
+ function matchFlat(file, pattern, partial, fileIndex = 0, end = file.length) {
154
+ let fi = fileIndex
155
+ let pi = 0
156
+ for (; fi < end && pi < pattern.length; fi++, pi++) {
157
+ if (pattern[pi] === GLOBSTAR || !hit(pattern[pi], file[fi])) return false
158
+ }
159
+ return ended(file, pattern, fi, pi, partial, end)
160
+ }
161
+
162
+ // minimatch 5.1.6's matchOne: a `**` swallows each count of parts in turn,
163
+ // each try of what is left matched once here, which minimatch tries anew.
164
+ function matchOld(file, pattern, partial) {
165
+ const memo = new Map()
166
+ const from = (start, patternStart) => {
167
+ const key = start * (pattern.length + 1) + patternStart
168
+ if (!memo.has(key)) memo.set(key, step(start, patternStart))
169
+ return memo.get(key)
170
+ }
171
+ const step = (start, patternStart) => {
172
+ let fi = start
173
+ let pi = patternStart
174
+ for (; fi < file.length && pi < pattern.length; fi++, pi++) {
175
+ if (pattern[pi] !== GLOBSTAR) {
176
+ if (!hit(pattern[pi], file[fi])) return false
177
+ continue
178
+ }
179
+ if (pi + 1 === pattern.length) return !traversalFrom(file, fi)
180
+ let fr = fi
181
+ for (; fr < file.length; fr++) {
182
+ if (from(fr, pi + 1)) return true
183
+ if (traversal(file[fr])) break
184
+ }
185
+ return partial && fr === file.length
186
+ }
187
+ return ended(file, pattern, fi, pi, partial)
188
+ }
189
+ return from(0, 0)
190
+ }
191
+
192
+ // minimatch 5.1.9's and 10's: a head, a tail, and the sections between `**`s.
193
+ function matchNew(file, pattern, partial) {
194
+ if (!pattern.includes(GLOBSTAR)) return matchFlat(file, pattern, partial)
195
+ const first = pattern.indexOf(GLOBSTAR)
196
+ const last = pattern.lastIndexOf(GLOBSTAR)
197
+ const head = pattern.slice(0, first)
198
+ const body = partial ? pattern.slice(first + 1) : pattern.slice(first + 1, last)
199
+ const tail = partial ? [] : pattern.slice(last + 1)
200
+ if (head.length && !matchFlat(file, head, partial, 0, Math.min(file.length, head.length))) return false
201
+ const fileIndex = head.length
202
+ let tailMatch = 0
203
+ if (tail.length) {
204
+ if (tail.length + fileIndex > file.length) return false
205
+ const tailStart = file.length - tail.length
206
+ if (matchFlat(file, tail, partial, tailStart)) tailMatch = tail.length
207
+ else {
208
+ if (file.at(-1) !== '' || fileIndex + tail.length === file.length) return false
209
+ if (!matchFlat(file, tail, partial, tailStart - 1)) return false
210
+ tailMatch = tail.length + 1
211
+ }
212
+ }
213
+ if (!body.length) {
214
+ const rest = file.slice(fileIndex, file.length - tailMatch)
215
+ return !rest.some(traversal) && (partial || tailMatch > 0 || rest.length > 0)
216
+ }
217
+ const sections = [[]]
218
+ for (const part of body) {
219
+ if (part === GLOBSTAR) sections.push([])
220
+ else sections.at(-1).push(part)
221
+ }
222
+ // Each section's last start, from the parts before the section that
223
+ // mirrors it, as minimatch reckons it.
224
+ const before = sections.map((_, i) => sections.slice(0, i).reduce((sum, section) => sum + section.length, 0))
225
+ const after = sections.map((section, i) => file.length - tailMatch - (before[sections.length - 1 - i] + section.length))
226
+ return Boolean(matchSections(file, { sections, after, partial, sawTail: tailMatch > 0, memo: new Map() }, fileIndex, 0))
227
+ }
228
+
229
+ // Whether the sections from `index` match from `fileIndex`: minimatch's
230
+ // answer, false, null where no later start can do, or true; each pair
231
+ // reckoned once here. minimatch gives up past 200 sections, which more
232
+ // than 100 `**` are refused before reaching.
233
+ function matchSections(file, walk, fileIndex, index) {
234
+ const { sections, after, partial, sawTail, memo } = walk
235
+ if (index === sections.length) {
236
+ const rest = file.slice(fileIndex)
237
+ return !rest.some(traversal) && (sawTail || rest.length > 0)
238
+ }
239
+ const key = fileIndex * (sections.length + 1) + index
240
+ if (memo.has(key)) return memo.get(key)
241
+ let found = partial || null
242
+ const section = sections[index]
243
+ for (let at = fileIndex; at <= after[index]; at++) {
244
+ if (matchFlat(file, section, partial, at, Math.min(file.length, at + section.length))) {
245
+ const sub = matchSections(file, walk, at + section.length, index + 1)
246
+ if (sub !== false) {
247
+ found = sub
248
+ break
249
+ }
250
+ }
251
+ if (traversal(file[at])) {
252
+ found = false
253
+ break
254
+ }
255
+ }
256
+ memo.set(key, found)
257
+ return found
258
+ }
259
+
260
+ // The part minimatch makes of `[object Object]`, the path npm-packlist has
261
+ // for a `browser` or `main` that is an object: one character of a class.
262
+ export const OBJECT_5 = caseless(`^${NO_TRAVERSAL_5}(?=.)[object Object]$`)
263
+ const OBJECT_10 = caseless(`^${NO_TRAVERSAL_10}[object Object]$`)
264
+
265
+ // minimatch 10's levelOneOptimize: `**`s in a row as one, and a part
266
+ // before `..` taken out with it.
267
+ function levelOne(parts) {
268
+ const out = []
269
+ for (const part of parts) {
270
+ const prev = out.at(-1)
271
+ if (part === '**' && prev === '**') continue
272
+ if (part === '..' && prev && prev !== '..' && prev !== '.' && prev !== '**') out.pop()
273
+ else out.push(part)
274
+ }
275
+ return out.length === 0 ? [''] : out
276
+ }
277
+
278
+ // A rule as ignore-walk reads one, or as npm-packlist makes one, by the
279
+ // minimatch pnpm bundles: `5.1.6`, `5.1.9` or `10.2`.
280
+ function compile(pattern, minimatch, where) {
281
+ if (pattern.startsWith('#')) return { negate: false, globParts: [], test: () => false }
282
+ checkLength(pattern, where)
283
+ const bangs = pattern.match(/^!*/u)[0].length
284
+ const body = pattern.slice(bangs)
285
+ const five = minimatch !== '10.2'
286
+ if (body.replace(/^\//u, '') === '[object Object]') return fromParts(bangs % 2 === 1, [[...body.startsWith('/') ? [''] : [], five ? OBJECT_5 : OBJECT_10]], minimatch)
287
+ checkGlob(body, where, { parent: true })
288
+ const split = body.split(/\/+/u)
289
+ const parts = five ? split : levelOne(split)
290
+ checkParts(pattern, parts, where)
291
+ return fromParts(bangs % 2 === 1, [parts], minimatch)
292
+ }
293
+
294
+ // The rules of lines as ignore-walk reads them, an ignore file's or those
295
+ // npm-packlist hands it: each line trimmed, and none of a blank one or a
296
+ // comment. A rule given made is kept as it is.
297
+ export function rulesOf(lines, minimatch, where) {
298
+ 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]))
299
+ }
300
+
301
+ // A path's parts, as minimatch splits it, and its last one that is not
302
+ // empty, which matchBase matches a pattern of one part against. Every rule
303
+ // splits the same few paths, so the last ones are kept.
304
+ const splits = new Map()
305
+ function splitOf(path) {
306
+ let found = splits.get(path)
307
+ if (found === undefined) {
308
+ const file = path.split(/\/+/u)
309
+ found = { file, base: [file.findLast(Boolean) ?? file[0]] }
310
+ if (splits.size >= 1024) splits.clear()
311
+ splits.set(path, found)
312
+ }
313
+ return found
314
+ }
315
+
316
+ // `globParts` are the patterns' parts, as text but for those given parsed;
317
+ // ignore-walk 8 reads them. `test(path, partial)` is whether one matches,
318
+ // with matchBase.
319
+ export function fromParts(negate, globParts, minimatch) {
320
+ const set = globParts.map((parts) => parts.map((part) => (typeof part === 'string' ? (minimatch === '10.2' ? part10(part) : part5(part)) : part)))
321
+ const matchOne = minimatch === '5.1.6' ? matchOld : matchNew
322
+ const test = (path, partial = false) => {
323
+ if (path === '/' && partial) return true
324
+ const { file, base } = splitOf(path)
325
+ return set.some((pattern) => matchOne(pattern.length === 1 ? base : file, pattern, partial))
326
+ }
327
+ return { negate, globParts, set, test }
328
+ }
@@ -0,0 +1,221 @@
1
+ // The walks of npm-packlist over ignore-walk that pnpm 9 and 10 (npm-packlist
2
+ // 5.1.3, ignore-walk 5) and pnpm 11 (npm-packlist 10.0.4, ignore-walk 8)
3
+ // run over a directory, kept to their steps, odd ones and all: a walker of a
4
+ // directory asks its parent of each entry by a path from there, and reads
5
+ // the ignore files among its entries, in the order ignoreFiles lists them.
6
+ // `view` reads the directory, and refuses what is not followed here.
7
+
8
+ import { basename, dirname, join, normalize } from '@preventive/vfs/path.js'
9
+ import { quote } from '../error.js'
10
+ import { glob } from './glob.js'
11
+ import { caseless, fromParts, rulesOf } from './minimatch.js'
12
+
13
+ const DEFAULTS = ['.npmignore', '.gitignore', '**/.git', '**/.svn', '**/.hg', '**/CVS', '**/.git/**', '**/.svn/**', '**/.hg/**', '**/CVS/**', '/.lock-wscript', '/.wafpickle-*', '/build/config.gypi', 'npm-debug.log', '**/.npmrc', '.*.swp', '.DS_Store', '**/.DS_Store/**', '._*', '**/._*/**', '*.orig']
14
+
15
+ const BUILTIN = Symbol('built-in rules')
16
+ const NECESSARY = Symbol('necessary rules')
17
+ const STRICT = Symbol('strict rules')
18
+
19
+ const MUST_HAVE_NAMES = ['readme', 'copying', 'license', 'licence']
20
+ const MUST_HAVE_RE = caseless(String.raw`^(?:readme|copying|license|licence)(?:\..*[^~$])?$`)
21
+ const NO_TRAVERSAL_5 = String.raw`(?!(?:^|\/)\.{1,2}(?:$|\/))`
22
+
23
+ // npm-packlist 5's `@(readme|copying|license|licence){,.*[^~$]}`, as glob
24
+ // and minimatch 5 read it: two patterns of one part.
25
+ const MUST_HAVES_5 = ['', String.raw`\.[^/]*?[^~$]`].map((rest) => [caseless(`^${NO_TRAVERSAL_5}(?=.)(?:${MUST_HAVE_NAMES.join('|')})${rest}$`)])
26
+
27
+ // npm-packlist 10's `!/readme{,.*[^~$]}` and the like, as minimatch 10 reads them.
28
+ const MUST_HAVES_10 = MUST_HAVE_NAMES.map((name) => fromParts(true, ['', String.raw`\.[^/]*?[^~$]`].map((rest) => ['', caseless(`^${name}${rest}$`)]), '10.2'))
29
+
30
+ const relOf = (walker, entry) => (walker.rel === '' ? entry : `${walker.rel}/${entry}`)
31
+
32
+ export function readRules(view, rel, minimatch, where) {
33
+ const here = `${where}: ${quote(rel)}`
34
+ return rulesOf([view.text(rel, here)], minimatch, here)
35
+ }
36
+
37
+ // What ignore-walk 5 and 8 make of one rule against an entry.
38
+ function ruleMatches(rule, entry, partial, base) {
39
+ const relative = base !== undefined && rule.globParts.some((part) => part.length <= (part.at(-1) ? 1 : 2))
40
+ return rule.test(`/${entry}`) || rule.test(entry) || (partial && (
41
+ rule.test(`/${entry}/`) || rule.test(`${entry}/`) || (rule.negate && (rule.test(`/${entry}`, true) || rule.test(entry, true)))
42
+ || (relative && (rule.test(`/${base}/`) || rule.test(`${base}/`) || (rule.negate && (rule.test(`/${base}`, true) || rule.test(base, true)))))))
43
+ }
44
+
45
+ function applyRules(walker, entry, partial, included, base) {
46
+ let kept = included
47
+ for (const file of walker.ignoreFiles) {
48
+ for (const rule of walker.rules.get(file) ?? []) {
49
+ if (rule.negate !== kept && ruleMatches(rule, entry, partial, base)) kept = rule.negate
50
+ }
51
+ }
52
+ return kept
53
+ }
54
+
55
+ // npm-packlist 5's pathHasPkg: a package's directory in node_modules.
56
+ function packageIn(entry) {
57
+ if (!entry.startsWith('node_modules/')) return false
58
+ const [first, ...rest] = entry.slice('node_modules/'.length).split('/', 2)
59
+ return first !== '' && (!first.startsWith('@') || rest.length === 1)
60
+ }
61
+
62
+ // npm-packlist 5's filterEntry over ignore-walk 5's.
63
+ function filter5(walker, entry, partial) {
64
+ const { isProject } = walker
65
+ if (!isProject && /^node_modules(?:$|\/)/iu.test(walker.rel)) return filter5(walker.parent, `${walker.basename}/${entry}`, partial)
66
+ if (isProject && (entry === 'node_modules' || packageIn(entry))) return false
67
+ if ((isProject && entry === 'package.json') || MUST_HAVE_RE.test(entry) || (isProject && entry === 'npm-shrinkwrap.json')) return true
68
+ if (isProject && entry === 'package-lock.json') return false
69
+ const included = isProject ? true : filter5(walker.parent, `${walker.basename}/${entry}`, partial)
70
+ return applyRules(walker, entry, partial, included)
71
+ }
72
+
73
+ // ignore-walk 8's filterEntry, which npm-packlist 10 keeps.
74
+ function filter10(walker, entry, partial, base) {
75
+ let included = true
76
+ if (walker.parent !== undefined) {
77
+ included = filter10(walker.parent, `${walker.basename}/${entry}`, partial, base ?? entry)
78
+ if (!included && !walker.exact) return false
79
+ }
80
+ return applyRules(walker, entry, partial, included, base)
81
+ }
82
+
83
+ // A walk of one directory: its ignore files read, its entries filtered,
84
+ // then each file kept and each directory walked. `entries` are its own, or,
85
+ // for npm-packlist 5's root where package.json has `files`, what those take.
86
+ function visit(view, walker, entries, engine, result) {
87
+ if (entries.length === 0) return
88
+ for (const entry of entries) {
89
+ if (walker.ignoreFiles.includes(entry)) engine.readIgnore(walker, entry)
90
+ }
91
+ if (engine.major >= 11 && walker.rules.has('package.json')) walker.rules.delete('.npmignore')
92
+ if (walker.rules.has('.npmignore') || (engine.major >= 11 && walker.rules.has('package.json'))) walker.rules.delete('.gitignore')
93
+ for (const entry of entries) {
94
+ const file = engine.filter(walker, entry, false)
95
+ const dir = engine.filter(walker, entry, true)
96
+ if ((!file && !dir) || entry.includes('*')) continue
97
+ const rel = relOf(walker, entry)
98
+ if (view.type(rel) !== 'directory') {
99
+ if (file) result.add(rel)
100
+ } else if (dir) visit(view, engine.child(walker, entry, rel, file), view.entries(rel), engine, result)
101
+ }
102
+ }
103
+
104
+ // npm-normalize-package-bin 2's bin: an object, or nothing.
105
+ function normalizeBin(pkg) {
106
+ const { bin } = pkg
107
+ const named = typeof bin === 'string' ? (pkg.name ? { [pkg.name]: bin } : {})
108
+ : Array.isArray(bin) ? Object.fromEntries(bin.map((path) => [basename(String(path)), path]))
109
+ : bin !== null && typeof bin === 'object' ? bin : {}
110
+ const clean = Object.entries(named).map(([key, path]) => [
111
+ join('/', basename(key.replaceAll(/[:\\]/gu, '/'))).slice(1),
112
+ typeof path === 'string' ? join('/', path).replaceAll('\\', '/').slice(1) : '',
113
+ ]).filter(([key, path]) => key !== '' && path !== '')
114
+ return clean.length > 0 ? Object.fromEntries(clean) : undefined
115
+ }
116
+
117
+ // npm-packlist 5's mustHaveFilesFromPackage, of `pkg` with its bin normalized.
118
+ const mustHaves5 = (pkg) => [
119
+ ...[pkg.browser, pkg.main, ...Object.values(pkg.bin ?? {})].filter(Boolean).map((path) => `/${path}`),
120
+ '/package.json', '/npm-shrinkwrap.json', '!/package-lock.json', MUST_HAVES_5,
121
+ ]
122
+
123
+ // npm-packlist 5's root entries where package.json has `files`: what glob
124
+ // takes of each pattern in turn, a `!` one's taken back out.
125
+ function filesEntries5(view, pkg, where) {
126
+ const taken = new Set()
127
+ const negates = new Set()
128
+ for (const pattern of new Set([...pkg.files, ...mustHaves5(pkg)])) {
129
+ const negate = typeof pattern === 'string' && pattern.match(/^!*/u)[0].length % 2 === 1
130
+ const body = typeof pattern === 'string' ? pattern.replace(/^!+/u, '').replace(/^\.?\/+/u, '') : pattern
131
+ for (const found of glob(view, body, where)) {
132
+ const path = found.replace(/\/+$/u, '')
133
+ ;(negate ? taken : negates).delete(path)
134
+ ;(negate ? negates : taken).add(path)
135
+ }
136
+ }
137
+ pkg.files = [...taken, ...[...negates].map((path) => `!${path}`)]
138
+ return [...new Set([...taken].map((path) => path.replace(/^\/+/u, '')))]
139
+ }
140
+
141
+ // `manifest` is undefined where npm-packlist fails to parse package.json,
142
+ // which it then reads no rules of. `minimatch` is the version pnpm bundles.
143
+ export function pack10(view, manifest, where, minimatch) {
144
+ const pkg = manifest === undefined ? undefined : { ...structuredClone(manifest), bin: normalizeBin(manifest) }
145
+ const files = Array.isArray(pkg?.files)
146
+ const rules = new Map([[BUILTIN, rulesOf([...DEFAULTS, '/package-lock.json', '/yarn.lock', '/pnpm-lock.yaml', '/archived-packages/**'], minimatch, where)]])
147
+ const root = { rel: '', isProject: true, rules, ignoreFiles: [BUILTIN, 'package.json', '.npmignore', '.gitignore', NECESSARY] }
148
+ const own = view.entries('').filter((entry) => entry !== '.git' && entry !== 'node_modules')
149
+ const engine = {
150
+ major: 10,
151
+ filter: filter5,
152
+ readIgnore(walker, entry) {
153
+ if (entry !== 'package.json') walker.rules.set(entry, readRules(view, relOf(walker, entry), minimatch, where))
154
+ else if (walker.isProject && files) walker.rules.set(entry, rulesOf(pkg.files.map((path) => `!${path}`), minimatch, where))
155
+ else if (walker.isProject && pkg !== undefined) walker.rules.set(NECESSARY, rulesOf(mustHaves5(pkg).map((path) => (Array.isArray(path) ? fromParts(true, path, minimatch) : `!${path}`)), minimatch, where))
156
+ },
157
+ child: (walker, entry, rel) => ({ rel, parent: walker, basename: basename(rel), isProject: false, rules: new Map(), ignoreFiles: walker.ignoreFiles }),
158
+ }
159
+ const result = new Set()
160
+ visit(view, root, files && own.includes('package.json') ? filesEntries5(view, pkg, where) : own, engine, result)
161
+ return result
162
+ }
163
+
164
+ // npm-packlist 10's processPackage: package.json's rules, and the strict ones.
165
+ // pnpm from 11.28 keeps a package.yaml and a package.json5 too, by `alternates`.
166
+ function processPackage(view, walker, pkg, where, alternates) {
167
+ const ignores = []
168
+ const strict = ['/.git', '!/package.json', ...MUST_HAVES_10, '/.git', '/node_modules', '.npmrc', '/package-lock.json', '/yarn.lock', '/pnpm-lock.yaml', '/bun.lockb']
169
+ for (const entry of pkg.files ?? []) {
170
+ let file = entry.startsWith('./') ? entry.slice(1) : entry
171
+ if (file.endsWith('/*')) file += '*'
172
+ const type = view.type(file.replace(/^!+/u, ''))
173
+ if (type === 'file') {
174
+ strict.unshift(`!${file}`)
175
+ walker.requiredFiles.push(file.startsWith('/') ? file.slice(1) : file)
176
+ } else if (type === 'directory') ignores.push(`!${file}`, `!${file}/**`)
177
+ else ignores.push(`!${file}`)
178
+ }
179
+ if (pkg.files) walker.rules.set('package.json', rulesOf(['*', ...ignores], '10.2', where))
180
+ const fields = [pkg.browser, pkg.main, ...pkg.bin === undefined || pkg.bin === null ? [] : Object.values(pkg.bin)].filter(Boolean).map((path) => `!/${path}`)
181
+ walker.rules.set(STRICT, rulesOf([...strict, ...fields, ...alternates ? ['!/package.yaml', '!/package.json5'] : []], '10.2', where))
182
+ }
183
+
184
+ // pnpm's normalizePackage: `./` taken off main, browser and each bin.
185
+ const stripDotSlash = (path) => (typeof path === 'string' ? path.replace(/^\.[/\\]/u, '') : path)
186
+
187
+ export function pack11(view, manifest, where, alternates) {
188
+ const { bin } = manifest
189
+ const pkg = {
190
+ ...manifest,
191
+ main: stripDotSlash(manifest.main),
192
+ browser: stripDotSlash(manifest.browser),
193
+ bin: bin !== null && typeof bin === 'object' ? Object.fromEntries(Object.entries(bin).map(([key, path]) => [key, stripDotSlash(path)])) : stripDotSlash(bin),
194
+ }
195
+ const defaults = rulesOf([...DEFAULTS, '/archived-packages/**'], '10.2', where)
196
+ const walkerOf = (fields) => {
197
+ const made = { rules: new Map([[BUILTIN, defaults]]), requiredFiles: [], ...fields }
198
+ if (!made.isPackage) made.rules.set(STRICT, rulesOf(['/.git', ...made.requiredFiles.map((file) => `!${file}`)], '10.2', where))
199
+ return made
200
+ }
201
+ const root = walkerOf({ rel: '', isPackage: true, ignoreFiles: [BUILTIN, 'package.json', '.npmignore', '.gitignore', STRICT] })
202
+ const engine = {
203
+ major: 11,
204
+ filter: filter10,
205
+ readIgnore(walker, entry) {
206
+ if (entry === 'package.json' && walker.isPackage) processPackage(view, walker, pkg, where, alternates)
207
+ else walker.rules.set(entry, readRules(view, relOf(walker, entry), '10.2', where))
208
+ },
209
+ child: (parent, entry, rel, file) => walkerOf({
210
+ rel,
211
+ parent,
212
+ basename: entry,
213
+ exact: file || filter10(parent, `${entry}/`, false),
214
+ ignoreFiles: [BUILTIN, '.npmignore', '.gitignore', STRICT],
215
+ requiredFiles: parent.requiredFiles.map(normalize).filter((path) => dirname(path) === entry).map((path) => basename(path)),
216
+ }),
217
+ }
218
+ const result = new Set()
219
+ visit(view, root, view.entries(''), engine, result)
220
+ return result
221
+ }