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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (31) hide show
  1. package/CHANGELOG.md +7 -6
  2. package/DOCUMENTATION.md +37 -5
  3. package/MIGRATING.md +289 -0
  4. package/build/cli/cli/commands/manage/deploy.d.ts.map +1 -1
  5. package/build/cli/cli/commands/manage/deploy.js +5 -4
  6. package/build/cli/cli/commands/manage/index.d.ts +1 -0
  7. package/build/cli/cli/commands/manage/index.d.ts.map +1 -1
  8. package/build/cli/cli/commands/manage/index.js +13 -11
  9. package/build/cli/cli/commands/manage/status.d.ts.map +1 -1
  10. package/build/cli/cli/commands/manage/status.js +7 -5
  11. package/build/cli/cli/index.js +15 -1
  12. package/build/cli/cli/managed/fastly-service.d.ts +7 -0
  13. package/build/cli/cli/managed/fastly-service.d.ts.map +1 -1
  14. package/build/cli/cli/managed/fastly-service.js +31 -1
  15. package/build/cli/cli/managed/fingerprint.d.ts +12 -0
  16. package/build/cli/cli/managed/fingerprint.d.ts.map +1 -1
  17. package/build/cli/cli/managed/fingerprint.js +25 -0
  18. package/build/cli/cli/util/config.d.ts +4 -0
  19. package/build/cli/cli/util/config.d.ts.map +1 -1
  20. package/build/cli/cli/util/config.js +33 -0
  21. package/build/cli/cli/util/output.js +1 -1
  22. package/build/server/hono/extensions.d.ts +3 -1
  23. package/build/server/hono/extensions.d.ts.map +1 -1
  24. package/build/server/hono/index.d.ts +6 -1
  25. package/build/server/hono/index.d.ts.map +1 -1
  26. package/build/server/hono/index.js +21 -13
  27. package/build/server/server/publisher-server/index.d.ts +2 -0
  28. package/build/server/server/publisher-server/index.d.ts.map +1 -1
  29. package/build/server/server/publisher-server/index.js +4 -4
  30. package/package.json +3 -2
  31. package/resources/templates/hono/src/index.ts +6 -3
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). `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()`, 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), `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), `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.
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`).
@@ -35,14 +35,14 @@ This file does not list v7 releases after 7.0.8, or v6 releases after 6.3.0. For
35
35
  - In the index, the key of a hidden file is `hidden:` and then the asset key. A collection that has hidden files requires the `hidden` feature, so an app built with 8.0.0 or later (before 8.1) does not serve it. An app built with v7 or with an 8.0 beta does not check `requires`: it serves the collection, but not its hidden files, also when the SPA file or the 404 page is hidden. Build and deploy your app with this version before you publish hidden files.
36
36
  - `publish-content` shows the number of hidden files. `collections list` shows the number of files and of hidden files in each collection, from the index metadata (`fileCount`, `hiddenFileCount`, which `publish-content` writes). For a collection published by an older version, it shows "unknown".
37
37
  - `getMatchingAsset(key, options)`: the second argument can now be an object, `{ applyAuto, includeHidden }`. A boolean (the value of `applyAuto`) continues to work.
38
- - `PublisherServer.serveRequest(request, options)`: the options `collectionName` (the collection for this call only), `pathname` (the path to look up, in place of the URL path), `fallback` (`false`: do not serve the SPA file or the 404 page), and `healthCheck` (`false`: do not answer `/healthz`). Without options, the behavior does not change.
39
- - `PublisherServer.serveFallback(request, { collectionName })`: serves the SPA file or the 404 page, as `serveRequest()` does when no file matches. Use it after `serveRequest()` with `fallback: false`.
38
+ - `PublisherServer.serveRequest(request, options)`: the options `collectionName` (the collection for this call only), `pathname` (the path to look up, in place of the URL path), `fallback` (`false`: do not serve the SPA file or the 404 page), `healthCheck` (`false`: do not answer `/healthz`), and `onMissing` (with collection selection: `'not-found'` or `'default'` for this call, in place of `collectionSelection.onMissing`). Without options, the behavior does not change.
39
+ - `PublisherServer.serveFallback(request, { collectionName, onMissing })`: serves the SPA file or the 404 page, as `serveRequest()` does when no file matches. Use it after `serveRequest()` with `fallback: false`.
40
40
  - Export the types `ServeRequestOptions` and `ServeFallbackOptions`.
41
41
  - Managed projects: `scaffold --managed` writes only `static-publish.project.js` in the current directory, and adds `.static-publish/` and the working directory to `.gitignore`. The project file has the fields of `static-publish.rc.js` at the top level, the fields of `publish-content.config.js` in `publishContent`, and the settings of the generated app in `managed`. `publish-content`, `collections`, and `clean` read it. A directory with both `static-publish.project.js` and `static-publish.rc.js` is an error. The type is `StaticPublishProject`.
42
42
  - Managed projects: `managed.fastlyToml` adds `local_server` and `setup` sections to the generated `fastly.toml`, for example a local Secret Store for `dev`. A resource with the name of one that the CLI writes is an error. `local_server` does not change the fingerprint.
43
43
  - `publish-content` purges the service of `managed.serviceId` in a managed project (after `--fastly-service-id` and `FASTLY_SERVICE_ID`, before `fastly.toml`).
44
44
  - Managed projects: the `dev` command generates the app in `.static-publish/app/`, installs it with `npm ci` only when its `package.json` or lockfile changed, and runs `fastly compute serve`. The app uses the lockfile of its template (`resources/templates/<name>/package-lock.json`), and the copy of this package that runs the CLI through a `file:` link.
45
- - Managed projects: `deploy` deploys the generated app only if its fingerprint changed (`--force` deploys anyway), records the fingerprint in the comment of the service version, and writes the Service ID of the first deploy (a new service) into `managed.serviceId`. A Service ID from `--fastly-service-id` or `FASTLY_SERVICE_ID` does not change the project file. `status` shows if a deploy is necessary, and the preview URLs. `dev` and `deploy` stop if `managed.staticPublishVersion` is not the version that runs; `upgrade` (or `--auto-upgrade` with a newer CLI) moves the project to it. In an ejected app, `deploy` runs `fastly compute publish`, with `--comment`, `--fastly-service-id`, and `--fastly-api-token` (`--force` and `--auto-upgrade` are errors there), and `status` shows the Service ID. Options after `--` go to `fastly compute deploy` (or `fastly compute publish`), for example `-- --status-check-timeout=180`. `deploy` refuses `--comment`, `--service-id`, `--token`, `--package`, `--dir`, and `--env` there.
45
+ - Managed projects: `deploy` deploys the generated app only if its fingerprint changed (`--force` deploys anyway), records the fingerprint in the comment of the service version, and writes the Service ID of the first deploy (a new service) into `managed.serviceId`. A Service ID from `--fastly-service-id` or `FASTLY_SERVICE_ID` does not change the project file. A version cloned by hand (no comment, the same package as the newest earlier version with a fingerprint) counts as that fingerprint. `status` shows if a deploy is necessary, and the preview URLs. `dev` and `deploy` stop if `managed.staticPublishVersion` is not the version that runs; `upgrade` (or `--auto-upgrade` with a newer CLI) moves the project to it. In an ejected app, `deploy` runs `fastly compute publish`, with `--comment`, `--fastly-service-id`, and `--fastly-api-token` (`--force` and `--auto-upgrade` are errors there), and `status` shows the Service ID. Options after `--` go to `fastly compute deploy` (or `fastly compute publish`), for example `-- --status-check-timeout=180`. `deploy` refuses `--comment`, `--service-id`, `--token`, `--package`, `--dir`, and `--env` there.
46
46
  - S3 mode: `s3.secretStoreLinkName` in `static-publish.rc.js` (in a managed project, in `static-publish.project.js`) sets the resource link name of the Secret Store with the S3 credentials. The default is `S3_CREDENTIALS`. The generated `fastly.toml` uses it. A call to `setSecretStoreForS3Credentials()` in the code of the app is used in place of it. The generated `fastly.toml` also uses `s3.fastlyBackendName` (the name of the backend, default `s3_storage`), and managed mode keeps both fields in the app.
47
47
  - Managed projects: `eject` converts a managed project into an ejected app in `./compute-js` (or `--dir`): the app that `deploy` would deploy, `static-publish.rc.js` (with `generatedFrom`) and `publish-content.config.js` from the project file (the paths point at the same directories), and this package pinned to the version that runs. It needs a published version, and it stops for functions or regular expressions in `publishContent`.
48
48
  - Docs: README "Managed and ejected apps", with the API token scopes for CI. `MIGRATING.md`: move an existing app to managed mode.
@@ -52,7 +52,8 @@ This file does not list v7 releases after 7.0.8, or v6 releases after 6.3.0. For
52
52
 
53
53
  ### Changed
54
54
 
55
- - The npm package includes `CHANGELOG.md`.
55
+ - The npm package includes `CHANGELOG.md` and `MIGRATING.md`.
56
+ - 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.
56
57
  - 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()`.
57
58
  - 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.
58
59
  - `PublisherServer.setResponseCache()`: the default of `maxBodySize` is now 16 MiB. It was 8 MiB.
package/DOCUMENTATION.md CHANGED
@@ -304,7 +304,7 @@ npx @fastly/compute-js-static-publish@beta deploy
304
304
 
305
305
  `deploy` generates the app, installs it if necessary, and runs `fastly compute build` and `fastly compute deploy`, only if the app changed. It needs a Fastly API token (`FASTLY_API_TOKEN` or `--fastly-api-token`). Options after `--` go to `fastly compute deploy`, for example `deploy -- --status-check-timeout=180`. `deploy` refuses `--comment`, `--service-id` (`-s`), `--token` (`-t`), `--package` (`-p`), `--dir` (`-C`), and `--env` there, because it sets them, or they deploy something else.
306
306
 
307
- - **The fingerprint** is a SHA-256 of the generated app and the version of this package. It does not depend on the content, on `publishContent`, on the Service ID, or on the path of this package on your computer. `deploy` writes it into the comment of the new service version (`static-publish <version> fp:<fingerprint>`, then ` | <text>` with `--comment <text>`, for example a commit SHA). The next `deploy` reads the comment of the active version, and does nothing if the fingerprint is the same. `--force` deploys anyway.
307
+ - **The fingerprint** is a SHA-256 of the generated app and the version of this package. It does not depend on the content, on `publishContent`, on the Service ID, or on the path of this package on your computer. `deploy` writes it into the comment of the new service version (`static-publish <version> fp:<fingerprint>`, then ` | <text>` with `--comment <text>`, for example a commit SHA). The next `deploy` reads the comment of the active version, and does nothing if the fingerprint is the same. A version that you clone by hand, for example to add a backend, has no comment, but it keeps the package of the version that it came from. Thus, if the active version has no fingerprint, `deploy` and `status` use the newest earlier version that has one, if the two versions have the same package. `--force` deploys anyway.
308
308
  - **The first deploy** makes a new service (the Fastly CLI asks for its name and domain, unless `--non-interactive`), and writes its ID into `managed.serviceId`. Commit the project file then. To deploy to a service that exists, use `--fastly-service-id` or `FASTLY_SERVICE_ID`. These do not change `managed.serviceId`: to make a service that exists the service of the project, set `managed.serviceId` in the project file. With S3 storage, the first deploy must be done on your computer, because the Fastly CLI asks for the S3 credentials of the Secret Store; with `--non-interactive`, it is an error.
309
309
  - `status` shows the fingerprint of the app, the fingerprint of the active version, and if a deploy is necessary, and the preview URLs of [collection selection](#-previews-collection-selection). Without an API token, the deployed fingerprint is unknown.
310
310
 
@@ -1060,10 +1060,11 @@ async function handleRequest(request) {
1060
1060
  | `pathname` | The path to look up, in place of the path of the request URL. It must be decoded, and it must start with `/`. | The decoded path of the request URL |
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
+ | `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` |
1063
1064
 
1064
1065
  `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.
1065
1066
 
1066
- `serveFallback(request, { collectionName })` 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:
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:
1067
1068
 
1068
1069
  ```js
1069
1070
  async function handleRequest(request) {
@@ -1212,7 +1213,7 @@ hono-extensions/
1212
1213
  - `beforeFiles`: before the published files.
1213
1214
  - `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.
1214
1215
 
1215
- A module default-exports `defineExtension()`. Give it a function for each phase that the module uses. Each function gets the Hono app and the options of the module, 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:
1216
+ 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:
1216
1217
 
1217
1218
  ```ts
1218
1219
  // hono-extensions/10-header.ts
@@ -1257,6 +1258,24 @@ templateOptions: {
1257
1258
  },
1258
1259
  ```
1259
1260
 
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):
1262
+
1263
+ ```ts
1264
+ // hono-extensions/10-theme.ts
1265
+ import { defineExtension } from '@fastly/compute-js-static-publish/hono';
1266
+
1267
+ export default defineExtension((app, options, { staticResponse }) => {
1268
+ app.use('/theme/*', async (c, next) => {
1269
+ if (c.var.staticPublisher.collectionName == null) {
1270
+ return next(); // not a preview: the published files of the app serve it
1271
+ }
1272
+ return await staticResponse(c, { onMissing: 'default' }) ?? c.text('Not found', 404);
1273
+ });
1274
+ });
1275
+ ```
1276
+
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.
1278
+
1260
1279
  **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.
1261
1280
 
1262
1281
  **Errors** in a module stop the build, and the message names the file: a default export that is not `defineExtension()`, an object with no phase, a key that is not a phase, or a phase that is not a function.
@@ -1319,6 +1338,7 @@ fire(app);
1319
1338
  `fromStaticPublishRc(rc)` returns:
1320
1339
 
1321
1340
  - `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
+ - `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.
1322
1342
  - `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.
1323
1343
  - `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.
1324
1344
  - `publisherServer`: the `PublisherServer`, to configure it. For example, `publisherServer.setResponseCache({ maxAge: 3600 })`.
@@ -1333,6 +1353,7 @@ If you make the `PublisherServer` yourself, use `fromPublisherServer(publisherSe
1333
1353
  | `path` | The path to serve, in place of the request path. For example, `./favicon.ico`. |
1334
1354
  | `rewriteRequestPath` | `(path, c) => string`. Changes the request path before it is resolved against `root`. |
1335
1355
  | `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
+ | `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`). |
1336
1357
 
1337
1358
  For example, to serve `/assets/*` from the `static` directory:
1338
1359
 
@@ -1340,7 +1361,18 @@ For example, to serve `/assets/*` from the `static` directory:
1340
1361
  app.use('/assets/*', serveStatic({ root: './static', rewriteRequestPath: (path) => path.replace(/^\/assets/, '') }));
1341
1362
  ```
1342
1363
 
1343
- `serveFallback()` takes the `collectionName` option, too. To give a default to all the middleware, pass it to `fromStaticPublishRc(rc, { collectionName })`. An option in a call replaces the default.
1364
+ `staticResponse()` is for a handler that decides itself whether to serve a file. For example, to serve `/theme/*` for a preview from the selected collection, or from the default collection if the preview is missing, and with a plain `404` and never the 404 page of the collection:
1365
+
1366
+ ```ts
1367
+ app.use('/theme/*', async (c, next) => {
1368
+ if (c.var.staticPublisher.collectionName == null) {
1369
+ return next(); // not a preview
1370
+ }
1371
+ return await staticResponse(c, { onMissing: 'default' }) ?? c.text('Not found', 404);
1372
+ });
1373
+ ```
1374
+
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.
1344
1376
 
1345
1377
  In TypeScript, use `StaticPublisherVariables` for the variables of the app, so that `c.var.staticPublisher` has a type:
1346
1378
 
@@ -1541,7 +1573,7 @@ In an ejected app, `status --json` gives `{ "schemaVersion": 1, "mode": "ejected
1541
1573
  | `config-invalid` | `2` | `static-publish.rc.js`, `static-publish.project.js`, or `publish-content.config.js` cannot be loaded, or is not valid |
1542
1574
  | `collection-name-invalid` | `2` | A collection name breaks the [rule](#-collections-publish-preview-promote) |
1543
1575
  | `collection-not-found` | `2` | The command needs a collection that does not exist |
1544
- | `project-dir-not-found` | `2` | `--project-dir` is not a directory, or has no config file |
1576
+ | `project-dir-not-found` | `2` | `--project-dir` is not a directory, or has no config file. Also a command for a project or an app (for example `status`) in a directory with no config file. |
1545
1577
  | `json-not-supported` | `2` | `--json` with a command that does not support it |
1546
1578
  | `credentials-missing` | `2` | An API token or S3 credentials are necessary, but not given |
1547
1579
  | `version-mismatch` | `2` | `managed.staticPublishVersion` is not the version of the CLI that runs |
package/MIGRATING.md ADDED
@@ -0,0 +1,289 @@
1
+ # Migration Guide
2
+
3
+ New major versions of `@fastly/compute-js-static-publish` can involve changes to the files that
4
+ are generated during scaffolding. For this reason, it is recommended that you re-scaffold your application.
5
+
6
+ This is straightforward if you're using `compute-js-static-publisher` out-of-the-box. Otherwise, read on.
7
+
8
+ > [!NOTE]
9
+ > This document is under construction.
10
+ >
11
+
12
+ ## Move an existing app to managed mode (8.1)
13
+
14
+ You do not have to do this. An ejected app (a `compute-js/` directory with `static-publish.rc.js`) continues to work.
15
+ In managed mode, this package generates the app from one file, `static-publish.project.js`, and you upgrade by
16
+ changing the version of this package. See "Managed and ejected apps" in `README.md`.
17
+
18
+ > [!IMPORTANT]
19
+ > Managed mode generates the app from a template: `plain` (the default) or `hono`. If you changed `src/index.js` (or
20
+ > other files of the app), move your changes into options of the project file, or into Hono extensions (see
21
+ > [An app with changes to `src/index.js`](#an-app-with-changes-to-srcindexjs)), or keep your app ejected.
22
+
23
+ These steps move a project with this layout. Change the paths to match your project:
24
+
25
+ ```
26
+ my-site/
27
+ ├── public/
28
+ └── compute-js/ ← static-publish.rc.js, publish-content.config.js, fastly.toml, ...
29
+ ```
30
+
31
+ 1. In `my-site/`, add this package as a dev dependency at 8.1.0 or later, so that the version is pinned:
32
+
33
+ ```sh
34
+ npm install --save-dev @fastly/compute-js-static-publish
35
+ ```
36
+
37
+ 2. Make `my-site/static-publish.project.js`. Paths in it are relative to `my-site/`:
38
+
39
+ ```js
40
+ /** @type {import('@fastly/compute-js-static-publish').StaticPublishProject} */
41
+ const project = {
42
+ // From compute-js/static-publish.rc.js: the storage fields (kvStore or s3), publishId,
43
+ // defaultCollectionName, and collectionSelection, if you have it. Do not copy generatedFrom.
44
+ storageMode: "kv-store",
45
+ kvStore: { kvStoreName: "site-content" },
46
+ publishId: "default",
47
+ defaultCollectionName: "live",
48
+ // A new working directory beside the project file.
49
+ staticPublisherWorkingDir: "./static-publisher",
50
+
51
+ // The contents of compute-js/publish-content.config.js, with rootDir relative to my-site/
52
+ // ('../public' becomes './public').
53
+ publishContent: {
54
+ rootDir: "./public",
55
+ server: { /* ... */ },
56
+ },
57
+
58
+ managed: {
59
+ // From compute-js/fastly.toml: name, description, authors, and service_id.
60
+ name: "my-site",
61
+ description: "My site",
62
+ authors: [ "me@example.com" ],
63
+ serviceId: "SERVICE_ID",
64
+ // The version of this package that you installed in step 1.
65
+ staticPublishVersion: "8.1.0",
66
+ },
67
+ };
68
+
69
+ export default project;
70
+ ```
71
+
72
+ If the app has no service yet, write the line ` serviceId: undefined,` (exactly), so that the first `deploy`
73
+ writes the Service ID into it.
74
+
75
+ 3. Add these lines to `my-site/.gitignore`:
76
+
77
+ ```
78
+ /.static-publish/
79
+ /static-publisher/
80
+ ```
81
+
82
+ 4. In `my-site/`, check the project, publish to the local KV Store, and run the app:
83
+
84
+ ```sh
85
+ npx compute-js-static-publish status
86
+ npx compute-js-static-publish publish-content --local
87
+ npx compute-js-static-publish dev
88
+ ```
89
+
90
+ The CLI uses only the files of the directory where it runs, so `compute-js/` has no effect here.
91
+
92
+ 5. Deploy. The first `deploy` deploys the generated app to the service of `managed.serviceId`, because the active
93
+ version has no fingerprint yet:
94
+
95
+ ```sh
96
+ FASTLY_API_TOKEN=... npx compute-js-static-publish deploy
97
+ ```
98
+
99
+ The collections in storage do not change. Publish again only to change the content.
100
+
101
+ 6. When the steps above work, take `compute-js/` out of the repo, and commit `static-publish.project.js`.
102
+
103
+ ### An app with changes to `src/index.js`
104
+
105
+ Managed mode generates `src/index.js` again for each build, so your changes to it would be lost. With the `hono`
106
+ template, you can keep your code in Hono extensions: modules in the folder `hono-extensions/`, beside the project file.
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,
110
+ and declares the Fastly resources that it uses (bindings).
111
+
112
+ 1. In step 2, add `template: "hono"` to `managed`.
113
+ 2. In `my-site/`, make the folder, and install its packages:
114
+
115
+ ```sh
116
+ npx compute-js-static-publish template init
117
+ cd hono-extensions
118
+ npm install
119
+ ```
120
+
121
+ 3. Move each part of your code into a module. See "Hono extensions" in `README.md` for the phases, the options, and
122
+ the bindings, and `examples/hono/` in the repository for two complete examples.
123
+ 4. Continue with step 3 above. `dev` and `deploy` build the app with your modules.
124
+
125
+ ## Move from `@fastly/hono-compute-js-static-publish` (8.1)
126
+
127
+ `@fastly/hono-compute-js-static-publish` supports v6 and v7 of this package. From 8.1, this package has Hono support itself, as `@fastly/compute-js-static-publish/hono`. First upgrade the app to v8 (see [Upgrade from v7 to v8](#upgrade-from-v7-to-v8)). Then:
128
+
129
+ 1. Remove the old package, and add the packages that a Hono app uses on Compute:
130
+
131
+ ```sh
132
+ npm uninstall @fastly/hono-compute-js-static-publish
133
+ npm install hono @fastly/hono-fastly-compute
134
+ ```
135
+
136
+ 2. Change the code. `fromStaticPublishRc()` now returns an object, not the `serveStatic` function:
137
+
138
+ ```js
139
+ // Before
140
+ import { fire } from 'hono/service-worker';
141
+ import { fromStaticPublishRc } from '@fastly/hono-compute-js-static-publish';
142
+ const serveStatic = fromStaticPublishRc(rc);
143
+
144
+ // After
145
+ import { fire } from '@fastly/hono-fastly-compute';
146
+ import { fromStaticPublishRc } from '@fastly/compute-js-static-publish/hono';
147
+ const { serveStatic, serveFallback } = fromStaticPublishRc(rc);
148
+ ```
149
+
150
+ Use `fire()` from `@fastly/hono-fastly-compute`, not from `hono/service-worker`. By default, the handler of `hono/service-worker` sends each 404 response to `fetch()`, and Compute has no default backend.
151
+
152
+ 3. Add `app.notFound(serveFallback())`. `serveStatic()` does not serve the SPA file or the 404 page.
153
+
154
+ 4. Change the types in the JSDoc of your config files to the main package, for example `import('@fastly/compute-js-static-publish').StaticPublishRc`. The `/hono` export does not have these types.
155
+
156
+ Differences of `serveStatic()`:
157
+
158
+ - It serves files with `PublisherServer.serveRequest()`. Thus it uses `autoIndex`, `autoExt`, the compressed variants, and the response cache. The old package looked up the request path in the index directly.
159
+ - It applies `publicDirPrefix` (deprecated). If it is set, `root` is relative to it.
160
+ - It serves only `GET` and `HEAD`. For other methods, it calls the next handler.
161
+ - For previews, use `selectCollection()` with `collectionSelection` in `static-publish.rc.js` (see [Using Hono](./README.md#-using-hono)).
162
+
163
+ ## Upgrade from v7 to v8
164
+
165
+ v8 can use the files that v7 published. The storage key layout did not change. v8 also accepts the v7 format of
166
+ `static-publish.rc.js` (`kvStoreName` at the top level). Thus, an app that uses the KV Store does not need a new
167
+ scaffold.
168
+
169
+ To upgrade an app that uses the KV Store:
170
+
171
+ 1. In the `compute-js/` directory of your app, install v8:
172
+
173
+ ```sh
174
+ npm install @fastly/compute-js-static-publish@beta
175
+ ```
176
+
177
+ 2. Make sure that the CLI can get a Fastly API token. Set the `FASTLY_API_TOKEN` environment variable, or use
178
+ `--fastly-api-token`. v8 no longer uses the token logged in by the Fastly CLI.
179
+
180
+ 3. Build and deploy your app again. The Wasm binary contains a copy of `static-publish.rc.js`, and the server code
181
+ changed.
182
+
183
+ 4. Publish your content again with `npm run publish-content`. This step is optional. v8 serves the content that v7
184
+ published.
185
+
186
+ ### Changes to examine
187
+
188
+ - **The CLI purges after it publishes.** In v8, `publish-content` purges the surrogate key `<publishId>-<collection>`
189
+ in KV Store mode too. It finds the Service ID from `--fastly-service-id`, then the `FASTLY_SERVICE_ID`
190
+ environment variable, then `service_id` in `fastly.toml`. If it finds a Service ID, the API token must have permission to purge
191
+ that service. If you do not want a purge, make sure that the CLI does not find a Service ID. If the purge fails,
192
+ the CLI shows a warning, and the publish is complete. `collections delete` purges the same way after it deletes a
193
+ collection.
194
+ - **`kvStoreAssetInclusionTest` has a new name.** In `publish-content.config.js`, use `assetInclusionTest`. The old
195
+ name continues to work, but it is deprecated.
196
+ - **Imports of files in `build/` are not supported.** Import the named exports of
197
+ `@fastly/compute-js-static-publish`.
198
+ - **`--public-dir` and `server.publicDirPrefix` are deprecated.** `publish-content` shows a warning if
199
+ `publicDirPrefix` is not empty. See [Stop using `publicDirPrefix`](#stop-using-publicdirprefix-deprecated).
200
+ - **The `@fastly/cli` dependency is removed** from this package. A scaffolded app continues to have `@fastly/cli` as
201
+ its own dependency.
202
+
203
+ ### Stop using `publicDirPrefix` (deprecated)
204
+
205
+ `--public-dir` and `server.publicDirPrefix` are deprecated. A future version will remove them. If `publish-content`
206
+ shows a warning about `server.publicDirPrefix`, do the steps in this section. If it does not show the warning, you do
207
+ not use this feature, and you do not have to do anything.
208
+
209
+ `publicDirPrefix` lets you publish files that requests cannot get. For example, with this layout, `rootDir` is
210
+ `'../site'` and `publicDirPrefix` is `'/public'`:
211
+
212
+ ```
213
+ site/
214
+ 404.html published as /404.html, but /404.html is not a URL
215
+ templates/
216
+ email.html published as /templates/email.html, but it is not a URL
217
+ public/
218
+ index.html published as /public/index.html, served at /index.html
219
+ ```
220
+
221
+ To stop using `publicDirPrefix`:
222
+
223
+ 1. Find the files that are under `rootDir` but not under the public directory (`site/public/` in the example). For
224
+ each file, do one of these steps:
225
+ - If your app does not use the file, do nothing. After step 2, the CLI does not publish it.
226
+ - If the file is your `spaFile` or your `notFoundPageFile`, or if your code reads the file with
227
+ `getMatchingAsset()`, move it into the public directory, and add it to `hiddenItems` in
228
+ `publish-content.config.js` (from 8.1.0). A hidden file is published, but requests cannot get it at its own URL,
229
+ for example `/404.html`. The server still serves a hidden `spaFile` or `notFoundPageFile` as the fallback page,
230
+ and your code gets a hidden file with `getMatchingAsset(key, { includeHidden: true })`. See "Hidden files" in
231
+ `README.md`. Your app must be built with 8.1.0 or later to serve a collection that has hidden files:
232
+
233
+ ```js
234
+ hiddenItems: [ '/404.html', '/templates/' ],
235
+ ```
236
+
237
+ Before 8.1.0, there are no hidden files. Move the file into the public directory. Then requests can also get it
238
+ at its own URL. To prevent this for a file that your code reads, return a response in `src/index.js` before you
239
+ call `serveRequest()`:
240
+
241
+ ```js
242
+ const url = new URL(request.url);
243
+ if (url.pathname.startsWith('/templates/')) {
244
+ return new Response('Not found', { status: 404 });
245
+ }
246
+ const response = await publisherServer.serveRequest(request);
247
+ ```
248
+
249
+ 2. In `publish-content.config.js`:
250
+ - Set `rootDir` to the public directory, for example `'../site/public'`.
251
+ - Remove `publicDirPrefix` from the `server` section.
252
+ - In `spaFile` and `notFoundPageFile`, remove the prefix, for example change `'/public/404.html'` to
253
+ `'/404.html'`. These values are asset keys, and asset keys are relative to `rootDir`.
254
+ - Do not change `staticItems`. These values are already relative to the public directory.
255
+
256
+ 3. If your code calls `getMatchingAsset()` with a key that starts with the prefix, remove the prefix from the key, for
257
+ example change `'/public/index.html'` to `'/index.html'`. Then build and deploy your app. Between the deploy and
258
+ step 4, your code does not find these files.
259
+
260
+ 4. Publish each collection that you serve again. Each collection keeps its old settings and its old index until you
261
+ publish it again. The keys of the files are the hashes of the content, so the CLI does not upload the same files
262
+ again.
263
+
264
+ ### Move from the KV Store to S3-compatible storage (BETA)
265
+
266
+ You do not have to move to S3-compatible storage. The KV Store continues to be the default storage mode.
267
+
268
+ There is no tool that moves your content from the KV Store to a bucket. The CLI publishes from your source files.
269
+ Thus, to move, you publish your content again into the bucket:
270
+
271
+ 1. Scaffold a new app with `--storage-mode=s3`, `--s3-region`, `--s3-bucket`, and, if necessary, `--s3-endpoint`.
272
+ Scaffold it into a different directory, so that you can compare the new files with your current app.
273
+
274
+ 2. Copy your changes from your current app into the new app, for example the changes to `src/index.js` and to
275
+ `publish-content.config.js`. Keep the same `publishId` and `defaultCollectionName`.
276
+
277
+ 3. Set up the S3 credentials for publishing and for the server. See "Using S3 Compatible Storage (Beta)" in
278
+ `README.md`.
279
+
280
+ 4. Publish each collection that you need again, from its source files. The collections that are in the KV Store
281
+ are not copied.
282
+
283
+ 5. Build and deploy the new app. Then examine your site.
284
+
285
+ 6. When you do not need the KV Store content, delete it. Before you do this, make sure that no service version
286
+ that is active or staged uses that KV Store.
287
+
288
+ > [!NOTE]
289
+ > S3-compatible storage is in beta. The configuration and these steps can change before this feature is stable.
@@ -1 +1 @@
1
- {"version":3,"file":"deploy.d.ts","sourceRoot":"","sources":["../../../../../src/cli/commands/manage/deploy.ts"],"names":[],"mappings":"AAiFA,wBAAsB,MAAM,CAAC,UAAU,EAAE,MAAM,EAAE,iBAqMhD"}
1
+ {"version":3,"file":"deploy.d.ts","sourceRoot":"","sources":["../../../../../src/cli/commands/manage/deploy.ts"],"names":[],"mappings":"AAiFA,wBAAsB,MAAM,CAAC,UAAU,EAAE,MAAM,EAAE,iBAsMhD"}
@@ -7,8 +7,8 @@ import fs from 'node:fs';
7
7
  import path from 'node:path';
8
8
  import { managedAppState, prepareManagedApp } from '../../managed/app.js';
9
9
  import { checkVersionForCommand, loadManagedProject, showTemplateFolderHint } from '../../managed/command-helpers.js';
10
- import { getActiveVersion, getVersionDomains } from '../../managed/fastly-service.js';
11
- import { formatVersionComment, parseVersionComment } from '../../managed/fingerprint.js';
10
+ import { getActiveVersion, getDeployedApp, getVersionDomains } from '../../managed/fastly-service.js';
11
+ import { formatVersionComment } from '../../managed/fingerprint.js';
12
12
  import { writeBackServiceId } from '../../managed/project-edit.js';
13
13
  import { loadApiToken } from '../../util/api-token.js';
14
14
  import { parseCommandLine } from '../../util/args.js';
@@ -176,9 +176,10 @@ export async function action(actionArgs) {
176
176
  const staticPublishVersion = getOwnVersion();
177
177
  if (serviceId != null && !force) {
178
178
  const active = await getActiveVersion(context, serviceId);
179
- const deployed = parseVersionComment(active?.comment);
179
+ const deployed = active != null ? await getDeployedApp(context, serviceId, active) : null;
180
180
  if (active != null && deployed?.fingerprint === fingerprint) {
181
- console.log(`✅ The active version ${active.number} already has this app (fingerprint ${fingerprint}). Nothing to deploy. Use --force to deploy anyway.`);
181
+ const from = deployed.fingerprintVersion != null ? `, the same package as version ${deployed.fingerprintVersion}` : '';
182
+ console.log(`✅ The active version ${active.number} already has this app (fingerprint ${fingerprint}${from}). Nothing to deploy. Use --force to deploy anyway.`);
182
183
  setJsonResult({
183
184
  deployed: false,
184
185
  reason: 'up-to-date',
@@ -1,2 +1,3 @@
1
+ export declare const MANAGEMENT_COMMANDS: readonly string[];
1
2
  export declare function action(actionArgs: string[]): Promise<void>;
2
3
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../../src/cli/commands/manage/index.ts"],"names":[],"mappings":"AAsFA,wBAAsB,MAAM,CAAC,UAAU,EAAE,MAAM,EAAE,iBAmChD"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../../src/cli/commands/manage/index.ts"],"names":[],"mappings":"AAmGA,eAAO,MAAM,mBAAmB,EAAE,SAAS,MAAM,EAAuB,CAAC;AAEzE,wBAAsB,MAAM,CAAC,UAAU,EAAE,MAAM,EAAE,iBAuBhD"}
@@ -81,18 +81,20 @@ Examples:
81
81
  ${cliCommand()} publish-content --project-dir=./compute-js
82
82
  `);
83
83
  }
84
+ const modes = {
85
+ 'clean': cleanCommand,
86
+ 'deploy': deployCommand,
87
+ 'dev': devCommand,
88
+ 'eject': ejectCommand,
89
+ 'status': statusCommand,
90
+ 'upgrade': upgradeCommand,
91
+ 'publish-content': publishContentCommand,
92
+ 'collections': collectionsCommands,
93
+ 'template': templateCommands,
94
+ };
95
+ // The commands for a project or an app. Scaffolding mode does not have them.
96
+ export const MANAGEMENT_COMMANDS = Object.keys(modes);
84
97
  export async function action(actionArgs) {
85
- const modes = {
86
- 'clean': cleanCommand,
87
- 'deploy': deployCommand,
88
- 'dev': devCommand,
89
- 'eject': ejectCommand,
90
- 'status': statusCommand,
91
- 'upgrade': upgradeCommand,
92
- 'publish-content': publishContentCommand,
93
- 'collections': collectionsCommands,
94
- 'template': templateCommands,
95
- };
96
98
  const commandAndArgs = getCommandAndArgs(actionArgs, modes);
97
99
  if (commandAndArgs.needHelp) {
98
100
  if (commandAndArgs.error != null) {
@@ -1 +1 @@
1
- {"version":3,"file":"status.d.ts","sourceRoot":"","sources":["../../../../../src/cli/commands/manage/status.ts"],"names":[],"mappings":"AAgDA,wBAAsB,MAAM,CAAC,UAAU,EAAE,MAAM,EAAE,iBAsIhD"}
1
+ {"version":3,"file":"status.d.ts","sourceRoot":"","sources":["../../../../../src/cli/commands/manage/status.ts"],"names":[],"mappings":"AA+CA,wBAAsB,MAAM,CAAC,UAAU,EAAE,MAAM,EAAE,iBAyIhD"}
@@ -5,8 +5,7 @@
5
5
  import path from 'node:path';
6
6
  import { managedAppState } from '../../managed/app.js';
7
7
  import { loadManagedProject } from '../../managed/command-helpers.js';
8
- import { getActiveVersion, getVersionDomains } from '../../managed/fastly-service.js';
9
- import { parseVersionComment } from '../../managed/fingerprint.js';
8
+ import { getActiveVersion, getDeployedApp, getVersionDomains } from '../../managed/fastly-service.js';
10
9
  import { checkProjectVersion } from '../../managed/version-check.js';
11
10
  import { loadApiToken } from '../../util/api-token.js';
12
11
  import { parseCommandLine } from '../../util/args.js';
@@ -81,6 +80,8 @@ export async function action(actionArgs) {
81
80
  let deployedFingerprint = null;
82
81
  let deployedStaticPublishVersion = null;
83
82
  let activeVersion = null;
83
+ // The version whose comment has the fingerprint, if it is not the active version.
84
+ let fingerprintVersion = null;
84
85
  let domain = null;
85
86
  let needsDeploy;
86
87
  const reasons = [];
@@ -102,13 +103,14 @@ export async function action(actionArgs) {
102
103
  else {
103
104
  activeVersion = active.number;
104
105
  domain = (await getVersionDomains(context, serviceId, active.number))[0] ?? null;
105
- const deployed = parseVersionComment(active.comment);
106
+ const deployed = await getDeployedApp(context, serviceId, active);
106
107
  if (deployed == null) {
107
108
  needsDeploy = true;
108
- reasons.push(`The active version (${active.number}) was not deployed by 'deploy' (its comment has no fingerprint).`);
109
+ reasons.push(`The active version (${active.number}) was not deployed by 'deploy': its comment has no fingerprint, and its package is not the package of the newest version that has one.`);
109
110
  }
110
111
  else {
111
112
  deployedFingerprint = deployed.fingerprint;
113
+ fingerprintVersion = deployed.fingerprintVersion ?? null;
112
114
  deployedStaticPublishVersion = deployed.staticPublishVersion;
113
115
  needsDeploy = deployed.fingerprint !== fingerprint;
114
116
  if (needsDeploy) {
@@ -137,7 +139,7 @@ export async function action(actionArgs) {
137
139
  console.log(`Version of the project : ${versionCheck.recorded ?? '(missing)'}`);
138
140
  console.log(`Version that runs : ${running}${versionCheck.result !== 'same' ? ` ⚠️ ${versionCheck.result}` : ''}`);
139
141
  console.log(`Fingerprint : ${fingerprint}`);
140
- console.log(`Deployed fingerprint : ${deployedFingerprint ?? '(unknown)'}${activeVersion != null ? ` (version ${activeVersion})` : ''}`);
142
+ console.log(`Deployed fingerprint : ${deployedFingerprint ?? '(unknown)'}${activeVersion != null ? ` (version ${activeVersion}${fingerprintVersion != null ? `, the same package as version ${fingerprintVersion}` : ''})` : ''}`);
141
143
  console.log(`Deploy necessary : ${needsDeploy == null ? 'unknown' : needsDeploy ? 'yes' : 'no'}`);
142
144
  for (const reason of reasons) {
143
145
  console.log(` * ${reason}`);
@@ -13,7 +13,7 @@ import { runTemplateHook } from './commands/run-template-hook.js';
13
13
  import { parseGlobalOptions } from './util/global-options.js';
14
14
  import { ConfigError, EXIT_USAGE, JSON_SCHEMA_VERSION, fail, isJsonMode, recordFailure, setJsonResult, setUpOutput, writeJsonOutput, } from './util/output.js';
15
15
  import { getOwnVersion } from './util/package.js';
16
- import { detectProjectMode } from './util/config.js';
16
+ import { detectProjectMode, findProjectDirsNear } from './util/config.js';
17
17
  import { PROJECT_FILE_NAME, RC_FILE_NAME } from '../models/config/static-publish-project.js';
18
18
  // Register storage builder providers
19
19
  import { registerStorageProviderBuilder } from './storage/storage-provider.js';
@@ -108,6 +108,20 @@ async function run(globalOptions) {
108
108
  return;
109
109
  }
110
110
  if (mode === 'scaffold') {
111
+ // A command for a project or an app, in a directory that has none.
112
+ const command = process.argv[2];
113
+ if (command != null && manageCommands.MANAGEMENT_COMMANDS.includes(command)) {
114
+ fail('project-dir-not-found', `'${command}' is a command for a managed project or an app, but this directory has no ${PROJECT_FILE_NAME} or ${RC_FILE_NAME}.`);
115
+ const near = findProjectDirsNear();
116
+ for (const { dir, mode: kind } of near.slice(0, 3)) {
117
+ const relative = path.relative(process.cwd(), dir) || '.';
118
+ console.error(` * ${relative} has ${kind === 'managed' ? PROJECT_FILE_NAME : RC_FILE_NAME}. Run the command there, or add --project-dir=${relative}.`);
119
+ }
120
+ if (near.length === 0) {
121
+ console.error(` * Run it in the directory of the project (with ${PROJECT_FILE_NAME}) or of the app (with ${RC_FILE_NAME}), or add --project-dir.`);
122
+ }
123
+ return;
124
+ }
111
125
  console.log("🧑‍💻Fastly Compute JavaScript Static Publisher (Scaffolding mode)");
112
126
  if (isJsonMode()) {
113
127
  fail('json-not-supported', '--json is not supported for scaffolding.');
@@ -1,8 +1,15 @@
1
1
  import { type FastlyApiContext } from '../util/api-token.js';
2
+ import { type DeployedApp } from './fingerprint.js';
2
3
  export type ActiveVersion = {
3
4
  number: number;
4
5
  comment: string | null;
5
6
  };
6
7
  export declare function getActiveVersion(context: FastlyApiContext, serviceId: string): Promise<ActiveVersion | null>;
7
8
  export declare function getVersionDomains(context: FastlyApiContext, serviceId: string, version: number): Promise<string[]>;
9
+ export declare function getVersions(context: FastlyApiContext, serviceId: string): Promise<{
10
+ number: number;
11
+ comment: string | null;
12
+ }[]>;
13
+ export declare function getPackageHash(context: FastlyApiContext, serviceId: string, version: number): Promise<string | null>;
14
+ export declare function getDeployedApp(context: FastlyApiContext, serviceId: string, active: ActiveVersion): Promise<DeployedApp | null>;
8
15
  //# sourceMappingURL=fastly-service.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"fastly-service.d.ts","sourceRoot":"","sources":["../../../../src/cli/managed/fastly-service.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,KAAK,gBAAgB,EAAiB,MAAM,sBAAsB,CAAC;AAE5E,MAAM,MAAM,aAAa,GAAG;IAC1B,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EA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,cAAc,CAAC,OAAO,EAAE,gBAAgB,EAAE,SAAS,EAAE,MAAM,EAAE,MAAM,EAAE,aAAa,GAAG,OAAO,CAAC,WAAW,GAAG,IAAI,CAAC,CAMrI"}
@@ -2,7 +2,8 @@
2
2
  * Copyright Fastly, Inc.
3
3
  * Licensed under the MIT license. See LICENSE file for details.
4
4
  */
5
- import { callFastlyApi } from '../util/api-token.js';
5
+ import { FetchError, callFastlyApi } from '../util/api-token.js';
6
+ import { findDeployedApp, parseVersionComment } from './fingerprint.js';
6
7
  // The active version of a service, or null if no version is active.
7
8
  export async function getActiveVersion(context, serviceId) {
8
9
  const response = await callFastlyApi(context, `/service/${encodeURIComponent(serviceId)}/details`, 'Get service details');
@@ -19,3 +20,32 @@ export async function getVersionDomains(context, serviceId, version) {
19
20
  const domains = await response.json();
20
21
  return domains.flatMap(x => typeof x.name === 'string' ? [x.name] : []);
21
22
  }
23
+ // The versions of a service, with their comments.
24
+ export async function getVersions(context, serviceId) {
25
+ const response = await callFastlyApi(context, `/service/${encodeURIComponent(serviceId)}/version`, 'List versions');
26
+ const versions = await response.json();
27
+ return versions.flatMap(x => typeof x.number === 'number' ? [{ number: x.number, comment: x.comment ?? null }] : []);
28
+ }
29
+ // The hash of the package of a service version, or null if it has no package.
30
+ export async function getPackageHash(context, serviceId, version) {
31
+ let response;
32
+ try {
33
+ response = await callFastlyApi(context, `/service/${encodeURIComponent(serviceId)}/version/${version}/package`, 'Get package');
34
+ }
35
+ catch (err) {
36
+ if (err instanceof FetchError && err.status === 404) {
37
+ return null;
38
+ }
39
+ throw err;
40
+ }
41
+ const pkg = await response.json();
42
+ return typeof pkg.metadata?.hashsum === 'string' && pkg.metadata.hashsum !== '' ? pkg.metadata.hashsum : null;
43
+ }
44
+ // The app that the active version runs (see findDeployedApp()).
45
+ export async function getDeployedApp(context, serviceId, active) {
46
+ const own = parseVersionComment(active.comment);
47
+ if (own != null) {
48
+ return own;
49
+ }
50
+ return findDeployedApp(active, await getVersions(context, serviceId), (version) => getPackageHash(context, serviceId, version));
51
+ }
@@ -10,4 +10,16 @@ export declare function parseVersionComment(comment: string | null | undefined):
10
10
  staticPublishVersion: string;
11
11
  fingerprint: string;
12
12
  } | null;
13
+ export type DeployedApp = {
14
+ staticPublishVersion: string;
15
+ fingerprint: string;
16
+ fingerprintVersion?: number;
17
+ };
18
+ export declare function findDeployedApp(active: {
19
+ number: number;
20
+ comment: string | null;
21
+ }, versions: {
22
+ number: number;
23
+ comment: string | null;
24
+ }[], getPackageHash: (version: number) => Promise<string | null>): Promise<DeployedApp | null>;
13
25
  //# sourceMappingURL=fingerprint.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"fingerprint.d.ts","sourceRoot":"","sources":["../../../../src/cli/managed/fingerprint.ts"],"names":[],"mappings":"AAkBA,wBAAgB,eAAe,CAAC,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAIrF;AAED,MAAM,MAAM,kBAAkB,GAAG;IAC/B,oBAAoB,EAAE,MAAM,CAAC;IAC7B,QAAQ,EAAE,MAAM,CAAC;IAGjB,YAAY,EAAE,MAAM,EAAE,CAAC;CACxB,CAAC;AAEF,wBAAgB,kBAAkB,CAAC,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,EAAE,OAAO,EAAE,kBAAkB,GAAG,MAAM,CA2BrG;AAGD,wBAAgB,oBAAoB,CAAC,oBAAoB,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,EAAE,WAAW,CAAC,EAAE,MAAM,GAAG,MAAM,CAGpH;AAED,wBAAgB,mBAAmB,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,GAAG;IAAE,oBAAoB,EAAE,MAAM,CAAC;IAAC,WAAW,EAAE,MAAM,CAAA;CAAE,GAAG,IAAI,CAMpI"}
1
+ {"version":3,"file":"fingerprint.d.ts","sourceRoot":"","sources":["../../../../src/cli/managed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function parseVersionComment(comment) {
58
58
  }
59
59
  return { staticPublishVersion: match[1], fingerprint: match[2] };
60
60
  }
61
+ // The app that the active version runs. The fingerprint is in the comment of
62
+ // the version that deploy made. A version cloned by hand (for example to add a
63
+ // backend) has no comment, but it has the package of the version that it was
64
+ // cloned from. Thus, if the active version has no fingerprint, the newest
65
+ // earlier version with a fingerprint is used, but only if its package hash is
66
+ // the same as the package hash of the active version. Each deploy uploads a
67
+ // new package with a different hash, also for the same app.
68
+ export async function findDeployedApp(active, versions, getPackageHash) {
69
+ const own = parseVersionComment(active.comment);
70
+ if (own != null) {
71
+ return own;
72
+ }
73
+ const earlier = versions
74
+ .filter(version => version.number < active.number)
75
+ .sort((a, b) => b.number - a.number)
76
+ .find(version => parseVersionComment(version.comment) != null);
77
+ if (earlier == null) {
78
+ return null;
79
+ }
80
+ const [activeHash, earlierHash] = await Promise.all([getPackageHash(active.number), getPackageHash(earlier.number)]);
81
+ if (activeHash == null || activeHash !== earlierHash) {
82
+ return null;
83
+ }
84
+ return { ...parseVersionComment(earlier.comment), fingerprintVersion: earlier.number };
85
+ }
@@ -8,6 +8,10 @@ export declare class LoadConfigError extends Error {
8
8
  }
9
9
  export type ProjectMode = 'managed' | 'ejected' | 'scaffold' | 'conflict';
10
10
  export declare function detectProjectMode(dir?: string): ProjectMode;
11
+ export declare function findProjectDirsNear(dir?: string): {
12
+ dir: string;
13
+ mode: 'managed' | 'ejected';
14
+ }[];
11
15
  export declare function getComputeAppDir(): string;
12
16
  export declare function configFileName(): string;
13
17
  export type StaticPublishProjectNormalized = {
@@ -1 +1 @@
1
- {"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../../../../src/cli/util/config.ts"],"names":[],"mappings":"AAWA,OAAO,EACL,KAAK,eAAe,EAKrB,MAAM,0CAA0C,CAAC;AAClD,OAAO,EACL,KAAK,2BAA2B,EAIjC,MAAM,+CAA+C,CAAC;AAWvD,OAAO,EACL,KAAK,8BAA8B,EAEpC,MAAM,+CAA+C,CAAC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AAM,8BAA8B,6EA2GzC,CAAC"}
@@ -29,6 +29,39 @@ export function detectProjectMode(dir = '.') {
29
29
  }
30
30
  return hasProject ? 'managed' : hasRc ? 'ejected' : 'scaffold';
31
31
  }
32
+ // The directories near dir that have a project file or an rc file: the parent
33
+ // directories, and the directories directly in dir (for example compute-js/).
34
+ // For the message when a command for a project or an app runs in another
35
+ // directory.
36
+ export function findProjectDirsNear(dir = '.') {
37
+ const found = [];
38
+ const add = (candidate) => {
39
+ const mode = detectProjectMode(candidate);
40
+ if (mode === 'managed' || mode === 'ejected') {
41
+ found.push({ dir: candidate, mode });
42
+ }
43
+ };
44
+ const start = path.resolve(dir);
45
+ for (let current = path.dirname(start);; current = path.dirname(current)) {
46
+ add(current);
47
+ if (path.dirname(current) === current) {
48
+ break;
49
+ }
50
+ }
51
+ let entries = [];
52
+ try {
53
+ entries = fs.readdirSync(start, { withFileTypes: true });
54
+ }
55
+ catch {
56
+ // An unreadable directory has no subdirectories to check.
57
+ }
58
+ for (const entry of entries) {
59
+ if (entry.isDirectory() && !entry.name.startsWith('.') && entry.name !== 'node_modules') {
60
+ add(path.join(start, entry.name));
61
+ }
62
+ }
63
+ return found;
64
+ }
32
65
  // The directory of the Compute app: the current directory in an ejected app,
33
66
  // or .static-publish/app in a managed project. The local KV Store file has
34
67
  // paths relative to it, because `fastly compute serve` runs there.
@@ -27,7 +27,7 @@ const USAGE_CODES = [
27
27
  'config-invalid', // a config file cannot be loaded or is not valid
28
28
  'collection-name-invalid', // a collection name breaks the rule
29
29
  'collection-not-found', // the command needs a collection that does not exist
30
- 'project-dir-not-found', // --project-dir is not a directory, or has no config file
30
+ 'project-dir-not-found', // --project-dir is not a directory, or has no config file, or a command for a project runs in a directory with no config file
31
31
  'json-not-supported', // --json with a command that does not support it
32
32
  'credentials-missing', // a token or credentials are necessary, but not given
33
33
  'version-mismatch', // managed.staticPublishVersion is not the version that runs
@@ -5,6 +5,7 @@ import type { KVStore } from 'fastly:kv-store';
5
5
  import type { Logger } from 'fastly:logger';
6
6
  import type { SecretStore } from 'fastly:secret-store';
7
7
  import type { Hono } from 'hono';
8
+ import type { PublisherServerMiddleware } from './index.js';
8
9
  export type ExtensionBindings = Record<string, string>;
9
10
  type ResourceTypes = {
10
11
  Acl: Acl;
@@ -24,7 +25,8 @@ export type ExtensionEnv<B extends ExtensionBindings> = {
24
25
  };
25
26
  export declare const EXTENSION_PHASES: readonly ['middleware', 'beforeFiles', 'afterFiles'];
26
27
  export type ExtensionPhase = typeof EXTENSION_PHASES[number];
27
- export type ExtensionPhaseFunction<B extends ExtensionBindings = ExtensionBindings, O = any> = (app: Hono<ExtensionEnv<B>, any, any>, options: O | undefined) => void;
28
+ export type ExtensionHelpers = Pick<PublisherServerMiddleware, 'publisherServer' | 'serveStatic' | 'staticResponse' | 'serveFallback'>;
29
+ export type ExtensionPhaseFunction<B extends ExtensionBindings = ExtensionBindings, O = any> = (app: Hono<ExtensionEnv<B>, any, any>, options: O | undefined, helpers: ExtensionHelpers) => void;
28
30
  export type ExtensionPhases<B extends ExtensionBindings = ExtensionBindings, O = any> = {
29
31
  [P in ExtensionPhase]?: ExtensionPhaseFunction<B, O>;
30
32
  };
@@ -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;AAIjC,MAAM,MAAM,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Ae,CAAC,EAAE,EAAE,CAAC,CAAC,GAAG,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,7 +1,7 @@
1
1
  import type { Context, MiddlewareHandler, NotFoundHandler } from 'hono';
2
2
  import { PublisherServer, type StaticPublishRc } from '../server/index.js';
3
3
  import { type ServeStaticPathOptions } from './path.js';
4
- export { type BindingResource, type DefineExtensionOptions, EXTENSION_PHASES, type Extension, type ExtensionBindings, type ExtensionEntry, type ExtensionEnv, type ExtensionPhase, type ExtensionPhaseFunction, type ExtensionPhases, defineExtension, mergeBindings, } from './extensions.js';
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 = {
6
6
  staticPublisher: {
7
7
  publisherServer: PublisherServer;
@@ -10,18 +10,23 @@ export type StaticPublisherVariables = {
10
10
  };
11
11
  };
12
12
  export type CollectionNameOption = string | null | ((c: Context) => string | null | undefined);
13
+ export type OnMissingOption = 'not-found' | 'default';
13
14
  export type ServeStaticOptions = ServeStaticPathOptions<Context> & {
14
15
  collectionName?: CollectionNameOption;
16
+ onMissing?: OnMissingOption;
15
17
  };
16
18
  export type ServeFallbackOptions = {
17
19
  collectionName?: CollectionNameOption;
20
+ onMissing?: OnMissingOption;
18
21
  };
19
22
  export type PublisherServerMiddlewareDefaults = {
20
23
  collectionName?: CollectionNameOption;
24
+ onMissing?: OnMissingOption;
21
25
  };
22
26
  export type PublisherServerMiddleware = {
23
27
  publisherServer: PublisherServer;
24
28
  serveStatic: (options?: ServeStaticOptions) => MiddlewareHandler;
29
+ staticResponse: (c: Context, options?: ServeStaticOptions) => Promise<Response | null>;
25
30
  serveFallback: (options?: ServeFallbackOptions) => NotFoundHandler;
26
31
  selectCollection: () => MiddlewareHandler;
27
32
  };
@@ -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,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;AAE/F,MAAM,MAAM,kBAAkB,GAAG,sBAAsB,CAAC,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AAsC,GAAG,yBAAyB,CA2DxI;AAED,wBAAgB,mBAAmB,CAAC,EAAE,EAAE,eAAe,EAAE,QAAQ,GAAE,iCAAsC,GAAG,yBAAyB,CAEpI"}
@@ -21,20 +21,27 @@ function resolveCollectionName(c, option, selection) {
21
21
  return selection != null ? selection.collectionName : undefined;
22
22
  }
23
23
  export function fromPublisherServer(server, defaults = {}) {
24
- const serveStatic = (callOptions = {}) => {
24
+ const staticResponse = async (c, callOptions = {}) => {
25
25
  const options = { ...defaults, ...callOptions };
26
+ const selection = getSelection(c, server);
27
+ // For a path source, the path without its prefix. A path option
28
+ // replaces the request path (see resolveServeStaticPathname()).
29
+ const requestPath = selection?.pathname ?? c.req.path;
30
+ const pathname = resolveServeStaticPathname(requestPath, c, options);
31
+ if (pathname == null) {
32
+ return null;
33
+ }
34
+ return server.serveRequest(c.req.raw, {
35
+ collectionName: resolveCollectionName(c, options.collectionName, selection),
36
+ pathname,
37
+ fallback: false,
38
+ healthCheck: false,
39
+ onMissing: options.onMissing,
40
+ });
41
+ };
42
+ const serveStatic = (callOptions = {}) => {
26
43
  return async (c, next) => {
27
- const selection = getSelection(c, server);
28
- // For a path source, the path without its prefix. A path option
29
- // replaces the request path (see resolveServeStaticPathname()).
30
- const requestPath = selection?.pathname ?? c.req.path;
31
- const pathname = resolveServeStaticPathname(requestPath, c, options);
32
- const response = pathname != null ? await server.serveRequest(c.req.raw, {
33
- collectionName: resolveCollectionName(c, options.collectionName, selection),
34
- pathname,
35
- fallback: false,
36
- healthCheck: false,
37
- }) : null;
44
+ const response = await staticResponse(c, callOptions);
38
45
  if (response == null) {
39
46
  await next();
40
47
  return;
@@ -47,6 +54,7 @@ export function fromPublisherServer(server, defaults = {}) {
47
54
  return async (c) => {
48
55
  const response = await server.serveFallback(c.req.raw, {
49
56
  collectionName: resolveCollectionName(c, options.collectionName, getSelection(c, server)),
57
+ onMissing: options.onMissing,
50
58
  });
51
59
  return response ?? c.text('404 Not Found', 404);
52
60
  };
@@ -65,7 +73,7 @@ export function fromPublisherServer(server, defaults = {}) {
65
73
  await next();
66
74
  };
67
75
  };
68
- return { publisherServer: server, serveStatic, serveFallback, selectCollection };
76
+ return { publisherServer: server, serveStatic, staticResponse, serveFallback, selectCollection };
69
77
  }
70
78
  export function fromStaticPublishRc(rc, defaults = {}) {
71
79
  return fromPublisherServer(PublisherServer.fromStaticPublishRc(rc), defaults);
@@ -25,9 +25,11 @@ export type ServeRequestOptions = {
25
25
  pathname?: string;
26
26
  fallback?: boolean;
27
27
  healthCheck?: boolean;
28
+ onMissing?: 'not-found' | 'default';
28
29
  };
29
30
  export type ServeFallbackOptions = {
30
31
  collectionName?: string | null;
32
+ onMissing?: 'not-found' | 'default';
31
33
  };
32
34
  export declare class PublisherServer {
33
35
  constructor(publishId: string, storageProvider: StorageProvider, defaultCollectionName: string);
@@ -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,C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,GAAG,IAAI,CAAC,GACtD,OAAO,CAAC,QAAQ,GAAG,IAAI,CAAC,CAE1B;YAEa,cAAc;IAiH5B,OAAO,CAAC,iBAAiB;IAgCnB,YAAY,CAAC,OAAO,EAAE,OAAO,EAAE,OAAO,GAAE,mBAAwB,GAAG,OAAO,CAAC,QAAQ,GAAG,IAAI,CAAC,CAoChG;IAMK,aAAa,CAAC,OAAO,EAAE,OAAO,EAAE,OAAO,GAAE,oBAAyB,GAAG,OAAO,CAAC,QAAQ,GAAG,IAAI,CAAC,CA6BlG;IAIK,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;YAyCvB,wBAAwB;CAiCvC"}
@@ -663,7 +663,7 @@ export class PublisherServer {
663
663
  if (options.healthCheck !== false && pathname === '/healthz') {
664
664
  return new Response("OK", { status: 200 });
665
665
  }
666
- const selected = await this.checkSelectedCollection(request, scope);
666
+ const selected = await this.checkSelectedCollection(request, scope, options.onMissing);
667
667
  if (selected instanceof Response) {
668
668
  return selected;
669
669
  }
@@ -688,7 +688,7 @@ export class PublisherServer {
688
688
  if (!requestAcceptsTextHtml(request)) {
689
689
  return null;
690
690
  }
691
- const selected = await this.checkSelectedCollection(request, scope);
691
+ const selected = await this.checkSelectedCollection(request, scope, options.onMissing);
692
692
  if (selected instanceof Response) {
693
693
  return selected;
694
694
  }
@@ -717,7 +717,7 @@ export class PublisherServer {
717
717
  // whether to mark the response as a preview, or a 404 response for onMissing:
718
718
  // 'not-found'. The check reads the index, also when the response cache has the
719
719
  // response.
720
- async checkSelectedCollection(request, scope) {
720
+ async checkSelectedCollection(request, scope, onMissing) {
721
721
  const config = this.collectionSelection;
722
722
  if (config == null || scope.collectionName === this.defaultCollectionName) {
723
723
  return { scope, preview: false };
@@ -725,7 +725,7 @@ export class PublisherServer {
725
725
  if (await this.isCollectionAvailableFor(scope)) {
726
726
  return { scope, preview: true };
727
727
  }
728
- if (config.onMissing === 'default') {
728
+ if ((onMissing ?? config.onMissing) === 'default') {
729
729
  this.currentScope = this.scopeForRequest(request, this.defaultCollectionName);
730
730
  return { scope: this.currentScope, preview: false };
731
731
  }
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.4",
4
+ "version": "8.1.0-beta.5",
5
5
  "description": "Static Publisher for Fastly Compute JavaScript",
6
6
  "main": "build/server/server/index.js",
7
7
  "exports": {
@@ -74,7 +74,7 @@
74
74
  "@types/nunjucks": "^3.2.6",
75
75
  "esbuild": "^0.28.2",
76
76
  "hono": "^4.13.14",
77
- "rimraf": "^4.3.0",
77
+ "rimraf": "^6.1.4",
78
78
  "typescript": "^7.0.2"
79
79
  },
80
80
  "engines": {
@@ -88,6 +88,7 @@
88
88
  "README.md",
89
89
  "DOCUMENTATION.md",
90
90
  "CHANGELOG.md",
91
+ "MIGRATING.md",
91
92
  "SECURITY.md"
92
93
  ]
93
94
  }
@@ -16,7 +16,10 @@ 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, serveFallback, selectCollection } = fromStaticPublishRc(rc);
19
+ const { serveStatic, staticResponse, serveFallback, selectCollection, publisherServer } = fromStaticPublishRc(rc);
20
+
21
+ // The helpers of the app that each phase of the extensions gets.
22
+ const helpers = { serveStatic, staticResponse, serveFallback, publisherServer };
20
23
 
21
24
  const app = new Hono<{ Bindings: typeof fire.Bindings, Variables: StaticPublisherVariables }>();
22
25
 
@@ -30,7 +33,7 @@ app.use('*', selectCollection());
30
33
  // them, then the beforeFiles phase.
31
34
  for (const phase of [ 'middleware', 'beforeFiles' ] as const) {
32
35
  for (const e of extensions) {
33
- e.module.phases[phase]?.(app, honoOptions?.extensions?.[e.name]);
36
+ e.module.phases[phase]?.(app, honoOptions?.extensions?.[e.name], helpers);
34
37
  }
35
38
  }
36
39
 
@@ -43,7 +46,7 @@ app.use('*', serveStatic());
43
46
  // The afterFiles phase of the extensions: only for the requests that no
44
47
  // published file matches.
45
48
  for (const e of extensions) {
46
- e.module.phases.afterFiles?.(app, honoOptions?.extensions?.[e.name]);
49
+ e.module.phases.afterFiles?.(app, honoOptions?.extensions?.[e.name], helpers);
47
50
  }
48
51
 
49
52
  // When nothing matches, serve the SPA file or the 404 page.