bulk-release 3.3.0 → 3.3.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.
Files changed (43) hide show
  1. package/CHANGELOG.md +11 -0
  2. package/README.md +23 -22
  3. package/package.json +2 -2
  4. package/src/main/js/cli.js +3 -3
  5. package/src/main/js/config.js +2 -1
  6. package/src/main/js/post/api/git.js +96 -47
  7. package/src/main/js/post/api/npm.js +24 -15
  8. package/src/main/js/post/courier/channels/changelog.js +5 -10
  9. package/src/main/js/post/courier/channels/cmd.js +5 -1
  10. package/src/main/js/post/courier/channels/gh-pages.js +4 -4
  11. package/src/main/js/post/courier/channels/gh-release.js +3 -3
  12. package/src/main/js/post/courier/channels/git-tag.js +6 -26
  13. package/src/main/js/post/courier/channels/index.js +19 -0
  14. package/src/main/js/post/courier/channels/meta.js +4 -4
  15. package/src/main/js/post/courier/channels/npm.js +20 -17
  16. package/src/main/js/post/courier/execute.js +88 -0
  17. package/src/main/js/post/courier/index.js +112 -283
  18. package/src/main/js/post/courier/plan.js +149 -0
  19. package/src/main/js/post/courier/semaphore.js +14 -24
  20. package/src/main/js/post/courier/seniority.js +7 -17
  21. package/src/main/js/post/depot/context.js +12 -1
  22. package/src/main/js/post/depot/deps.js +13 -1
  23. package/src/main/js/post/depot/exec.js +2 -2
  24. package/src/main/js/post/depot/reconcile.js +15 -23
  25. package/src/main/js/post/depot/steps/clean.js +1 -2
  26. package/src/main/js/post/depot/steps/contextify.js +9 -0
  27. package/src/main/js/post/depot/steps/pack.js +6 -4
  28. package/src/main/js/post/depot/steps/publish.js +2 -2
  29. package/src/main/js/post/log.js +10 -1
  30. package/src/main/js/post/modes/deliver.js +14 -36
  31. package/src/main/js/post/modes/pack.js +8 -16
  32. package/src/main/js/post/modes/receive.js +7 -14
  33. package/src/main/js/post/modes/verify.js +17 -2
  34. package/src/main/js/post/parcel/build.js +17 -2
  35. package/src/main/js/post/parcel/directive.js +10 -24
  36. package/src/main/js/post/parcel/index.js +5 -0
  37. package/src/main/js/post/parcel/verify-directive.js +81 -0
  38. package/src/main/js/post/parcel/verify.js +82 -78
  39. package/src/main/js/post/release.js +5 -4
  40. package/src/main/js/post/tar.js +65 -21
  41. package/src/main/js/util.js +32 -5
  42. package/src/test/js/utils/mock.js +0 -3
  43. package/src/test/js/utils/repo.js +10 -4
@@ -23,7 +23,7 @@ export const runVerify = async ({cwd, flags}) => {
23
23
  }
24
24
 
25
25
  const {verified, errors} = verifyParcels(tars, context)
26
- errors.push(...await verifyManifests(verified, context))
26
+ errors.push(...await linkErrors(tars), ...await strangerErrors(inputDir, outputDir, verified), ...await verifyManifests(verified, context))
27
27
 
28
28
  if (errors.length) {
29
29
  for (const e of errors) log.error(`verify: ${e}`)
@@ -33,10 +33,25 @@ export const runVerify = async ({cwd, flags}) => {
33
33
  if (path.resolve(inputDir) !== outputDir) {
34
34
  await fs.ensureDir(outputDir)
35
35
  for (const tarPath of verified) {
36
- await fs.copy(tarPath, path.join(outputDir, path.basename(tarPath)))
36
+ await fs.copyFile(tarPath, path.join(outputDir, path.basename(tarPath)))
37
37
  }
38
38
  log.info(`${verified.length} parcel(s) verified and copied to ${outputDir}`)
39
39
  } else {
40
40
  log.info(`${verified.length} parcel(s) verified in place`)
41
41
  }
42
42
  }
43
+
44
+ // A link could point verify and the courier at different files.
45
+ const linkErrors = async (tars) => {
46
+ const links = []
47
+ for (const tarPath of tars) if (!(await fs.lstat(tarPath)).isFile()) links.push(tarPath)
48
+ return links.map(t => `not a regular file: ${JSON.stringify(path.basename(t))}`)
49
+ }
50
+
51
+ // Whatever already lies in the output dir would go out with the verified parcels, unverified.
52
+ const strangerErrors = async (inputDir, outputDir, verified) => {
53
+ if (path.resolve(inputDir) === outputDir) return []
54
+ const names = new Set(verified.map(t => path.basename(t)))
55
+ const present = await glob(path.join(outputDir, 'parcel.*.tar'))
56
+ return present.filter(t => !names.has(path.basename(t))).map(t => `unverified parcel in ${outputDir}: ${JSON.stringify(path.basename(t))}`)
57
+ }
@@ -1,7 +1,22 @@
1
1
  import {asTuple, msgJoin} from '../../util.js'
2
2
  import {mergePopulate} from './populate.js'
3
3
 
4
- export const sanitizePkgName = (name) => name.replace(/[^a-z0-9-]/ig, '-').replace(/^-+|-+$/g, '')
4
+ const escapeName = (s) => s.replace(/[^a-z0-9-]/g, (c) => [...Buffer.from(c)].map(b => `_${b.toString(16).padStart(2, '0')}`).join(''))
5
+
6
+ // Package name as a parcel name segment. Injective, so different packages never share a parcel name:
7
+ // [a-z0-9-] stay as is, `@scope/name` becomes `scope__name`, any other char is escaped as `_xx` (utf-8 bytes).
8
+ export const sanitizePkgName = (name) => {
9
+ const [, scope, local] = /^@([^/]+)\/(.+)$/.exec(name) || []
10
+ return scope === undefined ? escapeName(name) : `${escapeName(scope)}__${escapeName(local)}`
11
+ }
12
+
13
+ // The package among `expected` a parcel name belongs to: parcel.{sha7}.{channel}.{name}.{version}.{hash}.tar,
14
+ // read by position, so no package whose name or version contains another's can be taken for it.
15
+ export const findPackage = (name, sha7, channel, expected) => Object.entries(expected).find(([pkgName, pkg]) => {
16
+ const prefix = `parcel.${sha7}.${channel}.${sanitizePkgName(pkgName)}.${pkg.version}.`
17
+ return name.startsWith(prefix) && /^[0-9a-f]+\.tar$/.test(name.slice(prefix.length))
18
+ })
19
+
5
20
 
6
21
  const gitFields = (a, pkg) => ({
7
22
  repoHost: a.repoHost,
@@ -17,7 +32,7 @@ const entry = {
17
32
  manifest: {
18
33
  channel: 'git-tag',
19
34
  name: pkg.name, version: pkg.version, tag: pkg.tag,
20
- cwd: ctx.git.root, sha: ctx.git.sha,
35
+ sha: ctx.git.sha,
21
36
  gitCommitterName: '${{GIT_COMMITTER_NAME}}',
22
37
  gitCommitterEmail: '${{GIT_COMMITTER_EMAIL}}',
23
38
  },
@@ -1,18 +1,12 @@
1
1
  import {fs, path, glob} from 'zx-extra'
2
- import {packTar, unpackTar} from '../tar.js'
2
+ import {packTar, readManifest, readMarker} from '../tar.js'
3
3
  import {log} from '../log.js'
4
-
5
- const GIT_CHANNELS = new Set(['git-tag', 'gh-release', 'changelog', 'gh-pages', 'meta'])
4
+ import {stepsOf} from '../courier/channels/index.js'
5
+ import {prevOf} from '../depot/context.js'
6
6
 
7
7
  // parcel.{sha7}.{channel}.{...}.tar — channel is the 3rd dot-segment
8
8
  export const parcelChannel = (name) => name.replace(/\.tar$/, '').split('.')[2]
9
9
 
10
- const splitSteps = (channelNames) => {
11
- const git = channelNames.filter(n => GIT_CHANNELS.has(n))
12
- const ext = channelNames.filter(n => !GIT_CHANNELS.has(n))
13
- return [git, ext].filter(s => s.length)
14
- }
15
-
16
10
  export const buildDirective = async (ctx, packedPkgs, outputDir) => {
17
11
  const {sha, timestamp} = packedPkgs[0].ctx.git
18
12
  const packages = {}
@@ -24,20 +18,14 @@ export const buildDirective = async (ctx, packedPkgs, outputDir) => {
24
18
  packages[pkg.name] = {
25
19
  version: pkg.version,
26
20
  tag: pkg.tag,
27
- deliver: splitSteps(pkg.activeTransport || []),
21
+ deliver: stepsOf(pkg.activeTransport || []), // read by 3.x couriers only: order is courier policy now
28
22
  parcels: pkgParcels,
29
23
  }
30
24
  parcels.push(...pkgParcels)
31
25
  }
32
26
 
33
27
  // Store dependency graph for parallel delivery in topo order
34
- const prev = {}
35
- if (ctx.prev) {
36
- for (const name of packedNames) {
37
- const deps = (ctx.prev.get(name) || []).filter(d => packedNames.has(d))
38
- if (deps.length) prev[name] = deps
39
- }
40
- }
28
+ const prev = ctx.prev ? prevOf(ctx.prev, [...packedNames]) : {}
41
29
 
42
30
  const sha7 = sha.slice(0, 7)
43
31
  const manifest = {
@@ -53,12 +41,9 @@ export const buildDirective = async (ctx, packedPkgs, outputDir) => {
53
41
  }
54
42
 
55
43
  export const parseDirective = async (tarPath) => {
56
- const content = await fs.readFile(tarPath, 'utf8').catch(() => null)
57
- if (content === 'released' || content === 'conflict') return null
58
-
59
- const {manifest} = await unpackTar(tarPath, tarPath + '.d')
60
- if (manifest.channel !== 'directive') return null
61
- return manifest
44
+ if (await readMarker(tarPath)) return null
45
+ const manifest = await readManifest(tarPath)
46
+ return manifest?.channel === 'directive' ? manifest : null
62
47
  }
63
48
 
64
49
  export const scanDirectives = async (dir) => {
@@ -73,9 +58,10 @@ export const scanDirectives = async (dir) => {
73
58
  return result.sort((a, b) => a.timestamp - b.timestamp)
74
59
  }
75
60
 
61
+ // Owned are the parcels the directive's packages list, the same ones the courier delivers.
76
62
  export const invalidateOrphans = async (dir, directive) => {
77
63
  const sha7 = directive.sha.slice(0, 7)
78
- const owned = new Set(directive.parcels || [])
64
+ const owned = new Set(Object.values(directive.packages || {}).flatMap(p => p.parcels || []))
79
65
  const all = await glob(path.join(dir, `parcel.${sha7}.*.tar`))
80
66
  let count = 0
81
67
 
@@ -2,4 +2,9 @@ export {buildParcels, sanitizePkgName} from './build.js'
2
2
  export {buildDirective, parseDirective, scanDirectives, invalidateOrphans, parcelChannel} from './directive.js'
3
3
  export {verifyParcels, verifyManifests} from './verify.js'
4
4
  export {DEFAULT_POPULATE, mergePopulate, matchSchema, validateValue, checkManifest} from './populate.js'
5
+ import {path} from 'zx-extra'
6
+
5
7
  export const PARCELS_DIR = 'parcels'
8
+
9
+ // Where pack puts parcels and their directive: one place, relative to the repo root.
10
+ export const parcelsDir = (root, flags) => path.resolve(root, typeof flags.pack === 'string' ? flags.pack : PARCELS_DIR)
@@ -0,0 +1,81 @@
1
+ // What the directive lists, checked against the context: the directive decides what goes out and in which order.
2
+
3
+ import {topoOrder} from '../../util.js'
4
+ import {log} from '../log.js'
5
+ import {stageOf} from '../courier/channels/index.js'
6
+ import {parcelChannel} from './directive.js'
7
+ import {findPackage} from './build.js'
8
+
9
+ const own = (obj, key) => Object.prototype.hasOwnProperty.call(obj, key)
10
+
11
+ const isMap = (v) => !!v && typeof v === 'object' && !Array.isArray(v)
12
+
13
+ // A courier marks a directive released only once nothing of it is left to deliver.
14
+ export const leftoverErrors = ({names, marked}) => {
15
+ const directive = [...names].find(n => parcelChannel(n) === 'directive')
16
+ const live = [...names].filter(n => !marked.has(n) && parcelChannel(n) !== 'directive')
17
+ return marked.get(directive) === 'released' && live.length ? [`directive is marked released, yet parcels are left: ${directive}`] : []
18
+ }
19
+
20
+ // The directive says what goes out and in which order. It may hold packages back, as when the phases ran with
21
+ // different flags, but what it lists is the context's: versions, tags, the dependencies, and one verified parcel
22
+ // of the package per context channel. Unlisted parcels stay orphans.
23
+ export const directiveErrors = (raw, {sha, sha7, timestamp, prev, packages}, seen) => {
24
+ const listed = Object.keys(isMap(raw.packages) ? raw.packages : {}).sort()
25
+ const unknown = listed.filter(n => !own(packages, n))
26
+ if (unknown.length) return [`directive lists packages the context does not: ${unknown.map(n => JSON.stringify(n)).join(', ')}`]
27
+ if (!listed.length) return ['directive lists no packages']
28
+
29
+ const heldBack = Object.keys(packages).filter(n => !listed.includes(n))
30
+ if (heldBack.length) log.warn(`directive holds back ${heldBack.join(', ')}: they are not delivered`)
31
+ const graph = graphErrors(raw.prev, listed)
32
+ return [
33
+ raw.sha !== sha && 'directive sha differs from the context',
34
+ timestamp !== undefined && raw.timestamp !== timestamp && 'directive timestamp differs from the commit time',
35
+ !sameNames(raw.queue, listed) && 'directive queue differs from its packages',
36
+ ...listed.flatMap(n => entryErrors(raw.packages[n], n, packages[n], seen, sha7)),
37
+ ...graph.length ? graph : dependencyErrors(raw.prev, prev, listed),
38
+ ].filter(Boolean)
39
+ }
40
+
41
+ const entryErrors = (entry, name, pkg, {names, marked}, sha7) => {
42
+ if (entry?.version !== pkg.version || entry?.tag !== pkg.tag) return [`directive entry of ${name} differs from the context`]
43
+ if (!Array.isArray(entry.parcels)) return [`directive entry of ${name} has no parcel list`]
44
+ const owned = entry.parcels.filter(f => names.has(f) && findPackage(f, sha7, parcelChannel(f), {[name]: pkg}))
45
+ if (owned.length !== entry.parcels.length || !sameNames(owned.map(parcelChannel), [...pkg.channels].sort()))
46
+ return [`directive does not list one verified parcel of ${name} per channel (${pkg.channels.join(', ')})`]
47
+ return markerErrors(owned, name, marked)
48
+ }
49
+
50
+ // A courier settles the claim first and drops no listed parcel: markers in any other place came from elsewhere.
51
+ const markerErrors = (parcels, name, marked) => {
52
+ if (parcels.some(f => marked.get(f) === 'orphan' || marked.get(f) === 'skip')) return [`directive lists dropped parcels of ${name}`]
53
+ const claim = parcels.find(f => stageOf(parcelChannel(f)) === 'claim')
54
+ if (claim && !marked.has(claim) && parcels.some(f => marked.has(f))) return [`parcels of ${name} are marked before its claim`]
55
+ return []
56
+ }
57
+
58
+ // What the directive waits on is a graph of what it lists, without cycles.
59
+ const graphErrors = (rawPrev = {}, listed) => {
60
+ const has = new Set(listed)
61
+ const edges = isMap(rawPrev) ? Object.entries(rawPrev) : null
62
+ if (!edges || edges.some(([n, deps]) => !has.has(n) || !Array.isArray(deps) || deps.some(d => !has.has(d))))
63
+ return ['directive prev names what the directive does not list']
64
+ try { topoOrder(listed, new Map(edges)) } catch { return ['directive prev has a cycle'] }
65
+ return []
66
+ }
67
+
68
+ // No dependent goes out without, or before, a package the context says it depends on.
69
+ const dependencyErrors = (rawPrev, prev, listed) => {
70
+ if (!prev) return []
71
+ const has = new Set(listed)
72
+ const depsOf = (n) => Array.isArray(rawPrev?.[n]) ? rawPrev[n] : []
73
+ const heldBack = listed.filter(n => (prev[n] || []).some(d => !has.has(d)))
74
+ const dropped = listed.filter(n => (prev[n] || []).some(d => has.has(d) && !depsOf(n).includes(d)))
75
+ return [
76
+ heldBack.length && `directive holds back what ${heldBack.join(', ')} depend on`,
77
+ dropped.length && `directive drops dependencies of ${dropped.join(', ')}`,
78
+ ]
79
+ }
80
+
81
+ const sameNames = (list, sorted) => Array.isArray(list) && JSON.stringify([...list].sort()) === JSON.stringify(sorted)
@@ -1,100 +1,104 @@
1
- import {fs, path} from 'zx-extra'
1
+ import {path} from 'zx-extra'
2
2
  import {parcelChannel} from './directive.js'
3
- import {sanitizePkgName} from './build.js'
3
+ import {findPackage} from './build.js'
4
4
  import {mergePopulate} from './populate.js'
5
- import {readManifest} from '../tar.js'
6
-
7
- const MARKERS = new Set(['released', 'skip', 'conflict', 'orphan'])
5
+ import {directiveErrors, leftoverErrors} from './verify-directive.js'
6
+ import {readManifest, readNpmManifest, readMarker} from '../tar.js'
8
7
 
9
8
  const own = (obj, key) => Object.prototype.hasOwnProperty.call(obj, key)
10
9
 
11
- const isMarker = async (tarPath) =>
12
- (await fs.stat(tarPath)).size <= 16 && MARKERS.has(await fs.readFile(tarPath, 'utf8'))
13
10
 
14
- const findPackage = (name, expected) => Object.entries(expected).find(([pkgName, pkg]) =>
15
- name.includes(`.${sanitizePkgName(pkgName)}.${pkg.version}.`)
16
- )
11
+ // Names come from an untrusted dir and end up in logs: only the characters pack itself writes.
12
+ const SAFE_NAME = /^[\w.@+-]+$/
17
13
 
18
14
  export const verifyParcels = (tars, context) => {
19
- const {sha7, packages: expected} = context
20
15
  const errors = []
21
16
  const verified = []
22
-
23
17
  for (const tarPath of tars) {
24
- const name = path.basename(tarPath)
25
-
26
- if (!name.startsWith(`parcel.${sha7}.`)) {
27
- errors.push(`sha mismatch: ${name}`)
28
- continue
29
- }
30
-
31
- const channel = parcelChannel(name)
32
- if (!channel) {
33
- errors.push(`malformed name: ${name}`)
34
- continue
35
- }
36
-
37
- if (channel === 'directive') {
38
- verified.push(tarPath)
39
- continue
40
- }
41
-
42
- const belongsTo = findPackage(name, expected)
43
- if (!belongsTo) {
44
- errors.push(`unexpected parcel (no matching package): ${name}`)
45
- continue
46
- }
47
-
48
- const [pkgName, pkg] = belongsTo
49
- if (!pkg.channels.includes(channel)) {
50
- errors.push(`unexpected channel '${channel}' for ${pkgName}: ${name}`)
51
- continue
52
- }
53
-
54
- verified.push(tarPath)
18
+ const error = nameError(path.basename(tarPath), context)
19
+ if (error) errors.push(error)
20
+ else verified.push(tarPath)
55
21
  }
56
-
22
+ errors.push(...directiveNameErrors(verified.map(t => path.basename(t)), context))
57
23
  return {verified, errors}
58
24
  }
59
25
 
60
- // Checks that pack kept what the context fixed: the channel, the release tag and the populate
61
- // rules of every manifest, and the commit time the directives are ordered by. No env, no schemas:
62
- // the courier checks the resolved manifests against the rules right before delivery.
63
- export const verifyManifests = async (tars, context) => {
64
- const errors = []
26
+ const nameError = (name, {sha7, packages}) => {
27
+ const channel = parcelChannel(name)
28
+ const [pkgName, pkg] = findPackage(name, sha7, channel, packages) || []
29
+ const checks = [
30
+ [!SAFE_NAME.test(name), `malformed name: ${JSON.stringify(name)}`],
31
+ [!name.startsWith(`parcel.${sha7}.`), `sha mismatch: ${name}`],
32
+ [!channel, `malformed name: ${name}`],
33
+ [channel !== 'directive' && !pkg, `unexpected parcel (no matching package): ${name}`],
34
+ [pkg && !pkg.channels.includes(channel), `unexpected channel '${channel}' for ${pkgName}: ${name}`],
35
+ ]
36
+ return checks.find(([failed]) => failed)?.[1]
37
+ }
65
38
 
39
+ // The directive decides what goes out, so there is one, named for the commit time: a second would go out too.
40
+ const directiveNameErrors = (names, {sha7, timestamp}) => {
41
+ const directives = names.filter(n => parcelChannel(n) === 'directive')
42
+ if (!names.length) return []
43
+ if (directives.length !== 1) return [`expected one directive among the parcels, found ${directives.length}`]
44
+ if (timestamp !== undefined && directives[0] !== `parcel.${sha7}.directive.${timestamp}.tar`)
45
+ return [`directive is not named for the commit time: ${directives[0]}`]
46
+ return []
47
+ }
48
+
49
+ // Checks that pack kept what the context fixed: the channel, package, version, release tag, commit, npm dist-tag
50
+ // and populate rules of every manifest (and of the npm tarball), and what the directive lists.
51
+ // No env, no schemas: the courier checks the resolved manifests right before delivery.
52
+ // A marker is what is left of a delivered parcel: it has nothing to check but its place, and the courier asks
53
+ // the remote about the claims markers stand for.
54
+ export const verifyManifests = async (tars, context) => {
55
+ const marked = new Map()
66
56
  for (const tarPath of tars) {
67
- const name = path.basename(tarPath)
68
- const channel = parcelChannel(name)
69
- if (await isMarker(tarPath)) continue
57
+ const marker = await readMarker(tarPath)
58
+ if (marker) marked.set(path.basename(tarPath), marker)
59
+ }
60
+ const seen = {names: new Set(tars.map(t => path.basename(t))), marked}
61
+ const errors = leftoverErrors(seen)
62
+ for (const tarPath of tars) if (!marked.has(path.basename(tarPath))) errors.push(...await manifestErrors(tarPath, context, seen))
63
+ return errors
64
+ }
70
65
 
71
- let raw
72
- try { raw = await readManifest(tarPath) } catch {
73
- errors.push(`unreadable manifest: ${name}`)
74
- continue
75
- }
76
- if (raw?.channel !== channel) {
77
- errors.push(`manifest channel does not match the parcel name: ${name}`)
78
- continue
79
- }
80
- if (own(raw, '__proto__')) {
81
- errors.push(`manifest has a '__proto__' key: ${name}`)
82
- continue
83
- }
66
+ const manifestErrors = async (tarPath, context, seen) => {
67
+ const name = path.basename(tarPath)
68
+ const {raw, flaw} = await openManifest(tarPath)
69
+ if (flaw) return [`${flaw}: ${name}`]
70
+ if (raw.channel !== parcelChannel(name)) return [`manifest channel does not match the parcel name: ${name}`]
71
+ const errors = raw.channel === 'directive' ? directiveErrors(raw, context, seen) : await parcelErrors(raw, tarPath, name, context)
72
+ return errors.map(e => `${e}: ${name}`)
73
+ }
84
74
 
85
- if (channel === 'directive') {
86
- const fileTs = Number(name.replace(/\.tar$/, '').split('.')[3])
87
- if (context.timestamp !== undefined && (raw.timestamp !== context.timestamp || fileTs !== context.timestamp))
88
- errors.push(`directive timestamp differs from the commit time: ${name}`)
89
- continue
90
- }
75
+ const openManifest = async (tarPath) => {
76
+ const raw = await readManifest(tarPath).catch(() => null)
77
+ if (!raw || typeof raw !== 'object') return {flaw: 'unreadable manifest'}
78
+ if (own(raw, '__proto__')) return {flaw: `manifest has a '__proto__' key`}
79
+ return {raw}
80
+ }
91
81
 
92
- const [, pkg] = findPackage(name, context.packages)
93
- if (own(raw, 'tag') && raw.tag !== pkg.tag)
94
- errors.push(`manifest tag differs from the context: ${name}`)
95
- if (JSON.stringify(raw.populate || mergePopulate()) !== JSON.stringify(pkg.populate || mergePopulate()))
96
- errors.push(`populate rules differ from the context: ${name}`)
97
- }
82
+ const parcelErrors = async (raw, tarPath, name, {sha, sha7, packages, snapshot}) => {
83
+ const [pkgName, pkg] = findPackage(name, sha7, raw.channel, packages)
84
+ return [
85
+ (raw.name !== pkgName || raw.version !== pkg.version) && 'manifest name or version differs from the parcel name',
86
+ own(raw, 'tag') && raw.tag !== pkg.tag && 'manifest tag differs from the context',
87
+ own(raw, 'sha') && raw.sha !== sha && 'manifest sha differs from the context',
88
+ populateOf(raw) !== populateOf(pkg) && 'populate rules differ from the context',
89
+ raw.channel === 'npm' && await npmFlaw(raw, tarPath, pkgName, pkg, snapshot),
90
+ ].filter(Boolean)
91
+ }
98
92
 
99
- return errors
93
+ const populateOf = ({populate}) => JSON.stringify(populate || mergePopulate())
94
+
95
+ // npm publishes the tarball under the name and version from its own package.json, and as `snapshot` only
96
+ // when the manifest has a preversion.
97
+ const npmFlaw = async (raw, tarPath, pkgName, pkg, snapshot) => {
98
+ if (snapshot !== undefined && Boolean(raw.preversion) !== snapshot) return 'npm dist-tag differs from the context'
99
+ const tarball = await readNpmManifest(tarPath).catch(() => null)
100
+ if (!tarball) return 'npm parcel has no readable, unambiguous package.tgz'
101
+ if (tarball.name !== pkgName || tarball.version !== pkg.version)
102
+ return `npm tarball ${JSON.stringify(`${tarball.name}@${tarball.version}`)} differs from the parcel name`
103
+ return null
100
104
  }
@@ -4,6 +4,7 @@ import {$, within} from 'zx-extra'
4
4
  import {queuefy} from '../util.js'
5
5
 
6
6
  import {createReport, log} from './log.js'
7
+ import {api} from './api/index.js'
7
8
  import {topo} from './depot/deps.js'
8
9
  import {exec} from './depot/exec.js'
9
10
  import {defaultOrder as channels} from './courier/index.js'
@@ -38,10 +39,6 @@ export const run = async ({cwd = process.cwd(), env: _env, flags = {}} = {}) =>
38
39
  })
39
40
 
40
41
  export const createContext = async ({flags, env, cwd}) => {
41
- // Ensure remote tags are up-to-date before analysis to avoid
42
- // inconsistencies between receive (context) and pack (parcels).
43
- try { await $({cwd, quiet: true})`git fetch origin --tags --force` } catch { /* offline / bare */ }
44
-
45
42
  const {packages, queue, root, prev, graphs} = await topo({cwd, flags})
46
43
  const report = createReport({packages, queue, flags})
47
44
 
@@ -51,6 +48,10 @@ export const createContext = async ({flags, env, cwd}) => {
51
48
  $.quiet = !$.verbose
52
49
  $.memo = new Map()
53
50
 
51
+ // Ensure remote tags are up-to-date before analysis to avoid
52
+ // inconsistencies between receive (context) and pack (parcels).
53
+ try { await api.git.fetchTags(cwd) } catch { /* offline / bare */ }
54
+
54
55
  return {cwd, env, flags, root, packages, queue, prev, graphs, report, channels,
55
56
  run: queuefy(exec, flags.concurrency || os.cpus().length)}
56
57
  }
@@ -1,8 +1,18 @@
1
1
  import tar from 'tar-stream'
2
2
  import crypto from 'node:crypto'
3
+ import zlib from 'node:zlib'
3
4
  import {pipeline} from 'node:stream/promises'
4
5
  import {fs, path} from 'zx-extra'
5
6
 
7
+ // A handled parcel is replaced by a marker: released, conflict, skip (3.x, held for credentials) or orphan.
8
+ const MARKERS = new Set(['released', 'skip', 'conflict', 'orphan'])
9
+
10
+ export const readMarker = async (tarPath) => {
11
+ if ((await fs.stat(tarPath)).size > 16) return null
12
+ const content = await fs.readFile(tarPath, 'utf8')
13
+ return MARKERS.has(content) ? content : null
14
+ }
15
+
6
16
  export const packTar = async (tarPath, manifest, files = []) => {
7
17
  await fs.ensureDir(path.dirname(tarPath))
8
18
  const pack = tar.pack()
@@ -41,34 +51,32 @@ const addDir = async (pack, prefix, dirPath) => {
41
51
  }
42
52
  }
43
53
 
54
+ // Parcels come from an untrusted phase: only plain files are taken, and only inside destDir.
55
+ // A bad entry fails the unpacking, it never escapes as an unhandled rejection.
44
56
  export const unpackTar = async (tarPath, destDir) => {
45
- await fs.ensureDir(destDir)
57
+ const root = path.resolve(destDir)
46
58
  const extract = tar.extract()
47
59
  let manifest = null
48
60
 
49
- const done = new Promise((resolve, reject) => {
50
- extract.on('entry', (header, stream, cb) => {
51
- const chunks = []
52
- stream.on('data', d => chunks.push(d))
53
- stream.on('end', async () => {
54
- const buf = Buffer.concat(chunks)
55
- if (header.name === 'manifest.json') {
56
- manifest = JSON.parse(buf.toString('utf8'))
57
- } else {
58
- const dest = path.join(destDir, header.name)
59
- await fs.ensureDir(path.dirname(dest))
60
- await fs.writeFile(dest, buf)
61
- }
62
- cb()
63
- })
64
- stream.resume()
65
- })
66
- extract.on('finish', resolve)
67
- extract.on('error', reject)
61
+ const take = async ({name, type}, buf) => {
62
+ if (name === 'manifest.json') {
63
+ manifest = JSON.parse(buf.toString('utf8'))
64
+ return
65
+ }
66
+ const dest = path.resolve(root, name)
67
+ if (type !== 'file' || !dest.startsWith(root + path.sep)) throw new Error(`unsafe entry in ${path.basename(tarPath)}: ${name}`)
68
+ await fs.outputFile(dest, buf)
69
+ }
70
+
71
+ extract.on('entry', (header, stream, cb) => {
72
+ const chunks = []
73
+ stream.on('data', d => chunks.push(d))
74
+ stream.on('end', () => take(header, Buffer.concat(chunks)).then(() => cb(), cb))
75
+ stream.resume()
68
76
  })
69
77
 
78
+ await fs.ensureDir(root)
70
79
  await pipeline(fs.createReadStream(tarPath), extract)
71
- await done
72
80
  return {manifest, dir: destDir}
73
81
  }
74
82
 
@@ -90,3 +98,39 @@ export const readManifest = async (tarPath) => {
90
98
  await pipeline(fs.createReadStream(tarPath), extract)
91
99
  return raw === null ? null : JSON.parse(raw)
92
100
  }
101
+
102
+ // Reads package.json from the npm tarball (package.tgz) inside a parcel — npm publishes
103
+ // under the name and version found there. Null if there is no tarball or it is ambiguous.
104
+ export const readNpmManifest = async (tarPath) => {
105
+ const outer = tar.extract()
106
+ const found = []
107
+
108
+ outer.on('entry', (header, stream, next) => {
109
+ if (header.name !== 'package.tgz') {
110
+ stream.on('end', next)
111
+ return stream.resume()
112
+ }
113
+
114
+ const inner = tar.extract()
115
+ inner.on('entry', (h, s, n) => {
116
+ const match = isNpmManifest(h.name)
117
+ const chunks = []
118
+ s.on('data', d => match && chunks.push(d))
119
+ s.on('end', () => {
120
+ if (match) found.push({type: h.type, json: Buffer.concat(chunks).toString('utf8')})
121
+ n()
122
+ })
123
+ s.resume()
124
+ })
125
+ pipeline(stream, zlib.createGunzip(), inner).then(() => next(), next)
126
+ })
127
+
128
+ await pipeline(fs.createReadStream(tarPath), outer)
129
+ if (found.length !== 1 || found[0].type !== 'file') return null
130
+ try { return JSON.parse(found[0].json) } catch { return null }
131
+ }
132
+
133
+ // npm drops the first path segment as it is, whatever it is called, then normalizes the rest and takes
134
+ // package.json from the top: every entry that lands there counts, so a second spelling can't hide behind the first.
135
+ const isNpmManifest = (name) =>
136
+ path.posix.normalize(name.split('/').slice(1).join('/')).replace(/^\/+/, '') === 'package.json'
@@ -1,3 +1,4 @@
1
+ import {AsyncResource} from 'node:async_hooks'
1
2
  import {$} from 'zx-extra'
2
3
 
3
4
  export const tpl = (str, context) =>
@@ -79,17 +80,43 @@ export const queuefy = (fn, concurrency = 1) => {
79
80
  const next = () => {
80
81
  if (active >= concurrency || queue.length === 0) return
81
82
  active++
82
- const {args, resolve, reject} = queue.shift()
83
- Promise.resolve().then(() => fn(...args)).then(
83
+ const {task, resolve, reject} = queue.shift()
84
+ Promise.resolve().then(task).then(
84
85
  v => { active--; resolve(v); next() },
85
86
  e => { active--; reject(e); next() }
86
87
  )
87
88
  }
89
+ // A call runs in its caller's async context (zx `within`, `$.scope`), not in the one that freed the slot.
88
90
  return (...args) => new Promise((resolve, reject) => {
89
- queue.push({args, resolve, reject})
91
+ queue.push({task: AsyncResource.bind(() => fn(...args)), resolve, reject})
90
92
  next()
91
93
  })
92
94
  }
93
95
 
94
- export const pool = async (tasks, concurrency, fn) =>
95
- Promise.all(tasks.map(queuefy(fn, concurrency)))
96
+ // Settled work reports its errors together: one as is (its exit code too), several as one AggregateError.
97
+ export const throwAll = (errors, what) => {
98
+ if (errors.length > 1) throw new AggregateError(errors, `${errors.length} ${what} failed`)
99
+ if (errors.length) throw errors[0]
100
+ }
101
+
102
+ // Keys ordered so that each comes after what it depends on (only keys among `keys` count); throws on a cycle.
103
+ export const topoOrder = (keys, deps) => {
104
+ const order = []
105
+ const visit = (key, path) => {
106
+ if (order.includes(key)) return
107
+ if (path.includes(key)) throw new Error(`dependency cycle: ${[...path, key].join(' → ')}`)
108
+ for (const dep of deps.get(key) || []) if (keys.includes(dep)) visit(dep, [...path, key])
109
+ order.push(key)
110
+ }
111
+ for (const key of keys) visit(key, [])
112
+ return order
113
+ }
114
+
115
+ // Runs tasks one at a time per key: lock(key, task).
116
+ export const keyedQueue = () => {
117
+ const queues = new Map()
118
+ return (key, task) => {
119
+ if (!queues.has(key)) queues.set(key, queuefy(task => task()))
120
+ return queues.get(key)(task)
121
+ }
122
+ }
@@ -42,8 +42,6 @@ export const gitResponses = (overrides = {}) => [
42
42
  ['git config --get remote.origin.url', overrides.origin ?? 'https://github.com/test-org/test-repo.git'],
43
43
  ['git tag -l', overrides.tags ?? ''],
44
44
  [/git log .+--format/, overrides.log ?? ''],
45
- ['git config user.name', ''],
46
- ['git config user.email', ''],
47
45
  [/git tag -m/, ''],
48
46
  ['git push', ''],
49
47
  ['git fetch', ''],
@@ -52,7 +50,6 @@ export const gitResponses = (overrides = {}) => [
52
50
  ['git add', ''],
53
51
  ['git commit', ''],
54
52
  [/git remote/, ''],
55
- [/git config --unset/, ''],
56
53
  ]
57
54
 
58
55
  export const npmResponses = (overrides = {}) => [