@fastly/compute-js-static-publish 8.1.0-beta.5 → 8.1.0-beta.7

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.
package/CHANGELOG.md CHANGED
@@ -12,9 +12,9 @@ This file does not list v7 releases after 7.0.8, or v6 releases after 6.3.0. For
12
12
  ### Added
13
13
 
14
14
  - `scaffold --template hono` (and `managed.template: 'hono'` in a managed project): a TypeScript Hono app. `src/index.ts` uses `selectCollection()`, `serveStatic()`, and `serveFallback()` of `@fastly/compute-js-static-publish/hono`, and `fire()` of `@fastly/hono-fastly-compute`. The app has `tsconfig.json`, and `typescript` as a dev dependency; the build does not check types (run `npx tsc`). In a managed project, a change of `managed.template` generates the app again with the new template, and changes the fingerprint.
15
- - Hono extensions for the `hono` template: modules in `hono-extensions/` default-export `defineExtension()` (from `@fastly/compute-js-static-publish/hono`), with a function for each phase that they use: `middleware`, `beforeFiles` (before the published files), and `afterFiles` (for the requests that no published file matches). Each phase function gets the app, the options of the module, and the helpers of the app (`serveStatic()`, `staticResponse()`, `serveFallback()`, and `publisherServer`). `c.env` in a module has the types of its bindings. The build bundles them into the app; the packages that the app provides stay imports. Options come from `templateOptions.hono.extensions` and bindings from `templateOptions.hono.bindings`, and `build.hono.extensionsDir` sets another folder. `template init` makes or updates the folder (with a `.gitignore` for `node_modules/`), and `template init --check` fails with the new error code `template-init-needed` if it is out of date. `dev -- --watch` and `npm run dev:watch` also watch the folder. `status --json` has `template`, with the packages that the template provides.
15
+ - Hono extensions for the `hono` template: modules in `hono-extensions/` default-export `defineExtension()` (from `@fastly/compute-js-static-publish/hono`), with a function for each phase that they use: `middleware`, `beforeFiles` (before the published files), and `afterFiles` (for the requests that no published file matches). Each phase function gets the app, the options of the module, and the helpers of the app (`serveStatic()`, `staticResponse()`, `serveFallback()`, `fallbackResponse()`, `isCollectionAvailable()`, and `publisherServer`). `c.env` in a module has the types of its bindings. The build bundles them into the app; the packages that the app provides stay imports. Options come from `templateOptions.hono.extensions` and bindings from `templateOptions.hono.bindings`, and `build.hono.extensionsDir` sets another folder. `template init` makes or updates the folder (with a `.gitignore` for `node_modules/`), and `template init --check` fails with the new error code `template-init-needed` if it is out of date. `dev -- --watch` and `npm run dev:watch` also watch the folder. `status --json` has `template`, with the packages that the template provides.
16
16
  - Examples of Hono extensions in `examples/hono/` (in the repository, not in the npm package): `grip` (realtime streams and Server-Sent Events with Fastly Fanout) and `oauth` (a login with GitHub or Google).
17
- - Hono support: `@fastly/compute-js-static-publish/hono`. `fromStaticPublishRc(rc)` (or `fromPublisherServer(server)`) returns `serveStatic()` (middleware that serves the published files with `serveRequest()`, and calls the next handler if no file matches; the option `onMissing` replaces `collectionSelection.onMissing` for one route), `staticResponse(c)` (the same response for use in a handler, or `null`; never the SPA file or the 404 page), `serveFallback()` (for `app.notFound()`: the SPA file or the 404 page), `selectCollection()` (collection selection for a Hono app; it sets `c.var.staticPublisher`, and `serveStatic()` and `serveFallback()` use the selected collection), and `publisherServer`. The type `StaticPublisherVariables` is for the variables of the app. `hono` v4 is an optional peer dependency. This replaces `@fastly/hono-compute-js-static-publish`, which supports only v6 and v7; `MIGRATING.md` has the steps.
17
+ - Hono support: `@fastly/compute-js-static-publish/hono`. `fromStaticPublishRc(rc)` (or `fromPublisherServer(server)`) returns `serveStatic()` (middleware that serves the published files with `serveRequest()`, and calls the next handler if no file matches; the option `onMissing` replaces `collectionSelection.onMissing` for one route), `staticResponse(c)` (the same response for use in a handler, or `null`; never the SPA file or the 404 page), `serveFallback()` (for `app.notFound()`: the SPA file or the 404 page), `fallbackResponse(c)` (the same response for use in a handler, or `null`), `isCollectionAvailable(c)` (whether the selected collection, or another one, is published and not expired), `selectCollection()` (collection selection for a Hono app; it sets `c.var.staticPublisher`, and `serveStatic()` and `serveFallback()` use the selected collection), and `publisherServer`. The type `StaticPublisherVariables` is for the variables of the app. The options `status` and `headers` change the response of a file. `hono` v4 is an optional peer dependency. This replaces `@fastly/hono-compute-js-static-publish`, which supports only v6 and v7; `MIGRATING.md` has the steps.
18
18
  - `--project-dir`: run a command for the app in another directory, for example from the root of the repo in CI. All relative paths are then relative to that directory.
19
19
  - `--version`: print the version of this package. It works in any directory.
20
20
  - `--non-interactive`: the CLI never asks a question, and missing input is an error. It is also on when the `CI` environment variable is set (to a value that is not empty, `false`, or `0`).
@@ -49,15 +49,15 @@ This file does not list v7 releases after 7.0.8, or v6 releases after 6.3.0. For
49
49
  - `--json`: `publish-content`, `collections list`, `collections delete`, `collections promote`, `status`, `deploy` (in a managed project), and `--version` write their result as one JSON object to stdout, with `schemaVersion: 1`. The log lines then go to stderr. With another command, `--json` is an error. The `publish-content` result shows the purge result for each environment (`purge.ok` is `false` if a purge failed).
50
50
  - Error codes: with `--json`, an error gives `{ "schemaVersion": 1, "error": { "code", "message" } }`. The README lists the codes, for example `collection-name-invalid` and `credentials-missing`.
51
51
  - README: "Using the CLI in CI", with the exit codes, the JSON output, and the error codes.
52
+ - `PublisherServer`: the options `status` and `headers` of `serveRequest()` and `serveFallback()` change the status and the headers of the response of a file, for one call. For a status other than `2xx`, the server does not evaluate the preconditions of the request.
53
+ - `PublisherServer`: `serveRequestStreaming()`, `serveFallbackStreaming()`, and `serveCachedStreaming()` return `{ response, fillPromise }`. On a Fastly service with `@fastly/js-compute` 4.2 or later (not in `fastly compute serve`), a response cache fill for a body with a known length streams the body to the visitor and into the cache at the same time. Pass `fillPromise` to `event.waitUntil()`. A body that does not have its declared length is not cached, and the next fill reads the whole body first. The `plain` template and the Hono helpers use them.
54
+ - `PublisherServer`: the function of `serveCached()` can return `{ response, length }`. With `length: null`, the response is not cached.
52
55
 
53
56
  ### Changed
54
57
 
55
- - The npm package includes `CHANGELOG.md` and `MIGRATING.md`.
56
58
  - A command for a managed project or an app (for example `status` or `deploy`) in a directory that has no `static-publish.project.js` or `static-publish.rc.js` now stops with an error that names the directories nearby that have one. Before, the CLI started scaffolding, and showed an unclear error for the command.
57
59
  - Scaffolding: the `src/index.js` of the `plain` app calls `serveRequest()` with `fallback: false`, then has the place for your own code, and then calls `serveFallback()` for the SPA file or the 404 page. Thus your code runs for each request that no published file matches, also when the collection has a fallback page. Code that must run before the published files goes before `serveRequest()`.
58
60
  - Scaffolding: the app has `@fastly/compute-js-static-publish` in `dependencies`. It was in `devDependencies`. The code of the app imports it, and the `postinstall` script of the app runs it, so `npm ci --omit=dev` needs it.
59
- - `PublisherServer.setResponseCache()`: the default of `maxBodySize` is now 16 MiB. It was 8 MiB.
60
- - Scaffolder: in the generated `src/index.js`, the place for your own code is before `serveRequest()`. It was after `serveRequest()`, where it did not run for a path that has no file when a 404 page or an SPA file is set.
61
61
  - The help and the hints of the CLI show the npx command with the dist-tag of a prerelease, for example `npx @fastly/compute-js-static-publish@beta dev` in 8.1.0-beta.2. Without the dist-tag, npx runs the latest stable version, which does not have the new commands. When the copy that runs is installed in the project or the app (so that a plain `npx` runs it), the command has no dist-tag, because with a dist-tag npx gets the version of that tag from npm. A stable version shows the command as before.
62
62
  - `collectionSelector.fromCookie()`: the activate and reset paths now redirect with `308`. Before, they used `302`.
63
63
  - Collection names have a rule: a DNS label (lowercase `a-z`, `0-9`, and `-`, from 1 to 63 characters, with no `-` at the start or the end). Thus a name is safe in storage keys, in the surrogate key of the purge, in a cookie, and in a hostname.
@@ -77,7 +77,20 @@ This file does not list v7 releases after 7.0.8, or v6 releases after 6.3.0. For
77
77
 
78
78
  ### Fixed
79
79
 
80
- - `collections promote` now purges the target collection, as `publish-content` and `collections delete` do. Before, after a promote (for example to `live`), the service could serve the old content of the target from the cache until it expired. The new options `--fastly-service-id` and `--purge-environment` work as in `publish-content`. If a Service ID is found, the command needs an API token, also in S3 mode, and stops before it writes anything if the token is missing.
80
+ - `PublisherServer`: a request for the 404 page with an `If-None-Match` that matched its `ETag` (or an `If-Modified-Since` after its time) got a `304` with no body. Now the server evaluates the preconditions only for a `2xx` response, as RFC 9110 says, so the response is always the `404` with the page.
81
+ - `scaffold` now escapes the values that it writes into `fastly.toml`. Before, a `"` or a `\` in `--name`, `--description`, or `--author`, or a KV Store name with a character such as `.`, gave a `fastly.toml` that was not valid.
82
+
83
+ ## [8.0.2] - 2026-11-16
84
+
85
+ ### Changed
86
+
87
+ - The npm package includes `CHANGELOG.md` and `MIGRATING.md`.
88
+ - `PublisherServer.setResponseCache()`: the default of `maxBodySize` is now 16 MiB. It was 8 MiB.
89
+ - Scaffolder: in the generated `src/index.js`, the place for your own code is before `serveRequest()`. It was after `serveRequest()`, where it did not run for a path that has no file when a 404 page or an SPA file is set.
90
+
91
+ ### Fixed
92
+
93
+ - `collections promote` now purges the target collection, as `publish-content` and `collections delete` do. Before, after a promote (for example to `live`), the service could serve the old content of the target from the cache until it expired. The new options `--fastly-service-id` and `--purge-environment` work as in `publish-content`. If a Service ID is found, the command needs an API token, also in S3 mode, and stops before it writes anything if the token is missing. Thus in S3 mode, if your pipeline has a Service ID, set `FASTLY_API_TOKEN` for `collections promote` too.
81
94
  - `collections promote --local`: the target collection got the index and settings files of the source collection. Thus a later `publish-content --local` to the source also changed the target, for example `live` after a promote from `staging`. Now the target has its own files. The KV Store and S3 modes were not affected.
82
95
  - `scaffold --storage-mode s3` without `--s3-endpoint` (a bucket on AWS): the command stopped with an uncaught `CredentialsProviderError` when the computer had no usable AWS credentials. Now it computes the host name of the bucket (`<bucket>.s3.<region>.amazonaws.com`, the same host name that the server uses), with no credentials and no network. A bucket name with a dot needs `--s3-endpoint`, and the command says so.
83
96
  - `PublisherServer` response cache: the request that caches a response now uses memory of about two times the body. Before, it used about four times the body. On a Fastly service, with `maxBodySize` set larger than the default, a response of 32 MiB caused a `500` for that request. With a response of 48 MiB, other requests that waited for the same response also got a `200` with an empty body.
@@ -86,7 +99,6 @@ This file does not list v7 releases after 7.0.8, or v6 releases after 6.3.0. For
86
99
  - `PublisherServer`: when no file matches a request, the server serves the SPA file or the 404 page only if the request accepts HTML. Now a request accepts HTML only if its `Accept` header is missing or empty, or has `text/html`, `text/*`, or `*/*` with a q-value that is not 0. The most specific of these media ranges gives the q-value. Before, almost all requests got the HTML page, for example a request with `Accept: application/json`, `Accept: image/*`, or `Accept: text/html;q=0`. Now `serveRequest()` returns `null` for such a request, and your app makes the response.
87
100
  - README: the Fastly Object Storage example uses the region `us-east-1` and the endpoint `https://us-east-1.object.fastlystorage.app`. The example used `us-east`, which is a legacy region: you cannot make a new bucket in it in the Fastly control panel. The README also links to the list of regions and endpoints.
88
101
  - README: the custom app example handles its route before `serveRequest()`, and the text says when `serveRequest()` returns `null`. Before, the example handled `/api/hello` after `serveRequest()`, so a request for it got the 404 page when a 404 page was set.
89
- - `scaffold` now escapes the values that it writes into `fastly.toml`. Before, a `"` or a `\` in `--name`, `--description`, or `--author`, or a KV Store name with a character such as `.`, gave a `fastly.toml` that was not valid.
90
102
 
91
103
  ## [8.0.1] - 2026-11-04
92
104
 
@@ -559,7 +571,8 @@ This file does not list v7 releases after 7.0.8, or v6 releases after 6.3.0. For
559
571
  - Updated generated app's webpack and webpack-cli versions
560
572
  - Use atob() and removed dependency on Buffer
561
573
 
562
- [unreleased]: https://github.com/fastly/compute-js-static-publish/compare/v8.0.1...HEAD
574
+ [unreleased]: https://github.com/fastly/compute-js-static-publish/compare/v8.0.2...HEAD
575
+ [8.0.2]: https://github.com/fastly/compute-js-static-publish/compare/v8.0.1...v8.0.2
563
576
  [8.0.1]: https://github.com/fastly/compute-js-static-publish/compare/v8.0.0...v8.0.1
564
577
  [8.0.0]: https://github.com/fastly/compute-js-static-publish/compare/v7.0.8...v8.0.0
565
578
  [7.0.8]: https://github.com/fastly/compute-js-static-publish/compare/v7.0.7...v7.0.8
package/DOCUMENTATION.md CHANGED
@@ -1061,10 +1061,12 @@ async function handleRequest(request) {
1061
1061
  | `fallback` | `false`: if no file matches, do not serve the SPA file or the 404 page. Return `null`. | `true` |
1062
1062
  | `healthCheck` | `false`: do not answer `/healthz`. | `true` |
1063
1063
  | `onMissing` | With [collection selection](#-previews-collection-selection): what to do for this call when the selected collection is not published or has expired. `'not-found'`: the `404` below. `'default'`: serve the default collection, as a normal response of the default collection (its headers, without `X-Robots-Tag: noindex`). Without collection selection, it does nothing. | `collectionSelection.onMissing` |
1064
+ | `status` | The status of the response of a file (also of the SPA file and the 404 page). For a status other than `2xx`, the server does not evaluate the preconditions of the request (`If-None-Match` and the others), so the response always has the body. It does not change other responses, such as the `404` of a collection that is not available. | The status of the file: `200`, or `404` for the 404 page |
1065
+ | `headers` | Headers to set on the response of a file. Each one replaces the header of the same name. | |
1064
1066
 
1065
1067
  `serveRequest()` returns `null` for a method other than `GET` and `HEAD`, and when there is no response (no file matches, and there is no fallback page or `fallback` is `false`). If the default collection has no settings in storage, the response is `500`. A collection other than the default collection that is not published, or that expired, gets a plain-text `404` that names it.
1066
1068
 
1067
- `serveFallback(request, { collectionName, onMissing })` serves the SPA file (`200`) or the 404 page (`404`) of the collection, as `serveRequest()` does when no file matches. It returns `null` for a method other than `GET` and `HEAD`, for a client that does not accept HTML, or when the collection has no fallback page. Use it with `fallback: false`, to run your own logic between the files and the fallback page. The scaffolded app (`src/index.js`) uses this order:
1069
+ `serveFallback(request, { collectionName, onMissing, status, headers })` serves the SPA file (`200`) or the 404 page (`404`) of the collection, as `serveRequest()` does when no file matches. It returns `null` for a method other than `GET` and `HEAD`, for a client that does not accept HTML, or when the collection has no fallback page. Use it with `fallback: false`, to run your own logic between the files and the fallback page. The scaffolded app (`src/index.js`) uses this order:
1068
1070
 
1069
1071
  ```js
1070
1072
  async function handleRequest(request) {
@@ -1159,9 +1161,31 @@ const response = await publisherServer.serveCached(request, pathname, async (fil
1159
1161
 
1160
1162
  The second argument identifies the response in the collection. If anything other than the path and `Accept-Encoding` changes your response, include it in this value.
1161
1163
 
1164
+ Your function can return a `Response`, `null` (not found), or `{ response, length }`. `length` is the number of bytes in the body. With `length: null`, the response is not cached. `serveCached()` reads the body, and stores it with its real length. If that is not `length`, it logs a warning. A `Response` from `serveAsset()` has a known length.
1165
+
1166
+ #### Streaming the response into the cache
1167
+
1168
+ `serveRequestStreaming()`, `serveFallbackStreaming()`, and `serveCachedStreaming()` take the same arguments as `serveRequest()`, `serveFallback()`, and `serveCached()`. When the response is not cached yet and the length of its body is known, the body goes to the visitor and into the cache at the same time. The visitor does not wait for the whole file, and the request does not keep the whole body in memory. They return `{ response, fillPromise }`. Pass `fillPromise` to `event.waitUntil()`:
1169
+
1170
+ ```js
1171
+ async function handleRequest(event) {
1172
+ const { response, fillPromise } = await publisherServer.serveRequestStreaming(event.request);
1173
+ event.waitUntil(fillPromise);
1174
+ return response ?? new Response('Not Found', { status: 404 });
1175
+ }
1176
+ ```
1177
+
1178
+ With `event.waitUntil()`, the fill continues after your handler returns, also if the visitor disconnects. Without it, the fill stops when your handler returns, and nothing is cached. `fillPromise` never rejects.
1179
+
1180
+ The scaffolded app of the `plain` template and the [Hono](#-using-hono) helpers use these methods.
1181
+
1182
+ The fill streams only on a Fastly service with `@fastly/js-compute` 4.2 or later. With an earlier version, in `fastly compute serve`, or for a body with a length that is not known, the fill reads the whole body first, as `serveCached()` does, and `fillPromise` is already resolved.
1183
+
1184
+ If a body does not have the number of bytes of `length`, nothing is cached, the requests for the response get an error, and an error is logged. The next fill for that response reads the whole body first.
1185
+
1162
1186
  Notes:
1163
1187
 
1164
- - A response is read completely before it is cached. The request that caches it uses memory of about two times the body, up to two times `maxBodySize`. A Compute instance has a limit on its memory, so do not set `maxBodySize` larger than 48 MiB (`48 * 1024 * 1024`). Other requests that wait for the same response get it when it is cached.
1188
+ - `serveRequest()`, `serveFallback()`, and `serveCached()`, and the streaming methods when the fill does not stream, read a response completely before it is cached. The request that caches it uses memory of about two times the body, up to two times `maxBodySize`. A Compute instance has a limit on its memory, so do not set `maxBodySize` larger than 48 MiB (`48 * 1024 * 1024`). Other requests that wait for the same response get it when it is cached. A streaming fill also caches only a body of `maxBodySize` or less.
1165
1189
  - A response is cached only if its body has the size in the file's metadata. If storage returns a different body, nothing is cached, the request gets an error, and the next request reads the file again.
1166
1190
  - With `--local`, `publish-content` cannot purge the local cache. Restart `fastly compute serve` to see newly published content, or leave the response cache off in local development.
1167
1191
  - On staging, a purge must include the `Fastly-Purge-Environment: staging` header to clear the staging cache. Without it, a purge clears only the production cache. Use `publish-content --purge-environment=production,staging` to purge both.
@@ -1258,23 +1282,67 @@ templateOptions: {
1258
1282
  },
1259
1283
  ```
1260
1284
 
1261
- **Helpers:** the third argument of each phase function has the `serveStatic()`, `staticResponse()`, `serveFallback()`, and `publisherServer` that the app uses (see [Using Hono](#-using-hono)). They are made once when the app starts, with the same `collectionSelection`, so a module can serve published files in its own order, with its own rules. For example, to serve `/theme/*` before a login check, on a preview, from the selected collection or from the default collection if the preview is missing, and with a plain `404` (never the 404 page of the collection):
1285
+ **The files step:** between `beforeFiles` and `afterFiles`, the app has a fixed step that serves the published files with `serveStatic()`. It is not a phase, and a module cannot remove it. A module can serve files in another way before it: a request that the module answers does not get to this step, and a request that the module passes on with `next()` does.
1286
+
1287
+ **Helpers:** the third argument of each phase function has the `serveStatic()`, `staticResponse()`, `serveFallback()`, `fallbackResponse()`, `isCollectionAvailable()`, and `publisherServer` that the app uses (see [Using Hono](#-using-hono)). They are made once when the app starts, with the same `collectionSelection`, so a module can serve published files in its own place in the order, with its own rules.
1288
+
1289
+ For example, a module that runs before a login check, and serves `/theme/*` on a preview: from the selected collection, or from the default collection if the preview is missing, and with a plain `404` (not the 404 page of the collection, which would show the preview without a login). Without a preview, the module does nothing, and the app serves the request as usual. In Hono, a handler cannot skip the handlers that come after it in the same `app.use()`, so the module decides first whether it takes part. Two ways to write it, which do the same:
1262
1290
 
1263
1291
  ```ts
1264
- // hono-extensions/10-theme.ts
1292
+ // hono-extensions/10-theme.ts: one handler with staticResponse()
1265
1293
  import { defineExtension } from '@fastly/compute-js-static-publish/hono';
1266
1294
 
1267
1295
  export default defineExtension((app, options, { staticResponse }) => {
1268
1296
  app.use('/theme/*', async (c, next) => {
1269
1297
  if (c.var.staticPublisher.collectionName == null) {
1270
- return next(); // not a preview: the published files of the app serve it
1298
+ return next(); // not a preview: the app serves it as usual
1271
1299
  }
1272
1300
  return await staticResponse(c, { onMissing: 'default' }) ?? c.text('Not found', 404);
1273
1301
  });
1274
1302
  });
1275
1303
  ```
1276
1304
 
1277
- With `onMissing: 'default'`, a missing preview gets a normal response of the default collection, with its headers. When the preview is published, the next request gets the file of the preview: `PublisherServer` checks the selected collection before it reads the response cache. This example is for a `host`, `query`, `cookie`, or `header` source. With a `path` source, the request path has the prefix (for example `/_preview/pr-1/theme/site.css`), so the route `/theme/*` does not match it: add the handler on `*`, and check `c.var.staticPublisher.pathname`, the path without the prefix. `staticResponse()` looks up that path.
1305
+ ```ts
1306
+ // hono-extensions/10-theme.ts: serveStatic() with except() of hono/combine
1307
+ import { defineExtension } from '@fastly/compute-js-static-publish/hono';
1308
+ import { except } from 'hono/combine';
1309
+
1310
+ export default defineExtension((app, options, { serveStatic }) => {
1311
+ const notPreview = (c) => c.var.staticPublisher.collectionName == null;
1312
+ app.use('/theme/*', except(notPreview,
1313
+ serveStatic({ onMissing: 'default' }),
1314
+ (c) => c.text('Not found', 404),
1315
+ ));
1316
+ });
1317
+ ```
1318
+
1319
+ `except(condition, ...middleware)` skips the middleware when the condition is true, and runs it in order otherwise. `serveStatic()` calls the next middleware when no file matches; `staticResponse()` returns `null`. To give the normal 404 page in place of the plain `404`, use `return c.notFound()`.
1320
+
1321
+ With `onMissing: 'default'`, a missing preview gets a normal response of the default collection, with its headers. When the preview is published, the next request gets the file of the preview: `PublisherServer` checks the selected collection before it reads the response cache. These examples are for a `host`, `query`, `cookie`, or `header` source. With a `path` source, the request path has the prefix (for example `/_preview/pr-1/theme/site.css`), so the route `/theme/*` does not match it: add the handler on `*`, and check `c.var.staticPublisher.pathname`, the path without the prefix. `serveStatic()` and `staticResponse()` look up that path.
1322
+
1323
+ For example, a module that runs after a login check, and shows the page `/preview-not-found/` of the default collection, with a `404`, when the selected preview is not available. Because it is a module, it can come after the login check, so that a visitor who is not logged in cannot learn which previews exist:
1324
+
1325
+ ```ts
1326
+ // hono-extensions/30-preview-not-found.ts
1327
+ import { defineExtension } from '@fastly/compute-js-static-publish/hono';
1328
+
1329
+ export default defineExtension((app, options, { isCollectionAvailable, staticResponse }) => {
1330
+ app.use('*', async (c, next) => {
1331
+ if (await isCollectionAvailable(c)) {
1332
+ return next();
1333
+ }
1334
+ return await staticResponse(c, { path: '/preview-not-found/', collectionName: null, status: 404 })
1335
+ ?? c.text('Preview not found', 404);
1336
+ });
1337
+ });
1338
+ ```
1339
+
1340
+ **`publisherServer` in a module:** the app has one `PublisherServer` for all requests. Use the other helpers where you can: they use the selected collection, and the path without the prefix of a `path` source. In a handler, a module can call these methods of `publisherServer`:
1341
+
1342
+ - `isCollectionAvailable()`, `serveRequest()`, `serveFallback()`, and `resolveCollection()`.
1343
+ - The methods that read the collection of the request: `getServerConfig()`, `getStaticItems()`, `getAssetEntryMap()`, `getMatchingAsset()`, and `testExtendedCache()`. They use the collection of the last `serveRequest()` or `serveFallback()` in the request (also through `serveStatic()` and the other helpers), or of `beginRequest()`, which uses the active collection, not the selected one. If neither ran in the request, call `publisherServer.beginRequest(c.req.raw)` first.
1344
+
1345
+ Do not call the `set…()` methods (`setActiveCollectionName()`, `setCollectionSelection()`, `setResponseCache()`, and the others) in a handler: they change the server for all requests. In the phase function, which runs one time when the app starts, they change the configuration of the whole app. Do not call the lower-level methods (`serveAsset()`, `serveCached()`, `serveCachedStreaming()`, `loadAssetVariant()`, `handlePreconditions()`, and `findAcceptEncodingsGroups()`). Use `staticResponse()` and `fallbackResponse()` in their place.
1278
1346
 
1279
1347
  **Bindings** put Fastly resources on `c.env`, as `buildFire()` of `@fastly/hono-fastly-compute` does. A module declares the bindings that it uses in the first argument of `defineExtension()`, and `c.env` in its handlers has their types, for example `ConfigStore | undefined` for `'ConfigStore:site_config'` (`undefined` if the resource does not exist or is not linked to the service). `templateOptions.hono.bindings` adds bindings for the app. The same name with the same resource in two places is allowed. The same name with two different resources stops the build, and the message names both places. `c.var` is not typed in a module, so that a module can set its own variables.
1280
1348
 
@@ -1340,6 +1408,8 @@ fire(app);
1340
1408
  - `serveStatic(options?)`: middleware that serves the file that matches the request. If no file matches, or the method is not `GET` or `HEAD`, it calls the next handler, so a route after it gets the request. It does not serve the SPA file or the 404 page, and it does not answer `/healthz`.
1341
1409
  - `staticResponse(c, options?)`: the same response as `serveStatic()`, for use inside a handler: the response of the file that matches the request, or `null` if no file matches or the method is not `GET` or `HEAD`. It takes the options of `serveStatic()`. Like `serveStatic()`, it never returns the SPA file or the 404 page.
1342
1410
  - `serveFallback(options?)`: for `app.notFound()`. It serves the SPA file or the 404 page. If there is neither, or the client does not accept HTML, it gives Hono's default 404 response.
1411
+ - `fallbackResponse(c, options?)`: the response of the SPA file or the 404 page, for use inside a handler, or `null` if there is neither, the client does not accept HTML, or the method is not `GET` or `HEAD`. It takes the options of `serveFallback()`.
1412
+ - `isCollectionAvailable(c, collectionName?)`: `true` if the collection is published, has not expired, and this version of the app can serve it. Without `collectionName`, it checks the collection that `selectCollection()` selected, or else the active collection. `collectionName` is as in the option of `serveStatic()`.
1343
1413
  - `selectCollection()`: middleware that selects the collection of each request with the [`collectionSelection`](#-previews-collection-selection) of `static-publish.rc.js`. It returns the redirects of the selection (a `sticky` source, and the activate and reset paths of the `cookie` source), and sets `c.var.staticPublisher`. Then `serveStatic()` and `serveFallback()` use the selected collection. For a `path` source, `serveStatic()` looks up the path without the prefix.
1344
1414
  - `publisherServer`: the `PublisherServer`, to configure it. For example, `publisherServer.setResponseCache({ maxAge: 3600 })`.
1345
1415
 
@@ -1354,6 +1424,8 @@ If you make the `PublisherServer` yourself, use `fromPublisherServer(publisherSe
1354
1424
  | `rewriteRequestPath` | `(path, c) => string`. Changes the request path before it is resolved against `root`. |
1355
1425
  | `collectionName` | The collection: a string, `null` for the default collection, or `(c) => string \| null \| undefined`. Without it, or if the function returns `undefined`, the collection is the one that `selectCollection()` selected, or else the active collection. |
1356
1426
  | `onMissing` | With collection selection: `'not-found'` or `'default'` when the selected collection is not published or has expired, for this route only. The default is `collectionSelection.onMissing`. With `'default'`, the response is a normal response of the default collection, with its headers (no `X-Robots-Tag: noindex`). |
1427
+ | `status` | The status of the response of a file. For a status other than `2xx`, the preconditions of the request are not evaluated, so the response always has the body. See the [options of `serveRequest()`](#options-of-serverequest). |
1428
+ | `headers` | Headers to set on the response of a file. Each one replaces the header of the same name. |
1357
1429
 
1358
1430
  For example, to serve `/assets/*` from the `static` directory:
1359
1431
 
@@ -1372,7 +1444,25 @@ app.use('/theme/*', async (c, next) => {
1372
1444
  });
1373
1445
  ```
1374
1446
 
1375
- `serveFallback()` takes the `collectionName` and `onMissing` options, too. To give a default to all the middleware, pass it to `fromStaticPublishRc(rc, { collectionName, onMissing })`. An option in a call replaces the default.
1447
+ To serve a page with another status, use `status`. For example, a `404` with the page `/preview-not-found/` of the default collection, when the selected preview is not available:
1448
+
1449
+ ```ts
1450
+ app.use('*', async (c, next) => {
1451
+ if (await isCollectionAvailable(c)) {
1452
+ return next();
1453
+ }
1454
+ return await staticResponse(c, { path: '/preview-not-found/', collectionName: null, status: 404 })
1455
+ ?? c.text('Preview not found', 404);
1456
+ });
1457
+ ```
1458
+
1459
+ `fallbackResponse()` is the same for the SPA file or the 404 page. For example, a `410` with the 404 page of the site, for a removed page:
1460
+
1461
+ ```ts
1462
+ app.get('/blog/removed-post', async (c) => await fallbackResponse(c, { status: 410 }) ?? c.text('Gone', 410));
1463
+ ```
1464
+
1465
+ `serveFallback()` and `fallbackResponse()` take the `collectionName`, `onMissing`, `status`, and `headers` options, too. To give a default to all the middleware, pass it to `fromStaticPublishRc(rc, { collectionName, onMissing })`. An option in a call replaces the default.
1376
1466
 
1377
1467
  In TypeScript, use `StaticPublisherVariables` for the variables of the app, so that `c.var.staticPublisher` has a type:
1378
1468
 
@@ -25,7 +25,7 @@ export type ExtensionEnv<B extends ExtensionBindings> = {
25
25
  };
26
26
  export declare const EXTENSION_PHASES: readonly ['middleware', 'beforeFiles', 'afterFiles'];
27
27
  export type ExtensionPhase = typeof EXTENSION_PHASES[number];
28
- export type ExtensionHelpers = Pick<PublisherServerMiddleware, 'publisherServer' | 'serveStatic' | 'staticResponse' | 'serveFallback'>;
28
+ export type ExtensionHelpers = Pick<PublisherServerMiddleware, 'publisherServer' | 'serveStatic' | 'staticResponse' | 'serveFallback' | 'fallbackResponse' | 'isCollectionAvailable'>;
29
29
  export type ExtensionPhaseFunction<B extends ExtensionBindings = ExtensionBindings, O = any> = (app: Hono<ExtensionEnv<B>, any, any>, options: O | undefined, helpers: ExtensionHelpers) => void;
30
30
  export type ExtensionPhases<B extends ExtensionBindings = ExtensionBindings, O = any> = {
31
31
  [P in ExtensionPhase]?: ExtensionPhaseFunction<B, O>;
@@ -1 +1 @@
1
- {"version":3,"file":"extensions.d.ts","sourceRoot":"","sources":["../../../src/hono/extensions.ts"],"names":[],"mappings":"AAYA,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,YAAY,CAAC;AACtC,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,gBAAgB,CAAC;AAC9C,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,qBAAqB,CAAC;AACvD,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,iBAAiB,CAAC;AAC/C,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,eAAe,CAAC;AAC5C,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,qBAAqB,CAAC;AACvD,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AACjC,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,YAAY,CAAC;AAI5D,MAAM,MAAM,iBAAiB,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;AAEvD,KAAK,aAAa,GAAG;IACnB,GAAG,EAAE,GAAG,CAAC;IACT,OAAO,EAAE,OAAO,CAAC;IACjB,WAAW,EAAE,WAAW,CAAC;IACzB,GAAG,EAAE,MAAM,CAAC;IACZ,OAAO,E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SAAS,CAAC;AACpH,wBAAgB,eAAe,CAAC,KAAK,CAAC,CAAC,SAAS,iBAAiB,EAAE,CAAC,GAAG,GAAG,EAAE,OAAO,EAAE,sBAAsB,CAAC,CAAC,CAAC,EAAE,MAAM,EAAE,sBAAsB,CAAC,CAAC,EAAE,CAAC,CAAC,GAAG,eAAe,CAAC,CAAC,EAAE,CAAC,CAAC,GAAG,SAAS,CAAC;AAwBzL,wBAAgB,aAAa,CAAC,WAAW,EAAE,iBAAiB,GAAG,SAAS,EAAE,OAAO,EAAE,cAAc,EAAE,GAAG,iBAAiB,CAgDtH"}
@@ -1,5 +1,5 @@
1
1
  import type { Context, MiddlewareHandler, NotFoundHandler } from 'hono';
2
- import { PublisherServer, type StaticPublishRc } from '../server/index.js';
2
+ import { PublisherServer, type ResponseOverrides, type StaticPublishRc } from '../server/index.js';
3
3
  import { type ServeStaticPathOptions } from './path.js';
4
4
  export { type BindingResource, type DefineExtensionOptions, EXTENSION_PHASES, type Extension, type ExtensionBindings, type ExtensionEntry, type ExtensionEnv, type ExtensionHelpers, type ExtensionPhase, type ExtensionPhaseFunction, type ExtensionPhases, defineExtension, mergeBindings, } from './extensions.js';
5
5
  export type StaticPublisherVariables = {
@@ -11,11 +11,11 @@ export type StaticPublisherVariables = {
11
11
  };
12
12
  export type CollectionNameOption = string | null | ((c: Context) => string | null | undefined);
13
13
  export type OnMissingOption = 'not-found' | 'default';
14
- export type ServeStaticOptions = ServeStaticPathOptions<Context> & {
14
+ export type ServeStaticOptions = ServeStaticPathOptions<Context> & ResponseOverrides & {
15
15
  collectionName?: CollectionNameOption;
16
16
  onMissing?: OnMissingOption;
17
17
  };
18
- export type ServeFallbackOptions = {
18
+ export type ServeFallbackOptions = ResponseOverrides & {
19
19
  collectionName?: CollectionNameOption;
20
20
  onMissing?: OnMissingOption;
21
21
  };
@@ -28,6 +28,8 @@ export type PublisherServerMiddleware = {
28
28
  serveStatic: (options?: ServeStaticOptions) => MiddlewareHandler;
29
29
  staticResponse: (c: Context, options?: ServeStaticOptions) => Promise<Response | null>;
30
30
  serveFallback: (options?: ServeFallbackOptions) => NotFoundHandler;
31
+ fallbackResponse: (c: Context, options?: ServeFallbackOptions) => Promise<Response | null>;
32
+ isCollectionAvailable: (c: Context, collectionName?: CollectionNameOption) => Promise<boolean>;
31
33
  selectCollection: () => MiddlewareHandler;
32
34
  };
33
35
  export declare function fromPublisherServer(server: PublisherServer, defaults?: PublisherServerMiddlewareDefaults): PublisherServerMiddleware;
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/hono/index.ts"],"names":[],"mappings":"AAUA,OAAO,KAAK,EAAE,OAAO,EAAE,iBAAiB,EAAE,eAAe,EAAE,MAAM,MAAM,CAAC;AAGxE,OAAO,EAAE,eAAe,EAAE,KAAK,eAAe,EAAE,MAAM,oBAAoB,CAAC;AAC3E,OAAO,EAAE,KAAK,sBAAsB,EAA8B,MAAM,WAAW,CAAC;AAEpF,OAAO,EACL,KAAK,eAAe,EACpB,KAAK,sBAAsB,EAC3B,gBAAgB,EAChB,KAAK,SAAS,EACd,KAAK,iBAAiB,EACtB,KAAK,cAAc,EACnB,KAAK,YAAY,EACjB,KAAK,gBAAgB,EACrB,KAAK,cAAc,EACnB,KAAK,sBAAsB,EAC3B,KAAK,eAAe,EACpB,eAAe,EACf,aAAa,GACd,MAAM,iBAAiB,CAAC;AAIzB,MAAM,MAAM,wBAAwB,GAAG;IACrC,eAAe,EAAE;QACf,eAAe,EAAE,eAAe,CAAC;QAGjC,cAAc,EAAE,MAAM,GAAG,IAAI,CAAC;QAE9B,QAAQ,CAAC,EAAE,MAAM,CAAC;KACnB,CAAC;CACH,CAAC;AAMF,MAAM,MAAM,oBAAoB,GAAG,MAAM,GAAG,IAAI,GAAG,CAAC,CAAC,CAAC,EAAE,OAAO,KAAK,MAAM,GAAG,IAAI,GAAG,SAAS,CAAC,CAAC;AAM/F,MAAM,MAAM,eAAe,GAAG,WAAW,GAAG,SAAS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B,KAAK,iBAAiB,CAAC;IAKjE,cAAc,EAAE,CAAC,CAAC,EAAE,OAAO,EAAE,OAAO,CAAC,EAAE,kBAAkB,KAAK,OAAO,CAAC,QAAQ,GAAG,IAAI,CAAC,CAAC;IAIvF,aAAa,EAAE,CAAC,OAAO,CAAC,EAAE,oBAAoB,KAAK,eAAe,CAAC;IAKnE,gBAAgB,EAAE,CAAC,CAAC,EAAE,OAAO,EAAE,OAAO,CAAC,EAAE,oBAAoB,KAAK,OAAO,CAAC,QAAQ,GAAG,IAAI,CAAC,CAAC;IAK3F,qBAAqB,EAAE,CAAC,CAAC,EAAE,OAAO,EAAE,cAAc,CAAC,EAAE,oBAAoB,KAAK,OAAO,CAAC,OAAO,CAAC,CAAC;IAK/F,gBAAgB,EAAE,MAAM,iBAAiB,CAAC;CAC3C,CAAC;AAmDF,wBAAgB,mBAAmB,CAAC,MAAM,EAAE,eAAe,EAAE,QAAQ,GAAE,iCAAsC,GAAG,yBAAyB,CA0FxI;AAED,wBAAgB,mBAAmB,CAAC,EAAE,EAAE,eAAe,EAAE,QAAQ,GAAE,iCAAsC,GAAG,yBAAyB,CAEpI"}
@@ -20,6 +20,30 @@ function resolveCollectionName(c, option, selection) {
20
20
  // undefined selects the active collection of the PublisherServer.
21
21
  return selection != null ? selection.collectionName : undefined;
22
22
  }
23
+ // The waitUntil() of the FetchEvent of the request, or null if Hono does not
24
+ // have it (for example, when app.request() runs the app in a test).
25
+ function getWaitUntil(c) {
26
+ try {
27
+ const executionCtx = c.executionCtx;
28
+ return typeof executionCtx?.waitUntil === 'function' ? (promise) => executionCtx.waitUntil(promise) : null;
29
+ }
30
+ catch {
31
+ // c.executionCtx throws if the app has no execution context.
32
+ return null;
33
+ }
34
+ }
35
+ // Serves with the streaming form of a PublisherServer method if the request
36
+ // has waitUntil(), so that the response cache fill continues after the handler
37
+ // returns. Otherwise, serves with the form that does not stream.
38
+ async function serveWithFill(c, streaming, buffered) {
39
+ const waitUntil = getWaitUntil(c);
40
+ if (waitUntil == null) {
41
+ return buffered();
42
+ }
43
+ const { response, fillPromise } = await streaming();
44
+ waitUntil(fillPromise);
45
+ return response;
46
+ }
23
47
  export function fromPublisherServer(server, defaults = {}) {
24
48
  const staticResponse = async (c, callOptions = {}) => {
25
49
  const options = { ...defaults, ...callOptions };
@@ -31,13 +55,16 @@ export function fromPublisherServer(server, defaults = {}) {
31
55
  if (pathname == null) {
32
56
  return null;
33
57
  }
34
- return server.serveRequest(c.req.raw, {
58
+ const serveOptions = {
35
59
  collectionName: resolveCollectionName(c, options.collectionName, selection),
36
60
  pathname,
37
61
  fallback: false,
38
62
  healthCheck: false,
39
63
  onMissing: options.onMissing,
40
- });
64
+ status: options.status,
65
+ headers: options.headers,
66
+ };
67
+ return serveWithFill(c, () => server.serveRequestStreaming(c.req.raw, serveOptions), () => server.serveRequest(c.req.raw, serveOptions));
41
68
  };
42
69
  const serveStatic = (callOptions = {}) => {
43
70
  return async (c, next) => {
@@ -49,16 +76,26 @@ export function fromPublisherServer(server, defaults = {}) {
49
76
  return response;
50
77
  };
51
78
  };
52
- const serveFallback = (callOptions = {}) => {
79
+ const fallbackResponse = async (c, callOptions = {}) => {
53
80
  const options = { ...defaults, ...callOptions };
81
+ const serveOptions = {
82
+ collectionName: resolveCollectionName(c, options.collectionName, getSelection(c, server)),
83
+ onMissing: options.onMissing,
84
+ status: options.status,
85
+ headers: options.headers,
86
+ };
87
+ return serveWithFill(c, () => server.serveFallbackStreaming(c.req.raw, serveOptions), () => server.serveFallback(c.req.raw, serveOptions));
88
+ };
89
+ const serveFallback = (callOptions = {}) => {
54
90
  return async (c) => {
55
- const response = await server.serveFallback(c.req.raw, {
56
- collectionName: resolveCollectionName(c, options.collectionName, getSelection(c, server)),
57
- onMissing: options.onMissing,
58
- });
59
- return response ?? c.text('404 Not Found', 404);
91
+ return await fallbackResponse(c, callOptions) ?? c.text('404 Not Found', 404);
60
92
  };
61
93
  };
94
+ const isCollectionAvailable = async (c, collectionName) => {
95
+ const option = collectionName !== undefined ? collectionName : defaults.collectionName;
96
+ const name = resolveCollectionName(c, option, getSelection(c, server));
97
+ return server.isCollectionAvailable(c.req.raw, name === undefined ? server.activeCollectionName : name);
98
+ };
62
99
  const selectCollection = () => {
63
100
  return async (c, next) => {
64
101
  const selection = server.resolveCollection(c.req.raw);
@@ -73,7 +110,15 @@ export function fromPublisherServer(server, defaults = {}) {
73
110
  await next();
74
111
  };
75
112
  };
76
- return { publisherServer: server, serveStatic, staticResponse, serveFallback, selectCollection };
113
+ return {
114
+ publisherServer: server,
115
+ serveStatic,
116
+ staticResponse,
117
+ serveFallback,
118
+ fallbackResponse,
119
+ isCollectionAvailable,
120
+ selectCollection,
121
+ };
77
122
  }
78
123
  export function fromStaticPublishRc(rc, defaults = {}) {
79
124
  return fromPublisherServer(PublisherServer.fromStaticPublishRc(rc), defaults);
@@ -7,5 +7,5 @@ export { type CollectionSelection, type CollectionSelectionSource, previewUrl, v
7
7
  export { CookieCollectionSelector, type CookieCollectionSelectorOpts, } from './collection-selector/from-cookie.js';
8
8
  export { type StorageProvider, type StorageProviderBuilder, type StorageEntry, registerStorageProviderBuilder, } from './storage/storage-provider.js';
9
9
  export { setSecretStoreForS3Credentials, setSecretStoreKeyForS3AccessKeyId, setSecretStoreKeyForS3SecretAccessKey, setS3CredentialsBuilder, } from './storage/s3-storage-provider.js';
10
- export { type GetMatchingAssetOptions, type ServeFallbackOptions, type ServeRequestOptions, PublisherServer, } from './publisher-server/index.js';
10
+ export { type GetMatchingAssetOptions, type ProduceResult, type ResponseOverrides, type ServeFallbackOptions, type ServeRequestOptions, type StreamingServeResult, PublisherServer, } from './publisher-server/index.js';
11
11
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/server/index.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,KAAK,eAAe,EAAE,MAAM,uCAAuC,CAAC;AAC7E,OAAO,EAAE,KAAK,oBAAoB,EA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M,sCAAsC,CAAC;AAC9C,OAAO,EACL,KAAK,eAAe,EACpB,KAAK,sBAAsB,EAC3B,KAAK,YAAY,EACjB,8BAA8B,GAC/B,MAAM,+BAA+B,CAAC;AACvC,OAAO,EACL,8BAA8B,EAC9B,iCAAiC,EACjC,qCAAqC,EACrC,uBAAuB,GACxB,MAAM,kCAAkC,CAAC;AAC1C,OAAO,EACL,KAAK,uBAAuB,EAC5B,KAAK,aAAa,EAClB,KAAK,iBAAiB,EACtB,KAAK,oBAAoB,EACzB,KAAK,mBAAmB,EACxB,KAAK,oBAAoB,EACzB,eAAe,GAChB,MAAM,6BAA6B,CAAC"}
@@ -26,10 +26,22 @@ export type ServeRequestOptions = {
26
26
  fallback?: boolean;
27
27
  healthCheck?: boolean;
28
28
  onMissing?: 'not-found' | 'default';
29
- };
29
+ } & ResponseOverrides;
30
30
  export type ServeFallbackOptions = {
31
31
  collectionName?: string | null;
32
32
  onMissing?: 'not-found' | 'default';
33
+ } & ResponseOverrides;
34
+ export type ResponseOverrides = {
35
+ status?: number;
36
+ headers?: HeadersInit;
37
+ };
38
+ export type ProduceResult = Response | {
39
+ response: Response;
40
+ length?: number | null;
41
+ } | null;
42
+ export type StreamingServeResult = {
43
+ response: Response | null;
44
+ fillPromise: Promise<void>;
33
45
  };
34
46
  export declare class PublisherServer {
35
47
  constructor(publishId: string, storageProvider: StorageProvider, defaultCollectionName: string);
@@ -91,11 +103,17 @@ export declare class PublisherServer {
91
103
  private findAssetVariantForAcceptEncodingsGroups;
92
104
  serveAsset(request: Request, asset: AssetEntry, init?: AssetInit): Promise<Response>;
93
105
  private serveAssetFor;
94
- serveCached(request: Request, keyPath: string, produce: (request: Request) => Promise<Response | null>): Promise<Response | null>;
106
+ serveCached(request: Request, keyPath: string, produce: (request: Request) => Promise<ProduceResult>): Promise<Response | null>;
107
+ serveCachedStreaming(request: Request, keyPath: string, produce: (request: Request) => Promise<ProduceResult>): Promise<StreamingServeResult>;
95
108
  private serveCachedFor;
109
+ private streamFill;
96
110
  private responseFromCache;
97
111
  serveRequest(request: Request, options?: ServeRequestOptions): Promise<Response | null>;
112
+ serveRequestStreaming(request: Request, options?: ServeRequestOptions): Promise<StreamingServeResult>;
113
+ private serveRequestWith;
98
114
  serveFallback(request: Request, options?: ServeFallbackOptions): Promise<Response | null>;
115
+ serveFallbackStreaming(request: Request, options?: ServeFallbackOptions): Promise<StreamingServeResult>;
116
+ private serveFallbackWith;
99
117
  isCollectionAvailable(request: Request, collectionName: string | null): Promise<boolean>;
100
118
  private isCollectionAvailableFor;
101
119
  private checkSelectedCollection;
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/server/publisher-server/index.ts"],"names":[],"mappings":"AASA,OAAO,EACL,KAAK,eAAe,EACrB,MAAM,0CAA0C,CAAC;AAClD,OAAO,EACL,KAAK,+BAA+B,EACrC,MAAM,gDAAgD,CAAC;AACxD,OAAO,EACL,KAAK,uBAAuB,EAC7B,MAAM,mCAAmC,CAAC;AAC3C,OAAO,EACL,KAAK,UAAU,EACf,KAAK,aAAa,EAClB,KAAK,oBAAoB,EAI1B,MAAM,8BAA8B,CAAC;AAEtC,OAAO,EACL,KAAK,mBAAmB,EAEzB,MAAM,6CAA6C,CAAC;AACrD,OAAO,EAAE,KAAK,uBAAuB,EAAsC,MAAM,kCAAkC,CAAC;AAGpH,OAAO,EACL,KAAK,YAAY,EACjB,KAAK,eAAe,EAErB,MAAM,gCAAgC,CAAC;AAGxC,OAAO,EAAE,YAAY,EAAE,MAAM,0BAA0B,CAAC;AAExD,OAAO,EAEL,KAAK,oBAAoB,EAW1B,MAAM,qBAAqB,CAAC;AAG7B,MAAM,MAAM,uBAAuB,GAAG;IAEpC,SAAS,CAAC,EAAE,OAAO,CAAC;IAGpB,aAAa,CAAC,EAAE,OAAO,CAAC;CACzB,CAAC;AAEF,KAAK,YAAY,GAAG;IAClB,YAAY,EAAE,YAAY,CAAC;CAC5B,GAAG,oBAAoB,CAAC;AA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OAAO,CAAC,CAE7F;YAEa,wBAAwB;YASxB,uBAAuB;IAyBrC,OAAO,CAAC,mBAAmB;IAqB3B,OAAO,CAAC,eAAe;YAQT,uBAAuB;YAwCvB,wBAAwB;CAiCvC"}
@@ -2,8 +2,8 @@
2
2
  * Copyright Fastly, Inc.
3
3
  * Licensed under the MIT license. See LICENSE file for details.
4
4
  */
5
- /// <reference types="@fastly/js-compute" />
6
5
  import { CoreCache } from 'fastly:cache';
6
+ import { env } from 'fastly:env';
7
7
  import { decodeAssetVariantMetadata, findAssetEntry, isHiddenIndexKey, } from '../../models/assets/index.js';
8
8
  import { parseItemPatterns, testItemPatterns } from '../../models/config/item-patterns.js';
9
9
  import { validateCollectionSelection, } from '../../models/config/collection-selection.js';
@@ -15,8 +15,9 @@ import { checkIfModifiedSince, getIfModifiedSinceHeader } from './serve-precondi
15
15
  import { checkIfNoneMatch, getIfNoneMatchHeader } from './serve-preconditions/if-none-match.js';
16
16
  import { ServerTiming } from '../util/server-timing.js';
17
17
  import { requestAcceptsTextHtml } from './accept-html.js';
18
- import { CACHEABLE_STATUSES, DEFAULT_MAX_BODY_SIZE, buildCacheFillRequest, buildResponseCacheKey, bytesInPieces, decodeCachedResponseMetadata, encodeCachedResponseMetadata, parseAcceptEncodingGroups, readBodyUpTo, streamBytesInPieces, } from './response-cache.js';
18
+ import { BodyLengthMismatchError, CACHEABLE_STATUSES, DEFAULT_MAX_BODY_SIZE, buildCacheFillRequest, buildResponseCacheKey, bytesInPieces, decodeCachedResponseMetadata, encodeCachedResponseMetadata, lengthMismatchMarkerKey, parseAcceptEncodingGroups, pipeBodyWithLength, readBodyUpTo, streamBytesInPieces, } from './response-cache.js';
19
19
  import { checkBodyLength } from '../util/body-length.js';
20
+ import { isSdkVersionAtLeast } from '../util/sdk-version.js';
20
21
  export function buildHeadersSubset(responseHeaders, keys) {
21
22
  const resultHeaders = new Headers();
22
23
  for (const value of keys) {
@@ -35,6 +36,74 @@ export function buildHeadersSubset(responseHeaders, keys) {
35
36
  // * Content-Location, Date, ETag, and Vary
36
37
  // * Cache-Control and Expires
37
38
  const headersToPreserveForUnmodified = ['Content-Location', 'ETag', 'Vary', 'Cache-Control', 'Expires'];
39
+ // RFC 9110 evaluates the preconditions only for a response that would be 2xx.
40
+ function isSuccessStatus(status) {
41
+ return status >= 200 && status < 300;
42
+ }
43
+ const PRECONDITION_HEADERS = ['If-Match', 'If-None-Match', 'If-Modified-Since', 'If-Unmodified-Since', 'If-Range'];
44
+ // The request without its precondition headers, for a response with a status
45
+ // other than 2xx.
46
+ function requestForStatus(request, status) {
47
+ if (status == null || isSuccessStatus(status)) {
48
+ return request;
49
+ }
50
+ const headers = new Headers(request.headers);
51
+ for (const name of PRECONDITION_HEADERS) {
52
+ headers.delete(name);
53
+ }
54
+ return new Request(request.url, { method: request.method, headers });
55
+ }
56
+ // Apply the overrides to the response of a file. The response of a file always
57
+ // has an ETag.
58
+ function applyResponseOverrides(response, overrides) {
59
+ if (response == null ||
60
+ (overrides.status == null && overrides.headers == null) ||
61
+ response.status === 304 ||
62
+ !response.headers.has('ETag')) {
63
+ return response;
64
+ }
65
+ const headers = new Headers(response.headers);
66
+ new Headers(overrides.headers).forEach((value, name) => {
67
+ headers.set(name, value);
68
+ });
69
+ const status = overrides.status ?? response.status;
70
+ return new Response(response.body, {
71
+ status,
72
+ statusText: status === response.status ? response.statusText : '',
73
+ headers,
74
+ });
75
+ }
76
+ const FILL_DONE = Promise.resolve();
77
+ // The length of the body of each full response that serveAsset() made.
78
+ const assetResponseLengths = new WeakMap();
79
+ function readProduceResult(result) {
80
+ if (result == null) {
81
+ return { response: null, length: undefined };
82
+ }
83
+ if (result instanceof Response) {
84
+ return { response: result, length: assetResponseLengths.get(result) };
85
+ }
86
+ const { response, length } = result;
87
+ if (length != null && !(Number.isSafeInteger(length) && length >= 0)) {
88
+ throw new TypeError(`length must be an integer of 0 or more, null, or undefined: ${length}`);
89
+ }
90
+ return { response, length };
91
+ }
92
+ // A streaming fill (insertAndStreamBack() with event.waitUntil()) is safe on a
93
+ // real service from js-compute 4.2. Earlier versions do not show the waiters an
94
+ // error when a fill fails. Viceroy (FASTLY_HOSTNAME is 'localhost') keeps an
95
+ // abandoned fill, and each later request for it gets an error. In these cases,
96
+ // serveCachedStreaming() reads the whole body first, as serveCached() does.
97
+ // The js-compute version is known when the module loads. The environment is
98
+ // read at the first request, and kept.
99
+ const SDK_SUPPORTS_STREAMING_FILL = isSdkVersionAtLeast(globalThis.fastly?.sdkVersion, 4, 2);
100
+ let streamingFillSupported;
101
+ function isStreamingFillSupported() {
102
+ if (streamingFillSupported === undefined) {
103
+ streamingFillSupported = SDK_SUPPORTS_STREAMING_FILL && env('FASTLY_HOSTNAME') !== 'localhost';
104
+ }
105
+ return streamingFillSupported;
106
+ }
38
107
  // The response for a collection other than the default collection that is not
39
108
  // published, or that expired. It can be published at any time, so no cache
40
109
  // stores this response.
@@ -158,7 +227,6 @@ export class PublisherServer {
158
227
  serverTiming,
159
228
  settings: undefined,
160
229
  assetEntryMap: undefined,
161
- doNotStoreResponse: false,
162
230
  };
163
231
  }
164
232
  // The scope of a request for a collection. A new request gets a new scope.
@@ -499,18 +567,23 @@ export class PublisherServer {
499
567
  if (scope.serverTiming != null) {
500
568
  headers.append('Server-Timing', scope.serverTiming.toHeaderValue());
501
569
  }
502
- const preconditionResponse = this.handlePreconditions(request, asset, headers);
503
- if (preconditionResponse != null) {
504
- return preconditionResponse;
570
+ const status = init?.status ?? 200;
571
+ if (isSuccessStatus(status)) {
572
+ const preconditionResponse = this.handlePreconditions(request, asset, headers);
573
+ if (preconditionResponse != null) {
574
+ return preconditionResponse;
575
+ }
505
576
  }
506
577
  // If the body does not have the size in its metadata, the response must not
507
578
  // look complete. An empty body throws here, and any other mismatch causes an
508
579
  // error in the body stream, so that the client gets an incomplete response.
509
580
  const body = await checkBodyLength(assetVariant.storageEntry.body, assetVariant.size, `File ${asset.key} (${assetVariant.contentEncoding ?? 'identity'})`);
510
- return new Response(body, {
511
- status: init?.status ?? 200,
581
+ const response = new Response(body, {
582
+ status,
512
583
  headers,
513
584
  });
585
+ assetResponseLengths.set(response, assetVariant.size);
586
+ return response;
514
587
  }
515
588
  // Serve a response through the response cache (see setResponseCache()).
516
589
  // keyPath identifies the response in the active collection. Include in it
@@ -519,12 +592,25 @@ export class PublisherServer {
519
592
  // range headers, and its result is cached if it is a 200 or 404 response, or
520
593
  // null (not found). Conditional requests and HEAD are then answered from the
521
594
  // cached response. If the cache is off, produce() gets the original request.
595
+ // produce() can also return { response, length } (see ProduceResult). The fill
596
+ // reads the whole body before it stores it.
522
597
  async serveCached(request, keyPath, produce) {
523
- return this.serveCachedFor(this.currentScope, request, keyPath, produce);
524
- }
525
- async serveCachedFor(scope, request, keyPath, produce) {
598
+ return (await this.serveCachedFor(this.currentScope, request, keyPath, produce, false)).response;
599
+ }
600
+ // As serveCached(), but a fill for a body with a known length (see
601
+ // ProduceResult) streams the body into the cache while the response sends it.
602
+ // Pass fillPromise to event.waitUntil(), or the fill stops when the handler
603
+ // returns. With js-compute earlier than 4.2, and in Viceroy, the fill reads
604
+ // the whole body first, and fillPromise is already resolved.
605
+ async serveCachedStreaming(request, keyPath, produce) {
606
+ return this.serveCachedFor(this.currentScope, request, keyPath, produce, true);
607
+ }
608
+ async serveCachedFor(scope, request, keyPath, produce, streaming) {
609
+ const produceResponse = async (request) => {
610
+ return { response: readProduceResult(await produce(request)).response, fillPromise: FILL_DONE };
611
+ };
526
612
  if (this.responseCache == null) {
527
- return produce(request);
613
+ return produceResponse(request);
528
614
  }
529
615
  const key = buildResponseCacheKey(this.publishId, scope.collectionName, keyPath, request);
530
616
  const lookupStart = performance.now();
@@ -534,30 +620,31 @@ export class PublisherServer {
534
620
  const metadata = state.found() && state.usable() ? decodeCachedResponseMetadata(entry.userMetadata()) : null;
535
621
  if (metadata?.tooLarge) {
536
622
  scope.serverTiming?.add('cache', performance.now() - lookupStart, 'bypass');
537
- return produce(request);
623
+ return produceResponse(request);
538
624
  }
539
625
  if (metadata != null) {
540
626
  // age() is in milliseconds. A hit younger than the time since a purge proves the entry was refilled.
541
627
  scope.serverTiming?.add('cache', performance.now() - lookupStart, `hit age=${Math.round(entry.age() / 1000)}s`);
542
- return this.responseFromCache(scope, request, metadata, entry.body());
628
+ return { response: this.responseFromCache(scope, request, metadata, entry.body()), fillPromise: FILL_DONE };
543
629
  }
544
630
  // Not usable, and another request is not filling it for us: serve without the cache.
545
631
  scope.serverTiming?.add('cache', performance.now() - lookupStart, 'bypass');
546
- return produce(request);
632
+ return produceResponse(request);
547
633
  }
548
634
  // This request must fill the entry (a miss, or a stale entry after a soft purge).
549
635
  scope.serverTiming?.add('cache', performance.now() - lookupStart, 'miss');
550
636
  let response;
637
+ let length;
551
638
  try {
552
- response = await produce(buildCacheFillRequest(request));
639
+ ({ response, length } = readProduceResult(await produce(buildCacheFillRequest(request))));
553
640
  }
554
641
  catch (err) {
555
642
  entry.cancel();
556
643
  throw err;
557
644
  }
558
- if (scope.doNotStoreResponse) {
645
+ if (length === null) {
559
646
  entry.cancel();
560
- return response;
647
+ return { response, fillPromise: FILL_DONE };
561
648
  }
562
649
  const insertOptions = {
563
650
  // The Core Cache takes maxAge in milliseconds. ResponseCacheOptions.maxAge is in seconds.
@@ -572,16 +659,34 @@ export class PublisherServer {
572
659
  length: 0,
573
660
  });
574
661
  writer.close();
575
- return null;
662
+ return { response: null, fillPromise: FILL_DONE };
576
663
  }
577
664
  if (!CACHEABLE_STATUSES.includes(response.status)) {
578
665
  entry.cancel();
579
- return response;
666
+ return { response, fillPromise: FILL_DONE };
580
667
  }
581
668
  const headers = new Headers(response.headers);
582
669
  // Server-Timing describes one request, so it is not stored.
583
670
  headers.delete('Server-Timing');
584
671
  const metadata = { status: response.status, headers: [...headers] };
672
+ const maxBodySize = this.responseCache.maxBodySize ?? DEFAULT_MAX_BODY_SIZE;
673
+ if (streaming &&
674
+ length !== undefined &&
675
+ length <= maxBodySize &&
676
+ isStreamingFillSupported() &&
677
+ CoreCache.lookup(lengthMismatchMarkerKey(key)) == null) {
678
+ // The fill streams the body into the entry, and the response streams it
679
+ // back from the entry. A fill that fails, or that does not have length
680
+ // bytes, is abandoned and not stored, and the requests that read the
681
+ // entry get an error.
682
+ const [writer, streamBack] = entry.insertAndStreamBack({
683
+ ...insertOptions,
684
+ userMetadata: encodeCachedResponseMetadata(metadata),
685
+ length,
686
+ });
687
+ const fillPromise = this.streamFill(key, insertOptions, writer, response.body, length);
688
+ return { response: this.responseFromCache(scope, request, metadata, streamBack.body()), fillPromise };
689
+ }
585
690
  // Read the whole body before the insertion starts. After it starts, a body
586
691
  // that is not complete is not safe: the requests that read the entry get
587
692
  // a short body that ends as if it is complete. If the read fails (for example,
@@ -589,7 +694,7 @@ export class PublisherServer {
589
694
  // cancel() stores nothing, and the next request fills the entry again.
590
695
  let readResult;
591
696
  try {
592
- readResult = await readBodyUpTo(response.body, this.responseCache.maxBodySize ?? DEFAULT_MAX_BODY_SIZE);
697
+ readResult = await readBodyUpTo(response.body, maxBodySize);
593
698
  }
594
699
  catch (err) {
595
700
  entry.cancel();
@@ -605,7 +710,12 @@ export class PublisherServer {
605
710
  length: 0,
606
711
  });
607
712
  writer.close();
608
- return this.responseFromCache(scope, request, metadata, readResult.body);
713
+ return { response: this.responseFromCache(scope, request, metadata, readResult.body), fillPromise: FILL_DONE };
714
+ }
715
+ // The fill stores the body that it read. A declared length that is not
716
+ // the length of that body is a mistake in produce(), so it is logged.
717
+ if (length !== undefined && length !== readResult.bytes.byteLength) {
718
+ console.warn(`Response cache: the body of '${key}' has ${readResult.bytes.byteLength} bytes, not the declared length ${length}. The fill stores the body that it read.`);
609
719
  }
610
720
  const writer = entry.insert({
611
721
  ...insertOptions,
@@ -618,7 +728,33 @@ export class PublisherServer {
618
728
  writer.append(piece);
619
729
  }
620
730
  writer.close();
621
- return this.responseFromCache(scope, request, metadata, streamBytesInPieces(readResult.bytes));
731
+ return { response: this.responseFromCache(scope, request, metadata, streamBytesInPieces(readResult.bytes)), fillPromise: FILL_DONE };
732
+ }
733
+ // Writes body into the entry. Never rejects: a failure is logged. If body
734
+ // does not have length bytes, the fill is abandoned, and a marker tells the
735
+ // next fill for key to read the whole body first.
736
+ async streamFill(key, insertOptions, writer, body, length) {
737
+ try {
738
+ await pipeBodyWithLength(body, length, (chunk) => writer.append(chunk));
739
+ writer.close();
740
+ }
741
+ catch (err) {
742
+ try {
743
+ writer.abandon();
744
+ }
745
+ catch {
746
+ // The entry is already closed or abandoned.
747
+ }
748
+ console.error(`Response cache: the fill of '${key}' stopped:`, String(err));
749
+ if (err instanceof BodyLengthMismatchError) {
750
+ try {
751
+ CoreCache.insert(lengthMismatchMarkerKey(key), { ...insertOptions, length: 0 }).close();
752
+ }
753
+ catch (markerErr) {
754
+ console.error(`Response cache: cannot store the length mismatch marker of '${key}':`, String(markerErr));
755
+ }
756
+ }
757
+ }
622
758
  }
623
759
  responseFromCache(scope, request, metadata, body) {
624
760
  if (metadata.notFound) {
@@ -631,9 +767,11 @@ export class PublisherServer {
631
767
  const lastModified = headers.get('Last-Modified');
632
768
  const lastModifiedMs = lastModified != null ? Date.parse(lastModified) : NaN;
633
769
  const lastModifiedTime = Number.isNaN(lastModifiedMs) ? 0 : Math.floor(lastModifiedMs / 1000);
634
- const preconditionResponse = this.handlePreconditionsForLastModified(request, lastModifiedTime, headers);
635
- if (preconditionResponse != null) {
636
- return preconditionResponse;
770
+ if (isSuccessStatus(metadata.status)) {
771
+ const preconditionResponse = this.handlePreconditionsForLastModified(request, lastModifiedTime, headers);
772
+ if (preconditionResponse != null) {
773
+ return preconditionResponse;
774
+ }
637
775
  }
638
776
  return new Response(request.method === 'HEAD' ? null : body, {
639
777
  status: metadata.status,
@@ -644,10 +782,18 @@ export class PublisherServer {
644
782
  // file or the 404 page (see options.fallback). Returns null if there is no
645
783
  // response for the request, for example for a method other than GET and HEAD.
646
784
  async serveRequest(request, options = {}) {
785
+ return (await this.serveRequestWith(request, options, false)).response;
786
+ }
787
+ // As serveRequest(), but the response cache fill streams (see
788
+ // serveCachedStreaming()). Pass fillPromise to event.waitUntil().
789
+ async serveRequestStreaming(request, options = {}) {
790
+ return this.serveRequestWith(request, options, true);
791
+ }
792
+ async serveRequestWith(request, options, streaming) {
647
793
  let scope = this.beginRequestFor(request, options.collectionName);
648
794
  // Only handle GET and HEAD
649
795
  if (request.method !== 'GET' && request.method !== 'HEAD') {
650
- return null;
796
+ return { response: null, fillPromise: FILL_DONE };
651
797
  }
652
798
  let pathname;
653
799
  if (options.pathname != null) {
@@ -661,48 +807,64 @@ export class PublisherServer {
661
807
  }
662
808
  // Custom health check route
663
809
  if (options.healthCheck !== false && pathname === '/healthz') {
664
- return new Response("OK", { status: 200 });
810
+ return { response: new Response("OK", { status: 200 }), fillPromise: FILL_DONE };
665
811
  }
666
812
  const selected = await this.checkSelectedCollection(request, scope, options.onMissing);
667
813
  if (selected instanceof Response) {
668
- return selected;
814
+ return { response: selected, fillPromise: FILL_DONE };
669
815
  }
670
816
  scope = selected.scope;
671
817
  // The fallback pages (SPA, not found) depend on whether the client accepts HTML.
672
818
  // With fallback: false, the response does not depend on HTML, so it has its own cache key.
673
819
  const fallback = options.fallback !== false && requestAcceptsTextHtml(request);
674
820
  const keyPath = fallback ? pathname : `${pathname}|no-html`;
675
- const response = await this.serveCachedFor(scope, request, keyPath, (fillRequest) => this.serveRequestFromStorage(scope, fillRequest, pathname, fallback));
676
- return selected.preview ? this.markPreviewResponse(request, selected.scope, response) : response;
821
+ const served = await this.serveCachedFor(scope, requestForStatus(request, options.status), keyPath, (fillRequest) => this.serveRequestFromStorage(scope, fillRequest, pathname, fallback), streaming);
822
+ const response = applyResponseOverrides(served.response, options);
823
+ return {
824
+ response: selected.preview ? this.markPreviewResponse(request, selected.scope, response) : response,
825
+ fillPromise: served.fillPromise,
826
+ };
677
827
  }
678
828
  // Serve the SPA file or the 404 page, as serveRequest() does when no file
679
829
  // matches. Use it after serveRequest() with fallback: false. Returns null for
680
830
  // a method other than GET and HEAD, if the client does not accept HTML, or if
681
831
  // the collection has no fallback page.
682
832
  async serveFallback(request, options = {}) {
833
+ return (await this.serveFallbackWith(request, options, false)).response;
834
+ }
835
+ // As serveFallback(), but the response cache fill streams (see
836
+ // serveCachedStreaming()). Pass fillPromise to event.waitUntil().
837
+ async serveFallbackStreaming(request, options = {}) {
838
+ return this.serveFallbackWith(request, options, true);
839
+ }
840
+ async serveFallbackWith(request, options, streaming) {
683
841
  let scope = this.beginRequestFor(request, options.collectionName);
684
842
  // Only handle GET and HEAD
685
843
  if (request.method !== 'GET' && request.method !== 'HEAD') {
686
- return null;
844
+ return { response: null, fillPromise: FILL_DONE };
687
845
  }
688
846
  if (!requestAcceptsTextHtml(request)) {
689
- return null;
847
+ return { response: null, fillPromise: FILL_DONE };
690
848
  }
691
849
  const selected = await this.checkSelectedCollection(request, scope, options.onMissing);
692
850
  if (selected instanceof Response) {
693
- return selected;
851
+ return { response: selected, fillPromise: FILL_DONE };
694
852
  }
695
853
  scope = selected.scope;
696
854
  // The fallback response is the same for all paths, so it has one cache key.
697
855
  // A path always starts with a slash, so this key is not the key of a path.
698
- const response = await this.serveCachedFor(scope, request, '|fallback', async (fillRequest) => {
856
+ const served = await this.serveCachedFor(scope, requestForStatus(request, options.status), '|fallback', async (fillRequest) => {
699
857
  const serverConfig = await this.getServerConfigFor(scope);
700
858
  if (serverConfig == null) {
701
859
  return null;
702
860
  }
703
861
  return this.serveFallbackFromStorage(scope, fillRequest, serverConfig);
704
- });
705
- return selected.preview ? this.markPreviewResponse(request, selected.scope, response) : response;
862
+ }, streaming);
863
+ const response = applyResponseOverrides(served.response, options);
864
+ return {
865
+ response: selected.preview ? this.markPreviewResponse(request, selected.scope, response) : response,
866
+ fillPromise: served.fillPromise,
867
+ };
706
868
  }
707
869
  // Returns true if the collection is published, has not expired, and can
708
870
  // be served by this version. It reads the settings and the index into the scope.
@@ -784,8 +946,7 @@ export class PublisherServer {
784
946
  // response cache does not store this response.
785
947
  if (serverConfig == null ||
786
948
  (scope.collectionName !== this.defaultCollectionName && await this.getAssetEntryMapFor(scope) == null)) {
787
- scope.doNotStoreResponse = true;
788
- return collectionNotAvailableResponse(scope.collectionName);
949
+ return { response: collectionNotAvailableResponse(scope.collectionName), length: null };
789
950
  }
790
951
  const asset = await this.getMatchingAssetFor(scope, serverConfig.publicDirPrefix + pathname, true, false);
791
952
  if (asset != null) {
@@ -27,6 +27,11 @@ export type ReadBodyResult = {
27
27
  body: ReadableStream<Uint8Array>;
28
28
  };
29
29
  export declare function readBodyUpTo(body: ReadableStream<Uint8Array> | null, maxLength: number): Promise<ReadBodyResult>;
30
+ export declare class BodyLengthMismatchError extends Error {
31
+ constructor(message: string);
32
+ }
33
+ export declare function pipeBodyWithLength(body: ReadableStream<Uint8Array> | null, length: number, append: (chunk: Uint8Array) => void): Promise<void>;
34
+ export declare function lengthMismatchMarkerKey(key: string): string;
30
35
  export declare const BODY_PIECE_SIZE: number;
31
36
  export declare function bytesInPieces(bytes: Uint8Array<ArrayBuffer>): Generator<Uint8Array<ArrayBuffer>>;
32
37
  export declare function streamBytesInPieces(bytes: Uint8Array<ArrayBuffer>): ReadableStream<Uint8Array>;
@@ -1 +1 @@
1
- {"version":3,"file":"response-cache.d.ts","sourceRoot":"","sources":["../../../../src/server/publisher-server/response-cache.ts"],"names":[],"mappings":"AAKA,OAAO,EACL,KAAK,uBAAuB,EAE7B,MAAM,mCAAmC,CAAC;AAE3C,MAAM,MAAM,oBAAoB,GAAG;IAIjC,MAAM,EAAE,MAAM,CAAC;IAIf,WAAW,CAAC,EAAE,MAAM,CAAC;CACtB,CAAC;AAEF,eAAO,MAAM,qBAAqB,QAAmB,CAAC;AAKtD,MAAM,MAAM,sBAAsB,GAC9B;IAAE,QAAQ,EAAE,IAAI,CAAC;IAAC,QAAQ,CAAC,EAAE,KAAK,CAAA;CAAE,GACpC;IAAE,QAAQ,CAAC,EAAE,KAAK,CAAC;IAAC,QAAQ,EAAE,IAAI,CAAA;CAAE,GACpC;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,CAM/D;AAED,MAAM,MAAM,cAAc,GACtB;IAAE,KAAK,EAAE,UAAU,CAAC,WAAW,CAAC,CAAA;CAAE,GAClC;IAAE,IAAI,EAAE,cAAc,CAAC,UAAU,CAAC,CAAA;CAAE,CAAC;AAMzC,wBAAsB,YAAY,CAChC,IAAI,EAAE,cAAc,CAAC,UAAU,CAAC,GAAG,IAAI,EACvC,SAAS,EAAE,MAAM,GAChB,OAAO,CAAC,cAAc,CAAC,CA8CzB;AAGD,qBAAa,uBAAwB,SAAQ,KAAK;IAChD,YAAY,OAAO,EAAE,MAAM,EAG1B;CACF;AAMD,wBAAsB,kBAAkB,CACtC,IAAI,EAAE,cAAc,CAAC,UAAU,CAAC,GAAG,IAAI,EACvC,MAAM,EAAE,MAAM,EACd,MAAM,EAAE,CAAC,KAAK,EAAE,UAAU,KAAK,IAAI,GAClC,OAAO,CAAC,IAAI,CAAC,CAoBf;AAID,wBAAgB,uBAAuB,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAE3D;AAED,eAAO,MAAM,eAAe,QAAc,CAAC;AAI3C,wBAAiB,aAAa,CAAC,KAAK,EAAE,UAAU,CAAC,WAAW,CAAC,GAAG,SAAS,CAAC,UAAU,CAAC,WAAW,CAAC,CAAC,CAIjG;AAGD,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,UAAU,CAAC,WAAW,CAAC,GAAG,cAAc,CAAC,UAAU,CAAC,CAY9F;AAED,wBAAgB,4BAA4B,CAAC,QAAQ,EAAE,sBAAsB,GAAG,MAAM,CAErF;AAED,wBAAgB,4BAA4B,CAAC,MAAM,EAAE,WAAW,GAAG,sBAAsB,GAAG,IAAI,CAgB/F"}
@@ -137,6 +137,43 @@ export async function readBodyUpTo(body, maxLength) {
137
137
  }
138
138
  return { bytes };
139
139
  }
140
+ // The body of a response has a number of bytes that is not its declared length.
141
+ export class BodyLengthMismatchError extends Error {
142
+ constructor(message) {
143
+ super(message);
144
+ this.name = 'BodyLengthMismatchError';
145
+ }
146
+ }
147
+ // Reads body, and gives each chunk to append(). Rejects with
148
+ // BodyLengthMismatchError if body has more or fewer bytes than length. A chunk
149
+ // that goes past length does not go to append(), and the read of body stops.
150
+ // An error from body or from append() rejects the promise.
151
+ export async function pipeBodyWithLength(body, length, append) {
152
+ let written = 0;
153
+ if (body != null) {
154
+ const reader = body.getReader();
155
+ for (;;) {
156
+ const { done, value } = await reader.read();
157
+ if (done) {
158
+ break;
159
+ }
160
+ if (written + value.byteLength > length) {
161
+ await reader.cancel().catch(() => { });
162
+ throw new BodyLengthMismatchError(`The body has more than ${length} bytes.`);
163
+ }
164
+ append(value);
165
+ written += value.byteLength;
166
+ }
167
+ }
168
+ if (written !== length) {
169
+ throw new BodyLengthMismatchError(`The body has ${written} bytes, not ${length}.`);
170
+ }
171
+ }
172
+ // The key of the marker that tells a cache fill for key to read the whole body
173
+ // first. A streaming fill stores it when the body did not have its declared length.
174
+ export function lengthMismatchMarkerKey(key) {
175
+ return `${key}|length-mismatch`;
176
+ }
140
177
  export const BODY_PIECE_SIZE = 1024 * 1024;
141
178
  // Gives bytes in pieces of BODY_PIECE_SIZE bytes. The pieces are views of
142
179
  // bytes, not copies.
@@ -0,0 +1,2 @@
1
+ export declare function isSdkVersionAtLeast(version: string | null | undefined, major: number, minor: number): boolean;
2
+ //# sourceMappingURL=sdk-version.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sdk-version.d.ts","sourceRoot":"","sources":["../../../../src/server/util/sdk-version.ts"],"names":[],"mappings":"AAOA,wBAAgB,mBAAmB,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,EAAE,KAAK,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,OAAO,CAQ7G"}
@@ -0,0 +1,15 @@
1
+ /*
2
+ * Copyright Fastly, Inc.
3
+ * Licensed under the MIT license. See LICENSE file for details.
4
+ */
5
+ // Returns true if version (for example, fastly.sdkVersion, '4.3.0') is
6
+ // major.minor or later. A version that is missing or cannot be read gives false.
7
+ export function isSdkVersionAtLeast(version, major, minor) {
8
+ const match = /^(\d+)\.(\d+)/.exec(version ?? '');
9
+ if (match == null) {
10
+ return false;
11
+ }
12
+ const versionMajor = Number(match[1]);
13
+ const versionMinor = Number(match[2]);
14
+ return versionMajor > major || (versionMajor === major && versionMinor >= minor);
15
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@fastly/compute-js-static-publish",
3
3
  "type": "module",
4
- "version": "8.1.0-beta.5",
4
+ "version": "8.1.0-beta.7",
5
5
  "description": "Static Publisher for Fastly Compute JavaScript",
6
6
  "main": "build/server/server/index.js",
7
7
  "exports": {
@@ -16,10 +16,18 @@ const honoOptions = rc.templateOptions?.hono;
16
16
  // with two different resources stops the build.
17
17
  const fire = buildFire(mergeBindings(honoOptions?.bindings, extensions) as BindingsDefs);
18
18
 
19
- const { serveStatic, staticResponse, serveFallback, selectCollection, publisherServer } = fromStaticPublishRc(rc);
19
+ const {
20
+ serveStatic,
21
+ staticResponse,
22
+ serveFallback,
23
+ fallbackResponse,
24
+ isCollectionAvailable,
25
+ selectCollection,
26
+ publisherServer,
27
+ } = fromStaticPublishRc(rc);
20
28
 
21
29
  // The helpers of the app that each phase of the extensions gets.
22
- const helpers = { serveStatic, staticResponse, serveFallback, publisherServer };
30
+ const helpers = { serveStatic, staticResponse, serveFallback, fallbackResponse, isCollectionAvailable, publisherServer };
23
31
 
24
32
  const app = new Hono<{ Bindings: typeof fire.Bindings, Variables: StaticPublisherVariables }>();
25
33
 
@@ -23,11 +23,13 @@ async function handleRequest(event) {
23
23
 
24
24
  // Serve the published file for the request. With fallback: false, a path
25
25
  // that has no file does not get the SPA file or the 404 page here.
26
- const response = await publisherServer.serveRequest(request, {
26
+ // waitUntil() lets the response cache fill continue after the response.
27
+ const { response, fillPromise } = await publisherServer.serveRequestStreaming(request, {
27
28
  collectionName: selection.collectionName,
28
29
  pathname: selection.pathname,
29
30
  fallback: false,
30
31
  });
32
+ event.waitUntil(fillPromise);
31
33
  if (response != null) {
32
34
  return response;
33
35
  }
@@ -37,8 +39,9 @@ async function handleRequest(event) {
37
39
  // for the requests that no published file matches.
38
40
 
39
41
  // When nothing else matches, serve the SPA file or the 404 page.
40
- const fallback = await publisherServer.serveFallback(request, {
42
+ const fallback = await publisherServer.serveFallbackStreaming(request, {
41
43
  collectionName: selection.collectionName,
42
44
  });
43
- return fallback ?? new Response('Not found', { status: 404 });
45
+ event.waitUntil(fallback.fillPromise);
46
+ return fallback.response ?? new Response('Not found', { status: 404 });
44
47
  }