zx-bulk-release 3.2.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 (44) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/README.md +58 -22
  3. package/package.json +7 -6
  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 +115 -228
  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 +14 -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 -1
  29. package/src/main/js/post/log.js +10 -1
  30. package/src/main/js/post/modes/deliver.js +14 -30
  31. package/src/main/js/post/modes/pack.js +8 -16
  32. package/src/main/js/post/modes/receive.js +10 -14
  33. package/src/main/js/post/modes/verify.js +18 -2
  34. package/src/main/js/post/parcel/build.js +24 -3
  35. package/src/main/js/post/parcel/directive.js +10 -24
  36. package/src/main/js/post/parcel/index.js +7 -1
  37. package/src/main/js/post/parcel/populate.js +136 -0
  38. package/src/main/js/post/parcel/verify-directive.js +81 -0
  39. package/src/main/js/post/parcel/verify.js +93 -36
  40. package/src/main/js/post/release.js +5 -4
  41. package/src/main/js/post/tar.js +83 -20
  42. package/src/main/js/util.js +32 -5
  43. package/src/test/js/utils/mock.js +0 -3
  44. package/src/test/js/utils/repo.js +10 -4
@@ -1,9 +1,6 @@
1
- import {$, within} from 'zx-extra'
2
-
3
1
  import {api} from '../api/index.js'
4
2
  import {log} from '../log.js'
5
- import {traverseQueue} from '../depot/deps.js'
6
- import {contextify} from '../depot/steps/contextify.js'
3
+ import {forEachPkg} from '../depot/steps/contextify.js'
7
4
  import {analyze} from '../depot/steps/analyze.js'
8
5
  import {clean} from '../depot/steps/clean.js'
9
6
  import {preflight} from '../depot/reconcile.js'
@@ -11,6 +8,7 @@ import {consumeRebuildSignal} from '../courier/semaphore.js'
11
8
  import {getActiveChannels} from '../courier/index.js'
12
9
  import {writeContext, buildContext} from '../depot/context.js'
13
10
  import {getLatest} from '../depot/generators/meta.js'
11
+ import {mergePopulate} from '../parcel/populate.js'
14
12
 
15
13
  export const runReceive = async ({cwd, env, flags}, ctx) => {
16
14
  const {report, packages, queue, prev} = ctx
@@ -29,22 +27,16 @@ export const runReceive = async ({cwd, env, flags}, ctx) => {
29
27
  log.info(`consumed rebuild signal for ${sha7}`)
30
28
  }
31
29
 
32
- const forEachPkg = (cb) => traverseQueue({queue, prev, cb: (name) => within(async () => {
33
- $.scope = name
34
- await contextify(packages[name], ctx)
35
- return cb(packages[name])
36
- })})
37
-
38
30
  try {
39
31
  // Phase 1: analyze all packages
40
- await forEachPkg(async (pkg) => {
32
+ await forEachPkg(ctx, async (pkg) => {
41
33
  report.setStatus('analyzing', pkg.name)
42
34
  await analyze(pkg)
43
35
  })
44
36
 
45
37
  // Phase 2: preflight — may fetch remote tags and re-resolve versions
46
38
  let tagsFetched = false
47
- await forEachPkg(async (pkg) => {
39
+ await forEachPkg(ctx, async (pkg) => {
48
40
  if (!pkg.releaseType) { pkg.skipped = true; return }
49
41
  const result = await preflight(pkg, pkg.ctx)
50
42
  if (result === 'skip') { pkg.skipped = true; return }
@@ -61,7 +53,7 @@ export const runReceive = async ({cwd, env, flags}, ctx) => {
61
53
  pkg.latest = await getLatest(pkg)
62
54
  }
63
55
 
64
- await forEachPkg(async (pkg) => {
56
+ await forEachPkg(ctx, async (pkg) => {
65
57
  if (pkg.releaseType) return
66
58
  pkg.skipped = false
67
59
  report.setStatus('re-analyzing', pkg.name)
@@ -74,6 +66,10 @@ export const runReceive = async ({cwd, env, flags}, ctx) => {
74
66
  const snapshot = !!flags.snapshot
75
67
  const context = buildContext(packages, queue, sha, {
76
68
  getChannels: (pkg) => getActiveChannels(pkg, ctx.channels, snapshot),
69
+ getPopulate: (pkg) => mergePopulate(pkg.config.populate),
70
+ timestamp: Number(await api.git.getCommitTimestamp(cwd)),
71
+ prev,
72
+ snapshot,
77
73
  })
78
74
  await writeContext(cwd, context)
79
75
 
@@ -87,7 +83,7 @@ export const runReceive = async ({cwd, env, flags}, ctx) => {
87
83
  api.gh.setOutput('status', 'proceed')
88
84
  }
89
85
  } catch (e) {
90
- report.error(e, e.stack).setStatus('failure')
86
+ report.error(e).setStatus('failure')
91
87
  throw e
92
88
  } finally {
93
89
  await clean(ctx)
@@ -1,6 +1,6 @@
1
1
  import {glob, path, fs} from 'zx-extra'
2
2
  import {log} from '../log.js'
3
- import {PARCELS_DIR, verifyParcels} from '../parcel/index.js'
3
+ import {PARCELS_DIR, verifyParcels, verifyManifests} from '../parcel/index.js'
4
4
  import {CONTEXT_FILE, readContext} from '../depot/context.js'
5
5
 
6
6
  export const runVerify = async ({cwd, flags}) => {
@@ -23,6 +23,7 @@ export const runVerify = async ({cwd, flags}) => {
23
23
  }
24
24
 
25
25
  const {verified, errors} = verifyParcels(tars, context)
26
+ errors.push(...await linkErrors(tars), ...await strangerErrors(inputDir, outputDir, verified), ...await verifyManifests(verified, context))
26
27
 
27
28
  if (errors.length) {
28
29
  for (const e of errors) log.error(`verify: ${e}`)
@@ -32,10 +33,25 @@ export const runVerify = async ({cwd, flags}) => {
32
33
  if (path.resolve(inputDir) !== outputDir) {
33
34
  await fs.ensureDir(outputDir)
34
35
  for (const tarPath of verified) {
35
- await fs.copy(tarPath, path.join(outputDir, path.basename(tarPath)))
36
+ await fs.copyFile(tarPath, path.join(outputDir, path.basename(tarPath)))
36
37
  }
37
38
  log.info(`${verified.length} parcel(s) verified and copied to ${outputDir}`)
38
39
  } else {
39
40
  log.info(`${verified.length} parcel(s) verified in place`)
40
41
  }
41
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,6 +1,22 @@
1
1
  import {asTuple, msgJoin} from '../../util.js'
2
+ import {mergePopulate} from './populate.js'
3
+
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
+ })
2
19
 
3
- export const sanitizePkgName = (name) => name.replace(/[^a-z0-9-]/ig, '-').replace(/^-+|-+$/g, '')
4
20
 
5
21
  const gitFields = (a, pkg) => ({
6
22
  repoHost: a.repoHost,
@@ -16,7 +32,7 @@ const entry = {
16
32
  manifest: {
17
33
  channel: 'git-tag',
18
34
  name: pkg.name, version: pkg.version, tag: pkg.tag,
19
- cwd: ctx.git.root, sha: ctx.git.sha,
35
+ sha: ctx.git.sha,
20
36
  gitCommitterName: '${{GIT_COMMITTER_NAME}}',
21
37
  gitCommitterEmail: '${{GIT_COMMITTER_EMAIL}}',
22
38
  },
@@ -88,5 +104,10 @@ export const buildParcels = (pkg, ctx, {
88
104
  repoName, repoHost, originUrl,
89
105
  } = {}) => {
90
106
  const a = {npmTarball, releaseNotes, docsDir, assetsDir, repoName, repoHost, originUrl}
91
- return channelNames.map(n => (entry[n] || defaultEntry(n))(pkg, ctx, a))
107
+ // The courier checks the resolved manifest against these rules right before delivery.
108
+ const populate = mergePopulate(pkg.config?.populate)
109
+ return channelNames.map(n => {
110
+ const parcel = (entry[n] || defaultEntry(n))(pkg, ctx, a)
111
+ return {...parcel, manifest: {...parcel.manifest, populate}}
112
+ })
92
113
  }
@@ -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
 
@@ -1,4 +1,10 @@
1
1
  export {buildParcels, sanitizePkgName} from './build.js'
2
2
  export {buildDirective, parseDirective, scanDirectives, invalidateOrphans, parcelChannel} from './directive.js'
3
- export {verifyParcels} from './verify.js'
3
+ export {verifyParcels, verifyManifests} from './verify.js'
4
+ export {DEFAULT_POPULATE, mergePopulate, matchSchema, validateValue, checkManifest} from './populate.js'
5
+ import {path} from 'zx-extra'
6
+
4
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,136 @@
1
+ // Populate rules: what manifest fields must look like after `${{VAR}}` substitution.
2
+ // Pack embeds them into every manifest, verify checks they match the context, and the courier
3
+ // checks the resolved manifests against them right before delivery.
4
+ // The default accepts anything, so substitution works as before until the config narrows it.
5
+ //
6
+ // populate: {
7
+ // schemas: {name: schema},
8
+ // channels: {[channel | '*']: {[field | '*']: {schema: name}}},
9
+ // }
10
+ //
11
+ // The schema of a field is picked by best match: channel.field → channel.* → *.field → *.*
12
+
13
+ export const PLACEHOLDER = /\$\{\{(\w+)\}\}/g
14
+
15
+ export const DEFAULT_POPULATE = {
16
+ schemas: {'*': {}},
17
+ channels: {'*': {'*': {schema: '*'}}},
18
+ }
19
+
20
+ const isObject = (v) => !!v && typeof v === 'object' && !Array.isArray(v)
21
+
22
+ const own = (obj, key) => isObject(obj) && Object.prototype.hasOwnProperty.call(obj, key)
23
+
24
+ const entriesOf = (obj, at) => {
25
+ if (!isObject(obj)) throw new Error(`${at}: must be an object`)
26
+ if (own(obj, '__proto__')) throw new Error(`${at}: '__proto__' key is not allowed`)
27
+ return Object.entries(obj)
28
+ }
29
+
30
+ const TYPES = new Set(['string', 'secret', 'url'])
31
+
32
+ const assertSchema = (schema, at) => {
33
+ if (!isObject(schema)) throw new Error(`${at}: must be an object`)
34
+ if (schema.type !== undefined && !TYPES.has(schema.type)) throw new Error(`${at}.type: unknown type '${schema.type}'`)
35
+ if (schema.enum !== undefined && !Array.isArray(schema.enum)) throw new Error(`${at}.enum: must be an array`)
36
+ if (schema.pattern !== undefined) {
37
+ if (typeof schema.pattern !== 'string') throw new Error(`${at}.pattern: must be a string`)
38
+ try { new RegExp(schema.pattern) } catch { throw new Error(`${at}.pattern: invalid regexp`) }
39
+ }
40
+ if (schema.type === 'url') for (const part of URL_PARTS) {
41
+ const expected = schema[part]
42
+ if (expected === undefined || typeof expected === 'string') continue
43
+ if (!Array.isArray(expected)) assertSchema(expected, `${at}.${part}`)
44
+ else if (!expected.every(v => typeof v === 'string')) throw new Error(`${at}.${part}: must be strings`)
45
+ }
46
+ }
47
+
48
+ // Throws on malformed rules, so a typo can't silently turn into "accept anything". Returns the rules.
49
+ export const assertPopulate = (populate, at = 'populate') => {
50
+ entriesOf(populate, at)
51
+ const {schemas = {}, channels = {}} = populate
52
+ for (const [name, schema] of entriesOf(schemas, `${at}.schemas`))
53
+ assertSchema(schema, `${at}.schemas.${name}`)
54
+ for (const [channel, fields] of entriesOf(channels, `${at}.channels`))
55
+ for (const [field, rule] of entriesOf(fields, `${at}.channels.${channel}`)) {
56
+ if (!isObject(rule) || typeof rule.schema !== 'string') throw new Error(`${at}.channels.${channel}.${field}: must be {schema: name}`)
57
+ if (!own(schemas, rule.schema) && !own(DEFAULT_POPULATE.schemas, rule.schema)) throw new Error(`${at}.channels.${channel}.${field}: unknown schema '${rule.schema}'`)
58
+ }
59
+
60
+ return populate
61
+ }
62
+
63
+ export const mergePopulate = (populate) => {
64
+ if (populate === undefined || populate === null) populate = {}
65
+ const {schemas, channels} = assertPopulate(populate)
66
+ const merged = JSON.parse(JSON.stringify(DEFAULT_POPULATE))
67
+ Object.assign(merged.schemas, schemas)
68
+ for (const [channel, fields] of Object.entries(channels || {}))
69
+ for (const [field, rule] of Object.entries(fields))
70
+ (merged.channels[channel] ??= {})[field] = {...merged.channels[channel][field], ...rule}
71
+
72
+ return merged
73
+ }
74
+
75
+ export const matchSchema = ({channels}, channel, field) =>
76
+ [[channel, field], [channel, '*'], ['*', field], ['*', '*']]
77
+ .map(([c, f]) => own(channels, c) && own(channels[c], f) ? channels[c][f].schema : undefined)
78
+ .find(v => v !== undefined) ?? '*'
79
+
80
+ // --- schema contract ---
81
+ // {} any value
82
+ // {type: 'string'} + const / enum / pattern (the pattern must match the whole value)
83
+ // {type: 'secret'} non-empty string
84
+ // {type: 'url', ...parts} absolute URL. A part is matched by a string (exact), an array (one of)
85
+ // or a nested schema. Parts not described must be empty, except
86
+ // protocol and hostname, which are not checked unless described.
87
+ // Errors name the field and part, never the actual value.
88
+
89
+ const URL_PARTS = ['protocol', 'username', 'password', 'hostname', 'port', 'pathname', 'search', 'hash']
90
+ const ALWAYS_SET = new Set(['protocol', 'hostname'])
91
+
92
+ const isEmptyPart = (part, value) => value === '' || (part === 'pathname' && value === '/')
93
+
94
+ const matchPart = (actual, expected, at) =>
95
+ typeof expected === 'string'
96
+ ? actual === expected ? [] : [`${at}: expected ${JSON.stringify(expected)}`]
97
+ : Array.isArray(expected)
98
+ ? expected.includes(actual) ? [] : [`${at}: expected one of ${JSON.stringify(expected)}`]
99
+ : validateValue(actual, expected, at)
100
+
101
+ const validateUrl = (value, schema, at) => {
102
+ let url
103
+ try { url = new URL(value) } catch { return [`${at}: must be an absolute URL`] }
104
+
105
+ return URL_PARTS.flatMap(part => schema[part] === undefined
106
+ ? ALWAYS_SET.has(part) || isEmptyPart(part, url[part]) ? [] : [`${at}.${part}: is not allowed`]
107
+ : matchPart(url[part], schema[part], `${at}.${part}`))
108
+ }
109
+
110
+ export const validateValue = (value, schema = {}, at = 'value') => {
111
+ if (!isObject(schema)) return [`${at}: invalid schema`]
112
+ const {type} = schema
113
+
114
+ if (type === 'url') return validateUrl(value, schema, at)
115
+ if (type === 'secret') return typeof value === 'string' && value ? [] : [`${at}: must be a non-empty secret`]
116
+ if (type === 'string' && typeof value !== 'string') return [`${at}: must be a string`]
117
+ if (type !== undefined && type !== 'string') return [`${at}: unknown schema type '${type}'`]
118
+
119
+ const errors = []
120
+ if ('const' in schema && value !== schema.const)
121
+ errors.push(`${at}: expected ${JSON.stringify(schema.const)}`)
122
+ if (schema.enum && !schema.enum.includes(value))
123
+ errors.push(`${at}: expected one of ${JSON.stringify(schema.enum)}`)
124
+ if (schema.pattern && !(typeof value === 'string' && new RegExp(`^(?:${schema.pattern})$`).test(value)))
125
+ errors.push(`${at}: does not match ${schema.pattern}`)
126
+
127
+ return errors
128
+ }
129
+
130
+ // Checks manifest values (resolved or as packed) against the schemas of their fields.
131
+ export const checkManifest = ({values, channel, populate}) =>
132
+ Object.entries(values).flatMap(([field, value]) => {
133
+ if (field === 'populate') return []
134
+ const ref = matchSchema(populate, channel, field)
135
+ return own(populate.schemas, ref) ? validateValue(value, populate.schemas[ref], field) : [`${field}: unknown schema '${ref}'`]
136
+ })
@@ -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,47 +1,104 @@
1
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
+ import {mergePopulate} from './populate.js'
5
+ import {directiveErrors, leftoverErrors} from './verify-directive.js'
6
+ import {readManifest, readNpmManifest, readMarker} from '../tar.js'
7
+
8
+ const own = (obj, key) => Object.prototype.hasOwnProperty.call(obj, key)
9
+
10
+
11
+ // Names come from an untrusted dir and end up in logs: only the characters pack itself writes.
12
+ const SAFE_NAME = /^[\w.@+-]+$/
4
13
 
5
14
  export const verifyParcels = (tars, context) => {
6
- const {sha7, packages: expected} = context
7
15
  const errors = []
8
16
  const verified = []
17
+ for (const tarPath of tars) {
18
+ const error = nameError(path.basename(tarPath), context)
19
+ if (error) errors.push(error)
20
+ else verified.push(tarPath)
21
+ }
22
+ errors.push(...directiveNameErrors(verified.map(t => path.basename(t)), context))
23
+ return {verified, errors}
24
+ }
25
+
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
+ }
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
+ }
9
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()
10
56
  for (const tarPath of tars) {
11
- const name = path.basename(tarPath)
12
-
13
- if (!name.startsWith(`parcel.${sha7}.`)) {
14
- errors.push(`sha mismatch: ${name}`)
15
- continue
16
- }
17
-
18
- const channel = parcelChannel(name)
19
- if (!channel) {
20
- errors.push(`malformed name: ${name}`)
21
- continue
22
- }
23
-
24
- if (channel === 'directive') {
25
- verified.push(tarPath)
26
- continue
27
- }
28
-
29
- const belongsTo = Object.entries(expected).find(([pkgName, pkg]) =>
30
- name.includes(`.${sanitizePkgName(pkgName)}.${pkg.version}.`)
31
- )
32
- if (!belongsTo) {
33
- errors.push(`unexpected parcel (no matching package): ${name}`)
34
- continue
35
- }
36
-
37
- const [pkgName, pkg] = belongsTo
38
- if (!pkg.channels.includes(channel)) {
39
- errors.push(`unexpected channel '${channel}' for ${pkgName}: ${name}`)
40
- continue
41
- }
42
-
43
- verified.push(tarPath)
57
+ const marker = await readMarker(tarPath)
58
+ if (marker) marked.set(path.basename(tarPath), marker)
44
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
+ }
45
65
 
46
- return {verified, errors}
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
+ }
74
+
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
+ }
81
+
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
+ }
92
+
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
47
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
  }