@preventive/upstream 1.11.0 → 1.13.0

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 (52) hide show
  1. package/advisories.d.ts +125 -83
  2. package/cargo.d.ts +59 -35
  3. package/cocoapods.d.ts +44 -57
  4. package/electron.d.ts +35 -25
  5. package/git.d.ts +25 -16
  6. package/github/write.d.ts +60 -29
  7. package/github.d.ts +207 -193
  8. package/npm.d.ts +150 -87
  9. package/package.d.ts +30 -16
  10. package/package.json +1 -1
  11. package/rubygems.d.ts +22 -9
  12. package/semver.d.ts +40 -19
  13. package/soldeer.d.ts +21 -12
  14. package/src/advisories/actions.js +13 -38
  15. package/src/advisories/common.js +29 -1
  16. package/src/advisories/github.js +5 -19
  17. package/src/advisories/index.js +5 -12
  18. package/src/advisories/npm.js +4 -19
  19. package/src/advisories/osv.js +23 -45
  20. package/src/advisories/packagist.js +1 -4
  21. package/src/advisories/patched.js +6 -18
  22. package/src/advisories/repos.js +8 -13
  23. package/src/advisories/rubysec.js +2 -7
  24. package/src/args.js +5 -10
  25. package/src/attributes.js +3 -4
  26. package/src/cache.js +9 -22
  27. package/src/cargo/crate.js +4 -7
  28. package/src/cargo/repos.js +1 -7
  29. package/src/cocoapods.js +3 -19
  30. package/src/download.js +4 -12
  31. package/src/electron.js +6 -8
  32. package/src/github/commit.js +1 -13
  33. package/src/github/read.js +19 -68
  34. package/src/github/write.js +0 -1
  35. package/src/http.js +2 -7
  36. package/src/lockfiles.js +3 -11
  37. package/src/npm/cacache.js +3 -8
  38. package/src/npm/registry.js +10 -4
  39. package/src/npm/repos.js +3 -15
  40. package/src/npm/tarball.js +5 -20
  41. package/src/npm/versions.js +7 -21
  42. package/src/package.js +1 -7
  43. package/src/pool.js +0 -1
  44. package/src/pypi/version.js +1 -5
  45. package/src/remote.js +4 -6
  46. package/src/rubygems/gem.js +2 -2
  47. package/src/rubygems/version.js +2 -10
  48. package/src/semver.js +3 -9
  49. package/src/soldeer.js +0 -4
  50. package/src/tree.js +14 -44
  51. package/src/weak-edges.js +0 -2
  52. package/weak-edges.d.ts +36 -24
package/src/npm/repos.js CHANGED
@@ -9,16 +9,10 @@ import { getDocument } from './registry.js'
9
9
 
10
10
  const DIR = 'npm/repos'
11
11
  const CONCURRENCY = 8
12
- // Stamped on each entry, and raised when getRepo would answer differently:
13
- // 2 is `repository` taking precedence over `bugs`; 3 the shorthand dropping
14
- // a `.git`, URLs read past whitespace, and `repository.directory`'s `\` read
15
- // as `/`; 4 a declared root answered as `''`, no directory declared left
16
- // out (unknown) rather than read as the root, and a declared directory's
17
- // empty and `.` parts dropped.
12
+ // Stamped on each entry, raised when getRepo would answer differently.
18
13
  const VERSION = 4
19
14
 
20
- // A slug a lookup gives: getRepo answers no repo ending in `.git`, the
21
- // suffix it drops (withoutDotGit; `.GIT` it keeps, and so does this).
15
+ // getRepo answers no repo ending in `.git` (withoutDotGit); `.GIT` it keeps, and so does this.
22
16
  const isLookedUpRepo = (github) => isRepo(github) && !github.endsWith('.git')
23
17
  // A write takes no slug a read would discard: whatever it writes reads back.
24
18
  const assertLookedUpRepo = assertion('"owner/name" with no trailing ".git"', isLookedUpRepo)
@@ -33,11 +27,7 @@ export async function getGitHub(name) {
33
27
  return link
34
28
  }
35
29
 
36
- // An entry under another VERSION was resolved by other rules, and may
37
- // name a repo getRepo no longer would (a stale tracker's, or a shorthand's
38
- // with its `.git`, or the root where a package declared no directory): a
39
- // miss, as is one naming a repo or a directory no lookup gives. One without
40
- // `directory` is a package whose place in its repo is unknown.
30
+ // One without `directory` is a package whose place in its repo is unknown.
41
31
  export async function readPackageRepoCache(name) {
42
32
  assertPackageName('readPackageRepoCache', 'name', name)
43
33
  const entry = await readRecord(DIR, name)
@@ -60,8 +50,6 @@ export async function resolvePackageRepos(packageNames, options = {}) {
60
50
  return new Map(names.flatMap((name, i) => (found[i] ? [[name, found[i]]] : [])))
61
51
  }
62
52
 
63
- // Through the cache. Null for a package the registry does not have, or
64
- // one naming no GitHub repo; any other failure throws.
65
53
  async function lookUpPackageRepo(name) {
66
54
  const stored = await readPackageRepoCache(name)
67
55
  if (stored) return stored
@@ -2,7 +2,7 @@ import { homedir } from 'node:os'
2
2
  import { join, resolve } from 'node:path'
3
3
 
4
4
  import { assertArgs, assertPackage, assertPackageName, isPlainObject, isSha, optional } from '../args.js'
5
- import { assertCache } from '../cache.js'
5
+ import { assertCache, assertCacheOptions } from '../cache.js'
6
6
  import { verifiedDownload } from '../download.js'
7
7
  import { NPM_REGISTRY, decode } from '../http.js'
8
8
  import { contentPath, readNpmCached } from './cacache.js'
@@ -28,14 +28,9 @@ function localPaths(name, version, integrity) {
28
28
  return [...npm, join(homedir(), '.audit/cache/tgz', `${name.replace(/^@/u, '').replace('/', ':')}-${version}.tgz`)]
29
29
  }
30
30
 
31
- // verifyDist's and getTarball's options: `cache` alone.
32
- const assertOptions = (method, options) => assertArgs(method, options, { cache: optional(assertCache) })
33
-
34
31
  const own = (object, key) => (Object.hasOwn(object, key) ? object[key] : undefined)
35
32
  const stringOr = (value) => (typeof value === 'string' ? value : undefined)
36
33
 
37
- // A string as it is, or an object's strings under `keys`, the rest undefined:
38
- // none where it is neither, or names none of them.
39
34
  function linkOf(value, keys) {
40
35
  if (typeof value === 'string') return value
41
36
  if (!isPlainObject(value)) return undefined
@@ -53,11 +48,8 @@ function jsonOf(bytes, from) {
53
48
  }
54
49
  }
55
50
 
56
- // A version as npm's own cache keeps it, where it keeps its name's full
57
- // packument, as npm 10 and later fetch it, whose entry for the version
58
- // matches `given` (matchingDist): that entry is the version's document. An
59
- // abbreviated packument, as earlier npm fetches, has none of the rest
60
- // getMeta answers, and is passed over.
51
+ // A version's document from the full packument npm 10 and later keep in their cache, where its entry for the
52
+ // version matches `given` (matchingDist). The abbreviated one earlier npm fetches lacks the rest getMeta answers.
61
53
  async function npmCachedVersion(name, version, given) {
62
54
  const url = `${NPM_REGISTRY}/${name.replace('/', '%2f')}`
63
55
  for (const root of npmCacheDirs()) {
@@ -73,13 +65,6 @@ async function npmCachedVersion(name, version, given) {
73
65
 
74
66
  const countOr = (value) => (Number.isSafeInteger(value) && value >= 0 ? value : undefined)
75
67
 
76
- // The version's document: with the `dist` the caller has, npm's own cache's
77
- // where it matches (npmCachedVersion), and neither `cache` nor the cache
78
- // set is read or written; else as getVersion has it. Beside its dist, the
79
- // document's gitHead where that is a full commit id, and its repository,
80
- // homepage and bugs, in the shapes a package.json gives them; and its
81
- // dist's unpackedSize where that is a count. Each but dist is left out
82
- // where there is none.
83
68
  export async function getMeta(name, version, options = {}) {
84
69
  assertPackage('getMeta', name, version)
85
70
  assertArgs('getMeta', options, { dist: null, cache: optional(assertCache) })
@@ -123,7 +108,7 @@ export async function getPublishTimes(name) {
123
108
 
124
109
  export async function verifyDist(name, version, dist, options = {}) {
125
110
  assertPackage('verifyDist', name, version)
126
- assertOptions('verifyDist', options)
111
+ assertCacheOptions('verifyDist', options)
127
112
  await getVersion('verifyDist', name, version, checkedDist('verifyDist', name, version, dist), options.cache)
128
113
  }
129
114
 
@@ -132,7 +117,7 @@ export async function verifyDist(name, version, dist, options = {}) {
132
117
  // against anything a cache itself holds.
133
118
  export async function getTarball(name, version, dist, options = {}) {
134
119
  assertPackage('getTarball', name, version)
135
- assertOptions('getTarball', options)
120
+ assertCacheOptions('getTarball', options)
136
121
  const { cache } = options
137
122
  const { tarball, integrity } = dist === undefined ? (await getVersion('getTarball', name, version, undefined, cache)).dist : checkedDist('getTarball', name, version, dist)
138
123
  return await verifiedDownload({ method: 'getTarball', dir: DIR, what: `${name}@${version}`, ext: 'tgz', algorithm: 'sha512', expected: integrity, local: localPaths(name, version, integrity), ours: true, cache, locate: () => tarball, options: withNpmToken(name, tarball) })
@@ -11,11 +11,9 @@ const DIR = 'npm/versions' // No expiry: the registry never takes a version twic
11
11
  // last character before `==` two bits, so only A, Q, g or w is canonical.
12
12
  const assertIntegrity = assertion('"sha512-" and a base64 sha512', matches(/^sha512-[\dA-Za-z+/]{85}[AQgw]==$/u))
13
13
 
14
- // `{ tarball, integrity }` and nothing else, the tarball exactly the
15
- // registry's own URL for that version. Each field is read once, and only
16
- // as the object's own, into a copy that is checked and used from then on:
17
- // the caller's object can change while a request is out, and a field on
18
- // its prototype is not one it has.
14
+ // `{ tarball, integrity }` alone, the tarball the registry's own URL for the version. Each is read once, as the
15
+ // object's own, into a copy checked and used from then on: the caller's object can change while a request is
16
+ // out, and a field on its prototype is not one it has.
19
17
  export function checkedDist(method, name, version, dist) {
20
18
  assertArgs(method, dist, { tarball: null, integrity: null }, 'dist')
21
19
  const [tarball, integrity] = ['tarball', 'integrity'].map((key) => (Object.hasOwn(dist, key) ? dist[key] : undefined))
@@ -28,8 +26,6 @@ export function checkedDist(method, name, version, dist) {
28
26
 
29
27
  const distOf = (method, name, version, json) => checkedDist(method, name, version, { tarball: json.dist?.tarball, integrity: json.dist?.integrity })
30
28
 
31
- // Whether a version document is one to keep, or to take as kept: for that
32
- // name and version, with a dist that passes.
33
29
  function isKeepable(method, name, version, json) {
34
30
  if (json?.name !== name || json.version !== version) return false
35
31
  try {
@@ -40,18 +36,15 @@ function isKeepable(method, name, version, json) {
40
36
  }
41
37
  }
42
38
 
43
- // The registry's document, kept whole in `cache` once it is keepable; one
44
- // whose dist is refused is answered all the same.
39
+ // One whose dist is refused is answered all the same.
45
40
  async function keepDocument(method, name, version, json, cache) {
46
41
  assert.ok(json.version === version, `${method}: the registry answered for ${name}@${show(json.version)}, not ${name}@${version}`)
47
42
  if (isKeepable(method, name, version, json)) await writeJSON(DIR, `${name}@${version}`, json, cache)
48
43
  return json
49
44
  }
50
45
 
51
- // A version's document, kept (readJSON) or else fetched, for what is not
52
- // an integrity: a package's repo (advisories.js), as trusted as
53
- // setCacheDir's repo records are. Null where the registry does not have
54
- // that version: its 404 alone, never a failure of the cache's.
46
+ // A version's document, kept or fetched, for what is not an integrity: a package's repo, as trusted as the
47
+ // cache's repo records. Null where the registry does not have that version (its 404 alone, not a cache failure).
55
48
  export async function getVersionDocument(method, name, version, cache) {
56
49
  const kept = await readJSON(DIR, `${name}@${version}`, cache)
57
50
  if (isKeepable(method, name, version, kept)) return kept
@@ -59,20 +52,13 @@ export async function getVersionDocument(method, name, version, cache) {
59
52
  return json && await keepDocument(method, name, version, json, cache)
60
53
  }
61
54
 
62
- // The dist of a version document a cache answers, where it is that
63
- // version's, its dist passes, and its tarball and integrity are `given`'s
64
- // (checkedDist): a cache never supplies a dist, only confirms one.
55
+ // A cache never supplies a dist, only confirms one.
65
56
  export function matchingDist(method, name, version, json, given) {
66
57
  if (!isKeepable(method, name, version, json)) return undefined
67
58
  const dist = distOf(method, name, version, json)
68
59
  return dist.integrity === given.integrity && dist.tarball === given.tarball ? dist : undefined
69
60
  }
70
61
 
71
- // A version's document, and its dist checked. A kept document is read only
72
- // for a caller that already has a dist, `given`, and answers with no
73
- // request where it matches (matchingDist). Else, or without one, the
74
- // registry is asked, and its document, kept in place of any other, throws
75
- // where it does not.
76
62
  export async function getVersion(method, name, version, given, cache) {
77
63
  if (given !== undefined) {
78
64
  const kept = await readJSON(DIR, `${name}@${version}`, cache)
package/src/package.js CHANGED
@@ -36,13 +36,7 @@ function repoSubdirectory(value) {
36
36
  return isRepoPath(path) ? path : undefined // No empty, `.`, `..` or `.git` part: a path inside the repo.
37
37
  }
38
38
 
39
- // `repository.directory` is a path its author may write with Windows' `\`.
40
- // A tree path is `/`-separated: a `\` is a name's own only in a homepage's
41
- // (`%5C`), which is the path itself. Its empty and `.` parts are dropped
42
- // (`./a//b/.` is `a/b`), and one of nothing else (`./`, `/`, `/.`, `.`, `''`)
43
- // declares the repo's root, `''`; one with a `..` part names none, whatever
44
- // it would come to. A package.json that declares none says nothing of where
45
- // in the repo it sits.
39
+ // `\` read as `/`: only a homepage's `%5C` is a name's own.
46
40
  function declaredDirectory(value) {
47
41
  if (typeof value !== 'string') return undefined
48
42
  const parts = value.replaceAll('\\', '/').split('/').filter((part) => part !== '' && part !== '.')
package/src/pool.js CHANGED
@@ -1,4 +1,3 @@
1
- // `fn` over `items`, at most `limit` at a time; results in `items` order.
2
1
  export async function pool(items, limit, fn) {
3
2
  const results = []
4
3
  let next = 0
@@ -2,7 +2,6 @@ import { compareVersions, parseVersion } from '@preventive/lockfile/pep440.js'
2
2
 
3
3
  import { assertion, matches } from '../args.js'
4
4
 
5
- // PEP 440 versions, by @preventive/lockfile, and GitHub's ranges of them.
6
5
  export { compareVersions }
7
6
 
8
7
  // 256 at most, before any regex runs.
@@ -24,8 +23,6 @@ const OPERATORS = {
24
23
  '>=': (cmp) => cmp >= 0,
25
24
  }
26
25
 
27
- // Undefined where a part isn't an operator and a version, or the range is
28
- // over 1,024 characters.
29
26
  function requirementsOf(text) {
30
27
  if (text.length > 1024) return undefined
31
28
  const parts = text.split(',').map((part) => PART.exec(part))
@@ -39,10 +36,9 @@ export function readRange(text) {
39
36
  return parts && ((version) => parts.every(([operator, against]) => OPERATORS[operator](compareVersions(version, against))))
40
37
  }
41
38
 
42
- // Whether a range is lower bounds alone, each below `version`.
43
39
  export const lowerBoundsBelow = (range, version) => requirementsOf(range)?.every(([operator, against]) => (operator === '>=' || operator === '>') && compareVersions(against, version) < 0) === true
44
40
 
45
- // Its release numbers; none where it has an epoch, which no line spans.
41
+ // None where it has an epoch, which no line spans.
46
42
  export function releaseOf(version) {
47
43
  const { epoch, release } = parseVersion(version)
48
44
  return epoch === '0' ? release.map(BigInt) : undefined
package/src/remote.js CHANGED
@@ -1,14 +1,12 @@
1
1
  import { isRepo } from './args.js'
2
2
 
3
- // `user:token@` is skipped, never returned. It is held to the characters
4
- // RFC 3986 allows there -- a `#`, `?` or `\` before the `@` ends the
5
- // authority early, so `https://evil.example#@github.com/a/b` goes to
6
- // evil.example -- and URL parsing has to agree the host is github.com.
3
+ // `user:token@` is skipped, never returned, and held to RFC 3986's characters: a `#`, `?` or `\` before the `@`
4
+ // ends the authority early (`https://evil.example#@github.com/a/b` goes to evil.example). URL parsing has to
5
+ // agree the host is github.com.
7
6
  const gitUrlRegex = /^(?i:(?:git\+)?(?:https?|git|ssh)):\/\/(?:[\w.~%!$&'()*+,;=:-]*@)?(?i:github\.com)(?::\d{1,5})?\/(?<repo>[\w-]+\/[\w.-]+?)(?:\.git)?\/?$/u
8
7
  const scpRegex = /^(?i:git\+ssh:\/\/)?git@(?i:github\.com):(?<repo>[\w-]+\/[\w.-]+?)(?:\.git)?$/u
9
8
 
10
- // A repo with every trailing `.git` dropped, so none ends in one: in a loop,
11
- // as a regex would backtrack over a long run of them in a crafted URL.
9
+ // In a loop, as a regex would backtrack over a long run of `.git` in a crafted URL.
12
10
  export function withoutDotGit(repo) {
13
11
  while (repo?.endsWith('.git')) repo = repo.slice(0, -4)
14
12
  return repo
@@ -2,7 +2,7 @@ import assert from 'node:assert/strict'
2
2
  import { readdir } from 'node:fs/promises'
3
3
  import { delimiter, join, resolve } from 'node:path'
4
4
 
5
- import { assertGem, assertSha256, assertion, isSha256, matches, printable } from '../args.js'
5
+ import { assertGem, assertSha256, assertion, isSha256, matches, optional, printable } from '../args.js'
6
6
  import { absolute, home } from '../cache.js'
7
7
  import { verifiedDownload } from '../download.js'
8
8
  import { RUBYGEMS, RUBYGEMS_INDEX, buildUrl, encodeSegment, request } from '../http.js'
@@ -89,7 +89,7 @@ export async function verifyChecksum(name, version, platform, checksum) {
89
89
 
90
90
  export async function getGem(name, version, platform, checksum) {
91
91
  const gem = gemOf('getGem', name, version, platform)
92
- if (checksum !== undefined) assertChecksum('getGem', 'checksum', checksum)
92
+ optional(assertChecksum)('getGem', 'checksum', checksum)
93
93
  const expected = checksum === undefined ? await getChecksum('getGem', gem) : hexOf(checksum)
94
94
  const locate = () => buildUrl(RUBYGEMS, ['gems', encodeSegment(gem.file)])
95
95
  return await verifiedDownload({ method: 'getGem', dir: DIR, what: gem.what, ext: 'gem', algorithm: 'sha256', expected, local: await localPaths(gem.file), locate })
@@ -21,7 +21,6 @@ const isPrerelease = (version) => /[A-Za-z]/u.test(version)
21
21
  // Gem::Version#partition_segments: numbers and runs of letters.
22
22
  const partition = (version) => (version.match(/\d+|[A-Za-z]+/gu) ?? []).map((part) => (/^\d/u.test(part) ? BigInt(part) : part))
23
23
 
24
- // Runs of `.` and `0` as [start, end), in one pass.
25
24
  const zeroRuns = (text) => Array.from(text.matchAll(/[.0]+/gu), (m) => [m.index, m.index + m[0].length])
26
25
 
27
26
  function startIn(text, [from, to], follows) {
@@ -91,8 +90,6 @@ const OPERATORS = {
91
90
  '<=': (cmp) => cmp <= 0,
92
91
  }
93
92
 
94
- // Undefined where a part isn't a requirement, or the range is over 1,024
95
- // characters.
96
93
  function requirementsOf(text) {
97
94
  if (text.length > 1024) return undefined
98
95
  const parts = text.split(',').map((part) => REQUIREMENT.exec(part))
@@ -100,8 +97,7 @@ function requirementsOf(text) {
100
97
  return parts.map(([, operator = '=', against]) => [operator, against])
101
98
  }
102
99
 
103
- // A test of a range, each version read once. A prerelease meets one as any
104
- // version does: only Gem::Dependency sets them apart.
100
+ // A prerelease meets a range as any version does: only Gem::Dependency sets them apart.
105
101
  export function readRange(text) {
106
102
  const parts = requirementsOf(text)
107
103
  if (parts === undefined) return undefined
@@ -114,14 +110,10 @@ export function readRange(text) {
114
110
  }
115
111
  }
116
112
 
117
- // Whether a range is lower bounds alone, `!=` among them, each below
118
- // `version`.
119
113
  export const lowerBoundsBelow = (range, version) => requirementsOf(range)?.every(([operator, against]) => operator === '!=' || ((operator === '>=' || operator === '>') && compareVersions(against, version) < 0)) === true
120
114
 
121
- // Of a range lowerBoundsBelow takes, whether a version meets each lower
122
- // bound, and the `!=` it keeps.
115
+ // Both only of a range lowerBoundsBelow takes.
123
116
  export const meetsLowerBounds = (range, version) => requirementsOf(range).every(([operator, against]) => operator === '!=' || OPERATORS[operator](compareVersions(version, against)))
124
117
  export const exclusionsOf = (range) => requirementsOf(range).filter(([operator]) => operator === '!=').map((part) => part.join(' '))
125
118
 
126
- // Its numbers before any letters, as Gem::Version reads it.
127
119
  export const releaseOf = (version) => numeric(read(version))
package/src/semver.js CHANGED
@@ -3,18 +3,12 @@ import { createRequire } from 'node:module'
3
3
  import { basename, dirname, resolve } from 'node:path'
4
4
  import requirePeer from './semver-peer.cjs'
5
5
 
6
- // npm's own semver, borrowed from the npm next to node rather than added
7
- // as a dependency: the same implementation `npm audit` uses. Where there is
8
- // no npm, as in a bundled serverless function, the `semver` package itself,
9
- // an optional peer dependency.
6
+ // npm's own semver, the one `npm audit` uses; a bundled serverless function has no npm to borrow it from.
10
7
 
11
- // Plain releases that semver.valid answers unchanged, so it need not be
12
- // loaded for them: no leading zeros, and at most 15 digits a part, under
13
- // Number.MAX_SAFE_INTEGER. Anything else, or any call with options, goes
14
- // to semver.
8
+ // Plain releases semver.valid answers unchanged, so it need not be loaded for them: no leading zeros, at most 15
9
+ // digits a part (under Number.MAX_SAFE_INTEGER). Anything else, or a call with options, goes to semver.
15
10
  const PLAIN_RELEASE = /^(?:0|[1-9]\d{0,14})\.(?:0|[1-9]\d{0,14})\.(?:0|[1-9]\d{0,14})$/u
16
11
 
17
- // What load() returns if it is semver, or null if it is not or throws.
18
12
  function attempt(load) {
19
13
  try {
20
14
  const lib = load()
package/src/soldeer.js CHANGED
@@ -6,8 +6,6 @@ import { SOLDEER_API, SOLDEER_REVISIONS, buildUrl, request } from './http.js'
6
6
 
7
7
  const DIR = 'soldeer/zips' // No expiry: the registry refuses a version it already has.
8
8
 
9
- // Where the registry keeps the version's zip; it says nothing of what the
10
- // zip hashes to.
11
9
  async function zipUrl(name, version) {
12
10
  const json = await request(buildUrl(SOLDEER_API, ['api', 'v1', 'revision-cli'], { project_name: name, revision: version }), { as: 'json' })
13
11
  const revision = json?.data?.[0]
@@ -17,8 +15,6 @@ async function zipUrl(name, version) {
17
15
  return revision.url
18
16
  }
19
17
 
20
- // The registry has no hash to check a zip against, so the caller brings
21
- // one, as soldeer.lock records it.
22
18
  export async function getZip(name, version, checksum) {
23
19
  assertSoldeerPackage('getZip', name, version)
24
20
  assertSha256('getZip', 'checksum', checksum)
package/src/tree.js CHANGED
@@ -8,17 +8,9 @@ import { isSha1, matches } from './args.js'
8
8
  import { withAttributes, writtenWithCrlf } from './attributes.js'
9
9
 
10
10
  const MAX_UNPACKED_BYTES = 2 ** 30
11
- // Read by @preventive/archive, which holds a tarball to its checks -- each
12
- // header's checksum and fields, the padding and the end, pax records of
13
- // which none repeats, names and link targets that stay within it, no name
14
- // twice as another entry -- and past those to only what git writes:
15
- // anything else, a pax `size` or a mode of 0000, would be extracted as it
16
- // is not hashed. POSIX ustar headers, as under GNU's magic a reader that
17
- // knows none takes GNU's own bytes for a name's prefix, their numbers as
18
- // octal digits; no extended header but an entry's own pax one; type flags
19
- // and modes as stored. Modes are as
20
- // its umask, 002 or 022, leaves them: a file 0664 or 0644, 0775 or 0755
21
- // executable; a directory 0775 or 0755; a symlink 0777.
11
+ // Past @preventive/archive's checks, only what git writes: anything else (a pax `size`, a mode 0000) would be
12
+ // extracted as it is not hashed. POSIX ustar, as under GNU's magic a reader that knows none takes its bytes for a
13
+ // name's prefix; octal numbers; no extended header but an entry's pax one; modes as a 002 or 022 umask leaves.
22
14
  const PAX_KEYS = new Set(['path', 'linkpath'])
23
15
  const MODES = { 0: [0o664, 0o644, 0o775, 0o755], 2: [0o777], 5: [0o775, 0o755] }
24
16
  // The extended headers git does not write, by the type a tar names them by.
@@ -30,8 +22,7 @@ const isTop = matches(/^(?!(?:con|prn|aux|nul|com\d|lpt\d)(?:\.|$))[\da-z][\w.-]
30
22
 
31
23
  export const objectId = (type, content) => createHash('sha1').update(`${type} ${content.length}\0`).update(content).digest()
32
24
 
33
- // Git keeps no empty directory: in a tarball, one is a submodule. Each as
34
- // [the directory holding it, its name, its path].
25
+ // Git keeps no empty directory: in a tarball, one is a submodule.
35
26
  function emptyDirs(dir, prefix = '') {
36
27
  return [...dir].flatMap(([name, entry]) => {
37
28
  if (!(entry instanceof Map)) return []
@@ -69,12 +60,9 @@ async function holdsNothing(sha, listed) {
69
60
 
70
61
  const CHUNK = 64 * 1024
71
62
 
72
- // The id of the blob that `eol=crlf`, a CR written before each LF with
73
- // none, writes out as these bytes: theirs with each LF's CR taken out,
74
- // hashed a chunk at a time, the bytes only read. Null where no blob writes
75
- // them so: an LF with no CR before it, a CR before that CR, or no LF at
76
- // all. Most files are passed over at their first LF, a binary one with
77
- // none at once.
63
+ // The id of the blob `eol=crlf` writes out as these bytes, each LF's CR taken out, hashed a chunk at a time. Null
64
+ // where no blob writes them so: an LF with no CR before it, a CR before that CR, or no LF at all; most files are
65
+ // passed over at their first LF.
78
66
  function crlfBlobId(written) {
79
67
  const first = written.indexOf(0x0a)
80
68
  if (first < 1 || written[first - 1] !== 0x0d) return null
@@ -98,13 +86,9 @@ function crlfBlobId(written) {
98
86
  return hash.update(chunk.subarray(0, at)).digest()
99
87
  }
100
88
 
101
- // Where a directory's id is not the one listed, its listing names what
102
- // `git archive` wrote otherwise, as a checkout writes it. A subtree with no
103
- // file in it, which only plumbing makes, it leaves out: one is put back
104
- // only once its own listings show it holds nothing. A file marked
105
- // `eol=crlf` it writes with CRLF where git has LF: one is hashed as the
106
- // blob listed, its bytes left as written, where that blob writes them and
107
- // the tree's .gitattributes have git write it so.
89
+ // Where a directory's id is not the one listed, what `git archive` wrote otherwise: a subtree with no file in it,
90
+ // which it leaves out, put back once its listings show it holds nothing; and a file it wrote with CRLF for
91
+ // `eol=crlf`, hashed as the blob listed where that blob writes those bytes and .gitattributes say so.
108
92
  async function mend(dir, sha, listed, base = '', above = []) {
109
93
  const own = dir.get('.gitattributes')
110
94
  const attributes = withAttributes(above, base, own && (own.body ?? null))
@@ -120,9 +104,6 @@ async function mend(dir, sha, listed, base = '', above = []) {
120
104
  }
121
105
  }
122
106
 
123
- // One entry of a tarball into `root`, the tree being built, whose top
124
- // directory is `top`, the first entry's: a reason where git writes no such
125
- // entry there, else nothing.
126
107
  function take(root, { storedName, storedLinkname, typeflag, storedMode, uid, gid, uname, gname, data, pax, extended, magic, octal }, top) {
127
108
  const path = nameOf(storedName)
128
109
  const flag = extended.find(({ kind }) => kind !== 'pax')
@@ -149,18 +130,9 @@ function take(root, { storedName, storedLinkname, typeflag, storedMode, uid, gid
149
130
  dir.set(name, typeflag === '0' ? { mode: storedMode & 0o100 ? '100755' : '100644', id: objectId('blob', data), body: data } : { mode: '120000', id: objectId('blob', Buffer.from(storedLinkname)) })
150
131
  }
151
132
 
152
- // The id of the git tree a gzipped tarball holds, as `git archive` writes
153
- // one, under a single top directory: a file's mode is its exec bit, a
154
- // symlink's blob its target. What a tarball cannot show comes from `list`,
155
- // which answers a listing of a tree by its id, as GitHub's trees API does
156
- // ({ type, path, sha } entries), walked from `expected`: a submodule's
157
- // commit for an empty directory, and, where the id comes out otherwise, the
158
- // subtrees with nothing in them it leaves out and the blobs of the files it
159
- // wrote with CRLF for `eol=crlf`. The id is `expected` only if those are
160
- // right. Where there is no such tree, a reason, never an id. A symlink may
161
- // climb `symlinksAbove` levels above the tarball's root, none unless given,
162
- // as @preventive/archive lets it: a subtree's, linking to the tree's root
163
- // as a monorepo package's LICENSE does, as many as it is deep, less one.
133
+ // The id of the git tree a gzipped tarball holds as `git archive` writes one, else a reason. What it can't show
134
+ // (a submodule's commit, then mend's) comes from `list`, a tree's listing by id as GitHub's trees API answers it,
135
+ // walked from `expected`.
164
136
  export async function gitTreeOfTarball(gzipped, { expected, list, symlinksAbove = 0 } = {}) {
165
137
  let tar
166
138
  try {
@@ -206,9 +178,7 @@ export async function gitTreeOfTarball(gzipped, { expected, list, symlinksAbove
206
178
  // GitHub lists a subtree's mode as `040000`, which git writes `40000`.
207
179
  const LISTED = new Set(['100644 blob', '100755 blob', '120000 blob', '040000 tree', '160000 commit'])
208
180
 
209
- // The id of the tree a listing such as GitHub's names, its entries
210
- // { path, mode, type, sha }, or null where one is not an entry a tree can
211
- // hold, or a name is there twice.
181
+ // The id of the tree a listing such as GitHub's names, its entries { path, mode, type, sha }.
212
182
  export function gitTreeOfListing(entries) {
213
183
  if (!entries.every((entry) => isEntry(entry) && LISTED.has(`${entry.mode} ${entry.type}`))) return null
214
184
  const dir = new Map(entries.map(({ path, mode, sha }) => [nameOf(path), { mode: mode.replace(/^0/u, ''), id: Buffer.from(sha, 'hex') }]))
package/src/weak-edges.js CHANGED
@@ -67,8 +67,6 @@ export const weakEdges = Object.freeze([
67
67
  },
68
68
  ].map(rule => Object.freeze({ ...rule, from: Object.freeze(rule.from), to: Object.freeze(rule.to) })))
69
69
 
70
- // Do not guess ownership from a partial or shortened path. A nested dependency
71
- // must be passed as its own package, not as node_modules/... inside its parent.
72
70
  function normalizedPath(path) {
73
71
  return typeof path === 'string' && !path.includes('\\') && !path.includes(':')
74
72
  && path.split('/').every(part => part !== '' && part !== '.' && part !== '..' && part !== 'node_modules')
package/weak-edges.d.ts CHANGED
@@ -1,36 +1,48 @@
1
- /** A resolved file, identified by its owning package rather than a display path. */
1
+ /**
2
+ * Curated weak loads: file edges to leave out of cycles and default inclusion explanations
3
+ *
4
+ * ```js
5
+ * import { getWeakEdge, weakEdges } from '@preventive/upstream/weak-edges.js'
6
+ * ```
7
+ *
8
+ * @module @preventive/upstream/weak-edges.js
9
+ */
10
+
11
+ /** A resolved file, identified by its owning package rather than a display path */
2
12
  export interface WeakEdgeFile {
3
- /** Exact npm package name, including scope. May be absent for own source. */
4
- package?: string
5
- /** Normalized /-separated path relative to the owning package or own-source root. */
6
- path: string
7
- /** Authoritative project ownership, not inferred from a package name or path. */
8
- ownSource?: boolean
13
+ /** Exact npm package name, scope included; may be absent for own source */
14
+ package?: string;
15
+ /** Normalized, `/`-separated, relative to the owning package's or own source's root */
16
+ path: string;
17
+ /** Authoritative project ownership, not inferred from a package name or path */
18
+ ownSource?: boolean;
9
19
  }
10
20
 
21
+ /** The files one end of a rule matches */
11
22
  export interface WeakEdgeSelector {
12
- /** Absent means any package or own source. Regular expressions match package names. */
13
- readonly package?: string | RegExp
14
- readonly path: RegExp
23
+ /** A package name, or a pattern of them; absent for any package or own source */
24
+ readonly package?: string | RegExp;
25
+ readonly path: RegExp;
15
26
  }
16
27
 
28
+ /** A weak load: an edge from a file `from` matches to one `to` matches */
17
29
  export interface WeakEdgeRule {
18
- readonly id: string
19
- readonly reason: string
20
- readonly from: WeakEdgeSelector
21
- readonly to: WeakEdgeSelector
22
- readonly ownSourceOnly?: boolean
30
+ readonly id: string;
31
+ readonly reason: string;
32
+ readonly from: WeakEdgeSelector;
33
+ readonly to: WeakEdgeSelector;
34
+ /** Match only a `to` of own source */
35
+ readonly ownSourceOnly?: boolean;
23
36
  }
24
37
 
25
- /** Curated weak loads: omit these file edges from cycles and default inclusion explanations. */
26
- export const weakEdges: readonly WeakEdgeRule[]
38
+ /** The inventory, frozen */
39
+ export const weakEdges: readonly WeakEdgeRule[];
27
40
 
28
41
  /**
29
- * Returns the matching inventory rule, or undefined for an unrecognized edge.
30
- * Own-source importers never match. import-fresh requires to.ownSource === true.
31
- * Own-source targets only match selectors without a package constraint.
32
- * Resolve nested installations to their actual owning package before calling;
33
- * absolute, non-normalized, or nested node_modules paths do not match.
34
- * Does not remove files, alter raw load records, or change runtime resolution.
42
+ * The inventory's rule for an edge, or undefined
43
+ *
44
+ * An edge from own source never matches, and a file of own source matches only a selector without `package`.
45
+ * Resolve nested installations to their owning package first: an absolute, unnormalized or nested `node_modules`
46
+ * path matches nothing.
35
47
  */
36
- export function getWeakEdge(from: WeakEdgeFile, to: WeakEdgeFile): WeakEdgeRule | undefined
48
+ export function getWeakEdge(from: WeakEdgeFile, to: WeakEdgeFile): WeakEdgeRule | undefined;