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/deploy.d.ts CHANGED
@@ -10,6 +10,16 @@ export interface DeployManifest {
10
10
  durationMs: number;
11
11
  microvmId: string;
12
12
  message?: string;
13
+ /**
14
+ * `staged` when the build published to `releases/<hash>/` for a later
15
+ * `promote` rather than to the live `site/`. Absent for a deploy. A staged
16
+ * build's record is kept apart from the hash's deployment manifest (see
17
+ * {@link manifestKey}), so staging a revision that is live never changes
18
+ * what `history` says about its deploy.
19
+ */
20
+ kind?: 'staged' | undefined;
21
+ /** When this hash's staged release was last promoted to the live site. */
22
+ promotedAt?: string | undefined;
13
23
  /**
14
24
  * The last revision verified for this hash (or found already serving).
15
25
  * Rollback reads it to reproduce the revision a hash is pinned to. A
@@ -18,8 +28,20 @@ export interface DeployManifest {
18
28
  */
19
29
  webFunction?: WebFunctionManifest;
20
30
  }
21
- /** Read one hash's deployment manifest, or undefined when there is none. */
22
- export declare function readManifest(ctx: OpsContext, hash: string): Promise<DeployManifest | undefined>;
31
+ /** What `deploy` (and `promote`) run once the site is live - see `DeployOptions.afterDeploy`. */
32
+ export type AfterDeploy = (ctx: OpsContext) => Promise<void>;
33
+ /**
34
+ * The build target that publishes the live `site/`: the name of its pending
35
+ * job and of its Cache-Control record.
36
+ */
37
+ export declare const LIVE_SITE_TARGET = "site";
38
+ /** Which record of a hash: its deployment manifest, or its staged build's record. */
39
+ export type ManifestKind = 'deploy' | 'staged';
40
+ /**
41
+ * Read one hash's deployment manifest (or, for `staged`, its staged build's
42
+ * record), or undefined when there is none.
43
+ */
44
+ export declare function readManifest(ctx: OpsContext, hash: string, kind?: ManifestKind): Promise<DeployManifest | undefined>;
23
45
  /**
24
46
  * Write a hash's manifest and return what was written. In SSR mode a `failed`
25
47
  * outcome keeps the `webFunction` block the hash's manifest already carried:
@@ -30,6 +52,17 @@ export declare function readManifest(ctx: OpsContext, hash: string): Promise<Dep
30
52
  export declare function writeManifest(ctx: OpsContext, manifest: DeployManifest, opts?: {
31
53
  ssr?: boolean | undefined;
32
54
  }): Promise<DeployManifest>;
55
+ /** A source zip uploaded for a build. */
56
+ export interface UploadedSource {
57
+ sourceKey: string;
58
+ fileCount: number;
59
+ zipBytes: number;
60
+ }
61
+ /**
62
+ * Zip the deployable files of the repo at `cwd` (with the revision hash
63
+ * injected as `.commit-hash`) and upload it to `build/<hash>.zip`.
64
+ */
65
+ export declare function uploadSource(ctx: OpsContext, cwd: string, hash: string): Promise<UploadedSource>;
33
66
  /** Artifact and result keys for one deploy hash. */
34
67
  export declare function artifactKeys(hash: string): {
35
68
  artifactKey: string;
@@ -55,7 +88,34 @@ export interface AgentStatus {
55
88
  state: 'idle' | 'building' | 'done' | 'failed';
56
89
  message?: string | undefined;
57
90
  }
58
- declare function manifestKey(hash: string): string;
91
+ /** Where history lists deployment manifests from. */
92
+ export declare const DEPLOY_MANIFESTS_PREFIX = "build/manifests/";
93
+ /** Where history lists staged builds' records from. */
94
+ export declare const STAGED_BUILDS_PREFIX = "build/staged/";
95
+ /**
96
+ * A hash's deployment manifest, or its staged build's record. They are
97
+ * separate objects: a stage - failed or not - of a revision that is already
98
+ * live must not overwrite the record of the deploy that put it there.
99
+ */
100
+ declare function manifestKey(hash: string, kind?: ManifestKind): string;
101
+ /**
102
+ * The agent's changed-paths manifest: the paths to invalidate, the rules it
103
+ * wrote, and (by appearing) the build's completion signal. Qualified by the
104
+ * build target as well as the hash, so a stage and a deploy of one revision
105
+ * never read each other's.
106
+ */
107
+ export declare function changedManifestKey(target: string, hash: string): string;
108
+ /**
109
+ * One queued build, as `pollBuild` waits for it: the agent marks its
110
+ * completion `##build:done:<hash>@<jobId>` and writes `changedKey` last.
111
+ */
112
+ export interface BuildJobRef {
113
+ hash: string;
114
+ jobId: string;
115
+ changedKey: string;
116
+ }
117
+ /** What one log line says about `job`: its outcome, or nothing. */
118
+ export declare function jobOutcome(message: string, job: BuildJobRef): AgentStatus | undefined;
59
119
  /**
60
120
  * Launch the builder MicroVM, retrying gateway errors (502/503/504) with a
61
121
  * bounded backoff. The control plane can answer 502 for a short window right
@@ -79,7 +139,7 @@ export declare function microvmLogGroup(ctx: OpsContext): string;
79
139
  * endpoint to keep the agent's event loop alive so the build triggers reliably.
80
140
  * Exported for tests.
81
141
  */
82
- export declare function pollBuild(ctx: OpsContext, hash: string, startTime: number, endpoint: string, token: string): Promise<AgentStatus>;
142
+ export declare function pollBuild(ctx: OpsContext, job: BuildJobRef, startTime: number, endpoint: string, token: string): Promise<AgentStatus>;
83
143
  /**
84
144
  * Run the builder MicroVM against a source zip already present at `sourceKey`, stream
85
145
  * its logs, terminate it, and record a deployment manifest. Shared by deploy + rollback.
@@ -93,7 +153,10 @@ export declare function runBuild(ctx: OpsContext, opts: {
93
153
  baseUrl?: string | undefined;
94
154
  /** S3 object tags for the synced site files; defaults to the stack tags. */
95
155
  objectTags?: Record<string, string> | undefined;
96
- /** Re-upload every file, so metadata-only fixes (content type, tags) land. */
156
+ /**
157
+ * Re-upload every file, so metadata-only fixes (content type, tags,
158
+ * Cache-Control) land. Implied when the `cacheControl` rules changed.
159
+ */
97
160
  refresh?: boolean | undefined;
98
161
  /**
99
162
  * Package the output as a Lambda Web Function revision artifact. When set,
@@ -101,6 +164,10 @@ export declare function runBuild(ctx: OpsContext, opts: {
101
164
  * the deploy outcome.
102
165
  */
103
166
  webFunction?: WebFunctionJob | undefined;
167
+ /** Where the agent records the static build's artifact manifest; absent, none is written. */
168
+ artifactManifestKey?: string | undefined;
169
+ /** Recorded on the deployment manifest; see {@link DeployManifest.kind}. */
170
+ kind?: 'staged' | undefined;
104
171
  }): Promise<DeployManifest>;
105
172
  export declare function invalidateCloudFront(ctx: OpsContext, paths?: string[]): Promise<void>;
106
173
  /** What a deploy's cache invalidation actually did, for the deploy summary. */
@@ -108,10 +175,15 @@ export interface InvalidationSummary {
108
175
  mode: 'none' | 'paths' | 'all';
109
176
  count: number;
110
177
  }
178
+ /**
179
+ * Invalidate a set of changed URL paths: nothing when it is empty, `/*` past
180
+ * the configured cap, otherwise exactly those paths.
181
+ */
182
+ export declare function invalidatePaths(ctx: OpsContext, paths: readonly string[]): Promise<InvalidationSummary>;
111
183
  /**
112
184
  * Invalidate only the URL paths that changed in this build (from the agent's manifest),
113
185
  * so unchanged pages stay cached. Falls back to `/*` when the manifest is missing or the
114
186
  * changed set is larger than the configured cap.
115
187
  */
116
- export declare function invalidateChanged(ctx: OpsContext, hash: string): Promise<InvalidationSummary>;
188
+ export declare function invalidateChanged(ctx: OpsContext, hash: string, target?: string): Promise<InvalidationSummary>;
117
189
  export { manifestKey };
package/dist/deploy.js CHANGED
@@ -1,10 +1,20 @@
1
1
  import { randomUUID } from 'node:crypto';
2
2
  import { AwsError, entryShim, networkConnectors, pollUntil, sleep, } from 'blogwright-core';
3
+ import { cacheControlRefreshReason, describeCacheControlRefresh, markCacheControlUnconfirmed, recordCacheControl, } from './cache-control.js';
3
4
  import { formatDuration, spinnerFrame } from './render.js';
5
+ import { buildRepoZip, COMMIT_FILE, listRepoFiles } from './repo.js';
4
6
  import { resolveSeo } from './seo.js';
5
- /** Read one hash's deployment manifest, or undefined when there is none. */
6
- export async function readManifest(ctx, hash) {
7
- const text = await ctx.clients.s3.getObjectText(ctx.names.bucket, manifestKey(hash));
7
+ /**
8
+ * The build target that publishes the live `site/`: the name of its pending
9
+ * job and of its Cache-Control record.
10
+ */
11
+ export const LIVE_SITE_TARGET = 'site';
12
+ /**
13
+ * Read one hash's deployment manifest (or, for `staged`, its staged build's
14
+ * record), or undefined when there is none.
15
+ */
16
+ export async function readManifest(ctx, hash, kind = 'deploy') {
17
+ const text = await ctx.clients.s3.getObjectText(ctx.names.bucket, manifestKey(hash, kind));
8
18
  if (!text)
9
19
  return undefined;
10
20
  try {
@@ -28,9 +38,22 @@ export async function writeManifest(ctx, manifest, opts = {}) {
28
38
  if (verified)
29
39
  record = { ...manifest, webFunction: verified };
30
40
  }
31
- await ctx.clients.s3.putObject(ctx.names.bucket, manifestKey(manifest.hash), JSON.stringify(record, null, 2), 'application/json');
41
+ await ctx.clients.s3.putObject(ctx.names.bucket, manifestKey(manifest.hash, manifest.kind === 'staged' ? 'staged' : 'deploy'), JSON.stringify(record, null, 2), 'application/json');
32
42
  return record;
33
43
  }
44
+ /**
45
+ * Zip the deployable files of the repo at `cwd` (with the revision hash
46
+ * injected as `.commit-hash`) and upload it to `build/<hash>.zip`.
47
+ */
48
+ export async function uploadSource(ctx, cwd, hash) {
49
+ const files = await listRepoFiles(ctx.ports, cwd, ctx.config.sourceIgnore, ctx.config.sourceInclude);
50
+ ctx.logger.step(`zipping ${files.length} files`);
51
+ const zip = await buildRepoZip(ctx.ports.fs, cwd, files, { [COMMIT_FILE]: hash });
52
+ const sourceKey = `build/${hash}.zip`;
53
+ await ctx.clients.s3.putObject(ctx.names.bucket, sourceKey, zip, 'application/zip');
54
+ ctx.logger.ok(`uploaded ${sourceKey} (${(zip.byteLength / 1024).toFixed(0)} KiB)`);
55
+ return { sourceKey, fileCount: files.length, zipBytes: zip.byteLength };
56
+ }
34
57
  /** Artifact and result keys for one deploy hash. */
35
58
  export function artifactKeys(hash) {
36
59
  return { artifactKey: `web/artifacts/${hash}.zip`, resultKey: `web/results/${hash}.json` };
@@ -51,8 +74,49 @@ export function webFunctionJob(ctx, hash) {
51
74
  resultKey,
52
75
  };
53
76
  }
54
- function manifestKey(hash) {
55
- return `build/manifests/${hash}.json`;
77
+ /** Where history lists deployment manifests from. */
78
+ export const DEPLOY_MANIFESTS_PREFIX = 'build/manifests/';
79
+ /** Where history lists staged builds' records from. */
80
+ export const STAGED_BUILDS_PREFIX = 'build/staged/';
81
+ /**
82
+ * A hash's deployment manifest, or its staged build's record. They are
83
+ * separate objects: a stage - failed or not - of a revision that is already
84
+ * live must not overwrite the record of the deploy that put it there.
85
+ */
86
+ function manifestKey(hash, kind = 'deploy') {
87
+ return `${kind === 'staged' ? STAGED_BUILDS_PREFIX : DEPLOY_MANIFESTS_PREFIX}${hash}.json`;
88
+ }
89
+ /**
90
+ * The agent's changed-paths manifest: the paths to invalidate, the rules it
91
+ * wrote, and (by appearing) the build's completion signal. Qualified by the
92
+ * build target as well as the hash, so a stage and a deploy of one revision
93
+ * never read each other's.
94
+ */
95
+ export function changedManifestKey(target, hash) {
96
+ return `build/changed/${target}/${hash}.json`;
97
+ }
98
+ /** What one log line says about `job`: its outcome, or nothing. */
99
+ export function jobOutcome(message, job) {
100
+ const marker = (state) => `##build:${state}:${job.hash}@${job.jobId}`;
101
+ if (message.includes(marker('done')))
102
+ return { state: 'done' };
103
+ const failed = message.split(`${marker('failed')}:`)[1];
104
+ if (message.includes(marker('failed')))
105
+ return { state: 'failed', message: failed?.trim() };
106
+ // A bare-hash marker comes from an agent older than job ids, which could have
107
+ // built another target's job for this hash: stop rather than take it as ours.
108
+ if (new RegExp(`##build:(done|failed):${escapeRegExp(job.hash)}(?=$|[:\\s])`).test(message)) {
109
+ return {
110
+ state: 'failed',
111
+ message: 'the builder image predates per-job build markers, so this build cannot be told ' +
112
+ "apart from another target's build of the same revision - run `blogwright " +
113
+ 'bootstrap` to rebuild the builder image',
114
+ };
115
+ }
116
+ return undefined;
117
+ }
118
+ function escapeRegExp(text) {
119
+ return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
56
120
  }
57
121
  /**
58
122
  * Nudge the MicroVM's endpoint to wake its event loop. A Firecracker-resumed process
@@ -121,7 +185,7 @@ export function microvmLogGroup(ctx) {
121
185
  * endpoint to keep the agent's event loop alive so the build triggers reliably.
122
186
  * Exported for tests.
123
187
  */
124
- export async function pollBuild(ctx, hash, startTime, endpoint, token) {
188
+ export async function pollBuild(ctx, job, startTime, endpoint, token) {
125
189
  const seen = new Set();
126
190
  // Anchored at VM launch (startTime), like the VM's own maximumDuration -
127
191
  // anchoring at poll start would keep polling a VM that is already dead for
@@ -131,7 +195,7 @@ export async function pollBuild(ctx, hash, startTime, endpoint, token) {
131
195
  let tick = 0;
132
196
  try {
133
197
  for (;;) {
134
- terminal.status(`${spinnerFrame(tick++)} building ${hash} in MicroVM … ${formatDuration(Date.now() - startTime)}`);
198
+ terminal.status(`${spinnerFrame(tick++)} building ${job.hash} in MicroVM … ${formatDuration(Date.now() - startTime)}`);
135
199
  await nudge(ctx, endpoint, token);
136
200
  const events = await ctx.clients.logs
137
201
  .filterEvents(microvmLogGroup(ctx), { startTime })
@@ -143,25 +207,20 @@ export async function pollBuild(ctx, hash, startTime, endpoint, token) {
143
207
  continue;
144
208
  seen.add(e.eventId);
145
209
  ctx.logger.info(` ${e.message.trimEnd()}`);
146
- // Hash-scoped structured markers so unrelated log lines (raw pnpm/astro output, or
147
- // an orphaned VM from a different deploy) can't be mistaken for this build's result.
148
- if (e.message.includes(`##build:done:${hash}`))
149
- result = { state: 'done' };
150
- else if (e.message.includes(`##build:failed:${hash}`)) {
151
- result = {
152
- state: 'failed',
153
- message: e.message.split(`##build:failed:${hash}:`)[1]?.trim(),
154
- };
155
- }
210
+ // Job-scoped structured markers, so unrelated log lines (raw pnpm/astro output, an
211
+ // orphaned VM, or another target's build of the same hash - the log group is shared)
212
+ // can't be mistaken for this build's result.
213
+ result ??= jobOutcome(e.message, job);
156
214
  }
157
215
  if (result)
158
216
  return result;
159
217
  // Log delivery can lag or drop (e.g. the VM logging to a group the deploy isn't tailing).
160
- // The agent writes build/changed/<hash>.json as its final step, so treat that artifact as
161
- // an authoritative completion signal too - a successful build then can't hang until the
162
- // deadline just because its logs never reached CloudWatch. runBuild clears any stale copy
163
- // before launch, so its presence means *this* build finished.
164
- if (await ctx.clients.s3.objectExists(ctx.names.bucket, `build/changed/${hash}.json`)) {
218
+ // The agent writes the job's changed-paths manifest as its final step, so treat that
219
+ // artifact as an authoritative completion signal too - a successful build then can't hang
220
+ // until the deadline just because its logs never reached CloudWatch. runBuild clears any
221
+ // stale copy before launch, and the key is the target's own, so its presence means *this*
222
+ // build finished.
223
+ if (await ctx.clients.s3.objectExists(ctx.names.bucket, job.changedKey)) {
165
224
  return { state: 'done' };
166
225
  }
167
226
  if (Date.now() >= deadline)
@@ -182,17 +241,32 @@ export async function runBuild(ctx, opts) {
182
241
  // robots.txt/sitemap.xml are the application's routes in SSR mode, so no SEO
183
242
  // payload is sent (and the agent writes none).
184
243
  const seo = opts.webFunction ? {} : resolveSeo(ctx, opts.baseUrl);
185
- const pendingKey = `build/pending/${opts.target ?? 'site'}.json`;
244
+ const target = opts.target ?? LIVE_SITE_TARGET;
245
+ const pendingKey = `build/pending/${target}.json`;
186
246
  const imageArn = ctx.state.resources['microvm-image']?.arn;
187
247
  const execRoleArn = ctx.state.resources['iam-exec-role']?.arn;
188
248
  if (typeof imageArn !== 'string' || typeof execRoleArn !== 'string') {
189
249
  throw new Error('infrastructure not bootstrapped (missing MicroVM image or exec role); run bootstrap first');
190
250
  }
191
- // Clear any stale completion manifest from a prior aborted build of this same hash, so its
192
- // reappearance is an unambiguous "this build finished" signal for pollBuild's S3 fallback.
193
- await ctx.clients.s3
194
- .deleteObject(ctx.names.bucket, `build/changed/${opts.hash}.json`)
195
- .catch(() => undefined);
251
+ // One id per queued job: the agent tags its completion markers with it, so neither another
252
+ // target's build of this hash nor an earlier build of it can be taken for this one.
253
+ const job = {
254
+ hash: opts.hash,
255
+ jobId: randomUUID(),
256
+ changedKey: changedManifestKey(target, opts.hash),
257
+ };
258
+ // Clear any stale completion manifest from a prior aborted build of this target and hash, so
259
+ // its reappearance is an unambiguous "this build finished" signal for pollBuild's S3 fallback.
260
+ await ctx.clients.s3.deleteObject(ctx.names.bucket, job.changedKey).catch(() => undefined);
261
+ // Checked even under an explicit --refresh: a build that changes the rules
262
+ // must mark the record first, whatever asked for the re-upload.
263
+ const rulesRefresh = await cacheControlRefreshReason(ctx, target);
264
+ if (rulesRefresh !== undefined) {
265
+ const implicit = opts.refresh === true ? '' : ' (an implicit --refresh)';
266
+ ctx.logger.step(`${describeCacheControlRefresh(rulesRefresh)}${implicit}`);
267
+ await markCacheControlUnconfirmed(ctx, target);
268
+ }
269
+ const refresh = opts.refresh === true || rulesRefresh !== undefined;
196
270
  const connectors = networkConnectors(ctx.config.region);
197
271
  const startedAt = new Date();
198
272
  ctx.logger.step(`running builder MicroVM for ${opts.hash}`);
@@ -218,6 +292,8 @@ export async function runBuild(ctx, opts) {
218
292
  // The agent (booting ~30s) polls this for the job; write it now that the VM exists.
219
293
  await ctx.clients.s3.putObject(ctx.names.bucket, pendingKey, JSON.stringify({
220
294
  hash: opts.hash,
295
+ jobId: job.jobId,
296
+ changedKey: job.changedKey,
221
297
  sourceKey: opts.sourceKey,
222
298
  sitePrefix,
223
299
  // Repo-relative build cwd and output dir (config paths.app/paths.dist);
@@ -225,8 +301,10 @@ export async function runBuild(ctx, opts) {
225
301
  appDir: ctx.config.paths.app,
226
302
  distDir: ctx.config.paths.dist,
227
303
  objectTags: opts.objectTags ?? ctx.tags,
228
- ...(opts.refresh ? { refresh: true } : {}),
304
+ cacheControl: ctx.config.cacheControl,
305
+ ...(refresh ? { refresh: true } : {}),
229
306
  ...(opts.webFunction ? { webFunction: opts.webFunction } : {}),
307
+ ...(opts.artifactManifestKey ? { artifactManifestKey: opts.artifactManifestKey } : {}),
230
308
  ...seo,
231
309
  }), 'application/json');
232
310
  // Confirm the MicroVM actually reached RUNNING (a FAILED launch must not fall through
@@ -242,7 +320,7 @@ export async function runBuild(ctx, opts) {
242
320
  const token = await ctx.clients.microvms
243
321
  .createAuthToken(run.microvmId, tokenMinutes)
244
322
  .catch(() => '');
245
- result = await pollBuild(ctx, opts.hash, startedAt.getTime(), endpoint, token);
323
+ result = await pollBuild(ctx, job, startedAt.getTime(), endpoint, token);
246
324
  }
247
325
  finally {
248
326
  // The pending-job cleanup must survive a terminate failure: a leaked
@@ -267,6 +345,7 @@ export async function runBuild(ctx, opts) {
267
345
  durationMs: finishedAt.getTime() - startedAt.getTime(),
268
346
  microvmId: run.microvmId,
269
347
  ...(result.message ? { message: result.message } : {}),
348
+ ...(opts.kind ? { kind: opts.kind } : {}),
270
349
  };
271
350
  // In SSR mode a successful build is NOT yet a successful deploy: the publish
272
351
  // step writes the manifest once the revision outcome is known. A failed build
@@ -275,8 +354,12 @@ export async function runBuild(ctx, opts) {
275
354
  await writeManifest(ctx, manifest, { ssr: Boolean(opts.webFunction) });
276
355
  }
277
356
  if (manifest.status === 'failed') {
357
+ // The record is left as it was - unconfirmed if this build was changing the rules - so the
358
+ // next build re-applies them.
278
359
  throw new Error(`build failed for ${opts.hash}${manifest.message ? `: ${manifest.message}` : ''}`);
279
360
  }
361
+ // The static files are published even in SSR mode, where the revision is still to come.
362
+ await recordCacheControl(ctx, target, job.changedKey);
280
363
  return manifest;
281
364
  }
282
365
  export async function invalidateCloudFront(ctx, paths = ['/*']) {
@@ -289,15 +372,31 @@ export async function invalidateCloudFront(ctx, paths = ['/*']) {
289
372
  : paths.join(', ');
290
373
  ctx.logger.ok(`CloudFront invalidation requested (${shown})`);
291
374
  }
375
+ /**
376
+ * Invalidate a set of changed URL paths: nothing when it is empty, `/*` past
377
+ * the configured cap, otherwise exactly those paths.
378
+ */
379
+ export async function invalidatePaths(ctx, paths) {
380
+ if (paths.length === 0) {
381
+ ctx.logger.ok('no content changed - skipping CloudFront invalidation');
382
+ return { mode: 'none', count: 0 };
383
+ }
384
+ if (paths.length > ctx.config.invalidationMaxPaths) {
385
+ ctx.logger.step(`${paths.length} paths changed (> cap) - invalidating everything (/*)`);
386
+ await invalidateCloudFront(ctx, ['/*']);
387
+ return { mode: 'all', count: paths.length };
388
+ }
389
+ await invalidateCloudFront(ctx, [...paths]);
390
+ return { mode: 'paths', count: paths.length };
391
+ }
292
392
  /**
293
393
  * Invalidate only the URL paths that changed in this build (from the agent's manifest),
294
394
  * so unchanged pages stay cached. Falls back to `/*` when the manifest is missing or the
295
395
  * changed set is larger than the configured cap.
296
396
  */
297
- export async function invalidateChanged(ctx, hash) {
298
- const text = await ctx.clients.s3
299
- .getObjectText(ctx.names.bucket, `build/changed/${hash}.json`)
300
- .catch(() => undefined);
397
+ export async function invalidateChanged(ctx, hash, target = LIVE_SITE_TARGET) {
398
+ const key = changedManifestKey(target, hash);
399
+ const text = await ctx.clients.s3.getObjectText(ctx.names.bucket, key).catch(() => undefined);
301
400
  let paths;
302
401
  if (text) {
303
402
  try {
@@ -312,23 +411,8 @@ export async function invalidateChanged(ctx, hash) {
312
411
  await invalidateCloudFront(ctx, ['/*']);
313
412
  return { mode: 'all', count: 0 };
314
413
  }
315
- let summary;
316
- if (paths.length === 0) {
317
- ctx.logger.ok('no content changed - skipping CloudFront invalidation');
318
- summary = { mode: 'none', count: 0 };
319
- }
320
- else if (paths.length > ctx.config.invalidationMaxPaths) {
321
- ctx.logger.step(`${paths.length} paths changed (> cap) - invalidating everything (/*)`);
322
- await invalidateCloudFront(ctx, ['/*']);
323
- summary = { mode: 'all', count: paths.length };
324
- }
325
- else {
326
- await invalidateCloudFront(ctx, paths);
327
- summary = { mode: 'paths', count: paths.length };
328
- }
329
- await ctx.clients.s3
330
- .deleteObject(ctx.names.bucket, `build/changed/${hash}.json`)
331
- .catch(() => undefined);
414
+ const summary = await invalidatePaths(ctx, paths);
415
+ await ctx.clients.s3.deleteObject(ctx.names.bucket, key).catch(() => undefined);
332
416
  return summary;
333
417
  }
334
418
  export { manifestKey };
package/dist/init.d.ts CHANGED
@@ -1,5 +1,7 @@
1
1
  import { type FileSystem, type Plugin, type Terminal } from 'blogwright-core';
2
- import type { Logger } from './logger.js';
2
+ import { type AwsHost } from './aws-session.js';
3
+ import { type Logger } from './logger.js';
4
+ import type { AwsLogin } from './ports.js';
3
5
  /**
4
6
  * One question, and how to ask it: shown text, a prefilled default, whether
5
7
  * an empty answer must re-prompt, and an optional validator. Exported - and
@@ -25,6 +27,13 @@ export interface Question {
25
27
  * asks through.
26
28
  */
27
29
  export declare function ask(terminal: Terminal, logger: Logger, q: Question): Promise<string | undefined>;
30
+ /** What `init`'s AWS questions need from the composition root. */
31
+ export interface InitAwsOptions {
32
+ /** `--profile`, the first default for the profile question. */
33
+ profile?: string | undefined;
34
+ host: AwsHost;
35
+ awsLogin: AwsLogin;
36
+ }
28
37
  /**
29
38
  * Run the wizard. Returns a process exit code; never throws for expected
30
39
  * refusals (non-interactive, an existing config file). `plugins` is every
@@ -35,4 +44,7 @@ export declare function ask(terminal: Terminal, logger: Logger, q: Question): Pr
35
44
  * single `fs.writeText` below ever runs, so the config file stays exactly
36
45
  * what it was - absent, on this path - rather than a partial write.
37
46
  */
38
- export declare function initSite(fs: FileSystem, terminal: Terminal, logger: Logger, plugins: readonly Plugin[], root?: string): Promise<number>;
47
+ export declare function initSite(fs: FileSystem, terminal: Terminal, logger: Logger, plugins: readonly Plugin[], options: {
48
+ aws: InitAwsOptions;
49
+ root?: string | undefined;
50
+ }): Promise<number>;