@fastly/compute-js-static-publish 8.1.0-beta.6 → 8.1.0-beta.8

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,7 +12,7 @@ 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()`, `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.
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`, `beforeFilesRoutes` (before the published files), and `afterFilesRoutes` (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
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.
@@ -50,15 +50,14 @@ This file does not list v7 releases after 7.0.8, or v6 releases after 6.3.0. For
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
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.
53
55
 
54
56
  ### Changed
55
57
 
56
- - The npm package includes `CHANGELOG.md` and `MIGRATING.md`.
57
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.
58
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()`.
59
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.
60
- - `PublisherServer.setResponseCache()`: the default of `maxBodySize` is now 16 MiB. It was 8 MiB.
61
- - 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.
62
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.
63
62
  - `collectionSelector.fromCookie()`: the activate and reset paths now redirect with `308`. Before, they used `302`.
64
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.
@@ -79,7 +78,19 @@ This file does not list v7 releases after 7.0.8, or v6 releases after 6.3.0. For
79
78
  ### Fixed
80
79
 
81
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.
82
- - `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.
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.
83
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.
84
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.
85
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.
@@ -88,7 +99,6 @@ This file does not list v7 releases after 7.0.8, or v6 releases after 6.3.0. For
88
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.
89
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.
90
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.
91
- - `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.
92
102
 
93
103
  ## [8.0.1] - 2026-11-04
94
104
 
@@ -561,7 +571,8 @@ This file does not list v7 releases after 7.0.8, or v6 releases after 6.3.0. For
561
571
  - Updated generated app's webpack and webpack-cli versions
562
572
  - Use atob() and removed dependency on Buffer
563
573
 
564
- [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
565
576
  [8.0.1]: https://github.com/fastly/compute-js-static-publish/compare/v8.0.0...v8.0.1
566
577
  [8.0.0]: https://github.com/fastly/compute-js-static-publish/compare/v7.0.8...v8.0.0
567
578
  [7.0.8]: https://github.com/fastly/compute-js-static-publish/compare/v7.0.7...v7.0.8
package/DOCUMENTATION.md CHANGED
@@ -1161,9 +1161,31 @@ const response = await publisherServer.serveCached(request, pathname, async (fil
1161
1161
 
1162
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.
1163
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
+
1164
1186
  Notes:
1165
1187
 
1166
- - 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.
1167
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.
1168
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.
1169
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.
@@ -1205,15 +1227,39 @@ hono-extensions/
1205
1227
 
1206
1228
  - **Modules** are the files directly in the folder, with the extension `.ts`, `.mts`, `.js`, or `.mjs`. Files that start with `_` or `.`, and `.d.ts` files, are not modules. The build does not look in subfolders, so use them, for example `lib/`, for your helpers.
1207
1229
  - **The name** of a module is the file name without the number prefix and the extension: `10-auth.ts` is `auth`. Two modules with the same name are an error.
1208
- - **The phases:** a module adds its handlers to the app in one or more phases. The app runs the phases in this order, and in each phase the modules in the order of the file names (add a number prefix to set the order):
1230
+ - **The phases:** a module adds its handlers to the app in one or more phases. In each phase, the app takes the modules in the order of the file names (add a number prefix to set the order). The phases are on two axes:
1209
1231
 
1210
1232
  ```
1211
- selectCollection() → middleware → beforeFiles → serveStatic() → afterFiles → serveFallback()
1233
+ selectCollection()
1234
+ middleware processing: wraps all of the routing below
1235
+ beforeFilesRoutes routing: the first route that answers wins
1236
+ → published files (serveStatic())
1237
+ → afterFilesRoutes
1238
+ → serveFallback()
1239
+ ```
1240
+
1241
+ - **Processing:** `middleware` wraps each request, for example a login check, a header on each response, or the time of a request. In a middleware, the code before `await next()` runs before the routes. The code after it runs after the response is made, also when a published file answered, and in the reverse order of the modules. All modules add their middleware before any module adds its routes, so a middleware such as a login check also applies to the routes of the other modules.
1242
+ - **Routing:** the routes that can answer a request, in this order. The first one that answers wins.
1243
+ - `beforeFilesRoutes`: before the published files. A route here wins over a file at the same path, for example an API.
1244
+ - The published files (`serveStatic()`).
1245
+ - `afterFilesRoutes`: only for the requests that no published file matches, before the SPA file or the 404 page. A file at the same path wins, for example for a redirect from an old URL, which stops when a file is published at that URL again. The published files are served only for `GET` and `HEAD`, so these routes also get all other methods.
1246
+
1247
+ A middleware that measures the time of each request, with the code before and after `await next()`:
1248
+
1249
+ ```ts
1250
+ // hono-extensions/05-timing.ts
1251
+ import { defineExtension } from '@fastly/compute-js-static-publish/hono';
1252
+
1253
+ export default defineExtension((app) => {
1254
+ app.use('*', async (c, next) => {
1255
+ const start = performance.now();
1256
+ await next();
1257
+ console.log(`${c.req.method} ${c.req.path} ${c.res.status} ${(performance.now() - start).toFixed(1)} ms`);
1258
+ });
1259
+ });
1212
1260
  ```
1213
1261
 
1214
- - `middleware`: before all other phases. All modules add their middleware before any module adds its routes, so a middleware such as a login check also applies to the routes of the other modules.
1215
- - `beforeFiles`: before the published files.
1216
- - `afterFiles`: after the published files. These handlers get only the requests that no published file matches, for example to make a page for a path that has no file, before the 404 page. The published files are served only for `GET` and `HEAD`, so these handlers also get all other methods.
1262
+ The time ends when the response is made. The body of a large file can still be on its way to the visitor then.
1217
1263
 
1218
1264
  A module default-exports `defineExtension()`. Give it a function for each phase that the module uses. Each function gets the Hono app, the options of the module, and the helpers of the app (see below), and adds handlers with `app.use()`, `app.get()`, `app.post()`, and the other methods of Hono. With only a function in place of the object, the function is the `middleware` phase:
1219
1265
 
@@ -1240,10 +1286,10 @@ export default defineExtension({ bindings: { config: 'ConfigStore:site_config' }
1240
1286
  c.header('cache-control', 'no-store');
1241
1287
  });
1242
1288
  },
1243
- beforeFiles: (app) => {
1289
+ beforeFilesRoutes: (app) => {
1244
1290
  app.get('/api/greeting', async (c) => c.json({ greeting: await c.env.config?.get('greeting') }));
1245
1291
  },
1246
- afterFiles: (app) => {
1292
+ afterFilesRoutes: (app) => {
1247
1293
  app.get('/blog/:slug', (c) => c.redirect(`/archive/${c.req.param('slug')}/`, 301));
1248
1294
  },
1249
1295
  });
@@ -1260,7 +1306,7 @@ templateOptions: {
1260
1306
  },
1261
1307
  ```
1262
1308
 
1263
- **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.
1309
+ **The files step:** between `beforeFilesRoutes` and `afterFilesRoutes`, 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.
1264
1310
 
1265
1311
  **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.
1266
1312
 
@@ -1320,7 +1366,7 @@ export default defineExtension((app, options, { isCollectionAvailable, staticRes
1320
1366
  - `isCollectionAvailable()`, `serveRequest()`, `serveFallback()`, and `resolveCollection()`.
1321
1367
  - 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.
1322
1368
 
1323
- 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()`, `loadAssetVariant()`, `handlePreconditions()`, and `findAcceptEncodingsGroups()`). Use `staticResponse()` and `fallbackResponse()` in their place.
1369
+ 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.
1324
1370
 
1325
1371
  **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.
1326
1372
 
@@ -1339,7 +1385,7 @@ Do not call the `set…()` methods (`setActiveCollectionName()`, `setCollectionS
1339
1385
 
1340
1386
  **Examples** in [`examples/hono/`](https://github.com/fastly/compute-js-static-publish/tree/beta/8.1/examples/hono) show complete extensions. They are not part of the npm package, and you cannot scaffold an app with them: for a new project, copy the `hono-extensions/` folder of an example into your project, and set it up as the README of the example shows. The README also shows how to add an example to a project that exists.
1341
1387
 
1342
- - [`grip`](https://github.com/fastly/compute-js-static-publish/tree/beta/8.1/examples/hono/grip): realtime streams and Server-Sent Events with Fastly Fanout, and a publish endpoint with a shared key. One module with two phases: the `middleware` phase hands off only `/events/*` to Fanout, and the `beforeFiles` phase has the endpoints.
1388
+ - [`grip`](https://github.com/fastly/compute-js-static-publish/tree/beta/8.1/examples/hono/grip): realtime streams and Server-Sent Events with Fastly Fanout, and a publish endpoint with a shared key. One module with two phases: the `middleware` phase hands off only `/events/*` to Fanout, and the `beforeFilesRoutes` phase has the endpoints.
1343
1389
  - [`oauth`](https://github.com/fastly/compute-js-static-publish/tree/beta/8.1/examples/hono/oauth): a login with GitHub or Google in front of some paths of the site (`protect`), with a signed session cookie.
1344
1390
 
1345
1391
  Each example takes its secrets from a Secret Store. For `dev`, `managed.fastlyToml` adds a local Secret Store that reads environment variables.
package/MIGRATING.md CHANGED
@@ -105,8 +105,8 @@ my-site/
105
105
  Managed mode generates `src/index.js` again for each build, so your changes to it would be lost. With the `hono`
106
106
  template, you can keep your code in Hono extensions: modules in the folder `hono-extensions/`, beside the project file.
107
107
  The build bundles them into the app. Code that ran before `serveRequest()`, for example a redirect of an old host name,
108
- a login check, or a proxy to another service, goes into a `middleware` or `beforeFiles` phase. Code that ran when no
109
- file matched, for example a special page for a path, goes into an `afterFiles` phase. Each module gets its own options,
108
+ a login check, or a proxy to another service, goes into a `middleware` or `beforeFilesRoutes` phase. Code that ran when no
109
+ file matched, for example a special page for a path, goes into an `afterFilesRoutes` phase. Each module gets its own options,
110
110
  and declares the Fastly resources that it uses (bindings).
111
111
 
112
112
  1. In step 2, add `template: "hono"` to `managed`.
@@ -23,7 +23,7 @@ export type ExtensionEnv<B extends ExtensionBindings> = {
23
23
  };
24
24
  Variables: Record<string, any>;
25
25
  };
26
- export declare const EXTENSION_PHASES: readonly ['middleware', 'beforeFiles', 'afterFiles'];
26
+ export declare const EXTENSION_PHASES: readonly ['middleware', 'beforeFilesRoutes', 'afterFilesRoutes'];
27
27
  export type ExtensionPhase = typeof EXTENSION_PHASES[number];
28
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;
@@ -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,EAAE,OAAO,CAAC;IACjB,MAAM,EAAE,MAAM,CAAC;IACf,WAAW,EAAE,WAAW,CAAC;CAC1B,CAAC;AAKF,MAAM,MAAM,eAAe,CAAC,CAAC,IAC3B,CAAC,SAAS,GAAG,MAAM,CAAC,IAAI,MAAM,EAAE,GAAG,CAAC,CAAC,SAAS,MAAM,aAAa,GAAG,aAAa,CAAC,CAAC,CAAC,GAAG,SAAS,GAAG,OAAO,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GAAG,SAAS,CAAC;AAwBzL,wBAAgB,aAAa,CAAC,WAAW,EAAE,iBAAiB,GAAG,SAAS,EAAE,OAAO,EAAE,cAAc,EAAE,GAAG,iBAAiB,CAoDtH"}
@@ -2,12 +2,23 @@
2
2
  * Copyright Fastly, Inc.
3
3
  * Licensed under the MIT license. See LICENSE file for details.
4
4
  */
5
- // The phases of the app, in the order that the app runs them:
6
- // - middleware: before all other phases, for example a login check.
7
- // - beforeFiles: before the published files.
8
- // - afterFiles: after the published files, only for the requests that no
9
- // published file matches.
10
- export const EXTENSION_PHASES = ['middleware', 'beforeFiles', 'afterFiles'];
5
+ // The phases of the app, in the order that the app adds them. They are on two
6
+ // axes:
7
+ // - Processing: middleware wraps each request, for example a login check, or
8
+ // the time of a request. The code before await next() runs before the routes,
9
+ // and the code after it runs after the response is made, in the reverse order.
10
+ // - Routing: the routes that can answer a request, in this order:
11
+ // - beforeFilesRoutes: before the published files. These routes win over a file.
12
+ // - (the published files, with serveStatic())
13
+ // - afterFilesRoutes: only for the requests that no published file matches,
14
+ // before the fallback (the SPA file or the 404 page).
15
+ export const EXTENSION_PHASES = ['middleware', 'beforeFilesRoutes', 'afterFilesRoutes'];
16
+ // The names of the phases in earlier betas of 8.1, and the phase that has
17
+ // each one now. mergeBindings() names the new phase in its error.
18
+ const RENAMED_PHASES = {
19
+ beforeFiles: 'beforeFilesRoutes',
20
+ afterFiles: 'afterFilesRoutes',
21
+ };
11
22
  export function defineExtension(optionsOrPhases, phases) {
12
23
  const [options, value] = phases === undefined ?
13
24
  [{}, optionsOrPhases] :
@@ -57,7 +68,11 @@ export function mergeBindings(appBindings, entries) {
57
68
  throw new Error(`${source}: defineExtension() needs a function, or an object with a function ` +
58
69
  `for one or more of the phases ${EXTENSION_PHASES.join(', ')}.` +
59
70
  (unknown.length === 1 ? ` '${unknown[0]}' is not a phase.` : '') +
60
- (unknown.length > 1 ? ` ${unknown.map(x => `'${x}'`).join(', ')} are not phases.` : ''));
71
+ (unknown.length > 1 ? ` ${unknown.map(x => `'${x}'`).join(', ')} are not phases.` : '') +
72
+ unknown
73
+ .filter(x => Object.prototype.hasOwnProperty.call(RENAMED_PHASES, x))
74
+ .map(x => ` Rename '${x}' to '${RENAMED_PHASES[x]}'.`)
75
+ .join(''));
61
76
  }
62
77
  for (const key of keys) {
63
78
  if (typeof phases[key] !== 'function') {
@@ -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,iBAAiB,EAAE,KAAK,eAAe,EAAE,MAAM,oBAAoB,CAAC;AACnG,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,CAAC;AAKtD,MAAM,MAAM,kBAAkB,GAAG,sBAAsB,CAAC,OAA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AiC,GAAG;IAC9C,cAAc,CAAC,EAAE,oBAAoB,CAAC;IACtC,SAAS,CAAC,EAAE,eAAe,CAAC;CAC7B,CAAC;AAEF,MAAM,MAAM,yBAAyB,GAAG;IACtC,eAAe,EAAE,eAAe,CAAC;IAIjC,WAAW,EAAE,CAAC,OAAO,CAAC,EAAE,kBAAkB,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,7 +55,7 @@ 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,
@@ -39,7 +63,8 @@ export function fromPublisherServer(server, defaults = {}) {
39
63
  onMissing: options.onMissing,
40
64
  status: options.status,
41
65
  headers: options.headers,
42
- });
66
+ };
67
+ return serveWithFill(c, () => server.serveRequestStreaming(c.req.raw, serveOptions), () => server.serveRequest(c.req.raw, serveOptions));
43
68
  };
44
69
  const serveStatic = (callOptions = {}) => {
45
70
  return async (c, next) => {
@@ -53,12 +78,13 @@ export function fromPublisherServer(server, defaults = {}) {
53
78
  };
54
79
  const fallbackResponse = async (c, callOptions = {}) => {
55
80
  const options = { ...defaults, ...callOptions };
56
- return server.serveFallback(c.req.raw, {
81
+ const serveOptions = {
57
82
  collectionName: resolveCollectionName(c, options.collectionName, getSelection(c, server)),
58
83
  onMissing: options.onMissing,
59
84
  status: options.status,
60
85
  headers: options.headers,
61
- });
86
+ };
87
+ return serveWithFill(c, () => server.serveFallbackStreaming(c.req.raw, serveOptions), () => server.serveFallback(c.req.raw, serveOptions));
62
88
  };
63
89
  const serveFallback = (callOptions = {}) => {
64
90
  return async (c) => {
@@ -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 ResponseOverrides, 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,EAAE,MAAM,4CAA4C,CAAC;AACvF,OAAO,EAAE,KAAK,oBAAoB,EAAE,MAAM,4CAA4C,CAAC;AACvF,OAAO,KAAK,kBAAkB,MAAM,gCAAgC,CAAC;AACrE,OAAO,EACL,KAAK,uBAAuB,EAC5B,iBAAiB,GAClB,MAAM,iCAAiC,CAAC;AACzC,OAAO,EACL,KAAK,mBAAmB,EACxB,KAAK,yBAAyB,EAC9B,UAAU,EACV,2BAA2B,GAC5B,MAAM,0CAA0C,CAAC;AAClD,OAAO,EACL,wBAAwB,EACxB,KAAK,4BAA4B,GAClC,MAAM,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,iBAAiB,EACtB,KAAK,oBAAoB,EACzB,KAAK,mBAAmB,EACxB,eAAe,GAChB,MAAM,6BAA6B,CAAC"}
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,EAAE,MAAM,4CAA4C,CAAC;AACvF,OAAO,EAAE,KAAK,oBAAoB,EAAE,MAAM,4CAA4C,CAAC;AACvF,OAAO,KAAK,kBAAkB,MAAM,gCAAgC,CAAC;AACrE,OAAO,EACL,KAAK,uBAAuB,EAC5B,iBAAiB,GAClB,MAAM,iCAAiC,CAAC;AACzC,OAAO,EACL,KAAK,mBAAmB,EACxB,KAAK,yBAAyB,EAC9B,UAAU,EACV,2BAA2B,GAC5B,MAAM,0CAA0C,CAAC;AAClD,OAAO,EACL,wBAAwB,EACxB,KAAK,4BAA4B,GAClC,MAAM,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"}
@@ -35,6 +35,14 @@ export type ResponseOverrides = {
35
35
  status?: number;
36
36
  headers?: HeadersInit;
37
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>;
45
+ };
38
46
  export declare class PublisherServer {
39
47
  constructor(publishId: string, storageProvider: StorageProvider, defaultCollectionName: string);
40
48
  static fromStaticPublishRc(config: StaticPublishRc): PublisherServer;
@@ -95,11 +103,17 @@ export declare class PublisherServer {
95
103
  private findAssetVariantForAcceptEncodingsGroups;
96
104
  serveAsset(request: Request, asset: AssetEntry, init?: AssetInit): Promise<Response>;
97
105
  private serveAssetFor;
98
- 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>;
99
108
  private serveCachedFor;
109
+ private streamFill;
100
110
  private responseFromCache;
101
111
  serveRequest(request: Request, options?: ServeRequestOptions): Promise<Response | null>;
112
+ serveRequestStreaming(request: Request, options?: ServeRequestOptions): Promise<StreamingServeResult>;
113
+ private serveRequestWith;
102
114
  serveFallback(request: Request, options?: ServeFallbackOptions): Promise<Response | null>;
115
+ serveFallbackStreaming(request: Request, options?: ServeFallbackOptions): Promise<StreamingServeResult>;
116
+ private serveFallbackWith;
103
117
  isCollectionAvailable(request: Request, collectionName: string | null): Promise<boolean>;
104
118
  private isCollectionAvailableFor;
105
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,KA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,MAAM,EACf,OAAO,EAAE,CAAC,OAAO,EAAE,OAAO,KAAK,OAAO,CAAC,aAAa,CAAC,GACpD,OAAO,CAAC,oBAAoB,CAAC,CAE/B;YAEa,cAAc;YAoJd,UAAU;IA2BxB,OAAO,CAAC,iBAAiB;IAkCnB,YAAY,CAAC,OAAO,EAAE,OAAO,EAAE,OAAO,GAAE,mBAAwB,GAAG,OAAO,CAAC,QAAQ,GAAG,IAAI,CAAC,CAEhG;IAIK,qBAAqB,CAAC,OAAO,EAAE,OAAO,EAAE,OAAO,GAAE,mBAAwB,GAAG,OAAO,CAAC,oBAAoB,CAAC,CAE9G;YAEa,gBAAgB;IAoDxB,aAAa,CAAC,OAAO,EAAE,OAAO,EAAE,OAAO,GAAE,oBAAyB,GAAG,OAAO,CAAC,QAAQ,GAAG,IAAI,CAAC,CAElG;IAIK,sBAAsB,CAAC,OAAO,EAAE,OAAO,EAAE,OAAO,GAAE,oBAAyB,GAAG,OAAO,CAAC,oBAAoB,CAAC,CAEhH;YAEa,iBAAiB;IA2CzB,qBAAqB,CAAC,OAAO,EAAE,OAAO,EAAE,cAAc,EAAE,MAAM,GAAG,IAAI,GAAG,OAAO,CAAC,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) {
@@ -72,6 +73,37 @@ function applyResponseOverrides(response, overrides) {
72
73
  headers,
73
74
  });
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
+ }
75
107
  // The response for a collection other than the default collection that is not
76
108
  // published, or that expired. It can be published at any time, so no cache
77
109
  // stores this response.
@@ -195,7 +227,6 @@ export class PublisherServer {
195
227
  serverTiming,
196
228
  settings: undefined,
197
229
  assetEntryMap: undefined,
198
- doNotStoreResponse: false,
199
230
  };
200
231
  }
201
232
  // The scope of a request for a collection. A new request gets a new scope.
@@ -547,10 +578,12 @@ export class PublisherServer {
547
578
  // look complete. An empty body throws here, and any other mismatch causes an
548
579
  // error in the body stream, so that the client gets an incomplete response.
549
580
  const body = await checkBodyLength(assetVariant.storageEntry.body, assetVariant.size, `File ${asset.key} (${assetVariant.contentEncoding ?? 'identity'})`);
550
- return new Response(body, {
581
+ const response = new Response(body, {
551
582
  status,
552
583
  headers,
553
584
  });
585
+ assetResponseLengths.set(response, assetVariant.size);
586
+ return response;
554
587
  }
555
588
  // Serve a response through the response cache (see setResponseCache()).
556
589
  // keyPath identifies the response in the active collection. Include in it
@@ -559,12 +592,25 @@ export class PublisherServer {
559
592
  // range headers, and its result is cached if it is a 200 or 404 response, or
560
593
  // null (not found). Conditional requests and HEAD are then answered from the
561
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.
562
597
  async serveCached(request, keyPath, produce) {
563
- return this.serveCachedFor(this.currentScope, request, keyPath, produce);
564
- }
565
- 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
+ };
566
612
  if (this.responseCache == null) {
567
- return produce(request);
613
+ return produceResponse(request);
568
614
  }
569
615
  const key = buildResponseCacheKey(this.publishId, scope.collectionName, keyPath, request);
570
616
  const lookupStart = performance.now();
@@ -574,30 +620,31 @@ export class PublisherServer {
574
620
  const metadata = state.found() && state.usable() ? decodeCachedResponseMetadata(entry.userMetadata()) : null;
575
621
  if (metadata?.tooLarge) {
576
622
  scope.serverTiming?.add('cache', performance.now() - lookupStart, 'bypass');
577
- return produce(request);
623
+ return produceResponse(request);
578
624
  }
579
625
  if (metadata != null) {
580
626
  // age() is in milliseconds. A hit younger than the time since a purge proves the entry was refilled.
581
627
  scope.serverTiming?.add('cache', performance.now() - lookupStart, `hit age=${Math.round(entry.age() / 1000)}s`);
582
- return this.responseFromCache(scope, request, metadata, entry.body());
628
+ return { response: this.responseFromCache(scope, request, metadata, entry.body()), fillPromise: FILL_DONE };
583
629
  }
584
630
  // Not usable, and another request is not filling it for us: serve without the cache.
585
631
  scope.serverTiming?.add('cache', performance.now() - lookupStart, 'bypass');
586
- return produce(request);
632
+ return produceResponse(request);
587
633
  }
588
634
  // This request must fill the entry (a miss, or a stale entry after a soft purge).
589
635
  scope.serverTiming?.add('cache', performance.now() - lookupStart, 'miss');
590
636
  let response;
637
+ let length;
591
638
  try {
592
- response = await produce(buildCacheFillRequest(request));
639
+ ({ response, length } = readProduceResult(await produce(buildCacheFillRequest(request))));
593
640
  }
594
641
  catch (err) {
595
642
  entry.cancel();
596
643
  throw err;
597
644
  }
598
- if (scope.doNotStoreResponse) {
645
+ if (length === null) {
599
646
  entry.cancel();
600
- return response;
647
+ return { response, fillPromise: FILL_DONE };
601
648
  }
602
649
  const insertOptions = {
603
650
  // The Core Cache takes maxAge in milliseconds. ResponseCacheOptions.maxAge is in seconds.
@@ -612,16 +659,34 @@ export class PublisherServer {
612
659
  length: 0,
613
660
  });
614
661
  writer.close();
615
- return null;
662
+ return { response: null, fillPromise: FILL_DONE };
616
663
  }
617
664
  if (!CACHEABLE_STATUSES.includes(response.status)) {
618
665
  entry.cancel();
619
- return response;
666
+ return { response, fillPromise: FILL_DONE };
620
667
  }
621
668
  const headers = new Headers(response.headers);
622
669
  // Server-Timing describes one request, so it is not stored.
623
670
  headers.delete('Server-Timing');
624
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
+ }
625
690
  // Read the whole body before the insertion starts. After it starts, a body
626
691
  // that is not complete is not safe: the requests that read the entry get
627
692
  // a short body that ends as if it is complete. If the read fails (for example,
@@ -629,7 +694,7 @@ export class PublisherServer {
629
694
  // cancel() stores nothing, and the next request fills the entry again.
630
695
  let readResult;
631
696
  try {
632
- readResult = await readBodyUpTo(response.body, this.responseCache.maxBodySize ?? DEFAULT_MAX_BODY_SIZE);
697
+ readResult = await readBodyUpTo(response.body, maxBodySize);
633
698
  }
634
699
  catch (err) {
635
700
  entry.cancel();
@@ -645,7 +710,12 @@ export class PublisherServer {
645
710
  length: 0,
646
711
  });
647
712
  writer.close();
648
- 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.`);
649
719
  }
650
720
  const writer = entry.insert({
651
721
  ...insertOptions,
@@ -658,7 +728,33 @@ export class PublisherServer {
658
728
  writer.append(piece);
659
729
  }
660
730
  writer.close();
661
- 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
+ }
662
758
  }
663
759
  responseFromCache(scope, request, metadata, body) {
664
760
  if (metadata.notFound) {
@@ -686,10 +782,18 @@ export class PublisherServer {
686
782
  // file or the 404 page (see options.fallback). Returns null if there is no
687
783
  // response for the request, for example for a method other than GET and HEAD.
688
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) {
689
793
  let scope = this.beginRequestFor(request, options.collectionName);
690
794
  // Only handle GET and HEAD
691
795
  if (request.method !== 'GET' && request.method !== 'HEAD') {
692
- return null;
796
+ return { response: null, fillPromise: FILL_DONE };
693
797
  }
694
798
  let pathname;
695
799
  if (options.pathname != null) {
@@ -703,48 +807,64 @@ export class PublisherServer {
703
807
  }
704
808
  // Custom health check route
705
809
  if (options.healthCheck !== false && pathname === '/healthz') {
706
- return new Response("OK", { status: 200 });
810
+ return { response: new Response("OK", { status: 200 }), fillPromise: FILL_DONE };
707
811
  }
708
812
  const selected = await this.checkSelectedCollection(request, scope, options.onMissing);
709
813
  if (selected instanceof Response) {
710
- return selected;
814
+ return { response: selected, fillPromise: FILL_DONE };
711
815
  }
712
816
  scope = selected.scope;
713
817
  // The fallback pages (SPA, not found) depend on whether the client accepts HTML.
714
818
  // With fallback: false, the response does not depend on HTML, so it has its own cache key.
715
819
  const fallback = options.fallback !== false && requestAcceptsTextHtml(request);
716
820
  const keyPath = fallback ? pathname : `${pathname}|no-html`;
717
- const response = applyResponseOverrides(await this.serveCachedFor(scope, requestForStatus(request, options.status), keyPath, (fillRequest) => this.serveRequestFromStorage(scope, fillRequest, pathname, fallback)), options);
718
- 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
+ };
719
827
  }
720
828
  // Serve the SPA file or the 404 page, as serveRequest() does when no file
721
829
  // matches. Use it after serveRequest() with fallback: false. Returns null for
722
830
  // a method other than GET and HEAD, if the client does not accept HTML, or if
723
831
  // the collection has no fallback page.
724
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) {
725
841
  let scope = this.beginRequestFor(request, options.collectionName);
726
842
  // Only handle GET and HEAD
727
843
  if (request.method !== 'GET' && request.method !== 'HEAD') {
728
- return null;
844
+ return { response: null, fillPromise: FILL_DONE };
729
845
  }
730
846
  if (!requestAcceptsTextHtml(request)) {
731
- return null;
847
+ return { response: null, fillPromise: FILL_DONE };
732
848
  }
733
849
  const selected = await this.checkSelectedCollection(request, scope, options.onMissing);
734
850
  if (selected instanceof Response) {
735
- return selected;
851
+ return { response: selected, fillPromise: FILL_DONE };
736
852
  }
737
853
  scope = selected.scope;
738
854
  // The fallback response is the same for all paths, so it has one cache key.
739
855
  // A path always starts with a slash, so this key is not the key of a path.
740
- const response = applyResponseOverrides(await this.serveCachedFor(scope, requestForStatus(request, options.status), '|fallback', async (fillRequest) => {
856
+ const served = await this.serveCachedFor(scope, requestForStatus(request, options.status), '|fallback', async (fillRequest) => {
741
857
  const serverConfig = await this.getServerConfigFor(scope);
742
858
  if (serverConfig == null) {
743
859
  return null;
744
860
  }
745
861
  return this.serveFallbackFromStorage(scope, fillRequest, serverConfig);
746
- }), options);
747
- 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
+ };
748
868
  }
749
869
  // Returns true if the collection is published, has not expired, and can
750
870
  // be served by this version. It reads the settings and the index into the scope.
@@ -826,8 +946,7 @@ export class PublisherServer {
826
946
  // response cache does not store this response.
827
947
  if (serverConfig == null ||
828
948
  (scope.collectionName !== this.defaultCollectionName && await this.getAssetEntryMapFor(scope) == null)) {
829
- scope.doNotStoreResponse = true;
830
- return collectionNotAvailableResponse(scope.collectionName);
949
+ return { response: collectionNotAvailableResponse(scope.collectionName), length: null };
831
950
  }
832
951
  const asset = await this.getMatchingAssetFor(scope, serverConfig.publicDirPrefix + pathname, true, false);
833
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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C,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.6",
4
+ "version": "8.1.0-beta.8",
5
5
  "description": "Static Publisher for Fastly Compute JavaScript",
6
6
  "main": "build/server/server/index.js",
7
7
  "exports": {
@@ -4,8 +4,8 @@
4
4
  // the project file (or in static-publish.rc.js).
5
5
  //
6
6
  // defineExtension() gets a function for each phase that the module uses. The
7
- // app runs the middleware phase of all modules, then their beforeFiles phase,
8
- // then the published files, then their afterFiles phase. With only a function
7
+ // app runs the middleware phase of all modules, then their beforeFilesRoutes phase,
8
+ // then the published files, then their afterFilesRoutes phase. With only a function
9
9
  // in place of the object, the function is the middleware phase.
10
10
  import { defineExtension } from '@fastly/compute-js-static-publish/hono';
11
11
 
@@ -16,7 +16,7 @@ export default defineExtension({
16
16
  c.header(options?.header ?? 'x-example', 'from an extension');
17
17
  });
18
18
  },
19
- beforeFiles: (app) => {
19
+ beforeFilesRoutes: (app) => {
20
20
  app.get('/api/example', (c) => c.json({ hello: 'from an extension' }));
21
21
  },
22
22
  });
@@ -1243,9 +1243,9 @@
1243
1243
  }
1244
1244
  },
1245
1245
  "node_modules/@fastly/js-compute": {
1246
- "version": "4.0.1",
1247
- "resolved": "https://registry.npmjs.org/@fastly/js-compute/-/js-compute-4.0.1.tgz",
1248
- "integrity": "sha512-G5O9NxPaqbFBTjgMPXdyMI6NktUhFipEO8HLavRmF7QZ5cqlFfcdVfD4Fm13s8B5t2IrVROq0oNWueJyfxuFSQ==",
1246
+ "version": "4.3.0",
1247
+ "resolved": "https://registry.npmjs.org/@fastly/js-compute/-/js-compute-4.3.0.tgz",
1248
+ "integrity": "sha512-JaxynSbhhHIvfltdopeAv4Uw89t7J4Yxf/ImNzttUPs/9vV3nQXlLGyLuQddtp0SEHqW/x5MfTzmDp5J1UKyZw==",
1249
1249
  "bundleDependencies": [
1250
1250
  "@fastly/wasmtime"
1251
1251
  ],
@@ -38,8 +38,8 @@ app.use('*', logFastlyServiceVersion());
38
38
  app.use('*', selectCollection());
39
39
 
40
40
  // The extensions, in file-name order: first the middleware phase of all of
41
- // them, then the beforeFiles phase.
42
- for (const phase of [ 'middleware', 'beforeFiles' ] as const) {
41
+ // them, then the beforeFilesRoutes phase.
42
+ for (const phase of [ 'middleware', 'beforeFilesRoutes' ] as const) {
43
43
  for (const e of extensions) {
44
44
  e.module.phases[phase]?.(app, honoOptions?.extensions?.[e.name], helpers);
45
45
  }
@@ -51,10 +51,10 @@ for (const phase of [ 'middleware', 'beforeFiles' ] as const) {
51
51
  // Serve the published files. If no file matches, the request goes to the next handler.
52
52
  app.use('*', serveStatic());
53
53
 
54
- // The afterFiles phase of the extensions: only for the requests that no
54
+ // The afterFilesRoutes phase of the extensions: only for the requests that no
55
55
  // published file matches.
56
56
  for (const e of extensions) {
57
- e.module.phases.afterFiles?.(app, honoOptions?.extensions?.[e.name], helpers);
57
+ e.module.phases.afterFilesRoutes?.(app, honoOptions?.extensions?.[e.name], helpers);
58
58
  }
59
59
 
60
60
  // When nothing matches, serve the SPA file or the 404 page.
@@ -1217,9 +1217,9 @@
1217
1217
  }
1218
1218
  },
1219
1219
  "node_modules/@fastly/js-compute": {
1220
- "version": "4.0.1",
1221
- "resolved": "https://registry.npmjs.org/@fastly/js-compute/-/js-compute-4.0.1.tgz",
1222
- "integrity": "sha512-G5O9NxPaqbFBTjgMPXdyMI6NktUhFipEO8HLavRmF7QZ5cqlFfcdVfD4Fm13s8B5t2IrVROq0oNWueJyfxuFSQ==",
1220
+ "version": "4.3.0",
1221
+ "resolved": "https://registry.npmjs.org/@fastly/js-compute/-/js-compute-4.3.0.tgz",
1222
+ "integrity": "sha512-JaxynSbhhHIvfltdopeAv4Uw89t7J4Yxf/ImNzttUPs/9vV3nQXlLGyLuQddtp0SEHqW/x5MfTzmDp5J1UKyZw==",
1223
1223
  "bundleDependencies": [
1224
1224
  "@fastly/wasmtime"
1225
1225
  ],
@@ -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
  }