@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
@@ -1,40 +1,13 @@
1
- // Overrides as pnpm 10 reads them. The root package.json gives Yarn's
2
- // `resolutions` and its own `pnpm.overrides`, the second winning a
3
- // selector both name; where the two name any, they are the overrides,
4
- // and pnpm-workspace.yaml's are passed over whole, as `pnpm install`
5
- // spreads the package.json's settings over the rest. Only where the
6
- // package.json names none are pnpm-workspace.yaml's `overrides` read. In
7
- // each, a value of `$name` is the specifier
8
- // the root package.json gives its own dependency `name` (optional over
9
- // regular over dev), and one of `catalog:` or `catalog:<name>` is what
10
- // that catalog gives the package the selector targets. A selector is a
11
- // package, `name` or `name@range`, and may lead with its parent and a
12
- // `>`: `bar@2>foo@1`. Anything pnpm cannot read — a selector it cannot
13
- // parse, a `$name` with no such dependency, a catalog without the entry,
14
- // or with one it refuses — is refused the same.
15
- //
16
- // The overrides are what the lockfile was resolved with, which is where
17
- // they did their work: with a frozen lockfile pnpm only holds them to the
18
- // lockfile's `overrides` (uptodate.js), and resolves anew where they
19
- // differ.
20
- //
21
- // An override to a directory — `link:`, `file:` or a path alone, such as
22
- // `./vendor/foo` — names it from the lockfile's directory, and is read
23
- // only from a Vfs given that holds it (tree.js): one outside the lockfile's
24
- // directory, or from the root or the home directory, is refused.
25
- //
26
- // pnpm 11 reads them from pnpm-workspace.yaml alone, trims each selector,
27
- // takes a catalog's `workspace:` entry, and reads `name@` with an exact
28
- // version as converging: a dependency on `name` whose range takes that
29
- // version is given it, where no other override is chosen. It refuses one
30
- // with a parent and an empty range, and one whose version is not exact.
1
+ // Overrides as pnpm's parseOverrides reads them. A frozen install holds them
2
+ // only to the lockfile's `overrides`, which they were resolved with. pnpm 11
3
+ // reads `name@` and an exact version as converging: a dependency on `name`
4
+ // whose range takes that version is given it where no override is chosen.
31
5
 
32
6
  import { valid } from '@preventive/upstream/semver.js'
33
7
  import { join } from '@preventive/vfs/path.js'
34
8
  import { DeptreeError, quote } from '../error.js'
35
9
 
36
- // validate-npm-package-name 5's validForOldPackages, which pnpm reads a
37
- // selector's name by: what npm ever took as a name.
10
+ // From validate-npm-package-name 5, by which pnpm reads a selector's name.
38
11
  const SCOPED = /^(?:@([^/]+?)\/)?([^/]+?)$/u
39
12
  export function validForOldPackages(name) {
40
13
  if (name === '' || name.startsWith('.') || name.startsWith('_') || name.trim() !== name) return false
@@ -44,16 +17,14 @@ export function validForOldPackages(name) {
44
17
  return m !== null && encodeURIComponent(m[1]) === m[1] && encodeURIComponent(m[2]) === m[2]
45
18
  }
46
19
 
47
- // @pnpm/parse-wanted-dependency: a name, where what comes before the first
48
- // `@` past the start is one, then what follows it.
20
+ // @pnpm/parse-wanted-dependency.
49
21
  function parseWanted(raw) {
50
22
  const at = raw.indexOf('@', 1)
51
23
  const name = at === -1 ? raw : raw.slice(0, at)
52
24
  return validForOldPackages(name) ? { name, range: at === -1 ? undefined : raw.slice(at + 1) } : undefined
53
25
  }
54
26
 
55
- // A `>` after anything but a space, `|` or `@` splits the parent from the
56
- // package, as pnpm's DELIMITER_REGEX has it; `foo@>1` is one package.
27
+ // pnpm's DELIMITER_REGEX: `foo@>1` is one package, `bar@2>foo@1` two.
57
28
  const DELIMITER = /[^ @|]>/u
58
29
 
59
30
  export function parseSelector(selector, where) {
@@ -65,8 +36,7 @@ export function parseSelector(selector, where) {
65
36
  return parsed.length === 1 ? { target: parsed[0] } : { parent: parsed[0], target: parsed[1] }
66
37
  }
67
38
 
68
- // A layer's overrides with each `$name` replaced; `manifest` is the root
69
- // package.json as parsed.
39
+ // A layer's overrides with each `$name` replaced from the root package.json.
70
40
  export function replaceReferences(overrides, manifest, where) {
71
41
  const own = { ...manifest.devDependencies, ...manifest.dependencies, ...manifest.optionalDependencies }
72
42
  const replaced = Object.create(null)
@@ -82,15 +52,11 @@ export function replaceReferences(overrides, manifest, where) {
82
52
 
83
53
  const CATALOG = 'catalog:'
84
54
 
85
- // The catalog a `catalog:` specifier names, `default` where it names none,
86
- // or undefined for another specifier.
87
55
  export const catalogOf = (spec) => (spec.startsWith(CATALOG) ? spec.slice(CATALOG.length).trim() || 'default' : undefined)
88
56
 
89
- // The entry catalog `catalog` of `catalogs` has for `name`, if any.
90
57
  export const catalogEntry = (catalogs, catalog, name) => (Object.hasOwn(catalogs, catalog) && Object.hasOwn(catalogs[catalog], name) ? catalogs[catalog][name] : undefined)
91
58
 
92
- // @pnpm/catalogs.resolver's resolveFromCatalog: the specifier a catalog
93
- // gives `name`, where `spec` asks for one.
59
+ // @pnpm/catalogs.resolver's resolveFromCatalog.
94
60
  function fromCatalog(catalogs, spec, name, where, major) {
95
61
  const catalog = catalogOf(spec)
96
62
  if (catalog === undefined) return spec
@@ -103,8 +69,7 @@ function fromCatalog(catalogs, spec, name, where, major) {
103
69
  return found
104
70
  }
105
71
 
106
- // The directory an override names, as pnpm's local resolver reads a
107
- // specifier, and by which protocol, or undefined for one that is none.
72
+ // As pnpm's local resolver reads a specifier.
108
73
  export function localOf(spec, where) {
109
74
  const protocol = ['file:', 'link:'].find((prefix) => spec.startsWith(prefix)) ?? (/^(?:[./]|~\/)/u.test(spec) ? '' : undefined)
110
75
  if (protocol === undefined) return undefined
@@ -114,10 +79,6 @@ export function localOf(spec, where) {
114
79
  return { protocol, dir }
115
80
  }
116
81
 
117
- // The overrides pnpm installs with, in order, as its parseOverrides has
118
- // them: each selector parsed, and its specifier with any catalog resolved,
119
- // and `local` the directory it names, where it names one. By selector,
120
- // they are what the lockfile's `overrides` is held to.
121
82
  export function listOverrides(overrides, catalogs, major = 10) {
122
83
  const seen = new Set()
123
84
  return Object.entries(overrides ?? {}).map(([raw, given]) => {
@@ -0,0 +1,120 @@
1
+ // A registry package as pnpm installs it: its tarball read as @pnpm/store.cafs
2
+ // reads it, and held to what npm packs, more than pnpm holds it to. A
3
+ // dependency the lockfile left out of a snapshot would leave the package to
4
+ // find it wherever it is hoisted, if anywhere.
5
+
6
+ import { normalize } from '@preventive/vfs/path.js'
7
+ import { DeptreeError, quote } from '../error.js'
8
+ import { checkNesting } from '../manifest.js'
9
+ import { fetchTarball, sameFile } from '../tarball.js'
10
+ import { localOf } from './overrides.js'
11
+
12
+ function nameOf(stored) {
13
+ const slash = stored.indexOf('/')
14
+ let name = slash === -1 ? stored : stored.slice(slash + 1)
15
+ if (name.includes('./')) name = normalize(`/${name}`).slice(1)
16
+ return name.replaceAll('//', '/')
17
+ }
18
+
19
+ // pnpm 9, 10 and 11 drop a name's first segment at a `\` as at a `/` where the
20
+ // ustar header holds the name, and pnpm 10 and 11, where a name has a `.\`,
21
+ // turn each `\` into a `/` before normalizing it; pnpm 12 takes every `\` for
22
+ // a separator, and fails on a `..` that makes.
23
+ function filesOf(entries, where) {
24
+ const files = new Map()
25
+ const tops = new Set()
26
+ for (const entry of entries) {
27
+ if (entry.storedName.includes('\\')) throw new DeptreeError(`${quote(entry.storedName)} has a backslash, which pnpm may take for a separator, and that is not supported`, where)
28
+ if (entry.type === 'directory') continue
29
+ if (entry.type !== 'file') throw new DeptreeError(`${quote(entry.name)} is a ${entry.type}, which is not supported`, where)
30
+ tops.add(entry.storedName.slice(0, Math.max(entry.storedName.indexOf('/'), 0)))
31
+ if (tops.size > 1 || tops.has('')) throw new DeptreeError('the tarball has files under more than one directory, or at its top', where)
32
+ const name = nameOf(entry.storedName)
33
+ if (name === '' || name.split('/').some((segment) => segment === '' || segment === '.' || segment === '..')) {
34
+ throw new DeptreeError(`${quote(entry.storedName)} names no file in the package`, where)
35
+ }
36
+ const file = { data: entry.data, mode: (entry.mode & 0o111) === 0 ? 0o644 : 0o755 }
37
+ const earlier = files.get(name)
38
+ if (earlier !== undefined && !sameFile(earlier, file)) throw new DeptreeError(`${quote(name)} is in the tarball twice`, where)
39
+ files.set(name, file)
40
+ }
41
+ return files
42
+ }
43
+
44
+ const decoder = new TextDecoder('utf-8', { fatal: true })
45
+ const same = (a, b) => JSON.stringify(a) === JSON.stringify(b)
46
+ const names = (value) => Object.keys(value ?? {})
47
+
48
+ // Undefined where `bin` names none beside a directories.bin: pnpm resolves that
49
+ // as having no bins and pnpm 11 rewrites a snapshot as having some, so bins are
50
+ // linked as the lockfile has it.
51
+ function hasBin({ bin, directories }, major) {
52
+ if (major >= 12) {
53
+ const named = typeof bin === 'string' ? bin !== '' : bin !== null && typeof bin === 'object' && !Array.isArray(bin) && Object.keys(bin).length > 0
54
+ return named || (directories !== null && typeof directories === 'object' && !Array.isArray(directories) && typeof directories.bin === 'string' && directories.bin !== '')
55
+ }
56
+ if (bin == null) return Boolean(directories?.bin)
57
+ if (bin && Object.keys(bin).length > 0) return true
58
+ return directories?.bin ? undefined : false
59
+ }
60
+
61
+ function readManifest(files, pkg, where) {
62
+ const file = files.get('package.json')
63
+ if (file === undefined) throw new DeptreeError('the tarball has no package.json', where)
64
+ let manifest
65
+ try {
66
+ manifest = JSON.parse(decoder.decode(file.data))
67
+ } catch {
68
+ throw new DeptreeError('package.json is not JSON', where)
69
+ }
70
+ if (manifest === null || typeof manifest !== 'object' || Array.isArray(manifest)) throw new DeptreeError('package.json is not an object', where)
71
+ checkNesting(manifest, `${where}: package.json`)
72
+ if (manifest.name !== pkg.name || manifest.version !== pkg.version) throw new DeptreeError(`package.json is for ${quote(`${manifest.name}@${manifest.version}`)}`, where)
73
+ return manifest
74
+ }
75
+
76
+ export function checkManifest(manifest, pkg, where, major) {
77
+ for (const field of ['os', 'cpu', 'libc']) {
78
+ if (!same(manifest[field], pkg[field])) throw new DeptreeError(`package.json's ${field} is not the lockfile's`, where)
79
+ }
80
+ const has = hasBin(manifest, major)
81
+ if (has !== undefined && has !== pkg.hasBin) throw new DeptreeError(`package.json ${pkg.hasBin ? 'has no bins, and the lockfile says it has' : 'has bins, and the lockfile says it has none'}`, where)
82
+ if (!same(listed(bundledOf(manifest)), listed(pkg.bundledDependencies))) throw new DeptreeError('package.json bundles other than the lockfile says', where)
83
+ }
84
+
85
+ const bundledOf = (manifest) => manifest.bundleDependencies ?? manifest.bundledDependencies
86
+
87
+ // pnpm 10 writes an empty list of bundled dependencies, pnpm 11 none.
88
+ const listed = (bundled) => (Array.isArray(bundled) && bundled.length === 0 ? undefined : bundled)
89
+
90
+ // `read` is the package.json as hook.js's hook has it, and `packages` the
91
+ // lockfile's, by which a `file:` target is the directory it resolves to.
92
+ export function checkDependencies(manifest, read, pkg, packages, where) {
93
+ const bundled = bundledOf(manifest)
94
+ const given = new Set([...names(pkg.dependencies), ...names(pkg.optionalDependencies)])
95
+ for (const name of [...names(read.dependencies), ...names(read.optionalDependencies)]) {
96
+ if (bundled === true || (Array.isArray(bundled) && bundled.includes(name)) || given.has(name)) continue
97
+ throw new DeptreeError(`package.json asks for ${quote(name)}, which the lockfile does not give it`, where)
98
+ }
99
+ for (const [name, spec] of [...Object.entries(read.dependencies ?? {}), ...Object.entries(read.optionalDependencies ?? {})]) {
100
+ const target = pkg.dependencies[name] ?? pkg.optionalDependencies[name]
101
+ if (target === undefined) continue
102
+ const local = localOf(spec, `${where}: package.json`)
103
+ if (local === undefined || target === `link:${local.dir}` || (local.protocol === 'file:' && packages[target]?.resolution.directory === local.dir)) continue
104
+ throw new DeptreeError(`the lockfile gives it ${quote(name)} as ${quote(target)}, and its package.json, overridden, names ${quote(local.dir)}`, where)
105
+ }
106
+ // A resolved optional peer is filed as optional, and pnpm's compatibility
107
+ // database adds peers to a few packages that their package.json lacks.
108
+ const optional = new Set([...names(read.optionalDependencies), ...names(manifest.peerDependencies), ...names(manifest.peerDependenciesMeta), ...names(pkg.peerDependencies), ...names(pkg.peerDependenciesMeta)])
109
+ for (const name of names(pkg.optionalDependencies)) {
110
+ if (!optional.has(name)) throw new DeptreeError(`the lockfile gives it ${quote(name)} as optional, which its package.json does not`, where)
111
+ }
112
+ }
113
+
114
+ export async function fetchPackage(pkg, where, major) {
115
+ const { entries } = await fetchTarball(pkg.name, pkg.version, pkg.resolution.integrity, where)
116
+ const files = filesOf(entries, where)
117
+ const manifest = readManifest(files, pkg, where)
118
+ checkManifest(manifest, pkg, where, major)
119
+ return { files, manifest }
120
+ }
@@ -1,134 +1,193 @@
1
- // The files pnpm installs of a directory a `file:` dependency names: its
2
- // directory fetcher picks them with npm-packlist — 5.1.3 for pnpm 10,
3
- // 10.0.4 for pnpm 11, its own port of it (fs-packlist) for pnpm 12 — and
4
- // hardlinks or copies them into the tree (tree.js). Only the built-in
5
- // rules are followed here. npm-packlist's leave out, by name and whatever
6
- // its case:
7
- //
8
- // - anywhere, `.git`, `.svn`, `.hg`, `CVS`, `.npmrc`, `.DS_Store`,
9
- // `npm-debug.log`, `.npmignore`, `.gitignore`, and a name starting
10
- // with `._`, or `.` and ending in `.swp`, or ending in `.orig`, with
11
- // everything in it;
12
- // - at the top, and with pnpm 11 in every directory, `.lock-wscript`,
13
- // `.wafpickle-*`, `build/config.gypi` and what is in
14
- // `archived-packages`;
15
- // - at the top, `node_modules` and the lockfiles `package-lock.json`,
16
- // `yarn.lock`, `pnpm-lock.yaml` and, with pnpm 11, `bun.lockb`;
17
- //
18
- // and every name with a `*` in it. pnpm 12's leave out, by name as it is
19
- // spelled:
20
- //
21
- // - anywhere, `.git`, `.svn`, `.hg` and `CVS`, with everything in them,
22
- // and a file `.npmrc`, `npm-debug.log`, `.DS_Store`,
23
- // `package-lock.json`, `yarn.lock` or `pnpm-lock.yaml`, or one whose
24
- // name ends in `.orig`;
25
- // - at the top, `node_modules`.
26
- //
27
- // A directory those do not describe is refused: one with a .npmignore
28
- // or .gitignore in it, or a package.json with `files` or bundled
29
- // dependencies, whose rules are not followed here; one with a link in
30
- // it, which the two pass over differently; and one where a file those
31
- // leave out is one npm-packlist would keep, a readme, copying, license or
32
- // licence file, or one `main`, `browser` or `bin` names, as the two keep
33
- // them differently, or, with pnpm 12, one in node_modules that `main` or
34
- // `bin` names, the only file it keeps of those its rules leave out. So is
35
- // a file whose mode is not 0o644 or 0o755, which linking a bin would
36
- // change otherwise than fixBin has it.
1
+ // The files pnpm's directory fetcher installs of a `file:` dependency, as its
2
+ // packlist picks them: npm-packlist 5.1.3 for pnpm 9 and 10, 10.0.4 for pnpm
3
+ // 11, and pnpm 12's own port of it, by package.json's `files`, `main` and
4
+ // `bin`, the .npmignore and .gitignore files where they read them, and their
5
+ // own rules. Of glob syntax only `*`, `?` and `**` are followed, which they
6
+ // all read alike. Refused are a link the walk comes on, which they treat
7
+ // differently, and a mode other than 0o644 or 0o755, which linking a bin
8
+ // would change otherwise than fixBin does.
37
9
 
38
- import { join } from '@preventive/vfs/path.js'
10
+ import { compareVersions, valid } from '@preventive/upstream/semver.js'
11
+ import { normalize } from '@preventive/vfs/path.js'
39
12
  import { DeptreeError, quote } from '../error.js'
40
- import { readBytes } from './project.js'
13
+ import { readBytes } from '../project.js'
14
+ import { bytesOf, gitignoreGlob, matched, matchedOrParents } from './gitignore.js'
15
+ import { pack10, pack11 } from './npm-packlist.js'
41
16
 
42
- // The rules each name is held to, folded, wherever it is.
43
- const ANYWHERE = /^(?:\.git|\.svn|\.hg|cvs|\.npmrc|\.ds_store|npm-debug\.log|\.npmignore|\.gitignore|\._.*|\..*\.swp|.*\.orig)$/u
17
+ const decoder = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true })
44
18
 
45
- // The rules held to the path, by its names folded, from the directory they
46
- // are read in: the top for npm-packlist 5, and every directory for
47
- // npm-packlist 10, which reads them again in each.
48
- const anchored = (names, directory) => (names.length === 1 && (names[0] === '.lock-wscript' || names[0].startsWith('.wafpickle-') || (directory && names[0] === 'archived-packages')))
49
- || (names.length === 2 && names[0] === 'build' && names[1] === 'config.gypi')
19
+ // How deep a directory is walked: each entry is matched against the rules
20
+ // of every directory above it, which takes time growing with the cube.
21
+ const MAX_DEPTH = 100
50
22
 
51
- // The names left out at the top alone.
52
- const TOP = ['node_modules', 'package-lock.json', 'yarn.lock', 'pnpm-lock.yaml']
53
- const TOP_11 = [...TOP, 'bun.lockb']
23
+ // The directory by paths from it, `.` parts and all, which refuses a link
24
+ // on the way to anything it is asked of.
25
+ function viewOf(project, dir, where) {
26
+ const types = new Map()
27
+ const absolute = (rel) => `/${[dir, ...rel.split('/').filter((part) => part !== '' && part !== '.')].filter(Boolean).join('/')}`
28
+ const type = (rel) => {
29
+ const path = absolute(rel)
30
+ if (!types.has(path)) {
31
+ let found
32
+ try {
33
+ found = project.lstat(path).type
34
+ } catch (error) {
35
+ if (!['ENOENT', 'ENOTDIR'].includes(error.code)) throw error
36
+ }
37
+ if (found === 'symlink') throw new DeptreeError('a link in a directory pnpm installs a copy of is not supported', `${where}: ${quote(normalize(rel))}`)
38
+ types.set(path, found)
39
+ }
40
+ return types.get(path)
41
+ }
42
+ const view = {
43
+ // What `rel` is once normalized, as path.join would; nothing outside.
44
+ type(rel) {
45
+ const normal = normalize(rel)
46
+ if (normal === '..' || normal.startsWith('../')) return undefined
47
+ const parts = normal.split('/').filter((part) => part !== '' && part !== '.')
48
+ for (let i = 1; i < parts.length; i++) if (type(parts.slice(0, i).join('/')) !== 'directory') return undefined
49
+ const found = parts.length === 0 ? 'directory' : type(parts.join('/'))
50
+ return rel.endsWith('/') && found !== 'directory' ? undefined : found
51
+ },
52
+ entries(rel) {
53
+ if (view.type(rel) !== 'directory') return undefined
54
+ if (normalize(rel).split('/').length > MAX_DEPTH) throw new DeptreeError(`a directory nested more than ${MAX_DEPTH} deep, each of whose entries the packlists match against the rules of every directory above it, is not supported`, `${where}: ${quote(normalize(rel))}`)
55
+ return project.readdir(absolute(rel))
56
+ },
57
+ text(rel, here) {
58
+ if (view.type(rel) !== 'file') throw new DeptreeError('it is not a file, which pnpm fails to read', here)
59
+ try {
60
+ return decoder.decode(readBytes(project, absolute(rel)))
61
+ } catch {
62
+ throw new DeptreeError('it is not UTF-8, which is not supported', here)
63
+ }
64
+ },
65
+ bytes: (rel) => readBytes(project, absolute(rel)),
66
+ lstat: (rel) => project.lstat(absolute(rel)),
67
+ }
68
+ return view
69
+ }
54
70
 
55
- // pnpm 12's rules: the names left out wherever they are, and the files.
71
+ // pnpm 12's lists of names.
56
72
  const VCS = new Set(['.git', '.svn', '.hg', 'CVS'])
57
73
  const CRUFT = new Set(['.npmrc', 'npm-debug.log', '.DS_Store', 'package-lock.json', 'yarn.lock', 'pnpm-lock.yaml'])
74
+ const alwaysExcluded = (rel) => CRUFT.has(rel.split('/').at(-1)) || rel.split('/').some((part) => VCS.has(part)) || rel.endsWith('.orig')
75
+ const asciiLower = (name) => name.replaceAll(/[A-Z]/gu, (char) => char.toLowerCase())
76
+ const alwaysIncluded = (name) => asciiLower(name) === 'package.json' || ['readme', 'license', 'licence'].some((start) => asciiLower(name).startsWith(start))
77
+ const ALTERNATES = new Set(['package.yaml', 'package.json5'])
78
+ const fieldPath = (path) => path.replace(/^(?:\.\/)+/u, '').replace(/^\/+/u, '')
58
79
 
59
- // Whether pnpm 12's rules leave out the entry at `names`, its path from the
60
- // package's directory by name, which is a directory where `directory`.
61
- function leftOut12(names, directory) {
62
- const name = names.at(-1)
63
- return VCS.has(name) || (names.length === 1 && name === 'node_modules') || (!directory && (CRUFT.has(name) || name.endsWith('.orig')))
80
+ // pnpm 12 makes one regexp of the globs of an ignore file, or of `files`,
81
+ // and drops them all where it grows too large, which none does below twice
82
+ // this many bytes of them.
83
+ const MAX_GLOBS_12 = 16 * 1024
84
+ const checkGlobs12 = (lines, what, where) => {
85
+ if (lines.reduce((sum, line) => sum + bytesOf(line).length + 1, 0) > MAX_GLOBS_12) throw new DeptreeError(`${what} of more than ${MAX_GLOBS_12 / 1024} KiB, all of which pnpm 12 may drop as too large a regexp, is not supported`, where)
64
86
  }
65
87
 
66
- // Whether pnpm 12 leaves out the file at `path` even where `main` or `bin`
67
- // names it: by all its rules but node_modules's.
68
- function alwaysLeftOut12(path) {
69
- const names = path.split('/')
70
- const name = names.at(-1)
71
- return names.some((each) => VCS.has(each)) || CRUFT.has(name) || name.endsWith('.orig')
88
+ // pnpm 12's `files` allowlist: its matcher, or undefined where no entry is
89
+ // one, and the files it names outright.
90
+ function filesOf12(view, files, where) {
91
+ checkGlobs12(files ?? [], 'its package.json has `files`', where)
92
+ const globs = []
93
+ for (const entry of files ?? []) {
94
+ const path = fieldPath(entry)
95
+ if (path !== '') globs.push(gitignoreGlob(path.startsWith('!') ? path : `/${path}`, `${where}: files[${quote(entry)}]`))
96
+ }
97
+ const named = new Set((files ?? []).filter((entry) => !entry.startsWith('!') && !entry.endsWith('/') && !/[*?[\]{}]/u.test(entry)).map(fieldPath).filter((path) => path !== '' && !path.split('/').includes('..') && view.type(path) === 'file'))
98
+ return { globs: globs.length > 0 ? globs : undefined, named }
72
99
  }
73
100
 
74
- // Whether npm-packlist's built-in rules, as pnpm `major` runs it, leave out
75
- // the entry at `names`, as for leftOut12.
76
- function leftOutByNpm(names, directory, major) {
77
- const folded = names.map((name) => name.toLowerCase())
78
- const readIn = major >= 11 ? folded.map((_, i) => folded.slice(i)) : [folded]
79
- return ANYWHERE.test(folded.at(-1)) || readIn.some((path) => anchored(path, directory))
80
- || (folded.length === 1 && (major >= 11 ? TOP_11 : TOP).includes(folded[0]))
101
+ function includedBy12(globs, rel, named) {
102
+ if (globs.some((glob) => glob.whitelist) && !named.has(rel)) {
103
+ const parts = rel.split('/')
104
+ for (let i = parts.length - 1; i >= 0; i--) if (matched(globs, parts.slice(0, i).join('/'), true) === 'whitelist') return false
105
+ }
106
+ return matchedOrParents(globs, rel, false) === 'ignore'
81
107
  }
82
108
 
83
- // npm-packlist's names it keeps, whatever else says.
84
- const MUST_HAVE = /^(?:readme|copying|license|licence)(?:\..*[^~$])?$/iu
109
+ // The ignore crate's walk: each directory's .npmignore and, unless the top
110
+ // has one, .gitignore, the nearest to match a path deciding, an .npmignore's
111
+ // before any .gitignore's. Neither is read where `files` has a matcher.
112
+ function walk12(view, { globs }, where) {
113
+ const useGit = view.type('.npmignore') !== 'file'
114
+ const found = []
115
+ const visit = (rel, stack) => {
116
+ const names = view.entries(rel)
117
+ const own = { dir: rel }
118
+ for (const [key, name] of [['custom', '.npmignore'], ['git', '.gitignore']]) {
119
+ if (globs === undefined && (key === 'custom' || useGit) && names.includes(name)) {
120
+ const path = rel === '' ? name : `${rel}/${name}`
121
+ const here = `${where}: ${quote(path)}`
122
+ const lines = view.text(path, here).split('\n')
123
+ checkGlobs12(lines, 'an ignore file', here)
124
+ own[key] = lines.map((line, i) => (i === 0 ? line.replace(/^\uFEFF/u, '') : line).replace(/\r$/u, '')).map((line) => gitignoreGlob(line, here)).filter(Boolean)
125
+ }
126
+ }
127
+ const chain = [own, ...stack]
128
+ for (const name of names) {
129
+ const path = rel === '' ? name : `${rel}/${name}`
130
+ if ((rel === '' && name === 'node_modules') || VCS.has(name)) continue
131
+ const isDir = view.type(path) === 'directory'
132
+ const verdict = (key) => chain.map((level) => level[key] === undefined ? undefined : matched(level[key], level.dir === '' ? path : path.slice(level.dir.length + 1), isDir)).find(Boolean)
133
+ if ((verdict('custom') ?? verdict('git')) === 'ignore') continue
134
+ if (isDir) visit(path, chain)
135
+ else found.push(path)
136
+ }
137
+ }
138
+ visit('', [])
139
+ return found
140
+ }
85
141
 
86
- // The paths a package.json's main, browser and bin name, from its
87
- // directory, whatever their case, that pnpm `major` may keep whatever its
88
- // rules say: with pnpm 12, those main and bin name that its rules but
89
- // node_modules's do not leave out.
90
- function namedByManifest(manifest, major) {
91
- const { main, browser, bin } = manifest
92
- const bins = typeof bin === 'string' ? [bin] : Object.values(bin ?? {})
93
- const paths = (major >= 12 ? [main, ...bins] : [main, browser, ...bins]).filter((path) => typeof path === 'string').map((path) => join('.', path))
94
- return (major >= 12 ? paths.filter((path) => !alwaysLeftOut12(path)) : paths).map((path) => path.toLowerCase())
142
+ function pack12(view, manifest, where) {
143
+ const files = Array.isArray(manifest.files) ? filesOf12(view, manifest.files, where) : { named: new Set() }
144
+ const main = typeof manifest.main === 'string' ? [manifest.main] : []
145
+ const bins = typeof manifest.bin === 'string' ? [manifest.bin] : manifest.bin !== null && typeof manifest.bin === 'object' && !Array.isArray(manifest.bin) ? Object.values(manifest.bin).filter((bin) => typeof bin === 'string') : []
146
+ const fields = [...main, ...bins].map(fieldPath)
147
+ const kept = new Set(walk12(view, files, where).filter((rel) => !alwaysExcluded(rel) && !rel.startsWith('node_modules/')
148
+ && (files.globs === undefined || includedBy12(files.globs, rel, files.named) || (!rel.includes('/') && alwaysIncluded(rel)) || fields.includes(rel))))
149
+ for (const name of view.entries('')) {
150
+ if (!alwaysExcluded(name) && (alwaysIncluded(name) || ALTERNATES.has(asciiLower(name))) && view.type(name) === 'file') kept.add(name)
151
+ }
152
+ // A main or bin path that stays inside, kept as it is spelled.
153
+ for (const path of fields) {
154
+ const parts = path.split('/')
155
+ if (path === '' || path.includes('\\') || parts.includes('..') || parts[0] === '.' || alwaysExcluded(path) || view.type(path) !== 'file') continue
156
+ if (parts.some((part) => part === '' || part === '.') || parts[0] === 'node_modules') throw new DeptreeError(`main or bin names ${quote(path)}, which pnpm 12 keeps as it is spelled, and which is not supported`, where)
157
+ kept.add(path)
158
+ }
159
+ return kept
95
160
  }
96
161
 
97
- // Whether a package.json's list of bundled dependencies may name any: an
98
- // empty one bundles none, with either npm-packlist.
99
162
  const bundles = (list) => Boolean(list) && !(Array.isArray(list) && list.length === 0)
100
163
 
101
- // The files of the package at `dir` of `project` npm-packlist picks, with
102
- // their data and modes, by their paths from it; `manifest` is its
103
- // package.json as parsed.
104
- export function packDirectory(project, dir, manifest, major, where) {
105
- if (manifest.files !== undefined) throw new DeptreeError('its package.json has `files`, which npm-packlist picks the files pnpm installs by, and which is not followed here', where)
164
+ function checkManifest(manifest, pnpm, view, where) {
165
+ const { files, bin } = manifest
106
166
  if (bundles(manifest.bundleDependencies) || bundles(manifest.bundledDependencies)) throw new DeptreeError('a directory with bundled dependencies is not supported', where)
107
- const named = namedByManifest(manifest, major)
108
- const leftOut = major >= 12 ? leftOut12 : (names, directory) => leftOutByNpm(names, directory, major)
167
+ if (files !== undefined && files !== null && !(Array.isArray(files) && files.every((entry) => typeof entry === 'string'))) throw new DeptreeError('its package.json has `files` that is not a list of strings, which is not supported', where)
168
+ if (Array.isArray(bin) && bin.some((path) => typeof path !== 'string') && !pnpm.startsWith('11.') && !pnpm.startsWith('12.')) throw new DeptreeError('its package.json has a bin list with other than strings, which npm-packlist then reads unnormalized, and which is not supported', where)
169
+ if (!pnpm.startsWith('11.')) return
170
+ if (bin !== null && typeof bin === 'object' && Object.values(bin).some((path) => typeof path !== 'string')) throw new DeptreeError('its package.json has a bin that is not a string, which pnpm 11 fails on', where)
171
+ if (compareVersions(pnpm, '11.28.0') < 0 && view.text('package.json', where).startsWith('\uFEFF')) throw new DeptreeError('its package.json starts with a byte order mark, which pnpm 11 fails on before 11.28', where)
172
+ }
173
+
174
+ // `version` is the version that installs, as host.pnpm gives it: `v11.28.2`
175
+ // is read as 11.28.2.
176
+ export function packDirectory(project, dir, manifest, version, where) {
177
+ const pnpm = valid(version)
178
+ const view = viewOf(project, dir, where)
179
+ checkManifest(manifest, pnpm, view, where)
180
+ const major = Number(pnpm.split('.')[0])
181
+ const kept = major >= 12 ? pack12(view, manifest, where)
182
+ : major === 11 ? pack11(view, manifest, where, compareVersions(pnpm, '11.28.0') >= 0)
183
+ : pack10(view, view.text('package.json', where).startsWith('\uFEFF') ? undefined : manifest, where, major === 10 && compareVersions(pnpm, '10.31.0') >= 0 ? '5.1.9' : '5.1.6')
109
184
  const files = new Map()
110
- const visit = (names) => {
111
- for (const entry of project.readdir(['', dir, ...names].join('/'))) {
112
- const at = [...names, entry]
113
- const rel = at.join('/')
114
- const here = `${where}: ${quote(rel)}`
115
- const { type, mode } = project.lstat(`/${dir}/${rel}`)
116
- if (type === 'symlink') throw new DeptreeError('a link in a directory pnpm installs a copy of is not supported', here)
117
- if (entry === '.npmignore' || entry === '.gitignore') throw new DeptreeError(`${entry}'s rules, which npm-packlist picks the files pnpm installs by, are not followed here`, here)
118
- if (major < 12 && names.length === 0 && entry !== 'node_modules' && entry.toLowerCase() === 'node_modules') throw new DeptreeError('a name that is node_modules but for its case is kept by pnpm 10 and left out by pnpm 11', here)
119
- if (major < 12 && entry.includes('*')) continue
120
- if (leftOut(at, type === 'directory')) {
121
- const folded = rel.toLowerCase()
122
- if ((major < 12 && MUST_HAVE.test(entry)) || named.some((kept) => kept === folded || kept.startsWith(`${folded}/`))) {
123
- throw new DeptreeError('whether pnpm installs it turns on rules of npm-packlist not followed here', here)
124
- }
125
- continue
126
- }
127
- if (type === 'directory') visit(at)
128
- else if (mode !== 0o644 && mode !== 0o755) throw new DeptreeError(`its mode, ${mode.toString(8)}, is not 644 or 755, which is not supported`, here)
129
- else files.set(rel, { data: readBytes(project, `/${dir}/${rel}`), mode })
130
- }
185
+ for (const rel of [...new Set([...kept].map((path) => path.replace(/^\.\//u, '')))].sort()) {
186
+ const here = `${where}: ${quote(rel)}`
187
+ if (rel.split('/').some((part) => part === '' || part === '.')) throw new DeptreeError('pnpm keeps it as a pattern spells it, which is not supported', here)
188
+ const { mode } = view.lstat(rel)
189
+ if (mode !== 0o644 && mode !== 0o755) throw new DeptreeError(`its mode, ${mode.toString(8)}, is not 644 or 755, which is not supported`, here)
190
+ files.set(rel, { data: view.bytes(rel), mode })
131
191
  }
132
- visit([])
133
192
  return files
134
193
  }