blogwright 0.4.0-beta.5 → 0.5.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 (50) hide show
  1. package/README.md +4 -1
  2. package/agent/agent-manifest.json +1 -1
  3. package/agent/server.js +2610 -616
  4. package/dist/adapters/process-aws-login.d.ts +19 -0
  5. package/dist/adapters/process-aws-login.js +28 -0
  6. package/dist/agent-package.js +2 -3
  7. package/dist/artifacts.d.ts +73 -0
  8. package/dist/artifacts.js +218 -0
  9. package/dist/aws-session.d.ts +118 -0
  10. package/dist/aws-session.js +360 -0
  11. package/dist/bin.js +6 -2
  12. package/dist/cache-control.d.ts +66 -0
  13. package/dist/cache-control.js +176 -0
  14. package/dist/cli.d.ts +22 -3
  15. package/dist/cli.js +122 -31
  16. package/dist/commands.d.ts +41 -9
  17. package/dist/commands.js +135 -126
  18. package/dist/context.d.ts +27 -5
  19. package/dist/context.js +59 -19
  20. package/dist/deploy.d.ts +78 -6
  21. package/dist/deploy.js +136 -52
  22. package/dist/init.d.ts +14 -2
  23. package/dist/init.js +145 -4
  24. package/dist/known-commands.d.ts +11 -9
  25. package/dist/known-commands.js +15 -9
  26. package/dist/live-release.d.ts +78 -0
  27. package/dist/live-release.js +159 -0
  28. package/dist/lock.d.ts +50 -0
  29. package/dist/lock.js +120 -0
  30. package/dist/nodes.d.ts +18 -0
  31. package/dist/nodes.js +405 -30
  32. package/dist/plugin-commands.d.ts +21 -0
  33. package/dist/plugin-commands.js +54 -3
  34. package/dist/plugins.d.ts +11 -9
  35. package/dist/plugins.js +29 -16
  36. package/dist/ports.d.ts +22 -1
  37. package/dist/releases.d.ts +54 -0
  38. package/dist/releases.js +527 -0
  39. package/dist/render.d.ts +18 -1
  40. package/dist/render.js +38 -6
  41. package/dist/repo.js +2 -3
  42. package/dist/rkey.d.ts +4 -3
  43. package/dist/rkey.js +4 -3
  44. package/dist/serving.d.ts +28 -0
  45. package/dist/serving.js +47 -0
  46. package/dist/verify.d.ts +45 -0
  47. package/dist/verify.js +183 -0
  48. package/dist/whoami.d.ts +23 -0
  49. package/dist/whoami.js +88 -0
  50. package/package.json +8 -8
package/dist/commands.js CHANGED
@@ -1,85 +1,17 @@
1
- import { AwsError, colors, findRepoRoot } from 'blogwright-core';
2
- /*
3
- * A STATIC, NON-OPTIONAL IMPORT, and deliberately the last one left in the
4
- * CLI. Task 29 deleted every other reference to `blogwright-pds` from the
5
- * dispatcher (`cli.ts` now knows no namespace by name; the package is
6
- * discovered and dispatched as an ordinary plugin), and this one still
7
- * stays, for two reasons:
8
- *
9
- * - THE SPI HAS NO LIFECYCLE HOOKS. `Plugin` (`blogwright-core`'s
10
- * `plugin.ts`) declares `commands`, `nodes`, `configKey`,
11
- * `validateConfig` and `init` - nothing a plugin could register to be
12
- * called after a successful deploy. `deploy` below therefore reaches
13
- * this function by name, exactly as it always has; routing it through
14
- * plugin dispatch would mean inventing a hook the change spec does not
15
- * describe.
16
- * - THE PACKAGE SHIPS BY DEFAULT. `blogwright-pds` is a non-optional
17
- * `dependencies` entry of `packages/cli/package.json` - that is how the
18
- * bundled plugin reaches a consuming repo that depends on `blogwright`
19
- * alone - so the import can never fail to resolve, and no optional-
20
- * dependency guard is needed around it.
21
- *
22
- * `syncAfterDeploy` no-ops for any environment but `production` and for a
23
- * site with no `pds` config block, so an unconfigured repo pays nothing for
24
- * it. Both halves are asserted in `commands.test.ts`.
25
- */
26
- import { syncAfterDeploy } from 'blogwright-pds';
27
- import { invalidateChanged, invalidateCloudFront, manifestKey, microvmLogGroup, readManifest, runBuild, webFunctionJob, } from './deploy.js';
1
+ import { AwsError, colors, findRepoRoot, stagedReleaseManifestKey, } from 'blogwright-core';
2
+ import { describeRelease, logRebuildComparison, newArtifactBuildManifestKey, readBuildArtifact, readRecordedBeforeRebuild, recordDeployArtifact, } from './artifacts.js';
3
+ import { cacheControlRecordKey } from './cache-control.js';
4
+ import { invalidateChanged, invalidateCloudFront, DEPLOY_MANIFESTS_PREFIX, manifestKey, STAGED_BUILDS_PREFIX, microvmLogGroup, readManifest, runBuild, uploadSource, webFunctionJob, } from './deploy.js';
28
5
  import { applyGraph, destroyGraph } from './graph.js';
6
+ import { forgetLiveRelease, markLiveReleasePublishing, recordLiveRelease, } from './live-release.js';
7
+ import { assertEnvUnlocked, withEnvLock } from './lock.js';
29
8
  import { clearRunningMicrovms } from './microvms.js';
30
- import { buildNodes, reconcileBuilderImage } from './nodes.js';
31
- import { formatDuration, logStatusEntries, historyHasRevisions, NO_REVISION, renderHistoryTable, renderSummary, } from './render.js';
9
+ import { buildNodes, reconcileBuilderImage, reconcileResponseHeadersOnDeploy } from './nodes.js';
10
+ import { describeInvalidation, formatDuration, logStatusEntries, historyHasRevisions, historyStatus, historyTime, NO_REVISION, renderHistoryTable, renderSummary, } from './render.js';
11
+ import { rollbackToStagedRelease, runAfterPublish } from './releases.js';
32
12
  import { buildRepoZip, COMMIT_FILE, listRepoFiles } from './repo.js';
13
+ import { assertServingModeMatches, configuredMode, recordedMode, siteBaseUrl } from './serving.js';
33
14
  import { assertNotSsrForPreviews, preflightWebFunction, recordManifest, publishRecordedRevision, publishWebRevision, readWebBuildResult, requireSsr, warnAboutSsrSeo, } from './web-functions.js';
34
- /** One line per invalidation outcome, shared by the summary card and logs. */
35
- function describeInvalidation(inv) {
36
- if (inv.mode === 'none')
37
- return 'nothing changed - skipped';
38
- if (inv.mode === 'paths')
39
- return `${inv.count} changed path${inv.count === 1 ? '' : 's'}`;
40
- return inv.count > 0 ? `everything (/*) - ${inv.count} paths over cap` : 'everything (/*)';
41
- }
42
- /**
43
- * Canonical origin the live site is served from: the custom domain if configured,
44
- * else the distribution's CloudFront domain. Used for robots.txt / sitemap.xml URLs.
45
- */
46
- function siteBaseUrl(ctx) {
47
- if (ctx.domain)
48
- return `https://${ctx.domain}`;
49
- const cf = ctx.state.resources['cloudfront-distribution']?.domainName;
50
- return typeof cf === 'string' ? `https://${cf}` : undefined;
51
- }
52
- /** The serving mode the config asks for. */
53
- function configuredMode(ctx) {
54
- return ctx.config.ssr ? 'ssr' : 'static';
55
- }
56
- /**
57
- * The serving mode the live distribution was left in, or undefined before the
58
- * first bootstrap. A distribution recorded without a mode was created before
59
- * SSR existed, so it is static - reading that as "unknown" would let the very
60
- * stacks the switch guard exists for through it.
61
- */
62
- function recordedMode(ctx) {
63
- const distribution = ctx.state.resources['cloudfront-distribution'];
64
- if (typeof distribution?.id !== 'string')
65
- return undefined;
66
- return distribution.mode === 'ssr' ? 'ssr' : 'static';
67
- }
68
- /**
69
- * Refuse to publish in a mode the distribution is not serving. The config and
70
- * the stack disagree only between editing `ssr` and re-bootstrapping, and a
71
- * deploy in that gap publishes where nothing serves from - or, static over
72
- * SSR, deletes the `site/` assets the live revision still references.
73
- */
74
- function assertServingModeMatches(ctx) {
75
- const recorded = recordedMode(ctx);
76
- const configured = configuredMode(ctx);
77
- if (recorded === undefined || recorded === configured)
78
- return;
79
- throw new Error(`"${ctx.env}" is configured for ${configured} serving but its distribution serves ` +
80
- `${recorded}. Run \`blogwright bootstrap ${ctx.env} --switch-mode\` first; nothing was ` +
81
- 'built or published.');
82
- }
83
15
  /** What a mode switch does to the live site while the next deploy has not run. */
84
16
  function servingWindow(mode) {
85
17
  return mode === 'ssr'
@@ -258,6 +190,9 @@ export async function destroy(ctx, opts) {
258
190
  throw new Error(`refusing to destroy "${ctx.env}" without --yes`);
259
191
  }
260
192
  await assertNoScopedState(ctx);
193
+ // Destroy removes the lock along with the bucket, so it does not take it -
194
+ // it refuses while another command holds it.
195
+ await assertEnvUnlocked(ctx, 'destroy', opts);
261
196
  ctx.logger.info(colors.bold(`Destroying "${ctx.env}"`));
262
197
  // Running builder MicroVMs pin the image and make its deletion fail; clear them first
263
198
  // (or let the operator cancel and wait for in-flight builds to finish).
@@ -291,8 +226,19 @@ async function webBuildResultOrFail(ctx, source) {
291
226
  throw err;
292
227
  }
293
228
  }
229
+ /**
230
+ * Keep the live-release record in step with `site/` after a build published
231
+ * there: the build's release when it recorded one, otherwise no record at all
232
+ * rather than a stale one.
233
+ */
234
+ async function noteLiveRelease(ctx, artifact, via) {
235
+ if (artifact)
236
+ await recordLiveRelease(ctx, artifact, via);
237
+ else
238
+ await forgetLiveRelease(ctx);
239
+ }
294
240
  /** Zip the repo, upload it, run the builder MicroVM, and invalidate the cache. */
295
- export async function deploy(ctx, opts = {}) {
241
+ export async function deploy(ctx, opts) {
296
242
  const startedAt = Date.now();
297
243
  const cwd = await findRepoRoot(ctx.ports.fs);
298
244
  const hash = await ctx.ports.vcs.revisionHash(cwd);
@@ -304,24 +250,36 @@ export async function deploy(ctx, opts = {}) {
304
250
  warnAboutSsrSeo(ctx);
305
251
  await preflightWebFunction(ctx);
306
252
  }
307
- const files = await listRepoFiles(ctx.ports, cwd, ctx.config.sourceIgnore, ctx.config.sourceInclude);
308
- ctx.logger.step(`zipping ${files.length} files`);
309
- const zip = await buildRepoZip(ctx.ports.fs, cwd, files, { [COMMIT_FILE]: hash });
310
- const sourceKey = `build/${hash}.zip`;
311
- await ctx.clients.s3.putObject(ctx.names.bucket, sourceKey, zip, 'application/zip');
312
- ctx.logger.ok(`uploaded ${sourceKey} (${(zip.byteLength / 1024).toFixed(0)} KiB)`);
253
+ await withEnvLock(ctx, 'deploy', hash, opts, () => deployLocked(ctx, opts, { cwd, hash, startedAt }));
254
+ }
255
+ /** The deploy itself, run holding the environment lock. */
256
+ async function deployLocked(ctx, opts, { cwd, hash, startedAt }) {
257
+ // Converge the response headers before anything is uploaded or built, so a
258
+ // policy CloudFront rejects stops the deploy with nothing published.
259
+ await reconcileResponseHeadersOnDeploy(ctx);
260
+ const { sourceKey, fileCount, zipBytes } = await uploadSource(ctx, cwd, hash);
313
261
  // Rebuild the builder image first if the agent bundle changed, so build-agent fixes
314
262
  // ship on the same deploy (no-op when unchanged).
315
263
  await reconcileBuilderImage(ctx);
264
+ // A static build records its manifest at a key of its own; finding it there
265
+ // afterwards proves this build wrote it.
266
+ const artifactKey = ctx.config.ssr ? undefined : newArtifactBuildManifestKey(hash);
267
+ // The build is about to change site/: until it finishes, the record must
268
+ // not keep naming the release it replaces.
269
+ if (!ctx.config.ssr)
270
+ await markLiveReleasePublishing(ctx, hash, 'deploy');
316
271
  const manifest = await runBuild(ctx, {
317
272
  hash,
318
273
  sourceKey,
319
274
  baseUrl: siteBaseUrl(ctx),
320
- ...(ctx.config.ssr ? { webFunction: webFunctionJob(ctx, hash) } : {}),
275
+ ...(ctx.config.ssr
276
+ ? { webFunction: webFunctionJob(ctx, hash) }
277
+ : { artifactManifestKey: artifactKey }),
321
278
  ...(opts.refresh ? { refresh: true } : {}),
322
279
  });
323
280
  let invalidation;
324
281
  let outcome;
282
+ let artifact;
325
283
  if (ctx.config.ssr) {
326
284
  const source = manifestSource(ctx, hash, startedAt, manifest.microvmId);
327
285
  const result = await webBuildResultOrFail(ctx, source);
@@ -330,9 +288,12 @@ export async function deploy(ctx, opts = {}) {
330
288
  }
331
289
  else {
332
290
  invalidation = await invalidateChanged(ctx, hash);
291
+ if (artifactKey)
292
+ artifact = await recordDeployArtifact(ctx, hash, artifactKey);
293
+ await noteLiveRelease(ctx, artifact, 'deploy');
333
294
  }
334
- // Production content changed - mirror it to the PDS (non-fatal; see syncAfterDeploy).
335
- await syncAfterDeploy(ctx);
295
+ // The site is live - plugins' post-deploy steps (the pds sync, for one) run now.
296
+ await opts.afterDeploy(ctx);
336
297
  const url = siteBaseUrl(ctx);
337
298
  const rows = [
338
299
  {
@@ -342,8 +303,9 @@ export async function deploy(ctx, opts = {}) {
342
303
  : hash,
343
304
  },
344
305
  { label: 'environment', value: ctx.env },
345
- { label: 'source', value: `${files.length} files, ${(zip.byteLength / 1024).toFixed(0)} KiB` },
306
+ { label: 'source', value: `${fileCount} files, ${(zipBytes / 1024).toFixed(0)} KiB` },
346
307
  { label: 'build', value: formatDuration(manifest.durationMs) },
308
+ ...(artifact ? [{ label: 'release', value: describeRelease(artifact) }] : []),
347
309
  { label: 'invalidated', value: describeInvalidation(invalidation) },
348
310
  ...(url ? [{ label: 'site', value: colors.cyan(url) }] : []),
349
311
  ];
@@ -407,39 +369,67 @@ async function rollbackSsr(ctx, hash, opts = {}) {
407
369
  }
408
370
  ctx.logger.info(` revision ${outcome.revisionId} (${outcome.created ? 'created' : 'unchanged'}), ` +
409
371
  `${describeInvalidation(outcome.invalidation)}`);
410
- // A rollback changes production content too, but the PDS mirrors the *working tree*
411
- // content, which a rollback does not restore - so only warn about the divergence.
412
- if (ctx.env === 'production' && ctx.config.pds) {
413
- ctx.logger.warn('rollback does not sync the PDS (records mirror the current repo content); ' +
414
- 'check out the rolled-back revision and run `blogwright pds sync` if needed');
372
+ }
373
+ /**
374
+ * Roll back to a hash. In a static environment a hash with a staged release
375
+ * is republished from its stored bytes, and any other - or any, with
376
+ * `--rebuild` - is rebuilt from its archived source zip; an SSR environment
377
+ * reproduces the recorded revision.
378
+ */
379
+ export async function rollback(ctx, hash, opts) {
380
+ assertServingModeMatches(ctx);
381
+ if (opts.rebuild && ctx.config.ssr) {
382
+ throw new Error('rollback --rebuild applies to static environments: an SSR rollback reproduces the ' +
383
+ 'recorded revision, and rebuilds by itself when that revision cannot be reproduced');
415
384
  }
385
+ const startedAt = Date.now();
386
+ await withEnvLock(ctx, 'rollback', hash, opts, async () => {
387
+ if (ctx.config.ssr)
388
+ await rollbackSsr(ctx, hash, opts);
389
+ else
390
+ await rollbackStatic(ctx, hash, opts);
391
+ await runAfterPublish(ctx, hash, opts.afterDeploy);
392
+ });
416
393
  ctx.logger.ok(`rolled back to ${hash} in ${formatDuration(Date.now() - startedAt)}`);
417
394
  }
418
- /** Re-run the builder against an existing source zip for the given hash. */
419
- export async function rollback(ctx, hash, opts = {}) {
420
- assertServingModeMatches(ctx);
421
- if (ctx.config.ssr)
422
- return rollbackSsr(ctx, hash, opts);
395
+ /**
396
+ * Static rollback, holding the environment lock. A hash with a staged release
397
+ * is republished from its stored bytes - or refused, when they can no longer
398
+ * be checked. Any other hash, or any with `--rebuild`, is rebuilt from its
399
+ * archived source zip into site/.
400
+ */
401
+ async function rollbackStatic(ctx, hash, opts) {
402
+ ctx.logger.info(colors.bold(`Rolling back "${ctx.env}" to ${hash}`));
403
+ if (!opts.rebuild && (await rollbackToStagedRelease(ctx, hash, opts)) === 'republished')
404
+ return;
423
405
  const sourceKey = `build/${hash}.zip`;
424
406
  if (!(await ctx.clients.s3.objectExists(ctx.names.bucket, sourceKey))) {
425
407
  throw new Error(`no build artifact at ${sourceKey}; cannot roll back to ${hash}`);
426
408
  }
427
- ctx.logger.info(colors.bold(`Rolling back "${ctx.env}" to ${hash}`));
428
- const startedAt = Date.now();
409
+ ctx.logger.step(opts.rebuild
410
+ ? `rebuilding ${hash} from ${sourceKey}, as --rebuild asks - any staged release of it is not used`
411
+ : `${hash} has no staged release (no record at ${stagedReleaseManifestKey(hash)}) - ` +
412
+ `rebuilding from ${sourceKey}`);
413
+ // The original record is what the rebuilt bytes are checked against. The
414
+ // rebuild records its own manifest under a fresh key and never replaces it.
415
+ const recorded = await readRecordedBeforeRebuild(ctx, hash);
416
+ const artifactKey = newArtifactBuildManifestKey(hash);
417
+ await markLiveReleasePublishing(ctx, hash, 'rollback');
429
418
  await runBuild(ctx, {
430
419
  hash,
431
420
  sourceKey,
432
421
  baseUrl: siteBaseUrl(ctx),
422
+ artifactManifestKey: artifactKey,
433
423
  ...(opts.refresh ? { refresh: true } : {}),
434
424
  });
435
425
  await invalidateChanged(ctx, hash);
436
- // A rollback changes production content too, but the PDS mirrors the *working tree*
437
- // content, which a rollback does not restore - so only warn about the divergence.
438
- if (ctx.env === 'production' && ctx.config.pds) {
439
- ctx.logger.warn('rollback does not sync the PDS (records mirror the current repo content); ' +
440
- 'check out the rolled-back revision and run `blogwright pds sync` if needed');
441
- }
442
- ctx.logger.ok(`rolled back to ${hash} in ${formatDuration(Date.now() - startedAt)}`);
426
+ const rebuilt = await readBuildArtifact(ctx, hash, artifactKey);
427
+ logRebuildComparison(ctx, recorded, rebuilt);
428
+ await noteLiveRelease(ctx, rebuilt, 'rollback');
429
+ }
430
+ /** The build target one PR's preview publishes as: its pending-job and record name. */
431
+ function previewTarget(id) {
432
+ return `preview-${id}`;
443
433
  }
444
434
  function assertPreviewId(id) {
445
435
  if (!/^[a-z0-9-]+$/.test(id)) {
@@ -476,7 +466,7 @@ export async function previewDeploy(ctx, id, opts = {}) {
476
466
  hash,
477
467
  sourceKey,
478
468
  sitePrefix: `previews/${id}/site/`,
479
- target: `preview-${id}`,
469
+ target: previewTarget(id),
480
470
  baseUrl: url,
481
471
  // Per-PR objects carry the PR id in the environment tag (preview-pr-42).
482
472
  objectTags: { ...ctx.tags, environment: `preview-${id}` },
@@ -489,6 +479,7 @@ export async function previewDeploy(ctx, id, opts = {}) {
489
479
  export async function previewDestroy(ctx, id) {
490
480
  assertPreviewId(id);
491
481
  const count = await ctx.clients.s3.deletePrefix(ctx.names.bucket, `previews/${id}/`);
482
+ await ctx.clients.s3.deleteObject(ctx.names.bucket, cacheControlRecordKey(previewTarget(id)));
492
483
  ctx.logger.ok(`removed preview ${id} (${count} object(s))`);
493
484
  }
494
485
  /** List active previews (by prefix). */
@@ -520,7 +511,7 @@ export async function previewTeardown(ctx, opts) {
520
511
  ctx.logger.ok('preview stack destroyed');
521
512
  }
522
513
  /** Empty the live site/ prefix (leaves infra and build history intact). */
523
- export async function deleteSite(ctx) {
514
+ export async function deleteSite(ctx, opts = {}) {
524
515
  if (ctx.config.ssr) {
525
516
  // Emptying site/ cannot unpublish a revision: the app renders every page
526
517
  // the revision serves, and its routes would keep answering from a server
@@ -530,13 +521,22 @@ export async function deleteSite(ctx) {
530
521
  `or switch the stack back to static serving with \`blogwright bootstrap ${ctx.env} ` +
531
522
  '--switch-mode` and deploy before deleting.');
532
523
  }
533
- const count = await ctx.clients.s3.deletePrefix(ctx.names.bucket, 'site/');
534
- ctx.logger.ok(`deleted ${count} object(s) under site/`);
535
- await invalidateCloudFront(ctx);
524
+ await withEnvLock(ctx, 'delete', undefined, opts, async () => {
525
+ await markLiveReleasePublishing(ctx, undefined, 'delete');
526
+ const count = await ctx.clients.s3.deletePrefix(ctx.names.bucket, 'site/');
527
+ await forgetLiveRelease(ctx);
528
+ ctx.logger.ok(`deleted ${count} object(s) under site/`);
529
+ await invalidateCloudFront(ctx);
530
+ });
536
531
  }
537
532
  /** List deployment history from build manifests. */
538
533
  export async function history(ctx) {
539
- const objects = await ctx.clients.s3.listObjects(ctx.names.bucket, 'build/manifests/');
534
+ // Deploys and staged builds are recorded apart, so a revision that was both
535
+ // deployed and staged shows a row for each.
536
+ const objects = [
537
+ ...(await ctx.clients.s3.listObjects(ctx.names.bucket, DEPLOY_MANIFESTS_PREFIX)),
538
+ ...(await ctx.clients.s3.listObjects(ctx.names.bucket, STAGED_BUILDS_PREFIX)),
539
+ ];
540
540
  if (objects.length === 0) {
541
541
  ctx.logger.info('no deployments yet');
542
542
  return;
@@ -556,7 +556,8 @@ export async function history(ctx) {
556
556
  }
557
557
  // Newest first. Codepoint sort, not localeCompare: collation must not depend on host locale/ICU
558
558
  // (finishedAt is ISO-8601, which orders correctly by codepoint).
559
- manifests.sort((a, b) => a.finishedAt > b.finishedAt ? -1 : a.finishedAt < b.finishedAt ? 1 : 0);
559
+ // A promotion is what puts a staged build live, so it orders by that time.
560
+ manifests.sort((a, b) => historyTime(a) > historyTime(b) ? -1 : historyTime(a) < historyTime(b) ? 1 : 0);
560
561
  if (ctx.ports.terminal.isInteractive) {
561
562
  for (const line of renderHistoryTable(manifests, Date.now()))
562
563
  ctx.logger.info(line);
@@ -564,28 +565,36 @@ export async function history(ctx) {
564
565
  }
565
566
  // The plain form is the stable contract for CI logs and agents. The revision
566
567
  // column is appended only once a hash recorded one, so static output is unchanged.
568
+ // The time column is when the row last changed the site: a build's finish, or
569
+ // for a promoted stage its promotion.
567
570
  const revisions = historyHasRevisions(manifests);
568
- ctx.logger.info(colors.bold(`hash status finished duration${revisions ? ' revision' : ''}`));
571
+ ctx.logger.info(colors.bold(`hash status time duration${revisions ? ' revision' : ''}`));
569
572
  for (const m of manifests) {
570
- const cell = m.status === 'succeeded'
571
- ? colors.green(m.status.padEnd(10))
572
- : colors.red(m.status.padEnd(10));
573
+ const shown = historyStatus(m);
574
+ const paint = shown === 'failed' ? colors.red : shown === 'staged' ? colors.yellow : colors.green;
575
+ const cell = paint(shown.padEnd(10));
573
576
  const duration = `${(m.durationMs / 1000).toFixed(0)}s`;
574
577
  const revision = revisions
575
578
  ? ` ${duration.padEnd(8)} ${m.webFunction?.revisionId ?? NO_REVISION}`
576
579
  : ` ${duration}`;
577
- ctx.logger.info(`${m.hash.padEnd(13)} ${cell} ${m.finishedAt}${revision}`);
580
+ ctx.logger.info(`${m.hash.padEnd(13)} ${cell} ${historyTime(m)}${revision}`);
578
581
  }
579
582
  }
580
583
  /** Show CloudWatch build logs for a given hash. */
581
584
  export async function logs(ctx, hash) {
582
- const text = await ctx.clients.s3.getObjectText(ctx.names.bucket, manifestKey(hash));
585
+ // The newest build of the hash: its deploy, or a stage made after it.
583
586
  let manifest;
584
- try {
585
- manifest = text ? JSON.parse(text) : undefined;
586
- }
587
- catch {
588
- ctx.logger.warn(`manifest for ${hash} is unreadable - showing the unfiltered log window`);
587
+ for (const kind of ['deploy', 'staged']) {
588
+ const text = await ctx.clients.s3.getObjectText(ctx.names.bucket, manifestKey(hash, kind));
589
+ let read;
590
+ try {
591
+ read = text ? JSON.parse(text) : undefined;
592
+ }
593
+ catch {
594
+ ctx.logger.warn(`manifest for ${hash} is unreadable - showing the unfiltered log window`);
595
+ }
596
+ if (read && (!manifest || read.finishedAt > manifest.finishedAt))
597
+ manifest = read;
589
598
  }
590
599
  // Filter to the build's time window (± a minute) from the manifest.
591
600
  const startTime = manifest ? Date.parse(manifest.startedAt) - 60_000 : undefined;
package/dist/context.d.ts CHANGED
@@ -1,4 +1,5 @@
1
- import { StateStore, type AwsClients, type FileSystem, type Names, type OpsConfig, type OpsState } from 'blogwright-core';
1
+ import { StateStore, type AwsClients, type CallerIdentity, type FileSystem, type Names, type OpsConfig, type OpsState } from 'blogwright-core';
2
+ import { type AwsHost, type ResolvedAwsProfile } from './aws-session.js';
2
3
  import { type Logger } from './logger.js';
3
4
  import type { Ports } from './ports.js';
4
5
  export interface OpsContext {
@@ -21,7 +22,12 @@ export interface OpsContext {
21
22
  */
22
23
  configDocument: Readonly<Record<string, unknown>>;
23
24
  names: Names;
25
+ /** Equals `identity.account`. */
24
26
  accountId: string;
27
+ /** Whose credentials this invocation signs with, from `sts:GetCallerIdentity`. */
28
+ identity: CallerIdentity;
29
+ /** The profile those credentials came from, and which precedence row chose it. */
30
+ awsProfile: ResolvedAwsProfile;
25
31
  clients: AwsClients;
26
32
  ports: Ports;
27
33
  /**
@@ -53,9 +59,19 @@ export interface ContextOptions {
53
59
  domain?: string | undefined;
54
60
  endpointOverride?: string | undefined;
55
61
  preview?: boolean | undefined;
62
+ /** `--profile`: the first row of AWS profile resolution. */
63
+ profile?: string | undefined;
64
+ /** The environment AWS resolution reads; defaults to `process.env`. */
65
+ processEnv?: NodeJS.ProcessEnv | undefined;
66
+ /** Home directory the shared AWS files resolve against; defaults to `os.homedir()`. */
67
+ home?: string | undefined;
68
+ /** Builds the AWS clients; defaults to core's `createClients`. Tests substitute it. */
69
+ createClients?: AwsHost['createClients'];
56
70
  /** Adapter overrides; anything omitted defaults to the real (node) adapter. */
57
71
  ports?: Partial<Ports> | undefined;
58
72
  }
73
+ /** The operator's machine as AWS resolution sees it, from `process` and `os`. */
74
+ export declare function createAwsHost(overrides?: Pick<ContextOptions, 'processEnv' | 'home' | 'createClients'>): AwsHost;
59
75
  /**
60
76
  * The directory holding the CLI's own `package.json` - `blogwright`'s package
61
77
  * root. Located from `import.meta.url` the same way {@link OpsContext.agentDir}
@@ -109,6 +125,10 @@ export interface ConfigSource {
109
125
  * re-deriving the candidate list a second time.
110
126
  */
111
127
  export declare function resolveConfigPath(fs: FileSystem, source: ConfigSource): Promise<string>;
128
+ /** Raised by {@link resolveConfigPath} when no candidate config file exists. */
129
+ export declare class ConfigNotFoundError extends Error {
130
+ constructor(env: string, candidates: readonly string[]);
131
+ }
112
132
  /**
113
133
  * Load and parse the first config candidate that exists, returning BOTH
114
134
  * halves `parseConfigDocument` produces: the validated `config` every
@@ -121,11 +141,13 @@ export declare function resolveConfigPath(fs: FileSystem, source: ConfigSource):
121
141
  export declare function loadConfig(fs: FileSystem, source: ConfigSource): Promise<{
122
142
  config: OpsConfig;
123
143
  raw: Readonly<Record<string, unknown>>;
144
+ path: string;
124
145
  }>;
125
146
  /**
126
- * Build the runtime context: load config, resolve the account id, derive names, create
127
- * clients, and load topology state from S3. The state bucket name is deterministic, which
128
- * resolves the bootstrap chicken-and-egg. This is the composition root - the only place
129
- * real adapters are constructed and wired.
147
+ * Build the runtime context: load config, resolve the AWS session (profile, caller
148
+ * identity, account pin), derive names, and load topology state from S3. The state
149
+ * bucket name is deterministic, which resolves the bootstrap chicken-and-egg; the pin
150
+ * is checked before it is derived, so a wrong account never reads or creates state.
151
+ * This is the composition root - the only place real adapters are constructed and wired.
130
152
  */
131
153
  export declare function createContext(opts: ContextOptions): Promise<OpsContext>;
package/dist/context.js CHANGED
@@ -1,10 +1,13 @@
1
1
  import { readFile } from 'node:fs/promises';
2
- import { basename, join, resolve } from 'node:path';
2
+ import { homedir } from 'node:os';
3
+ import { basename, join, relative, resolve } from 'node:path';
3
4
  import { fileURLToPath } from 'node:url';
4
- import { createClients, createNodeFileSystem, createNodeTerminal, deriveNames, findRepoRoot, parseConfigDocument, StateStore, } from 'blogwright-core';
5
+ import { createNodeFileSystem, createNodeTerminal, deriveNames, findRepoRoot, parseConfigDocument, StateStore, } from 'blogwright-core';
5
6
  import { createFetchPing } from './adapters/fetch-ping.js';
6
7
  import { createNodeModuleLoader } from './adapters/node-module-loader.js';
8
+ import { createProcessAwsLogin } from './adapters/process-aws-login.js';
7
9
  import { createProcessVcs } from './adapters/process-vcs.js';
10
+ import { emitSessionLine, formatIdentityLine, resolveAwsSession, } from './aws-session.js';
8
11
  import { createLogger } from './logger.js';
9
12
  /**
10
13
  * The `app` tag value, by precedence: the explicit `config.app`, else the
@@ -14,6 +17,31 @@ import { createLogger } from './logger.js';
14
17
  export function deriveAppTag(config, domain, repoRoot) {
15
18
  return config.app ?? domain ?? basename(repoRoot);
16
19
  }
20
+ /**
21
+ * The real adapter for every port not supplied in `overrides`. Shared by
22
+ * `createContext` and the pre-context paths (`whoami`, `init`) through
23
+ * `bin.ts`, so all three wire the same adapters.
24
+ */
25
+ function createPorts(overrides = {}) {
26
+ return {
27
+ fs: overrides.fs ?? createNodeFileSystem(),
28
+ vcs: overrides.vcs ?? createProcessVcs(),
29
+ terminal: overrides.terminal ?? createNodeTerminal(),
30
+ ping: overrides.ping ?? createFetchPing(),
31
+ loader: overrides.loader ?? createNodeModuleLoader(),
32
+ awsLogin: overrides.awsLogin ?? createProcessAwsLogin(),
33
+ };
34
+ }
35
+ /** The operator's machine as AWS resolution sees it, from `process` and `os`. */
36
+ export function createAwsHost(overrides = {}) {
37
+ return {
38
+ processEnv: overrides.processEnv ?? process.env,
39
+ home: overrides.home ?? homedir(),
40
+ platform: process.platform,
41
+ cwd: process.cwd(),
42
+ createClients: overrides.createClients,
43
+ };
44
+ }
17
45
  /**
18
46
  * The directory holding the CLI's own `package.json` - `blogwright`'s package
19
47
  * root. Located from `import.meta.url` the same way {@link OpsContext.agentDir}
@@ -94,7 +122,14 @@ export async function resolveConfigPath(fs, source) {
94
122
  if (await fs.exists(path))
95
123
  return path;
96
124
  }
97
- throw new Error(`no config found for environment "${source.env}" - looked for ${candidates.join(', ')}`);
125
+ throw new ConfigNotFoundError(source.env, candidates);
126
+ }
127
+ /** Raised by {@link resolveConfigPath} when no candidate config file exists. */
128
+ export class ConfigNotFoundError extends Error {
129
+ constructor(env, candidates) {
130
+ super(`no config found for environment "${env}" - looked for ${candidates.join(', ')}`);
131
+ this.name = 'ConfigNotFoundError';
132
+ }
98
133
  }
99
134
  /**
100
135
  * Load and parse the first config candidate that exists, returning BOTH
@@ -106,37 +141,40 @@ export async function resolveConfigPath(fs, source) {
106
141
  * be read and parsed a second time at dispatch. Exported for tests.
107
142
  */
108
143
  export async function loadConfig(fs, source) {
109
- return parseConfigDocument(await fs.readText(await resolveConfigPath(fs, source)));
144
+ const path = await resolveConfigPath(fs, source);
145
+ return { ...parseConfigDocument(await fs.readText(path)), path };
110
146
  }
111
147
  /**
112
- * Build the runtime context: load config, resolve the account id, derive names, create
113
- * clients, and load topology state from S3. The state bucket name is deterministic, which
114
- * resolves the bootstrap chicken-and-egg. This is the composition root - the only place
115
- * real adapters are constructed and wired.
148
+ * Build the runtime context: load config, resolve the AWS session (profile, caller
149
+ * identity, account pin), derive names, and load topology state from S3. The state
150
+ * bucket name is deterministic, which resolves the bootstrap chicken-and-egg; the pin
151
+ * is checked before it is derived, so a wrong account never reads or creates state.
152
+ * This is the composition root - the only place real adapters are constructed and wired.
116
153
  */
117
154
  export async function createContext(opts) {
118
- const fs = opts.ports?.fs ?? createNodeFileSystem();
119
- const ports = {
120
- fs,
121
- vcs: opts.ports?.vcs ?? createProcessVcs(),
122
- terminal: opts.ports?.terminal ?? createNodeTerminal(),
123
- ping: opts.ports?.ping ?? createFetchPing(),
124
- loader: opts.ports?.loader ?? createNodeModuleLoader(),
125
- };
155
+ const ports = createPorts(opts.ports);
126
156
  const logger = createLogger(ports.terminal);
127
157
  const agentDir = join(cliPackageDir(), 'agent');
128
158
  const root = await findRepoRoot(ports.fs);
129
- const { config, raw: configDocument } = await loadConfig(ports.fs, {
159
+ const { config, raw: configDocument, path: configPath, } = await loadConfig(ports.fs, {
130
160
  env: opts.env,
131
161
  root,
132
162
  configPath: opts.configPath,
133
163
  });
134
164
  const domain = opts.domain ?? config.domain;
135
- const clients = createClients({
165
+ const session = await resolveAwsSession({
136
166
  region: config.region,
137
167
  endpointOverride: opts.endpointOverride,
168
+ flag: opts.profile,
169
+ aws: config.aws,
170
+ configLabel: relative(root, configPath) || configPath,
171
+ host: createAwsHost(opts),
172
+ ports,
173
+ logger,
138
174
  });
139
- const accountId = await clients.sts.getAccountId();
175
+ emitSessionLine(formatIdentityLine(session), ports.terminal, logger);
176
+ const { clients, identity } = session;
177
+ const accountId = identity.account;
140
178
  const names = deriveNames(opts.env, accountId, config);
141
179
  const store = new StateStore(clients.s3, names.bucket, opts.env);
142
180
  // load() already returns empty state for a not-yet-created bucket/object; any other
@@ -150,6 +188,8 @@ export async function createContext(opts) {
150
188
  configDocument,
151
189
  names,
152
190
  accountId,
191
+ identity,
192
+ awsProfile: session.profile,
153
193
  clients,
154
194
  ports,
155
195
  agentDir,