@preventive/deptree 1.0.0-alpha.9 → 1.0.1

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.
@@ -74,8 +74,14 @@ function readManifest(files, pkg, where) {
74
74
  return manifest
75
75
  }
76
76
 
77
- export function checkManifest(manifest, pkg, where, major) {
77
+ // npm's abbreviated metadata, which pnpm resolves from unless a setting such
78
+ // as supportedArchitectures.libc has it ask for the full document, has no
79
+ // libc, nor has the package.json pnpm 9 and 10 keep in the store: a lockfile
80
+ // may leave out a libc a registry package's package.json has. One it names is
81
+ // held to it, as a directory's always is: pnpm reads that package.json whole.
82
+ export function checkManifest(manifest, pkg, where, major, registry = false) {
78
83
  for (const field of ['os', 'cpu', 'libc']) {
84
+ if (registry && field === 'libc' && pkg.libc === undefined) continue
79
85
  if (!same(manifest[field], pkg[field])) throw new DeptreeError(`package.json's ${field} is not the lockfile's`, where)
80
86
  }
81
87
  const has = hasBin(manifest, major)
@@ -114,10 +120,10 @@ export function checkDependencies(manifest, read, pkg, packages, where) {
114
120
  }
115
121
  }
116
122
 
117
- export async function fetchPackage(pkg, where, major) {
118
- const { entries } = await fetchTarball(pkg.name, pkg.version, pkg.resolution.integrity, where)
123
+ export async function fetchPackage(pkg, where, major, fetching) {
124
+ const { entries, about } = await fetchTarball(pkg.name, pkg.version, pkg.resolution.integrity, where, fetching)
119
125
  const files = filesOf(entries, where)
120
126
  const manifest = readManifest(files, pkg, where)
121
- checkManifest(manifest, pkg, where, major)
122
- return { files, manifest }
127
+ checkManifest(manifest, pkg, where, major, true)
128
+ return { files, manifest, about }
123
129
  }
@@ -6,6 +6,7 @@
6
6
  // all read alike. Refused are a link the walk comes on, which they treat
7
7
  // differently, and a mode a checkout does not have under umask 022 or 002.
8
8
 
9
+ import { utf8toString } from '@exodus/bytes/utf8.js'
9
10
  import { compareVersions, valid } from '@preventive/upstream/semver.js'
10
11
  import { normalize } from '@preventive/vfs/path.js'
11
12
  import { DeptreeError, quote } from '../error.js'
@@ -13,7 +14,6 @@ import { readBytes } from '../project.js'
13
14
  import { bytesOf, gitignoreGlob, matched, matchedOrParents } from './gitignore.js'
14
15
  import { pack10, pack11 } from './npm-packlist.js'
15
16
 
16
- const decoder = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true })
17
17
 
18
18
  const MODES = new Set([0o644, 0o664, 0o755, 0o775])
19
19
 
@@ -58,7 +58,7 @@ function viewOf(project, dir, where) {
58
58
  text(rel, here) {
59
59
  if (view.type(rel) !== 'file') throw new DeptreeError('it is not a file, which pnpm fails to read', here)
60
60
  try {
61
- return decoder.decode(readBytes(project, absolute(rel)))
61
+ return utf8toString(readBytes(project, absolute(rel)))
62
62
  } catch {
63
63
  throw new DeptreeError('it is not UTF-8, which is not supported', here)
64
64
  }
package/src/pnpm/tree.js CHANGED
@@ -1,7 +1,9 @@
1
1
  // The node_modules tree pnpm 9, 10, 11 or 12 installs from a frozen lockfile
2
2
  // with the isolated linker and --ignore-scripts, in a Vfs rooted at the
3
3
  // lockfile's directory; patched still, as pnpm patches before scripts. Bins are
4
- // not linked, though what linking does to their files is (bins.js).
4
+ // not linked, though what linking does to their files is (bins.js). With
5
+ // `sizeEstimateOnly`, its directories and links alone, each package's sized
6
+ // by its version document, of which nothing is fetched but those documents.
5
7
 
6
8
  import { packageKeyOf } from '@preventive/lockfile/pnpm.js'
7
9
  import { compareVersions } from '@preventive/upstream/semver.js'
@@ -12,11 +14,11 @@ import { DeptreeError, quote, refusalOf } from '../error.js'
12
14
  import { checkNoModules, checkWrite, fold, isInside, makeDirs, mount, writeLink } from '../mount.js'
13
15
  import { applyPatch, parsePatch } from '../patch.js'
14
16
  import { checkProject, typeOf } from '../project.js'
15
- import { REGISTRY, tarballUrl } from '../tarball.js'
17
+ import { NO_ABOUT, REGISTRY, fetchSize, fetchingOf, tarballUrl } from '../tarball.js'
16
18
  import { binTargets, checkPatchOfBins, executableMode, fixBin, hoistedBinTargets, requiresBuild } from './bins.js'
17
19
  import { buildGraph } from './graph.js'
18
20
  import { hoist } from './hoist.js'
19
- import { hoistedBuilds, hoistedLayout, hoistedModules, packageIdOf, prodPackages, workspaceHoists } from './hoisted.js'
21
+ import { checkNoneDropped, hoistedBuilds, hoistedLayout, hoistedModules, packageIdOf, prodPackages, workspaceHoists } from './hoisted.js'
20
22
  import { checkLocalOverrides, createFreshnessCheck, readDirectoryPackage, readLinked } from './local.js'
21
23
  import { createPatchedCheck, skippedSnapshots } from './install.js'
22
24
  import { checkDependencies, fetchPackage } from './package.js'
@@ -65,28 +67,39 @@ function checkSource(node, installed) {
65
67
  if (!resolution.integrity?.startsWith('sha512-')) throw new DeptreeError('expected a sha512 integrity', quote(key))
66
68
  }
67
69
 
70
+ const bytesOf = (files) => files.values().reduce((sum, file) => sum + file.data.length, 0)
71
+
68
72
  // By name@version, as the lockfile reader gives a package's snapshots one
69
- // resolution and manifest.
70
- async function fetchAll(nodes, project, host) {
73
+ // resolution and manifest. With `sizeEstimateOnly`, a registry package's size
74
+ // alone, with no files or package.json; a directory is read whole all the
75
+ // same, and its size is its files'.
76
+ async function fetchAll(nodes, project, host, fetching) {
71
77
  const packages = new Map([...nodes.values()].map(({ key, pkg }) => [packageKeyOf(key), pkg]))
72
78
  const fetched = new Map()
79
+ const fetch = (pkg, where) => (fetching.sizeEstimateOnly ? fetchSize(pkg.name, pkg.version, pkg.resolution.integrity, where, fetching) : fetchPackage(pkg, where, host.major, fetching))
80
+ const read = (pkg, where) => {
81
+ const got = readDirectoryPackage(project, pkg, where, host)
82
+ return fetching.sizeEstimateOnly ? { ...got, size: bytesOf(got.files) } : got
83
+ }
73
84
  await eachConcurrently(packages, async ([id, pkg]) => {
74
- fetched.set(id, pkg.resolution.type === 'directory' ? readDirectoryPackage(project, pkg, quote(id), host) : await fetchPackage(pkg, quote(id), host.major))
85
+ fetched.set(id, pkg.resolution.type === 'directory' ? read(pkg, quote(id)) : await fetch(pkg, quote(id)))
75
86
  }, ([id]) => quote(id))
76
87
  return fetched
77
88
  }
78
89
 
79
- async function fetchNodes(nodes, lockfile, hook, project, host) {
80
- const fetched = await fetchAll(nodes, project, host)
90
+ async function fetchNodes(nodes, lockfile, hook, project, host, fetching) {
91
+ const fetched = await fetchAll(nodes, project, host, fetching)
81
92
  const fresh = createFreshnessCheck(lockfile, host.major)
82
93
  const byDir = new Map()
83
94
  for (const node of nodes.values()) {
84
95
  const id = packageKeyOf(node.key)
85
96
  const got = fetched.get(id)
86
- got.read ??= hook(got.manifest, `${quote(id)}: package.json`)
87
- checkDependencies(got.manifest, got.read, node.pkg, lockfile.packages, quote(node.key))
88
- fresh?.(node, got.read)
89
- byDir.set(node.dir, { ...node, files: got.files, manifest: got.manifest })
97
+ if (got.manifest !== undefined) {
98
+ got.read ??= hook(got.manifest, `${quote(id)}: package.json`)
99
+ checkDependencies(got.manifest, got.read, node.pkg, lockfile.packages, quote(node.key))
100
+ fresh?.(node, got.read)
101
+ }
102
+ byDir.set(node.dir, { ...node, files: got.files, manifest: got.manifest, about: got.about ?? NO_ABOUT, size: got.size })
90
103
  }
91
104
  return { byDir, tarballs: [...fetched.values()].filter((got) => !got.local).length }
92
105
  }
@@ -184,8 +197,8 @@ function reachedInProd(importers, nodes, byDir) {
184
197
  return reached
185
198
  }
186
199
 
187
- function installedOf(node, dev, patches) {
188
- const { key, name, dir, pkg: { version, resolution, optional, patchHash } } = node
200
+ function installedOf(node, dev, patches, sizeEstimateOnly) {
201
+ const { key, name, dir, about, size, pkg: { version, resolution, optional, patchHash } } = node
189
202
  return {
190
203
  path: dir,
191
204
  key,
@@ -193,9 +206,11 @@ function installedOf(node, dev, patches) {
193
206
  version,
194
207
  integrity: resolution.integrity,
195
208
  directory: resolution.directory,
209
+ ...about,
196
210
  dev,
197
211
  optional,
198
212
  patch: patchHash === undefined ? undefined : { hash: patchHash, path: patches.get(patchHash).path },
213
+ ...sizeEstimateOnly ? { size } : {},
199
214
  }
200
215
  }
201
216
 
@@ -220,8 +235,9 @@ const COPYING = new Set(['copy', 'clone', 'clone-or-copy'])
220
235
 
221
236
  // The hoisted layout of pnpm 10 and 11 (hoisted.js): nothing but the packages
222
237
  // and links, each copy a parent before what lands in its node_modules, as
223
- // pnpm keeps only its state in node_modules/.pnpm.
224
- async function buildHoisted({ lockfile, settings, host, project, hook, installed, manifests, names, patched, skipped }) {
238
+ // pnpm keeps only its state in node_modules/.pnpm. With `sizeEstimateOnly`,
239
+ // what pnpm's build pass does to the files is not followed.
240
+ async function buildHoisted({ lockfile, settings, host, project, hook, installed, manifests, names, patched, skipped, fetching }) {
225
241
  const { major } = host
226
242
  const since = (version) => compareVersions(host.pnpm, version) >= 0
227
243
  if (!COPYING.has(settings.packageImportMethod)) {
@@ -231,29 +247,35 @@ async function buildHoisted({ lockfile, settings, host, project, hook, installed
231
247
  const { placed, links, projects } = hoistedLayout(lockfile, { autoInstallPeers: settings.autoInstallPeers, skipped, directories, rootLinks: since('11.28.1') })
232
248
  if (since('11.28.0')) for (const [path, id] of workspaceHoists(placed, lockfile, settings, names)) links.set(path, id)
233
249
  for (const node of placed.values()) checkSource(node, installed)
234
- const { byDir, tarballs } = await fetchNodes(placed, lockfile, hook, project, host)
235
- const linked = readLinked(links, byDir, manifests, project)
236
250
  // pnpm builds where any patch is configured, though scripts are ignored.
237
251
  const building = Object.keys(settings.patchedDependencies ?? {}).length > 0
238
252
  const hardlinks = since('10.21.0')
239
253
  const keepsModules = since('11.25.0')
254
+ if (fetching.sizeEstimateOnly && building && hardlinks && !keepsModules) checkNoneDropped(placed, host.pnpm)
255
+ const { byDir, tarballs } = await fetchNodes(placed, lockfile, hook, project, host, fetching)
256
+ const linked = readLinked(links, byDir, manifests, project)
257
+ const prod = prodPackages(lockfile, skipped, directories)
258
+ const dev = (node) => !prod.has(packageIdOf(node.key, node.pkg, directories))
259
+ if (fetching.sizeEstimateOnly) return { byDir, links, targets: new Map(), executable: new Map(), tarballs, dev }
240
260
  const idOf = since('11.23.0') ? (key) => packageIdOf(key, lockfile.packages[key], directories) : (key) => key
241
261
  const changesOf = (node) => parsedPatch(patched, node.pkg.patchHash).parsed
242
262
  const builds = building ? hoistedBuilds(byDir, new Set(projects), (node) => node.pkg.patchHash !== undefined || requiresBuild(node.manifest, node.files, major), { hardlinks, keepsModules, idOf, changesOf, pnpm: host.pnpm }) : []
243
263
  const targets = hoistedBinTargets({ nodes: byDir, projects: new Map([...manifests, ...linked]), modules: hoistedModules(byDir, links, projects, manifests, lockfile), builds, hardlinks, keepsModules, idOf, major })
244
- const prod = prodPackages(lockfile, skipped, directories)
245
- return { byDir, links, targets, executable: new Map(), tarballs, dev: (node) => !prod.has(packageIdOf(node.key, node.pkg, directories)) }
264
+ return { byDir, links, targets, executable: new Map(), tarballs, dev }
246
265
  }
247
266
 
248
267
  // The isolated layout: each package in node_modules/.pnpm, linked from what
249
268
  // needs it and where it is hoisted.
250
- async function buildIsolated({ lockfile, settings, host, project, hook, installed, manifests, names, skipped }) {
269
+ async function buildIsolated({ lockfile, settings, host, project, hook, installed, manifests, names, skipped, fetching }) {
251
270
  const { major } = host
252
271
  const { nodes, direct, hoisting } = await buildGraph(lockfile, skipped, settings.virtualStoreDirMaxLength, major)
253
272
  for (const node of nodes.values()) checkSource(node, installed)
254
- const { byDir, tarballs } = await fetchNodes(nodes, lockfile, hook, project, host)
273
+ const { byDir, tarballs } = await fetchNodes(nodes, lockfile, hook, project, host, fetching)
255
274
  const links = linksOf(byDir, direct, settings, names, major, hoisting)
256
275
  const linked = readLinked(links, byDir, manifests, project)
276
+ const prod = reachedInProd(lockfile.importers, nodes, byDir)
277
+ const dev = (node) => !prod.has(node.dir)
278
+ if (fetching.sizeEstimateOnly) return { byDir, links, targets: new Map(), executable: new Map(), tarballs, dev }
257
279
  const targets = binTargets({
258
280
  nodes: byDir,
259
281
  projects: new Map([...manifests, ...linked]),
@@ -264,13 +286,14 @@ async function buildIsolated({ lockfile, settings, host, project, hook, installe
264
286
  peers: settings.autoInstallPeers,
265
287
  major,
266
288
  })
267
- const prod = reachedInProd(lockfile.importers, nodes, byDir)
268
- return { byDir, links, targets, executable: executableElsewhere(byDir, targets, settings.packageImportMethod, major), tarballs, dev: (node) => !prod.has(node.dir) }
289
+ return { byDir, links, targets, executable: executableElsewhere(byDir, targets, settings.packageImportMethod, major), tarballs, dev }
269
290
  }
270
291
 
271
292
  export async function buildPnpmTree(options) {
272
293
  const { project, host: given, vfs: into } = options ?? {}
273
294
  if (into !== undefined && !(into instanceof Vfs)) throw new TypeError('vfs must be a Vfs, or left out')
295
+ const fetching = fetchingOf(options ?? {})
296
+ if (fetching.sizeEstimateOnly && into !== undefined) throw new TypeError('vfs is not taken with sizeEstimateOnly, whose tree has no files to mount')
274
297
  if (project !== undefined) checkProject(project)
275
298
  const machine = checkHost(given)
276
299
  const folded = machine.os === 'darwin'
@@ -303,7 +326,7 @@ export async function buildPnpmTree(options) {
303
326
  const names = settings.hoistWorkspacePackages ? workspaceNames(manifests) : new Map()
304
327
  const { skipped, incompatible } = skippedSnapshots(lockfile, { host, settings })
305
328
  const hoisted = settings.nodeLinker === 'hoisted'
306
- const { byDir, links, targets, executable, tarballs, dev } = await (hoisted ? buildHoisted : buildIsolated)({ lockfile, settings, host, project, hook, installed, manifests, names, patched, skipped })
329
+ const { byDir, links, targets, executable, tarballs, dev } = await (hoisted ? buildHoisted : buildIsolated)({ lockfile, settings, host, project, hook, installed, manifests, names, patched, skipped, fetching })
307
330
 
308
331
  const vfs = new Vfs()
309
332
  if (!hoisted) makeDirs(vfs, 'node_modules/.pnpm')
@@ -311,14 +334,17 @@ export async function buildPnpmTree(options) {
311
334
  const listed = []
312
335
  const composing = { major, checkPatched: createPatchedCheck({ host, settings }) }
313
336
  // Each node is let go once written, and a package's files with its last.
337
+ // With `sizeEstimateOnly`, its directory alone is made, and its size
338
+ // counted.
314
339
  for (const node of byDir.values()) {
315
340
  byDir.delete(node.dir)
316
341
  try {
317
- writeNode(vfs, node.dir, compose(node, patched, { targets: targets.get(node.dir) ?? new Set(), executable: executable.get(node.dir) ?? new Set() }, composing), stats)
342
+ writeNode(vfs, node.dir, fetching.sizeEstimateOnly ? new Map() : compose(node, patched, { targets: targets.get(node.dir) ?? new Set(), executable: executable.get(node.dir) ?? new Set() }, composing), stats)
318
343
  } catch (error) {
319
344
  throw refusalOf(error, quote(node.key))
320
345
  }
321
- listed.push(installedOf(node, dev(node), patched))
346
+ if (fetching.sizeEstimateOnly) stats.bytes += node.size ?? 0
347
+ listed.push(installedOf(node, dev(node), patched, fetching.sizeEstimateOnly))
322
348
  }
323
349
  for (const [path, target] of links) {
324
350
  try {
package/src/project.js CHANGED
@@ -1,6 +1,7 @@
1
1
  // The project, the lockfile's directory, as a Vfs or anything with its
2
2
  // methods, by paths from `/`; it is only read, and only where a builder says.
3
3
 
4
+ import { utf8toString } from '@exodus/bytes/utf8.js'
4
5
  import { DeptreeError, quote } from './error.js'
5
6
 
6
7
  export function checkProject(project) {
@@ -19,13 +20,11 @@ export function typeOf(project, path, follow = true) {
19
20
  }
20
21
  }
21
22
 
22
- // A BOM is kept, as in text handed in, for the reader to drop as pnpm does.
23
- const decoder = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true })
24
-
25
- // `bytes` as text, refused with `detail` where they are not UTF-8.
23
+ // `bytes` as text, refused with `detail` where they are not UTF-8. A BOM is
24
+ // kept, as in text handed in, for the reader to drop as pnpm does.
26
25
  export function decodeUtf8(bytes, detail, where) {
27
26
  try {
28
- return decoder.decode(bytes)
27
+ return utf8toString(bytes)
29
28
  } catch {
30
29
  throw new DeptreeError(detail, where)
31
30
  }
@@ -32,12 +32,17 @@ function checkLibs(doc) {
32
32
  }
33
33
 
34
34
  const BOOLEANS = ['remappings_generate', 'remappings_regenerate', 'remappings_version', 'recursive_deps']
35
+ const SETTINGS = new Set([...BOOLEANS, 'remappings_prefix', 'remappings_location'])
35
36
 
36
- // read_soldeer_config's SoldeerConfig, by serde; unknown fields passed over.
37
+ // read_soldeer_config's SoldeerConfig, by serde, which passes over a field
38
+ // it does not have; one is refused here, as a later Soldeer may install
39
+ // otherwise by it.
37
40
  function checkSettings(settings, file) {
38
41
  if (settings === undefined) return
39
42
  const where = `${file}: soldeer`
40
43
  if (!isTable(settings)) throw new DeptreeError('not a table, which Soldeer fails on', where)
44
+ const other = Object.keys(settings).find((key) => !SETTINGS.has(key))
45
+ if (other !== undefined) throw new DeptreeError('a setting Soldeer 0.12 does not have, which is not supported', `${where}.${other}`)
41
46
  for (const key of BOOLEANS) {
42
47
  if (settings[key] !== undefined && typeof settings[key] !== 'boolean') throw new DeptreeError('not true or false, which Soldeer fails on', `${where}.${key}`)
43
48
  }
@@ -4,6 +4,7 @@
4
4
 
5
5
  import { decompress } from '@preventive/archive/compression.js'
6
6
  import { ArchiveError, unpack } from '@preventive/archive/tar.js'
7
+ import { HttpError } from '@preventive/upstream/github.js'
7
8
  import { DeptreeError, quote } from '../error.js'
8
9
  import { MAX_BYTES } from '../tarball.js'
9
10
  import { isGit } from './zip.js'
@@ -21,12 +22,26 @@ export function githubRepoOf(url) {
21
22
  return repo === undefined || /\/\.\.?$/u.test(repo) ? undefined : repo
22
23
  }
23
24
 
25
+ // A repository renamed or transferred since the lockfile named it, which
26
+ // GitHub answers with a redirect that git's clone follows, is asked for by
27
+ // the name GitHub gives it now, as upstream's getRepo follows the redirect;
28
+ // any other redirect is refused there. The commit holds what is fetched.
29
+ async function tarballOf(github, repo, rev) {
30
+ try {
31
+ return await github.getRepoTarball({ repo, sha: rev })
32
+ } catch (error) {
33
+ if (!(error instanceof HttpError) || error.status < 300 || error.status >= 400) throw error
34
+ const moved = await github.getRepo({ repo, followRedirect: true })
35
+ return await github.getRepoTarball({ repo: moved.full_name, sha: rev })
36
+ }
37
+ }
38
+
24
39
  // GitHub's tarball, which upstream holds to the tree GitHub names for the
25
40
  // commit, files, symlinks and the submodules it shows as empty directories
26
41
  // alike. Unpacked as a checkout with umask 0o022 writes it: directories
27
42
  // 0o755, files 0o644 or 0o755 by the bit git keeps, symlinks as symlinks.
28
43
  export async function checkoutOf(github, repo, rev, where) {
29
- const bytes = await github.getRepoTarball({ repo, sha: rev })
44
+ const bytes = await tarballOf(github, repo, rev)
30
45
  let entries
31
46
  try {
32
47
  entries = unpack(await decompress(bytes, 'gzip', { limit: MAX_BYTES }))
@@ -1,11 +1,12 @@
1
1
  // The dependencies folder `soldeer install` makes from a soldeer.lock.
2
2
 
3
+ import { utf8fromStringLoose } from '@exodus/bytes/utf8.js'
3
4
  import { parseSoldeerLockfile } from '@preventive/lockfile/soldeer.js'
4
5
  import { getZip } from '@preventive/upstream/soldeer.js'
5
6
  import { Vfs } from '@preventive/vfs'
6
7
  import { eachConcurrently } from '../concurrent.js'
7
8
  import { DeptreeError, quote } from '../error.js'
8
- import { fold, makeDirs, mount, writeFiles } from '../mount.js'
9
+ import { checkNoDir, fold, makeDirs, mount, writeFiles } from '../mount.js'
9
10
  import { configOf } from './config.js'
10
11
  import { checkoutOf, githubRepoOf } from './git.js'
11
12
  import { checkHost, inputsOf } from './inputs.js'
@@ -17,18 +18,11 @@ const NAME = /^(?=.{3,100}$)[@\da-z][\da-z-]*[\da-z]$/u
17
18
  const VERSION = /^(?=.{1,128}$)[\dA-Za-z][\w.+-]*$/u
18
19
  // A folder sanitize_filename leaves as it is on Unix: none of the characters
19
20
  // it replaces, and at most 255 bytes, past which it cuts the name short.
20
- const encoder = new TextEncoder()
21
- const isKept = (folder) => !/[/?<>\\:*|"\p{Cc}]/u.test(folder) && encoder.encode(folder).length <= 255
21
+ const isKept = (folder) => !/[/?<>\\:*|"\p{Cc}]/u.test(folder) && utf8fromStringLoose(folder).length <= 255
22
22
 
23
23
  const GITHUB = 'github must be a GitHub client from createClient, which a git dependency is fetched through'
24
24
 
25
- function checkNoDependencies(vfs, folded) {
26
- for (const name of vfs.readdir('/')) {
27
- if (name === 'dependencies' || (folded && fold(name) === 'dependencies')) {
28
- throw new DeptreeError('a dependencies folder is there already, which is neither kept beside the tree nor removed', `vfs[${quote(`/${name}`)}]`)
29
- }
30
- }
31
- }
25
+ const checkNoDependencies = checkNoDir('dependencies', 'a dependencies folder')
32
26
 
33
27
  const about = (name) => `dependencies[${quote(name)}]`
34
28
 
@@ -68,7 +62,7 @@ async function fetchAll(dependencies, github) {
68
62
  export async function buildSoldeerTree(options) {
69
63
  const { host: given, vfs: into, github } = options ?? {}
70
64
  if (into !== undefined && !(into instanceof Vfs)) throw new TypeError('vfs must be a Vfs, or left out')
71
- if (github !== undefined && typeof github?.getRepoTarball !== 'function') throw new TypeError(GITHUB)
65
+ if (github !== undefined && (typeof github?.getRepoTarball !== 'function' || typeof github.getRepo !== 'function')) throw new TypeError(GITHUB)
72
66
  const inputs = inputsOf(options ?? {})
73
67
  const folded = checkHost(given).os === 'darwin'
74
68
  // Refused before anything is fetched; mount checks again.
@@ -84,6 +78,6 @@ export async function buildSoldeerTree(options) {
84
78
  for (const { folder } of dependencies) {
85
79
  writeFiles(vfs, `dependencies/${folder}`, extracted.get(folder), stats)
86
80
  }
87
- const installed = dependencies.map(({ type, name, version, checksum, git, rev, folder }) => ({ path: `dependencies/${folder}`, name, version, ...(type === 'git' ? { git, rev } : { checksum }) }))
81
+ const installed = dependencies.map(({ type, name, version, checksum, git, rev, folder }) => ({ path: `dependencies/${folder}`, name, version, ...(type === 'git' ? { git, rev, commit: rev } : { checksum }) }))
88
82
  return { vfs: mount(vfs, into, folded, checkNoDependencies), stats, installed }
89
83
  }
@@ -4,6 +4,7 @@
4
4
  // every directory is 0o755, and a file's mode its Unix mode as the zip crate
5
5
  // reads it, or 0o644 where it reads none; a symlink is a file of its target.
6
6
 
7
+ import { utf8fromStringLoose, utf8toStringLoose } from '@exodus/bytes/utf8.js'
7
8
  import { ArchiveError, unzip } from '@preventive/archive/zip.js'
8
9
  import { DeptreeError, quote } from '../error.js'
9
10
  import { bytesSha256Hex } from '../hash.js'
@@ -16,8 +17,6 @@ const S_IFLNK = 0o120000
16
17
  const [NTFS, TIMESTAMP, UNICODE_COMMENT, AES] = [0x000a, 0x5455, 0x6375, 0x9901]
17
18
 
18
19
  // As the archive reader decodes a name: a leading U+FEFF is part of it.
19
- const decoder = new TextDecoder('utf-8', { ignoreBOM: true })
20
- const encoder = new TextEncoder()
21
20
 
22
21
  const ones = (byte) => [...byte.toString(2)].filter((bit) => bit === '1').length
23
22
 
@@ -93,7 +92,7 @@ export async function extractZip(bytes, checksum, where) {
93
92
  const last = new Map()
94
93
  for (const [index, entry] of entries.entries()) {
95
94
  const record = records[index]
96
- if (decoder.decode(record.name) !== entry.storedName) throw new Error('unreachable: unzip lists entries out of the central directory\'s order')
95
+ if (utf8toStringLoose(record.name) !== entry.storedName) throw new Error('unreachable: unzip lists entries out of the central directory\'s order')
97
96
  const here = `${where}: ${quote(entry.storedName)}`
98
97
  if (record.extra !== undefined) throw new DeptreeError(`${record.extra}, which Soldeer fails on`, here)
99
98
  if (!(record.flags & UTF8) && record.name.some((byte) => byte >= 0x80)) throw new DeptreeError('a name not flagged UTF-8, which Soldeer reads as CP437, is not supported', here)
@@ -113,7 +112,7 @@ export async function extractZip(bytes, checksum, where) {
113
112
  continue
114
113
  }
115
114
  const mode = unixMode(records[index])
116
- const data = entry.type === 'symlink' ? encoder.encode(entry.linkname) : entry.data
115
+ const data = entry.type === 'symlink' ? utf8fromStringLoose(entry.linkname) : entry.data
117
116
  // A file written again keeps its mode where the zip crate reads none.
118
117
  const kept = mode === undefined || (mode & S_IFLNK) === S_IFLNK ? files.get(entry.name)?.mode ?? 0o644 : mode & 0o777 & ~0o022
119
118
  files.set(entry.name, { data, mode: kept })
package/src/tarball.js CHANGED
@@ -1,9 +1,12 @@
1
1
  // A registry tarball, fetched through @preventive/upstream, which checks the
2
- // integrity it is given, and checked again here, as that is the lockfile's.
2
+ // integrity it is given, and checked again here, as that is the lockfile's;
3
+ // and its version's document from the registry, where asked for, for what
4
+ // it says of where the package comes from, or alone, for its size.
3
5
 
4
- import { CompressionError, decompress } from '@preventive/archive/compression.js'
6
+ import { decompress } from '@preventive/archive/compression.js'
5
7
  import { unpack } from '@preventive/archive/tar.js'
6
8
  import { getMeta, getTarball } from '@preventive/upstream/npm.js'
9
+ import { settled } from './concurrent.js'
7
10
  import { DeptreeError, quote } from './error.js'
8
11
  import { matchesIntegrity } from './hash.js'
9
12
  import { fold } from './mount.js'
@@ -79,47 +82,59 @@ export function withDirs(files, where, dirs = new Set()) {
79
82
  return { files, dirs }
80
83
  }
81
84
 
82
- // Old tarballs, as npm 1.0 packed them through the system's tar, may run on
83
- // in zeros past their gzip stream, to a whole 10240-byte record. Node's
84
- // zlib, which npm, pnpm and yarn unpack through, stops at a zero byte after
85
- // the stream; the platform's stream refuses anything there, so the zeros are
86
- // cut off. The stream's last four bytes are the length its last member
87
- // inflates to, under 2^32 as MAX_BYTES is, so it ends within three bytes
88
- // past the last that is not zero; or, where that member is empty, as zlib
89
- // writes one, `03 00` and eight zeros, within nine. It ends at the one place
90
- // it decompresses whole. Each place tried inflates it all again, which only
91
- // a padded tarball pays for.
92
- async function gunzip(bytes) {
93
- const inflate = (end) => decompress(bytes.subarray(0, end), 'gzip', { limit: MAX_BYTES })
94
- try {
95
- return await inflate(bytes.length)
96
- } catch (error) {
97
- if (!(error instanceof CompressionError) || error.limited || bytes.at(-1) !== 0) throw error
98
- const last = bytes.findLastIndex((byte) => byte !== 0)
99
- for (let end = last + 1; end <= Math.min(last + 10, bytes.length - 1); end++) {
100
- try {
101
- return await inflate(end)
102
- } catch {
103
- // Not where the stream ends: the next byte may be.
104
- }
105
- }
106
- throw error
85
+ // What a version document says of where a package comes from, each
86
+ // undefined where it says nothing: `commit` is its gitHead.
87
+ const aboutOf = ({ gitHead, repository, homepage, bugs }) => ({ commit: gitHead, repository, homepage, bugs })
88
+ export const NO_ABOUT = Object.freeze(aboutOf({}))
89
+
90
+ // What a tree's options say of what it fetches from npm's registry:
91
+ // `metadata`, true unless given false; `cache`, as upstream's CacheOptions
92
+ // take it, which keeps each version's document and tarball; and
93
+ // `sizeEstimateOnly`, false unless given true, for each version's document
94
+ // alone (fetchSize).
95
+ export function fetchingOf({ metadata = true, cache, sizeEstimateOnly = false }) {
96
+ if (typeof metadata !== 'boolean') throw new TypeError('metadata must be a boolean, or left out')
97
+ if (cache !== undefined && cache !== false && (typeof cache?.read !== 'function' || typeof cache?.write !== 'function')) {
98
+ throw new TypeError('cache must be false, or a store with read and write, or left out')
107
99
  }
100
+ if (typeof sizeEstimateOnly !== 'boolean') throw new TypeError('sizeEstimateOnly must be a boolean, or left out')
101
+ return { metadata, cache, sizeEstimateOnly }
108
102
  }
109
103
 
110
- // The registry's sha512 of a version, for a tarball ownTarball let through
111
- // unpinned.
112
- export async function registryIntegrity(name, version, where) {
113
- checkId(name, version, where)
114
- return (await getMeta(name, version)).dist.integrity
115
- }
104
+ const SHA512 = /^sha512-[\d+/A-Za-z]{86}==$/u
116
105
 
117
- export async function fetchTarball(name, version, integrity, where) {
106
+ // Kept as `cache` says. Without a `given` integrity, as ownTarball lets one
107
+ // through unpinned, the registry's is taken from the version document, which
108
+ // getMeta holds to the registry's own tarball, and `about` is what that
109
+ // says, whatever `metadata` is. Else, with `metadata`, the document is asked
110
+ // for beside the tarball, given the dist the tarball is fetched by, which
111
+ // getMeta holds the document's to as text, the registry's being the one a
112
+ // lockfile copies, so nothing is hashed again. Else NO_ABOUT.
113
+ export async function fetchTarball(name, version, given, where, { metadata, cache }) {
118
114
  checkId(name, version, where)
119
- if (!/^sha512-[\d+/A-Za-z]{86}==$/u.test(integrity)) throw new DeptreeError('a tarball with no sha512 integrity is not supported', where)
120
- const bytes = await getTarball(name, version, { tarball: tarballUrl(name, version), integrity })
115
+ const meta = given === undefined ? await getMeta(name, version, { cache }) : undefined
116
+ const integrity = given ?? meta.dist.integrity
117
+ if (!SHA512.test(integrity)) throw new DeptreeError('a tarball with no sha512 integrity is not supported', where)
118
+ const dist = { tarball: tarballUrl(name, version), integrity }
119
+ let about = NO_ABOUT
120
+ if (meta !== undefined) about = aboutOf(meta)
121
+ else if (metadata) about = getMeta(name, version, { dist, cache }).then(aboutOf)
122
+ const [bytes, said] = await settled([getTarball(name, version, dist, { cache }), about])
121
123
  if (!await matchesIntegrity(bytes, integrity)) throw new DeptreeError(`the tarball is not ${integrity}`, where)
122
124
  if (bytes[0] !== 0x1f || bytes[1] !== 0x8b || bytes[2] !== 0x08) throw new DeptreeError('the tarball is not gzipped', where)
123
- const tar = await gunzip(bytes)
124
- return { bytes, entries: unpack(tar), inflated: tar.length, integrity }
125
+ const tar = await decompress(bytes, 'gzip', { limit: MAX_BYTES })
126
+ return { bytes, tar, entries: unpack(tar), inflated: tar.length, integrity, about: said }
127
+ }
128
+
129
+ // The version's document alone, asked for as fetchTarball asks for it with
130
+ // `metadata` and the lockfile's integrity, which getMeta holds the
131
+ // registry's to; no tarball is fetched. `size` is the document's
132
+ // unpackedSize, the bytes of the tarball's files as the registry counted
133
+ // them, or undefined where it has none; `about` what it says of where the
134
+ // package comes from.
135
+ export async function fetchSize(name, version, integrity, where, { cache }) {
136
+ checkId(name, version, where)
137
+ if (!SHA512.test(integrity)) throw new DeptreeError('a tarball with no sha512 integrity is not supported', where)
138
+ const meta = await getMeta(name, version, { dist: { tarball: tarballUrl(name, version), integrity }, cache })
139
+ return { size: meta.unpackedSize, about: aboutOf(meta) }
125
140
  }
@@ -5,12 +5,15 @@
5
5
  // dependencies), and a package.json of the lockfile's name and version.
6
6
  // And a directory by `file:`, as yarn's copy fetcher installs it.
7
7
 
8
+ import { fromBase64 } from '@exodus/bytes/base64.js'
9
+ import { toHex } from '@exodus/bytes/hex.js'
10
+ import { getPublishTimes } from '@preventive/upstream/npm.js'
8
11
  import { normalize } from '@preventive/vfs/path.js'
9
12
  import { DeptreeError, quote } from '../error.js'
10
13
  import { sha1Hex } from '../hash.js'
11
14
  import { readManifest } from '../manifest.js'
12
15
  import { decodeUtf8, readBytes, typeOf } from '../project.js'
13
- import { fetchTarball, fromMirror, isModules, ownTarball, registryIntegrity, sameFile, withDirs } from '../tarball.js'
16
+ import { fetchTarball, fromMirror, isModules, ownTarball, sameFile, withDirs } from '../tarball.js'
14
17
  import { fixLists } from './manifest.js'
15
18
  import { kindOf, splitPattern } from './resolve.js'
16
19
 
@@ -44,20 +47,62 @@ function entriesOf(entries, where) {
44
47
 
45
48
  const decoder = new TextDecoder('utf-8', { fatal: true })
46
49
 
50
+ // yarn writes the registry's sha512 where it has one, and else a sha1 of its
51
+ // shasum. Since this time the registry has made one for every version as it
52
+ // was published, by any client: firebase-tools@4.0.3, published then by npm
53
+ // 3.10.8, is the first it signed over one it made, and superstatic@6.0.0, at
54
+ // 2018-08-03T20:22:28.120Z, the last over none. It has since made one for
55
+ // every version published before too.
56
+ export const SHA512_SINCE = '2018-08-05T14:58:16.253Z'
57
+
58
+ // The hex of an integrity that is a sha1 alone.
59
+ function sha1Of(integrity) {
60
+ if (integrity === undefined || !/^sha1-[\d+/A-Za-z]{26}[048AEIMQUYcgkosw]=$/u.test(integrity)) return undefined
61
+ return toHex(fromBase64(integrity.slice(5)))
62
+ }
63
+
47
64
  // `name` is the one fetched, as an `npm:` alias asks for it. yarn writes no
48
65
  // integrity for a pattern that names the tarball's URL, but the sha1 after
49
- // its `#`: the tarball is held to that, and to the registry's sha512.
66
+ // its `#`: the tarball is held to that, and to the registry's sha512. One
67
+ // with a sha1 integrity alone is held to it, and to the registry's sha512,
68
+ // where it was published before SHA512_SINCE.
50
69
  export function registryTarball(entry, name, where) {
51
70
  const { resolution } = entry
52
71
  if (resolution === undefined) throw new DeptreeError('a directory, by file: or link:, is not supported', where)
53
72
  const url = resolution.type === 'tarball' ? fromMirror(resolution.tarball) : resolution.tarball
54
73
  const byUrl = entry.patterns.some((pattern) => kindOf(splitPattern(pattern).range, where) === 'tarball')
55
- return ownTarball(url, name, entry.version, resolution.integrity, where, byUrl && resolution.sha1 !== undefined)
74
+ const sha1 = sha1Of(resolution.integrity)
75
+ if (sha1 === undefined) return ownTarball(url, name, entry.version, resolution.integrity, where, byUrl && resolution.sha1 !== undefined)
76
+ return { ...ownTarball(url, name, entry.version, undefined, where, true), sha1 }
77
+ }
78
+
79
+ // `times` keeps getPublishTimes' answer for each name, fetched once.
80
+ async function checkPublished({ name, version }, where, times) {
81
+ if (!times.has(name)) times.set(name, getPublishTimes(name))
82
+ const published = (await times.get(name)).get(version)
83
+ if (published === undefined) throw new DeptreeError(`a sha1 integrity alone, where the registry gives no time ${name}@${version} was published at`, where)
84
+ if (published >= SHA512_SINCE) throw new DeptreeError(`a sha1 integrity alone, which yarn does not write for ${name}@${version}, published at ${published}: the registry has given every version a sha512 since ${SHA512_SINCE}`, where)
85
+ }
86
+
87
+ export function checkSha1(pinned, sha1, where) {
88
+ if (pinned !== undefined && sha1 !== pinned) throw new DeptreeError(`the tarball's sha1 is not ${pinned}`, where)
89
+ }
90
+
91
+ // Another entry of a package yarn's cache keeps in one place, held to the
92
+ // first's, `head`, as fetchYarnPackage holds that one: yarn fetches it once.
93
+ export async function checkShared({ name, version, integrity, sha1: pinned }, head, where, times) {
94
+ if (pinned !== undefined) await checkPublished({ name, version }, where, times)
95
+ checkSha1(pinned, head.sha1, where)
96
+ if (integrity !== undefined && integrity !== head.integrity) throw new DeptreeError(`the tarball is not ${integrity}`, where)
56
97
  }
57
98
 
58
- export async function fetchYarnPackage({ name, version, integrity }, where) {
59
- const fetched = await fetchTarball(name, version, integrity ?? await registryIntegrity(name, version, where), where)
99
+ // One the lockfile gives no sha512 is fetched by the registry's, as
100
+ // fetchTarball takes it unpinned.
101
+ export async function fetchYarnPackage({ name, version, integrity, sha1: pinned }, where, times, fetching) {
102
+ if (pinned !== undefined) await checkPublished({ name, version }, where, times)
103
+ const fetched = await fetchTarball(name, version, integrity, where, fetching)
60
104
  const sha1 = await sha1Hex(fetched.bytes)
105
+ checkSha1(pinned, sha1, where)
61
106
  const { files, dirs } = entriesOf(fetched.entries, where)
62
107
  const file = files.get('package.json')
63
108
  if (file === undefined) throw new DeptreeError('the tarball has no package.json', where)
@@ -69,7 +114,7 @@ export async function fetchYarnPackage({ name, version, integrity }, where) {
69
114
  }
70
115
  const manifest = readManifest(text, `${where}: package.json`)
71
116
  if (manifest.name !== name || manifest.version !== version) throw new DeptreeError(`package.json is for ${quote(`${manifest.name}@${manifest.version}`)}`, where)
72
- return { ...withBins({ files, dirs }, manifest, where), sha1, integrity: fetched.integrity }
117
+ return { ...withBins({ files, dirs }, manifest, where), sha1, integrity: fetched.integrity, about: fetched.about }
73
118
  }
74
119
 
75
120
  // A directory by `file:`, as yarn's copy fetcher installs it: all in it, each