@preventive/deptree 1.0.0-alpha.2 → 1.0.0-alpha.4

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.
@@ -7,6 +7,17 @@ import { valid } from '@preventive/upstream/semver.js'
7
7
  import { DeptreeError, quote } from '../error.js'
8
8
  import { REGISTRY } from '../tarball.js'
9
9
 
10
+ const ON_FAIL = new Set(['download', 'error', 'warn', 'ignore'])
11
+ const IMPORT_METHODS = new Set(['auto', 'hardlink', 'copy', 'clone', 'clone-or-copy'])
12
+
13
+ const show = (value) => (typeof value === 'string' ? quote(value) : Array.isArray(value) ? 'a list' : value === null ? 'null' : typeof value === 'object' ? 'a mapping' : String(value))
14
+
15
+ // A reader of one of the values of `allowed`.
16
+ const oneOf = (allowed) => (value, where) => {
17
+ if (allowed.has(value)) return value
18
+ throw new DeptreeError(`expected one of ${[...allowed].join(', ')}, found ${show(value)}`, where)
19
+ }
20
+
10
21
  export const readers = {
11
22
  boolean(value, where) {
12
23
  if (typeof value === 'boolean') return value
@@ -42,10 +53,8 @@ export const readers = {
42
53
  if (value !== null && typeof value === 'object' && !Array.isArray(value)) return value
43
54
  throw new DeptreeError(`expected a mapping, found ${show(value)}`, where)
44
55
  },
45
- onFail(value, where) {
46
- if (ON_FAIL.has(value)) return value
47
- throw new DeptreeError(`expected one of ${[...ON_FAIL].join(', ')}, found ${show(value)}`, where)
48
- },
56
+ importMethod: oneOf(IMPORT_METHODS),
57
+ onFail: oneOf(ON_FAIL),
49
58
  linkWorkspacePackages(value, where) {
50
59
  return value === 'deep' ? true : readers.boolean(value, where)
51
60
  },
@@ -72,10 +81,6 @@ export const readers = {
72
81
  },
73
82
  }
74
83
 
75
- const ON_FAIL = new Set(['download', 'error', 'warn', 'ignore'])
76
-
77
- const show = (value) => (typeof value === 'string' ? quote(value) : Array.isArray(value) ? 'a list' : value === null ? 'null' : typeof value === 'object' ? 'a mapping' : String(value))
78
-
79
84
  // Read, and held to one value: the default, or the only one built for.
80
85
  const only = (kind, wanted, why) => ({ kind, check: (value, where) => {
81
86
  if (value !== wanted) throw new DeptreeError(`${show(value)} is not supported: ${why}`, where)
@@ -130,6 +135,9 @@ export const READ = {
130
135
  autoInstallPeers: { kind: 'boolean' },
131
136
  dedupePeers: { kind: 'boolean' },
132
137
  peersSuffixMaxLength: { kind: 'count' },
138
+ // Whether a package installed from a directory has the files of each of
139
+ // its snapshots as one, hardlinked, or each as its own (tree.js).
140
+ packageImportMethod: { kind: 'importMethod' },
133
141
  // Neither pnpm's .npmrc nor ours has these.
134
142
  supportedArchitectures: { kind: 'mapping', check: checkArchitectures, rc: false },
135
143
  patchedDependencies: { kind: 'mapping', check: checkPatches, rc: false },
@@ -158,7 +166,7 @@ const READ_11 = {
158
166
  }
159
167
 
160
168
  // What pnpm 11 has that leaves the tree as it is. The tree follows the
161
- // lockfile, as pnpm 11's does with trustLockfile: minimumReleaseAge and the
169
+ // lockfile, as pnpm 11's and 12's do with trustLockfile: minimumReleaseAge and the
162
170
  // rest of what pnpm 11 checks the lockfile against the registry by before
163
171
  // it installs — each package's publish time, its tarball URL, its trust —
164
172
  // are passed over.
@@ -178,6 +186,34 @@ const IGNORED_11 = new Set([
178
186
  'nodeVersionFromEnginesRuntime', 'cliOptions', 'explicitlySetKeys', 'packageManager', 'wantedPackageManager',
179
187
  ])
180
188
 
189
+ // What pnpm 12 has that pnpm 11 has not: those that leave an isolated
190
+ // tree as it is — resolution's, the hoisted linker's, the tasks of
191
+ // `pnpm run`, the global install's — and a Cargo or Python install beside
192
+ // the tree's, which is refused where it is enabled.
193
+ const IGNORED_12 = new Set([
194
+ 'autoDedupe', 'autoInstallPeersFromHighestMatch', 'externalDependencies', 'hoistingLimits', 'globalShims',
195
+ 'concurrencyGroups', 'pipelines', 'pipelineBase', 'publishWaitTimeout', 'saveTypes', 'tools', 'macosBackup',
196
+ ])
197
+ const notEnabled = (value, where) => {
198
+ if (value.enabled !== undefined && value.enabled !== null && value.enabled !== false) never('an install of Cargo or Python packages beside the tree is not supported')(value.enabled, `${where}.enabled`)
199
+ }
200
+ const READ_12 = {
201
+ __proto__: null,
202
+ cargo: { kind: 'mapping', check: notEnabled },
203
+ python: { kind: 'mapping', check: notEnabled },
204
+ }
205
+
206
+ // What pnpm 11 reads or passes over that pnpm 12 does not know: it drops
207
+ // each, and fails on one where the root package.json pins the pnpm that
208
+ // runs.
209
+ const UNRECOGNIZED_12 = new Set([
210
+ 'allowNonAppliedPatches', 'alwaysAuth', 'email', 'enginePinManifest', 'ignoreDepScripts', 'ignorePatchFailures',
211
+ 'lockfileDirectory', 'managePackageManagerVersions', 'nodeVersionFromEnginesRuntime', 'packageManagerStrict',
212
+ 'packageManagerStrictVersion', 'shamefullyFlatten', 'useNodeVersion',
213
+ ])
214
+
215
+ export const unrecognized12 = (where) => new DeptreeError('pnpm 12 does not know it, and fails on it where the root package.json pins the pnpm that runs', where)
216
+
181
217
  // The keys of the root package.json's `pnpm` field pnpm 10 reads; it
182
218
  // passes over any other there.
183
219
  export const MANIFEST_KEYS = [
@@ -206,7 +242,7 @@ export const IGNORED = new Set([
206
242
  'fetchRetryMintimeout', 'fetchTimeout', 'httpProxy', 'httpsProxy', 'key', 'localAddress', 'maxsockets',
207
243
  'networkConcurrency', 'noProxy', 'noproxy', 'offline', 'preferOffline', 'proxy', 'strictSsl', 'userAgent',
208
244
  // the store, caches and state, none of it in node_modules
209
- 'cacheDir', 'modulesCacheMaxAge', 'packageImportMethod', 'sideEffectsCache', 'sideEffectsCacheReadonly',
245
+ 'cacheDir', 'modulesCacheMaxAge', 'sideEffectsCache', 'sideEffectsCacheReadonly',
210
246
  'stateDir', 'storeDir', 'strictStorePkgContentCheck', 'verifyStoreIntegrity',
211
247
  // scripts, which are not run, and bins, which are not written
212
248
  'allowBuilds', 'childConcurrency', 'dangerouslyAllowAllBuilds', 'enablePrePostScripts', 'extendNodePath',
@@ -252,13 +288,34 @@ function checkCatalogs(value, where) {
252
288
  for (const [name, catalog] of Object.entries(value)) checkCatalog(readers.mapping(catalog, `${where}.${name}`), `${where}.${name}`)
253
289
  }
254
290
 
291
+ // What pnpm of `major` does with a setting, as far as is known here: reads
292
+ // it, with `read`; leaves the tree as it is, with none; or for pnpm 12,
293
+ // does not recognize it. Undefined for one not known. pnpm 12 takes a
294
+ // pattern only as a list.
295
+ function lookup(name, major) {
296
+ if (major >= 12 && UNRECOGNIZED_12.has(name)) return { unrecognized: true }
297
+ if (major >= 12 && name in READ_12) return { read: READ_12[name] }
298
+ if (major >= 11 && name in READ_11) return { read: READ_11[name] }
299
+ if (IGNORED.has(name) || (major >= 11 && IGNORED_11.has(name)) || (major >= 12 && IGNORED_12.has(name))) return {}
300
+ if (!(name in READ)) return undefined
301
+ return { read: major >= 12 && READ[name].kind === 'texts' ? { ...READ[name], kind: 'list' } : READ[name] }
302
+ }
303
+
255
304
  // What reads a setting for pnpm of `major`, or undefined for one that
256
- // leaves the tree as it is; one that is neither is refused.
257
- export function readerOf(name, where, major) {
258
- if (major >= 11 && name in READ_11) return READ_11[name]
259
- if (IGNORED.has(name) || (major >= 11 && IGNORED_11.has(name))) return undefined
260
- if (!(name in READ)) throw new DeptreeError('unsupported setting', where)
261
- return READ[name]
305
+ // leaves the tree as it is; one not known is refused. `pinned` is whether
306
+ // pnpm 12 fails on one it does not recognize.
307
+ export function readerOf(name, where, major, pinned = false) {
308
+ const found = lookup(name, major)
309
+ if (found === undefined) throw new DeptreeError('unsupported setting', where)
310
+ if (found.unrecognized && pinned) throw unrecognized12(where)
311
+ return found.read
312
+ }
313
+
314
+ // Whether pnpm 12 knows a setting, read or passed over, as far as is known
315
+ // here.
316
+ export function known12(name) {
317
+ const found = lookup(name, 12)
318
+ return found !== undefined && !found.unrecognized
262
319
  }
263
320
 
264
321
  // By selector, the patch file, relative to the workspace's directory.
@@ -30,16 +30,23 @@
30
30
  //
31
31
  // pnpm 11 reads its settings from pnpm-workspace.yaml alone: an .npmrc
32
32
  // for credentials and registries, and the package.json for none but the
33
- // Node its engines.runtime pins, which it takes for nodeVersion. Of the
33
+ // Node its engines.runtime pins, runtimeNodeVersion, which it takes where
34
+ // nodeVersion is not set. Of the
34
35
  // yaml it passes over a key not in camelCase, and one about the machine,
35
36
  // the run or a login; it has settings pnpm 10 has not (READ_11, IGNORED_11),
36
37
  // and reads linkWorkspacePackages for a frozen install too.
38
+ //
39
+ // pnpm 12 reads them as pnpm 11 does, and has settings of its own (READ_12,
40
+ // IGNORED_12); where the root package.json pins the pnpm that runs, it
41
+ // fails on a key of pnpm-workspace.yaml with a value it does not know,
42
+ // pnpm 11's that it has not among them (UNRECOGNIZED_12), which it drops
43
+ // otherwise.
37
44
 
38
45
  import { valid, validRange } from '@preventive/upstream/semver.js'
39
46
  import { DeptreeError, quote } from '../error.js'
40
47
  import { parseNpmrc } from './npmrc.js'
41
48
  import { replaceReferences } from './overrides.js'
42
- import { IGNORED, MANIFEST_KEYS, READ, checkRegistry, readerOf, readers } from './readers.js'
49
+ import { IGNORED, MANIFEST_KEYS, READ, checkRegistry, known12, readerOf, readers, unrecognized12 } from './readers.js'
43
50
 
44
51
  // An .npmrc value read only where it can mean one thing: not quoted, not
45
52
  // escaped, with no `;` or `#` that ini would cut it at. Neither file's
@@ -124,15 +131,19 @@ function fromManifest(manifest) {
124
131
  // pnpm 11 passes over a key not in camelCase.
125
132
  const CAMEL = /^[a-z][\dA-Za-z]*$/u
126
133
 
127
- function fromWorkspace(workspace, major) {
134
+ // pnpm 12 passes over a key with no value. `pinned` is readerOf's.
135
+ function fromWorkspace(workspace, major, pinned) {
128
136
  if (workspace === null || typeof workspace !== 'object' || Array.isArray(workspace)) throw new DeptreeError('expected a mapping', 'pnpm-workspace.yaml')
129
137
  const settings = new Map()
130
138
  for (const [name, value] of Object.entries(workspace)) {
131
139
  const where = `pnpm-workspace.yaml: ${name}`
132
140
  noEnvironment(name, where)
133
141
  noEnvironment(value, where)
134
- if (major >= 11 && !CAMEL.test(name)) continue
135
- const read = readerOf(name, where, major)
142
+ if (major >= 11 && !CAMEL.test(name)) {
143
+ if (major >= 12 && pinned && value !== null && !known12(camelCase(name))) throw unrecognized12(where)
144
+ continue
145
+ }
146
+ const read = readerOf(name, where, major, pinned && value !== null)
136
147
  if (read !== undefined) settings.set(name, { value, where, read })
137
148
  }
138
149
  return settings
@@ -155,6 +166,7 @@ function derive(get) {
155
166
  hoistWorkspacePackages: get('hoistWorkspacePackages') ?? true,
156
167
  engineStrict: get('engineStrict') ?? false,
157
168
  nodeVersion: get('nodeVersion'),
169
+ runtimeNodeVersion: undefined,
158
170
  supportedArchitectures: get('supportedArchitectures'),
159
171
  patchedDependencies: get('patchedDependencies'),
160
172
  overrides: get('overrides'),
@@ -168,6 +180,7 @@ function derive(get) {
168
180
  linkWorkspacePackages: get('linkWorkspacePackages') ?? false,
169
181
  pmOnFail: get('pmOnFail'),
170
182
  runtimeOnFail: get('runtimeOnFail'),
183
+ packageImportMethod: get('packageImportMethod') ?? 'auto',
171
184
  }
172
185
  }
173
186
 
@@ -199,16 +212,17 @@ function settle(layers, manifest) {
199
212
 
200
213
  // `workspace` is pnpm-workspace.yaml as parsed and `npmrc` the text of the
201
214
  // .npmrc, either of which may be undefined; `manifest` the root
202
- // package.json as parsed. Overrides that name nothing are none, and leave
215
+ // package.json as parsed; `pinned` whether it pins the pnpm that runs,
216
+ // which pnpm 12 holds pnpm-workspace.yaml's keys to. Overrides that name nothing are none, and leave
203
217
  // those below them.
204
- export function readSettings({ workspace, npmrc, manifest, major = 10 }) {
205
- const fromYaml = () => (workspace === undefined ? new Map() : fromWorkspace(workspace, major))
218
+ export function readSettings({ workspace, npmrc, manifest, major = 10, pinned = false }) {
219
+ const fromYaml = () => (workspace === undefined ? new Map() : fromWorkspace(workspace, major, pinned))
206
220
  // pnpm 11 reads its settings from pnpm-workspace.yaml alone, and none
207
221
  // from the package.json, its `resolutions` none.
208
222
  if (major >= 11) {
209
223
  if (npmrc !== undefined) checkNpmrcRegistries(npmrc)
210
224
  const settings = settle([fromYaml()], manifest)
211
- settings.nodeVersion ??= runtimeNode(manifest, settings.runtimeOnFail)
225
+ settings.runtimeNodeVersion = runtimeNode(manifest, settings.runtimeOnFail)
212
226
  return settings
213
227
  }
214
228
  const rc = npmrc === undefined ? { settings: new Map(), environment: false } : fromNpmrc(npmrc)
@@ -221,7 +235,8 @@ export function readSettings({ workspace, npmrc, manifest, major = 10 }) {
221
235
  }
222
236
 
223
237
  // The Node the root package.json's devEngines.runtime or engines.runtime
224
- // pins, which pnpm 11 takes for nodeVersion where none is set: the first
238
+ // pins, which pnpm 11 takes for nodeVersion where none is set, and so does
239
+ // pnpm 12 but for a patched package's engines (install.js): the first
225
240
  // that names a range for Node decides, and gives its version where that is
226
241
  // exact. One to download, which gives the range's lowest, is refused;
227
242
  // runtimeOnFail stands for each one's onFail.
package/src/pnpm/tree.js CHANGED
@@ -1,4 +1,4 @@
1
- // A node_modules tree as pnpm 10 or 11 installs it from a frozen lockfile
1
+ // A node_modules tree as pnpm 10, 11 or 12 installs it from a frozen lockfile
2
2
  // with the isolated linker, held in a Vfs rooted at the lockfile's directory:
3
3
  // each package's files at node_modules/.pnpm/<its directory>/node_modules/
4
4
  // <its name>, its dependencies linked beside it, the hoisted aliases in
@@ -19,30 +19,29 @@
19
19
  // Each package is fetched once, and each snapshot's files composed in
20
20
  // memory — its package's, patched, bins fixed — before one write of each.
21
21
 
22
- import { packageKeyOf, parsePnpmLockfile } from '@preventive/lockfile/pnpm.js'
22
+ import { packageKeyOf } from '@preventive/lockfile/pnpm.js'
23
23
  import { Vfs, VfsError } from '@preventive/vfs'
24
24
  import { dirname, relative } from '@preventive/vfs/path.js'
25
+ import { eachConcurrently } from '../concurrent.js'
25
26
  import { DeptreeError, quote } from '../error.js'
26
27
  import { checkNoModules, mount } from '../mount.js'
27
28
  import { applyPatch, parsePatch } from '../patch.js'
28
29
  import { REGISTRY, checkDependencies, checkManifest, fetchPackage, sameBytes, tarballUrl } from '../tarball.js'
29
- import { binTargets, checkPatchOfBins, fixBin } from './bins.js'
30
+ import { binTargets, checkPatchOfBins, fixBin, requiresBuild } from './bins.js'
30
31
  import { buildGraph } from './graph.js'
31
32
  import { hoist } from './hoist.js'
32
- import { checkLocalOverrides, readDirectoryPackage, readLinked } from './local.js'
33
+ import { checkLocalOverrides, createFreshnessCheck, readDirectoryPackage, readLinked } from './local.js'
33
34
  import { createPatchedCheck, skippedSnapshots } from './install.js'
34
35
  import { checkCollisions, checkLinks, checkOptional } from './checks.js'
35
36
  import { createHook } from './hook.js'
36
37
  import { listOverrides } from './overrides.js'
37
- import { checkHost, inputsOf, manifestsOf, patchesOf, readWorkspace } from './inputs.js'
38
+ import { checkHost, inputsOf, manifestsOf, patchesOf, readLockfile } from './inputs.js'
38
39
  import { checkProject } from './project.js'
39
- import { checkProjects, workspaceNames } from './projects.js'
40
+ import { checkProjects, pinsPnpm, workspaceNames } from './projects.js'
40
41
  import { readSettings } from './settings.js'
41
42
  import { checkUpToDate } from './uptodate.js'
42
43
  import { checkWorkspace } from './workspace.js'
43
44
 
44
- const CONCURRENCY = 8
45
-
46
45
  // What the lockfile holds that no tree is built for here.
47
46
  function checkLockfile(lockfile) {
48
47
  if (lockfile.settings.excludeLinksFromLockfile) throw new DeptreeError('links left out of the lockfile would be left out of the tree', 'settings.excludeLinksFromLockfile')
@@ -82,9 +81,9 @@ const PACKAGE_FIELDS = ['resolution', 'os', 'cpu', 'libc', 'hasBin', 'bundledDep
82
81
  const packageFields = (pkg) => JSON.stringify(PACKAGE_FIELDS.map((field) => pkg[field]))
83
82
 
84
83
  // Each package's files and package.json, by its name and version: a
85
- // package is fetched once however many snapshots it has, a few at a time,
86
- // and the first failure stops the rest from starting. One installed from
87
- // a directory is read from `project`, as npm-packlist picks its files.
84
+ // package is fetched once however many snapshots it has, a few at a time.
85
+ // One installed from a directory is read from `project`, as npm-packlist
86
+ // picks its files.
88
87
  async function fetchAll(nodes, project, major) {
89
88
  const packages = new Map()
90
89
  for (const { key, pkg } of nodes.values()) {
@@ -92,32 +91,25 @@ async function fetchAll(nodes, project, major) {
92
91
  if (!packages.has(id)) packages.set(id, pkg)
93
92
  else if (packageFields(packages.get(id)) !== packageFields(pkg)) throw new DeptreeError(`its snapshots differ on what the package is: ${PACKAGE_FIELDS.join(', ')}`, quote(id))
94
93
  }
95
- const queue = [...packages]
96
94
  const fetched = new Map()
97
- let failed = false
98
- const worker = async () => {
99
- while (queue.length > 0 && !failed) {
100
- const [id, pkg] = queue.shift()
101
- try {
102
- if (pkg.resolution.type === 'directory') {
103
- const got = readDirectoryPackage(project, pkg, quote(id), major)
104
- checkManifest(got.manifest, pkg, quote(id))
105
- fetched.set(id, { ...got, local: true })
106
- } else fetched.set(id, await fetchPackage(pkg, quote(id)))
107
- } catch (error) {
108
- failed = true
109
- throw error instanceof DeptreeError ? error : new DeptreeError(error.message, quote(id), { cause: error })
110
- }
95
+ await eachConcurrently(packages, async ([id, pkg]) => {
96
+ try {
97
+ if (pkg.resolution.type === 'directory') {
98
+ const got = readDirectoryPackage(project, pkg, quote(id), major)
99
+ checkManifest(got.manifest, pkg, quote(id), major)
100
+ fetched.set(id, { ...got, local: true })
101
+ } else fetched.set(id, await fetchPackage(pkg, quote(id), major))
102
+ } catch (error) {
103
+ throw error instanceof DeptreeError ? error : new DeptreeError(error.message, quote(id), { cause: error })
111
104
  }
112
- }
113
- await Promise.all(Array.from({ length: Math.min(CONCURRENCY, queue.length) }, worker))
105
+ })
114
106
  return fetched
115
107
  }
116
108
 
117
109
  // Each node with its package's files and package.json, by its directory:
118
110
  // its dependencies held to the package.json, as `hook` reads it once for
119
111
  // each package; and the number of tarballs fetched.
120
- async function fetchNodes(nodes, hook, project, major) {
112
+ async function fetchNodes(nodes, hook, project, major, fresh) {
121
113
  const fetched = await fetchAll(nodes, project, major)
122
114
  const byDir = new Map()
123
115
  for (const node of nodes.values()) {
@@ -125,6 +117,7 @@ async function fetchNodes(nodes, hook, project, major) {
125
117
  const got = fetched.get(id)
126
118
  got.read ??= hook(got.manifest, `${quote(id)}: package.json`)
127
119
  checkDependencies(got.manifest, got.read, node.pkg, quote(node.key))
120
+ fresh?.(node, got.read)
128
121
  byDir.set(node.dir, { ...node, files: got.files, manifest: got.manifest })
129
122
  }
130
123
  return { byDir, tarballs: [...fetched.values()].filter((got) => !got.local).length }
@@ -133,19 +126,22 @@ async function fetchNodes(nodes, hook, project, major) {
133
126
  // A package installed from a directory has one file for each of its
134
127
  // files, hardlinked into each of its snapshots: fixBin makes it
135
128
  // executable in all of them, though a CRLF `#!` line it rewrites is
136
- // written as a file of that snapshot's own. By directory, the files a
137
- // snapshot has made executable by another's: `targets` is binTargets's.
138
- function executableElsewhere(byDir, targets) {
129
+ // written as a file of that snapshot's own. Each snapshot has its own
130
+ // copy instead where pnpm builds the package, or, with pnpm 11 and 12,
131
+ // where packageImportMethod is other than auto or hardlink. By
132
+ // directory, the files a snapshot has made executable by another's:
133
+ // `targets` is binTargets's.
134
+ function executableElsewhere(byDir, targets, packageImportMethod, major) {
135
+ const linked = major < 11 || packageImportMethod === 'auto' || packageImportMethod === 'hardlink'
136
+ const shared = [...byDir.values()].filter((node) => linked && node.pkg.resolution.type === 'directory' && !requiresBuild(node.manifest, node.files, major))
139
137
  const byPackage = new Map()
140
- for (const node of byDir.values()) {
141
- if (node.pkg.resolution.type !== 'directory') continue
138
+ for (const node of shared) {
142
139
  const id = packageKeyOf(node.key)
143
140
  if (!byPackage.has(id)) byPackage.set(id, new Set())
144
141
  for (const path of targets.get(node.dir) ?? []) byPackage.get(id).add(path)
145
142
  }
146
143
  const executable = new Map()
147
- for (const node of byDir.values()) {
148
- if (node.pkg.resolution.type !== 'directory') continue
144
+ for (const node of shared) {
149
145
  const own = targets.get(node.dir) ?? new Set()
150
146
  executable.set(node.dir, new Set([...byPackage.get(packageKeyOf(node.key))].filter((path) => !own.has(path))))
151
147
  }
@@ -166,14 +162,14 @@ function compose(node, patches, { targets, executable }, { major, checkPatched }
166
162
  patch.parsed ??= parsePatch(patch.text, patch.path)
167
163
  // Once for each package, whatever its snapshots.
168
164
  patch.applied ??= new WeakMap()
169
- if (!patch.applied.has(files)) patch.applied.set(files, applyPatch(files, patch.parsed))
165
+ if (!patch.applied.has(files)) patch.applied.set(files, applyPatch(files, patch.parsed, { createdMode: major >= 12 ? 0o644 : undefined }))
170
166
  files = patch.applied.get(files)
171
167
  const manifest = checkPatchOfBins(node, files, targets, where, major)
172
168
  checkPatched?.(manifest, where)
173
169
  }
174
170
  if (targets.size === 0 && executable.size === 0) return files
175
171
  files = new Map(files)
176
- for (const path of targets) files.set(path, fixBin(files.get(path), `${where}: ${quote(path)}`))
172
+ for (const path of targets) files.set(path, fixBin(files.get(path), `${where}: ${quote(path)}`, major))
177
173
  for (const path of executable) files.set(path, { ...files.get(path), mode: 0o755 })
178
174
  return files
179
175
  }
@@ -203,18 +199,19 @@ function linkTarget(path, target) {
203
199
  return relative(`${root}/${dirname(path)}`, `${root}/${target}`) || '.'
204
200
  }
205
201
 
206
- // Every link in the tree, by its path: each node's children beside it and
207
- // itself inside it where it depends on itself, then what is hoisted, then
208
- // each project's direct dependencies, which win over a hoisted alias.
209
- // `byDir` is the graph by directory.
210
- function linksOf(byDir, direct, settings, projects, major) {
202
+ // Every link in the tree, by its path: each node's children beside it and,
203
+ // but with pnpm 12, itself inside it where it depends on itself, then what
204
+ // is hoisted, then each project's direct dependencies, which win over a
205
+ // hoisted alias.
206
+ // `byDir` is the graph by directory, and `hoisting` graph.js's.
207
+ function linksOf(byDir, direct, settings, projects, major, hoisting) {
211
208
  const links = new Map()
212
209
  for (const node of byDir.values()) {
213
210
  for (const [alias, dir] of node.children) if (alias !== node.name) links.set(`${node.modules}/${alias}`, dir)
214
211
  const self = node.children.get(node.name)
215
- if (byDir.has(self)) links.set(`${node.dir}/node_modules/${node.name}`, self)
212
+ if (major < 12 && byDir.has(self)) links.set(`${node.dir}/node_modules/${node.name}`, self)
216
213
  }
217
- for (const [path, dir] of hoist(byDir, direct, settings, projects, major)) links.set(path, dir)
214
+ for (const [path, dir] of hoist(byDir, direct, settings, projects, major, hoisting)) links.set(path, dir)
218
215
  for (const [id, children] of direct) {
219
216
  for (const [alias, dir] of children) links.set(`${id === '.' ? '' : `${id}/`}node_modules/${alias}`, dir)
220
217
  }
@@ -230,33 +227,32 @@ export async function buildPnpmTree(options) {
230
227
  // Refused before anything is fetched; mount checks again.
231
228
  if (into !== undefined) checkNoModules(into, folded)
232
229
  const inputs = inputsOf(options)
233
- const { lockfile, env } = parsePnpmLockfile(inputs.lockfile)
230
+ const { lockfile, env } = readLockfile(inputs.lockfile)
234
231
  if (!('.' in lockfile.importers)) throw new DeptreeError('expected the root project, whose package.json holds settings', 'importers')
235
232
  // Before the project is read for any importer: none leads out of it.
236
233
  checkLockfile(lockfile)
237
- const workspace = readWorkspace(inputs.workspace)
238
- const { manifests, pnpm, major } = manifestsOf(inputs, workspace, lockfile, given.pnpm)
234
+ const { manifests, pnpm, major, workspace } = manifestsOf(inputs, lockfile, given.pnpm)
239
235
  const host = { pnpm, major, ...machine }
240
236
  // pnpm 11 locks config dependencies there, which are refused, and the
241
237
  // pnpm a project pins, which leaves the tree as it is.
242
238
  if (env !== undefined && host.major < 11) throw new DeptreeError('the env document pnpm 11 writes is not supported', 'env')
243
239
  if (env !== undefined && Object.keys(env.importers['.'].configDependencies).length > 0) throw new DeptreeError('config dependencies are not supported', 'env.importers["."].configDependencies')
244
- const settings = readSettings({ workspace, npmrc: inputs.npmrc, manifest: manifests.get('.'), major: host.major })
240
+ const settings = readSettings({ workspace, npmrc: inputs.npmrc, manifest: manifests.get('.'), major: host.major, pinned: pinsPnpm(manifests.get('.'), host.pnpm) })
245
241
  checkWorkspace(Object.keys(lockfile.importers), settings.packages, host.major)
246
242
  const overrides = listOverrides(settings.overrides, settings.catalogs, host.major)
247
243
  const installed = checkLocalOverrides(overrides, project)
248
244
  const patches = patchesOf(inputs, settings.patchedDependencies)
249
245
  const patched = await checkUpToDate(lockfile, settings, overrides, patches, host.major)
250
246
  const hook = createHook({ overrides, ignored: settings.ignoredOptionalDependencies, major: host.major })
251
- checkProjects(lockfile, manifests, { hook, host, settings })
247
+ checkProjects(lockfile, manifests, { hook, host, settings, env })
252
248
  checkOptional(lockfile)
253
249
  const projects = settings.hoistWorkspacePackages ? workspaceNames(manifests) : new Map()
254
250
  const { skipped, incompatible } = skippedSnapshots(lockfile, { host, settings })
255
- const { nodes, direct } = await buildGraph(lockfile, skipped, settings.virtualStoreDirMaxLength, host.major)
251
+ const { nodes, direct, hoisting } = await buildGraph(lockfile, skipped, settings.virtualStoreDirMaxLength, host.major)
256
252
  for (const node of nodes.values()) checkSource(node, installed)
257
253
 
258
- const { byDir, tarballs } = await fetchNodes(nodes, hook, project, host.major)
259
- const links = linksOf(byDir, direct, settings, projects, host.major)
254
+ const { byDir, tarballs } = await fetchNodes(nodes, hook, project, host.major, createFreshnessCheck(lockfile, host.major))
255
+ const links = linksOf(byDir, direct, settings, projects, host.major, hoisting)
260
256
  const linked = readLinked(links, byDir, manifests, project)
261
257
  const targets = binTargets({
262
258
  nodes: byDir,
@@ -268,7 +264,7 @@ export async function buildPnpmTree(options) {
268
264
  peers: settings.autoInstallPeers,
269
265
  major: host.major,
270
266
  })
271
- const executable = executableElsewhere(byDir, targets)
267
+ const executable = executableElsewhere(byDir, targets, settings.packageImportMethod, host.major)
272
268
 
273
269
  const vfs = new Vfs()
274
270
  vfs.mkdir('/node_modules/.pnpm', { recursive: true })
@@ -17,8 +17,16 @@
17
17
  // refused, and so is a glob reaching outside the workspace's directory.
18
18
  // pnpm 11 leaves out what a `!` glob takes with micromatch too, a name
19
19
  // starting with a dot and all.
20
-
21
- import { normalize } from '@preventive/vfs/path.js'
20
+ //
21
+ // pnpm 12 finds them its own way (its projects walk, with wax), and the
22
+ // same but in four places: a `**` may take no name before one a glob
23
+ // spells with a leading dot; nothing under a node_modules or a
24
+ // bower_components is walked into or taken, wherever it is; where a glob
25
+ // with a `*` takes a directory, the first of its manifests that is there
26
+ // is read, which fails where it is not a file; and the projects come in
27
+ // the order of their paths by name.
28
+
29
+ import { compareNames, normalize } from '@preventive/vfs/path.js'
22
30
  import { DeptreeError, quote } from '../error.js'
23
31
  import { escape } from '../matcher.js'
24
32
  import { typeOf } from './project.js'
@@ -84,29 +92,66 @@ function enters({ names: glob, dot }, names) {
84
92
  }
85
93
 
86
94
  // `packages`, the globs or undefined, as the globs that take and those
87
- // that leave out; `major` pnpm's major version.
95
+ // that leave out, with how pnpm `major` walks for them: which directories
96
+ // it enters for a glob, which it ignores, and which manifests it drops
97
+ // whatever the globs say. pnpm 12 reads the manifest of a directory a
98
+ // glob with a `*` takes, which is `wild`, whatever it is.
88
99
  function compileAll(packages, major) {
89
- const globs = { include: [], exclude: [] }
100
+ const twelve = major >= 12
101
+ const globs = { include: [], exclude: [], enters: twelve ? enters12 : enters, ignored: twelve ? ignored12 : ignored, dropped: twelve ? ignored12 : () => false }
90
102
  for (const glob of packages ?? []) {
91
103
  const exclude = glob.startsWith('!')
92
- globs[exclude ? 'exclude' : 'include'].push(compile(exclude ? glob.slice(1) : glob, 'pnpm-workspace.yaml: packages', exclude && major >= 11))
104
+ const compiled = compile(exclude ? glob.slice(1) : glob, 'pnpm-workspace.yaml: packages', exclude && major >= 11)
105
+ globs[exclude ? 'exclude' : 'include'].push({ ...compiled, wild: twelve && glob.includes('*') })
93
106
  }
94
107
  return globs
95
108
  }
96
109
 
110
+ // The manifest pnpm reads of the directory at `names`, given the names in
111
+ // it: the first of them there that is a file, a link that leads nowhere
112
+ // passed over. pnpm 12 reads the first there, where a glob with a `*`
113
+ // takes the directory, and fails where that is not a file.
114
+ function manifestOf(project, globs, names, entries) {
115
+ const wild = () => globs.include.some((glob) => glob.wild && takes(glob, [...names, 'package.json']))
116
+ for (const name of MANIFESTS) {
117
+ if (!entries.includes(name)) continue
118
+ const type = typeOf(project, `/${[...names, name].join('/')}`)
119
+ if (type === 'file') return name
120
+ if (type !== undefined && wild()) throw new DeptreeError(`pnpm 12 reads this as a manifest, and fails on it as a ${type}`, quote([...names, name].join('/')))
121
+ }
122
+ return undefined
123
+ }
124
+
125
+ // Two paths in the order of their names, as pnpm 12 has them.
126
+ function byNames(a, b) {
127
+ const x = a.split('/')
128
+ const y = b.split('/')
129
+ for (let i = 0; i < Math.min(x.length, y.length); i++) if (x[i] !== y[i]) return compareNames(x[i], y[i])
130
+ return x.length - y.length
131
+ }
132
+
97
133
  // What find-packages leaves out, as tinyglobby reads it, which does not
98
134
  // take a name with a leading dot for `**`: what is under node_modules or
99
135
  // bower_components.
100
- const IGNORED = ['node_modules', 'bower_components'].map((name) => ({ names: ['**', NAME(name, false), '**'], dot: false }))
136
+ const LEFT_OUT = ['node_modules', 'bower_components']
137
+ const IGNORED = LEFT_OUT.map((name) => ({ names: ['**', NAME(name, false), '**'], dot: false }))
101
138
  const ignored = (names) => IGNORED.some((glob) => takes(glob, names))
102
139
 
140
+ // What pnpm 12 never walks into or takes: anything with one of those in
141
+ // its path.
142
+ const ignored12 = (names) => names.some((name) => LEFT_OUT.includes(name))
143
+
144
+ // Whether pnpm 12 walks into the directory at `names` for a glob: where
145
+ // the glob's names before its last may take it.
146
+ const enters12 = (glob, names) => reach(glob, names).slice(0, glob.names.length).some(Boolean)
147
+
103
148
  // Whether the globs take the manifest at `names`. What find-packages
104
149
  // ignores it is not ignored for, in a directory tinyglobby walks into.
105
- const taken = ({ include, exclude }, names) => include.some((glob) => takes(glob, names)) && !exclude.some((glob) => takes(glob, names))
150
+ const taken = ({ include, exclude, dropped }, names) => include.some((glob) => takes(glob, names)) && !exclude.some((glob) => takes(glob, names)) && !dropped(names)
106
151
 
107
152
  // Whether tinyglobby walks into the directory at `names`, which it does
108
- // through a link to one too.
109
- const walked = ({ include }, names) => include.some((glob) => enters(glob, names)) && !ignored(names)
153
+ // through a link to one too; or pnpm 12.
154
+ const walked = (globs, names) => globs.include.some((glob) => globs.enters(glob, names)) && !globs.ignored(names)
110
155
 
111
156
  // `ids` are the projects' directories, `.` the root; `packages` the globs,
112
157
  // or undefined; `major` pnpm's major version. pnpm finds a project where
@@ -165,9 +210,7 @@ export function findProjects(project, packages, major = 10) {
165
210
  const { names, link } = pending.pop()
166
211
  const dir = names.join('/')
167
212
  const entries = project.readdir(`/${dir}`)
168
- const found = names.length === 0 || taken(globs, [...names, 'package.json'])
169
- ? MANIFESTS.find((name) => entries.includes(name) && typeOf(project, `/${[...names, name].join('/')}`) === 'file')
170
- : undefined
213
+ const found = names.length === 0 || taken(globs, [...names, 'package.json']) ? manifestOf(project, globs, names, entries) : undefined
171
214
  if (names.length === 0 && found === undefined) throw new DeptreeError('pnpm takes a workspace with no manifest at its root for one with no root project, which is not supported', quote('package.json'))
172
215
  if (found !== undefined) {
173
216
  const file = [...names, found].join('/')
@@ -192,5 +235,5 @@ export function findProjects(project, packages, major = 10) {
192
235
  else throw new DeptreeError(`a link to a directory in one tinyglobby follows, ${quote(path)}, is not supported`, quote(link))
193
236
  }
194
237
  }
195
- return ['.', ...ids.sort()]
238
+ return ['.', ...major >= 12 ? ids.sort(byNames) : ids.sort()]
196
239
  }