@fastly/compute-js-static-publish 8.0.1 → 8.1.0-beta.2

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 (247) hide show
  1. package/DOCUMENTATION.md +792 -35
  2. package/README.md +13 -3
  3. package/README.short.md +13 -3
  4. package/build/cli/cli/commands/manage/clean.d.ts.map +1 -1
  5. package/build/cli/cli/commands/manage/clean.js +14 -8
  6. package/build/cli/cli/commands/manage/collections/delete.d.ts.map +1 -1
  7. package/build/cli/cli/commands/manage/collections/delete.js +32 -15
  8. package/build/cli/cli/commands/manage/collections/index.d.ts.map +1 -1
  9. package/build/cli/cli/commands/manage/collections/index.js +10 -4
  10. package/build/cli/cli/commands/manage/collections/list.d.ts.map +1 -1
  11. package/build/cli/cli/commands/manage/collections/list.js +49 -8
  12. package/build/cli/cli/commands/manage/collections/promote.d.ts.map +1 -1
  13. package/build/cli/cli/commands/manage/collections/promote.js +69 -21
  14. package/build/cli/cli/commands/manage/collections/update-expiration.d.ts.map +1 -1
  15. package/build/cli/cli/commands/manage/collections/update-expiration.js +12 -12
  16. package/build/cli/cli/commands/manage/deploy.d.ts +2 -0
  17. package/build/cli/cli/commands/manage/deploy.d.ts.map +1 -0
  18. package/build/cli/cli/commands/manage/deploy.js +194 -0
  19. package/build/cli/cli/commands/manage/dev.d.ts +2 -0
  20. package/build/cli/cli/commands/manage/dev.d.ts.map +1 -0
  21. package/build/cli/cli/commands/manage/dev.js +78 -0
  22. package/build/cli/cli/commands/manage/eject.d.ts +2 -0
  23. package/build/cli/cli/commands/manage/eject.d.ts.map +1 -0
  24. package/build/cli/cli/commands/manage/eject.js +155 -0
  25. package/build/cli/cli/commands/manage/index.d.ts.map +1 -1
  26. package/build/cli/cli/commands/manage/index.js +42 -5
  27. package/build/cli/cli/commands/manage/publish-content.d.ts.map +1 -1
  28. package/build/cli/cli/commands/manage/publish-content.js +83 -37
  29. package/build/cli/cli/commands/manage/status.d.ts +2 -0
  30. package/build/cli/cli/commands/manage/status.d.ts.map +1 -0
  31. package/build/cli/cli/commands/manage/status.js +162 -0
  32. package/build/cli/cli/commands/manage/template/index.d.ts +2 -0
  33. package/build/cli/cli/commands/manage/template/index.d.ts.map +1 -0
  34. package/build/cli/cli/commands/manage/template/index.js +43 -0
  35. package/build/cli/cli/commands/manage/template/init.d.ts +13 -0
  36. package/build/cli/cli/commands/manage/template/init.d.ts.map +1 -0
  37. package/build/cli/cli/commands/manage/template/init.js +172 -0
  38. package/build/cli/cli/commands/manage/upgrade.d.ts +2 -0
  39. package/build/cli/cli/commands/manage/upgrade.d.ts.map +1 -0
  40. package/build/cli/cli/commands/manage/upgrade.js +59 -0
  41. package/build/cli/cli/commands/run-dev-watch.d.ts +8 -0
  42. package/build/cli/cli/commands/run-dev-watch.d.ts.map +1 -0
  43. package/build/cli/cli/commands/run-dev-watch.js +41 -0
  44. package/build/cli/cli/commands/run-template-hook.d.ts +2 -0
  45. package/build/cli/cli/commands/run-template-hook.d.ts.map +1 -0
  46. package/build/cli/cli/commands/run-template-hook.js +28 -0
  47. package/build/cli/cli/commands/scaffold/app-template.d.ts +17 -0
  48. package/build/cli/cli/commands/scaffold/app-template.d.ts.map +1 -0
  49. package/build/cli/cli/commands/scaffold/app-template.js +54 -0
  50. package/build/cli/cli/commands/scaffold/fastly-toml-sections.d.ts +5 -0
  51. package/build/cli/cli/commands/scaffold/fastly-toml-sections.d.ts.map +1 -0
  52. package/build/cli/cli/commands/scaffold/fastly-toml-sections.js +154 -0
  53. package/build/cli/cli/commands/scaffold/generate-app.d.ts +47 -0
  54. package/build/cli/cli/commands/scaffold/generate-app.d.ts.map +1 -0
  55. package/build/cli/cli/commands/scaffold/generate-app.js +164 -0
  56. package/build/cli/cli/commands/scaffold/index.d.ts +6 -0
  57. package/build/cli/cli/commands/scaffold/index.d.ts.map +1 -1
  58. package/build/cli/cli/commands/scaffold/index.js +208 -290
  59. package/build/cli/cli/commands/scaffold/render.d.ts +7 -0
  60. package/build/cli/cli/commands/scaffold/render.d.ts.map +1 -0
  61. package/build/cli/cli/commands/scaffold/render.js +72 -0
  62. package/build/cli/cli/hono/build.d.ts +43 -0
  63. package/build/cli/cli/hono/build.d.ts.map +1 -0
  64. package/build/cli/cli/hono/build.js +298 -0
  65. package/build/cli/cli/index.js +98 -5
  66. package/build/cli/cli/managed/app.d.ts +21 -0
  67. package/build/cli/cli/managed/app.d.ts.map +1 -0
  68. package/build/cli/cli/managed/app.js +162 -0
  69. package/build/cli/cli/managed/command-helpers.d.ts +6 -0
  70. package/build/cli/cli/managed/command-helpers.d.ts.map +1 -0
  71. package/build/cli/cli/managed/command-helpers.js +81 -0
  72. package/build/cli/cli/managed/eject.d.ts +6 -0
  73. package/build/cli/cli/managed/eject.d.ts.map +1 -0
  74. package/build/cli/cli/managed/eject.js +68 -0
  75. package/build/cli/cli/managed/fastly-service.d.ts +8 -0
  76. package/build/cli/cli/managed/fastly-service.d.ts.map +1 -0
  77. package/build/cli/cli/managed/fastly-service.js +21 -0
  78. package/build/cli/cli/managed/fingerprint.d.ts +13 -0
  79. package/build/cli/cli/managed/fingerprint.d.ts.map +1 -0
  80. package/build/cli/cli/managed/fingerprint.js +60 -0
  81. package/build/cli/cli/managed/lockfile.d.ts +31 -0
  82. package/build/cli/cli/managed/lockfile.d.ts.map +1 -0
  83. package/build/cli/cli/managed/lockfile.js +62 -0
  84. package/build/cli/cli/managed/project-edit.d.ts +3 -0
  85. package/build/cli/cli/managed/project-edit.d.ts.map +1 -0
  86. package/build/cli/cli/managed/project-edit.js +35 -0
  87. package/build/cli/cli/managed/project-file.d.ts +16 -0
  88. package/build/cli/cli/managed/project-file.d.ts.map +1 -0
  89. package/build/cli/cli/managed/project-file.js +119 -0
  90. package/build/cli/cli/managed/template-init.d.ts +12 -0
  91. package/build/cli/cli/managed/template-init.d.ts.map +1 -0
  92. package/build/cli/cli/managed/template-init.js +120 -0
  93. package/build/cli/cli/managed/version-check.d.ts +25 -0
  94. package/build/cli/cli/managed/version-check.d.ts.map +1 -0
  95. package/build/cli/cli/managed/version-check.js +84 -0
  96. package/build/cli/cli/storage/kv-store-local-provider.d.ts +1 -0
  97. package/build/cli/cli/storage/kv-store-local-provider.d.ts.map +1 -1
  98. package/build/cli/cli/storage/kv-store-local-provider.js +6 -3
  99. package/build/cli/cli/storage/kv-store-provider.d.ts +1 -0
  100. package/build/cli/cli/storage/kv-store-provider.d.ts.map +1 -1
  101. package/build/cli/cli/storage/kv-store-provider.js +9 -1
  102. package/build/cli/cli/storage/s3-storage-provider.d.ts +1 -0
  103. package/build/cli/cli/storage/s3-storage-provider.d.ts.map +1 -1
  104. package/build/cli/cli/storage/s3-storage-provider.js +4 -0
  105. package/build/cli/cli/storage/storage-provider.d.ts +3 -0
  106. package/build/cli/cli/storage/storage-provider.d.ts.map +1 -1
  107. package/build/cli/cli/storage/storage-provider.js +32 -0
  108. package/build/cli/cli/util/api-token.d.ts.map +1 -1
  109. package/build/cli/cli/util/collection-name.d.ts +3 -0
  110. package/build/cli/cli/util/collection-name.d.ts.map +1 -0
  111. package/build/cli/cli/util/collection-name.js +24 -0
  112. package/build/cli/cli/util/collection-selection-flags.d.ts +13 -0
  113. package/build/cli/cli/util/collection-selection-flags.d.ts.map +1 -0
  114. package/build/cli/cli/util/collection-selection-flags.js +131 -0
  115. package/build/cli/cli/util/config.d.ts +13 -0
  116. package/build/cli/cli/util/config.d.ts.map +1 -1
  117. package/build/cli/cli/util/config.js +172 -38
  118. package/build/cli/cli/util/data.d.ts.map +1 -1
  119. package/build/cli/cli/util/global-options.d.ts +13 -0
  120. package/build/cli/cli/util/global-options.d.ts.map +1 -0
  121. package/build/cli/cli/util/global-options.js +53 -0
  122. package/build/cli/cli/util/kv-store-items.d.ts +1 -0
  123. package/build/cli/cli/util/kv-store-items.d.ts.map +1 -1
  124. package/build/cli/cli/util/kv-store-items.js +16 -40
  125. package/build/cli/cli/util/kv-store-local-server.d.ts +1 -1
  126. package/build/cli/cli/util/kv-store-local-server.d.ts.map +1 -1
  127. package/build/cli/cli/util/kv-store-local-server.js +4 -2
  128. package/build/cli/cli/util/output.d.ts +31 -0
  129. package/build/cli/cli/util/output.d.ts.map +1 -0
  130. package/build/cli/cli/util/output.js +139 -0
  131. package/build/cli/cli/util/package.d.ts +6 -0
  132. package/build/cli/cli/util/package.d.ts.map +1 -1
  133. package/build/cli/cli/util/package.js +23 -0
  134. package/build/cli/cli/util/progress.d.ts.map +1 -1
  135. package/build/cli/cli/util/purge.d.ts +6 -2
  136. package/build/cli/cli/util/purge.d.ts.map +1 -1
  137. package/build/cli/cli/util/purge.js +7 -2
  138. package/build/cli/cli/util/resources.d.ts +2 -0
  139. package/build/cli/cli/util/resources.d.ts.map +1 -0
  140. package/build/cli/cli/util/resources.js +8 -0
  141. package/build/cli/cli/util/service-id.d.ts +1 -0
  142. package/build/cli/cli/util/service-id.d.ts.map +1 -1
  143. package/build/cli/cli/util/service-id.js +5 -1
  144. package/build/cli/cli/util/variants.d.ts.map +1 -1
  145. package/build/cli/models/assets/index.d.ts +6 -0
  146. package/build/cli/models/assets/index.d.ts.map +1 -1
  147. package/build/cli/models/assets/index.js +24 -0
  148. package/build/cli/models/collections/index.d.ts +3 -0
  149. package/build/cli/models/collections/index.d.ts.map +1 -0
  150. package/build/cli/models/collections/index.js +15 -0
  151. package/build/cli/models/compression/index.d.ts +1 -1
  152. package/build/cli/models/compression/index.d.ts.map +1 -1
  153. package/build/cli/models/config/collection-selection.d.ts +55 -0
  154. package/build/cli/models/config/collection-selection.d.ts.map +1 -0
  155. package/build/cli/models/config/collection-selection.js +238 -0
  156. package/build/cli/models/config/item-patterns.d.ts +4 -0
  157. package/build/cli/models/config/item-patterns.d.ts.map +1 -0
  158. package/build/cli/models/config/item-patterns.js +43 -0
  159. package/build/cli/models/config/publish-content-config.d.ts +6 -1
  160. package/build/cli/models/config/publish-content-config.d.ts.map +1 -1
  161. package/build/cli/models/config/static-publish-project.d.ts +23 -0
  162. package/build/cli/models/config/static-publish-project.d.ts.map +1 -0
  163. package/build/cli/models/config/static-publish-project.js +11 -0
  164. package/build/cli/models/config/static-publish-rc.d.ts +25 -0
  165. package/build/cli/models/config/static-publish-rc.d.ts.map +1 -1
  166. package/build/cli/models/config/static-publish-rc.js +31 -0
  167. package/build/cli/models/config/template-settings.d.ts +10 -0
  168. package/build/cli/models/config/template-settings.d.ts.map +1 -0
  169. package/build/cli/models/config/template-settings.js +72 -0
  170. package/build/cli/models/server/index.d.ts.map +1 -1
  171. package/build/cli/models/server/index.js +6 -2
  172. package/build/server/hono/extensions.d.ts +48 -0
  173. package/build/server/hono/extensions.d.ts.map +1 -0
  174. package/build/server/hono/extensions.js +65 -0
  175. package/build/server/hono/index.d.ts +30 -0
  176. package/build/server/hono/index.d.ts.map +1 -0
  177. package/build/server/hono/index.js +72 -0
  178. package/build/server/hono/path.d.ts +7 -0
  179. package/build/server/hono/path.d.ts.map +1 -0
  180. package/build/server/hono/path.js +32 -0
  181. package/build/server/models/assets/index.d.ts +6 -0
  182. package/build/server/models/assets/index.d.ts.map +1 -1
  183. package/build/server/models/assets/index.js +24 -0
  184. package/build/server/models/collections/index.d.ts +3 -0
  185. package/build/server/models/collections/index.d.ts.map +1 -0
  186. package/build/server/models/collections/index.js +15 -0
  187. package/build/server/models/compression/index.d.ts +1 -1
  188. package/build/server/models/compression/index.d.ts.map +1 -1
  189. package/build/server/models/config/collection-selection.d.ts +55 -0
  190. package/build/server/models/config/collection-selection.d.ts.map +1 -0
  191. package/build/server/models/config/collection-selection.js +238 -0
  192. package/build/server/models/config/item-patterns.d.ts +4 -0
  193. package/build/server/models/config/item-patterns.d.ts.map +1 -0
  194. package/build/server/models/config/item-patterns.js +43 -0
  195. package/build/server/models/config/publish-content-config.d.ts +6 -1
  196. package/build/server/models/config/publish-content-config.d.ts.map +1 -1
  197. package/build/server/models/config/static-publish-project.d.ts +23 -0
  198. package/build/server/models/config/static-publish-project.d.ts.map +1 -0
  199. package/build/server/models/config/static-publish-project.js +11 -0
  200. package/build/server/models/config/static-publish-rc.d.ts +25 -0
  201. package/build/server/models/config/static-publish-rc.d.ts.map +1 -1
  202. package/build/server/models/config/static-publish-rc.js +31 -0
  203. package/build/server/models/server/index.d.ts.map +1 -1
  204. package/build/server/models/server/index.js +6 -2
  205. package/build/server/server/collection-selection/index.d.ts +11 -0
  206. package/build/server/server/collection-selection/index.d.ts.map +1 -0
  207. package/build/server/server/collection-selection/index.js +192 -0
  208. package/build/server/server/collection-selector/from-cookie.d.ts.map +1 -1
  209. package/build/server/server/collection-selector/from-cookie.js +6 -8
  210. package/build/server/server/collection-selector/from-request.d.ts.map +1 -1
  211. package/build/server/server/index.d.ts +4 -1
  212. package/build/server/server/index.d.ts.map +1 -1
  213. package/build/server/server/index.js +3 -1
  214. package/build/server/server/publisher-server/accept-html.d.ts +2 -0
  215. package/build/server/server/publisher-server/accept-html.d.ts.map +1 -0
  216. package/build/server/server/publisher-server/accept-html.js +50 -0
  217. package/build/server/server/publisher-server/index.d.ts +59 -7
  218. package/build/server/server/publisher-server/index.d.ts.map +1 -1
  219. package/build/server/server/publisher-server/index.js +362 -145
  220. package/build/server/server/publisher-server/response-cache.d.ts +3 -0
  221. package/build/server/server/publisher-server/response-cache.d.ts.map +1 -1
  222. package/build/server/server/publisher-server/response-cache.js +24 -1
  223. package/build/server/server/storage/kv-store-provider.d.ts.map +1 -1
  224. package/build/server/server/storage/s3-storage-provider.d.ts.map +1 -1
  225. package/build/server/server/storage/storage-provider.d.ts.map +1 -1
  226. package/build/server/server/util/body-length.d.ts.map +1 -1
  227. package/build/server/server/util/server-timing.d.ts.map +1 -1
  228. package/package.json +21 -3
  229. package/resources/app/fastly.toml.njk +58 -0
  230. package/resources/app/gitignore.njk +9 -0
  231. package/resources/app/publish-content.config.from-project.js.njk +9 -0
  232. package/resources/app/publish-content.config.js.njk +35 -0
  233. package/resources/app/static-publish.project.js.njk +83 -0
  234. package/resources/app/static-publish.rc.js.njk +43 -0
  235. package/resources/template-init/hono/_example.ts +22 -0
  236. package/resources/template-init/hono/tsconfig.json +17 -0
  237. package/resources/templates/hono/package-lock.json +4123 -0
  238. package/resources/templates/hono/package.json +15 -0
  239. package/resources/templates/hono/scripts/template_postinstall.js +10 -0
  240. package/resources/templates/hono/scripts/template_prebuild.js +8 -0
  241. package/resources/templates/hono/scripts/template_watch.js +15 -0
  242. package/resources/templates/hono/src/hono-extensions.generated.d.ts +5 -0
  243. package/resources/templates/hono/src/index.ts +53 -0
  244. package/resources/templates/hono/tsconfig.json +17 -0
  245. package/resources/templates/plain/package-lock.json +4088 -0
  246. package/resources/templates/plain/package.json +10 -0
  247. package/resources/templates/plain/src/index.js +34 -0
package/DOCUMENTATION.md CHANGED
@@ -24,6 +24,7 @@
24
24
  - [🧹 Cleaning Up](#-cleaning-up)
25
25
  - [🔄 Content Compression](#-content-compression)
26
26
  - [🧩 Using PublisherServer in Custom Apps](#-using-publisherserver-in-custom-apps)
27
+ - [🔥 Using Hono](#-using-hono)
27
28
  - [📥 Using Published Assets in Your Code](#-using-published-assets-in-your-code)
28
29
  - [📚 CLI Reference](#-cli-reference)
29
30
  - [📕 Appendix](#-appendix)
@@ -56,7 +57,7 @@ Serve static websites and web apps at the edge — no backends and no CDN in
56
57
  Create a directory for your project, place your static files in `./public`, then type:
57
58
 
58
59
  ```sh
59
- npx @fastly/compute-js-static-publish@latest \
60
+ npx @fastly/compute-js-static-publish@beta \
60
61
  --root-dir=./public \
61
62
  --kv-store-name=site-content
62
63
  ```
@@ -117,7 +118,7 @@ FASTLY_API_TOKEN=$(npx fastly auth token) npm run fastly:publish
117
118
  Create a directory for your project, place your static files in `./public`, then type:
118
119
 
119
120
  ```sh
120
- npx @fastly/compute-js-static-publish@latest \
121
+ npx @fastly/compute-js-static-publish@beta \
121
122
  --root-dir=./public \
122
123
  --storage-mode=s3 \
123
124
  --s3-region=<s3 region> \
@@ -128,13 +129,15 @@ npx @fastly/compute-js-static-publish@latest \
128
129
  > If the storage requires a custom endpoint, such as is the case with Fastly Object Storage, specify it using `--s3-endpoint=<endpoint>`. For example:
129
130
  >
130
131
  > ```sh
131
- > npx @fastly/compute-js-static-publish@latest \
132
+ > npx @fastly/compute-js-static-publish@beta \
132
133
  > --root-dir=./public \
133
134
  > --storage-mode=s3 \
134
- > --s3-region=us-east \
135
+ > --s3-region=us-east-1 \
135
136
  > --s3-bucket=my-static-content-bucket \
136
- > --s3-endpoint=https://us-east.object.fastlystorage.app
137
+ > --s3-endpoint=https://us-east-1.object.fastlystorage.app
137
138
  > ```
139
+ >
140
+ > For the regions of Fastly Object Storage and their endpoints, see [Working with Object Storage](https://www.fastly.com/documentation/guides/platform/object-storage/working-with-object-storage/#managing-object-storage-buckets-and-objects).
138
141
 
139
142
  You get a Compute app in `./compute-js` with:
140
143
 
@@ -208,10 +211,158 @@ my-project/
208
211
  ├── static-publisher/ # ⚠️ Do not commit - generated content for local dev and publishing
209
212
  │ ├── kvstore.json # Simulates KV Store content for local preview
210
213
  │ └── kv-store-content/ # Preprocessed and compressed files for KV upload
214
+ ├── scripts/ # Optional: template hooks (template_<hook>.js, template_watch.js)
211
215
  └── src/
212
216
  └── index.js # Your Compute app entry point
213
217
  ```
214
218
 
219
+ ### Managed and ejected apps
220
+
221
+ From 8.1.0, a project can be **managed** or **ejected**:
222
+
223
+ | | Managed | Ejected |
224
+ |---|---|---|
225
+ | In the repo | One file, `static-publish.project.js`, in the project dir | The app dir (`compute-js/`) with `static-publish.rc.js` and `publish-content.config.js`, as above |
226
+ | Who owns the app code | This package: it generates the app | You |
227
+ | Upgrade this package | Run `upgrade`; the next `deploy` deploys the new app | Change the files by hand (see `MIGRATING.md`) |
228
+ | Deploy | `deploy`, only when the generated app changed | `npm run fastly:deploy` (or `deploy`) |
229
+ | Customize | The options of the project file | Anything |
230
+
231
+ An **ejected app** is in the repo, and you own its code. Every app that `scaffold` makes without `--managed`, and every app made before 8.1.0, is an ejected app. A **managed project** has only a project file in the repo, and this package generates the app when it needs it.
232
+
233
+ `scaffold` makes an ejected app, as before. `scaffold --managed` makes a managed project. `eject` converts a managed project into an ejected app. To move an existing app to managed mode, see `MIGRATING.md`.
234
+
235
+ #### Managed projects
236
+
237
+ `scaffold --managed` writes only one file, `static-publish.project.js`, in the current directory (the project dir), and adds `.static-publish/` and the working directory to the `.gitignore` there:
238
+
239
+ ```
240
+ my-site/
241
+ ├── static-publish.project.js # Commit this: the only config file
242
+ ├── public/ # Your static site files
243
+ ├── .gitignore # Ignores .static-publish/ and static-publisher/
244
+ └── static-publisher/ # ⚠️ Do not commit - the working directory
245
+ ```
246
+
247
+ The project file has the settings that an ejected app has in its two files:
248
+
249
+ - The top level has the fields of `static-publish.rc.js` (`storageMode`, `kvStore` or `s3`, `publishId`, `defaultCollectionName`, `staticPublisherWorkingDir`, `collectionSelection`), and the settings of the template (`build` and `templateOptions`, see [Hono extensions](#hono-extensions)).
250
+ - `publishContent` has the fields of `publish-content.config.js`. `publish-content --config <file>` replaces it for one run.
251
+ - `managed` has the settings of the generated app (`name`, `description`, `authors`, `serviceId`, `staticPublishVersion`, the version of this package that the project uses, and `fastlyToml`, see below).
252
+
253
+ Paths in the project file are relative to it. The name of the file marks the mode: a directory with `static-publish.project.js` is a managed project, and a directory with `static-publish.rc.js` is an ejected app. A directory with both is an error.
254
+
255
+ `publish-content`, `collections`, and `clean` run in the project dir (or with `--project-dir`), and read the project file. `publish-content` purges the service of `managed.serviceId`, after `--fastly-service-id` and `FASTLY_SERVICE_ID`.
256
+
257
+ To run the app on your computer:
258
+
259
+ ```sh
260
+ npx @fastly/compute-js-static-publish@beta publish-content --local
261
+ npx @fastly/compute-js-static-publish@beta dev
262
+ ```
263
+
264
+ `dev` generates the app in `.static-publish/app/`, installs its dependencies with `npm ci` if they changed, and runs `fastly compute serve` in it. Options after `--` go to `fastly compute serve`, for example `dev -- --addr=127.0.0.1:8080`. With `dev -- --watch`, a change in the app builds and restarts it, and the watch script of the template (`scripts/template_watch.js`, see [Template hooks](#-template-hooks)), if it has one, runs next to `fastly compute serve`. The app serves the content of the local KV Store, `kvstore.json` in the working directory.
265
+
266
+ **Local resources and setup in `fastly.toml`.** The CLI generates the `fastly.toml` of the app. To add resources for `fastly compute serve` (`[local_server]`) or for the first deploy, which makes the service (`[setup]`), add them to `managed.fastlyToml`, in the structure of [`fastly.toml`](https://www.fastly.com/documentation/reference/compute/fastly-toml/). For example, a local Secret Store and a local Config Store:
267
+
268
+ ```js
269
+ managed: {
270
+ // ...
271
+ fastlyToml: {
272
+ local_server: {
273
+ secret_stores: { oauth: [ { key: 'GITHUB_CLIENT_SECRET', env: 'GITHUB_CLIENT_SECRET' } ] },
274
+ config_stores: { site_config: { format: 'inline-toml', contents: { greeting: 'hello' } } },
275
+ },
276
+ setup: {
277
+ secret_stores: { oauth: { entries: { GITHUB_CLIENT_SECRET: { description: 'The client secret' } } } },
278
+ },
279
+ },
280
+ },
281
+ ```
282
+
283
+ - Only `local_server` and `setup` can be added. The CLI writes the other parts of `fastly.toml`.
284
+ - The CLI also writes some resources: the KV Store of the content, and in S3 mode, the `S3_CREDENTIALS` Secret Store and the `s3_storage` backend. A resource with one of these names is an error.
285
+ - Do not put a secret in the project file: in `local_server`, read it from an environment variable (`env`) or a file (`file`) that is not committed.
286
+ - `local_server` does not change the fingerprint, because it is only for `fastly compute serve`. `setup` changes it.
287
+ - `eject` writes the sections into the `fastly.toml` of the ejected app.
288
+
289
+ `managed.template` selects the template of the app: `plain` (the default) or `hono`. To switch, change it. The next `dev` or `deploy` generates the app again with the new template, and `npm ci` installs its dependencies. The fingerprint changes, so `deploy` deploys again. Files of the old template can stay in `.static-publish/app/`. They do not change the build. To remove them, delete `.static-publish/`: the next `dev` or `deploy` generates it again.
290
+
291
+ The same version of this package always generates the same app, with the same versions of all dependencies: this package has a lockfile for the app of each template. The app uses the copy of this package that runs the CLI, through a `file:` link. Thus, add this package as a dev dependency of your project, and run the CLI from it, so that the version is pinned:
292
+
293
+ ```sh
294
+ npm install --save-dev @fastly/compute-js-static-publish
295
+ ```
296
+
297
+ To deploy the app:
298
+
299
+ ```sh
300
+ npx @fastly/compute-js-static-publish@beta deploy
301
+ ```
302
+
303
+ `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`).
304
+
305
+ - **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.
306
+ - **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`. 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.
307
+ - `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.
308
+
309
+ **The version of this package.** `managed.staticPublishVersion` records the version of this package that the project uses. `dev` and `deploy` compare it with the version that runs:
310
+
311
+ | The CLI that runs | Result |
312
+ |---|---|
313
+ | The same version | Continue. |
314
+ | A newer version | Stop. Run `upgrade` to move the project to the new version (and commit the project file), or use `--auto-upgrade`. |
315
+ | An older version | Stop. An older version never deploys over an app that a newer version made. |
316
+
317
+ Thus a new release of this package never changes your app by itself, also with `npx @fastly/compute-js-static-publish@latest`.
318
+
319
+ **Eject.** `eject` converts a managed project into an ejected app that you own:
320
+
321
+ - It writes the app that `deploy` would deploy into `./compute-js` (or `--dir`). It refuses a directory that exists, unless `--force`.
322
+ - It splits the project file into `compute-js/static-publish.rc.js` (with `generatedFrom`) and `compute-js/publish-content.config.js`, and writes the paths again, so that they point at the same directories (for example `staticPublisherWorkingDir: '../static-publisher'`). Then it deletes `static-publish.project.js`.
323
+ - `publishContent` must be data: eject cannot copy functions or regular expressions (for example `assetInclusionTest`). If it has them, eject stops before it writes anything. Remove them, eject, and add them to `compute-js/publish-content.config.js` by hand.
324
+ - `package.json` gets `"@fastly/compute-js-static-publish": "^<version>"`, and the lockfile has exactly `<version>`, so that the first ejected build is the same app. This needs a version that is published on npm, and one `npm install` (network access).
325
+ - After eject, run the commands in `compute-js/`. Run `publish-content --local` again before `npm run dev:start`. You can delete `.static-publish/`.
326
+
327
+ **API token scopes.** Give CI the least access that it needs. As far as we know (check the [Fastly documentation of API tokens](https://www.fastly.com/documentation/reference/api/auth-tokens/)):
328
+
329
+ | Command | Scope |
330
+ |---|---|
331
+ | `status` (the active version of the service) | `global:read` |
332
+ | `publish-content` and `collections` with the KV Store (writes) | `global` |
333
+ | The purge after `publish-content` (S3 storage) | `purge_select` |
334
+ | `deploy` | `global` |
335
+
336
+ Limit the token to the service of the project, where possible.
337
+
338
+
339
+ ### 🪝 Template hooks
340
+
341
+ The `package.json` of a scaffolded app has these scripts:
342
+
343
+ ```json
344
+ "prebuild": "compute-js-static-publish run-template-hook prebuild",
345
+ "build": "js-compute-runtime ./src/index.js ./bin/main.wasm",
346
+ "postbuild": "compute-js-static-publish run-template-hook postbuild",
347
+ "postinstall": "compute-js-static-publish run-template-hook postinstall"
348
+ ```
349
+
350
+ `run-template-hook <name>` runs `scripts/template_<name>.js` if that file exists, and otherwise does nothing. Thus, to run your own code before or after each build, or after each `npm install`, add one of these files:
351
+
352
+ - `scripts/template_prebuild.js`
353
+ - `scripts/template_postbuild.js`
354
+ - `scripts/template_postinstall.js`
355
+
356
+ The file runs with Node.js, in the directory of the app. If it fails, the build or the install fails. `fastly compute build`, `fastly compute serve`, and `fastly compute publish` run `npm run build`, so they also run the build hooks. `npm install --ignore-scripts` does not run the hooks.
357
+
358
+ The app also has a `dev:watch` script:
359
+
360
+ ```json
361
+ "dev:watch": "compute-js-static-publish run-dev-watch"
362
+ ```
363
+
364
+ `npm run dev:watch` runs `fastly compute serve --watch`, which builds and restarts the app when a file in the app directory changes. Options after `--` go to `fastly compute serve`, for example `npm run dev:watch -- --addr=127.0.0.1:8080`. If the app has `scripts/template_watch.js`, that file runs with Node.js next to the Fastly CLI, until the Fastly CLI stops. Use it to watch files outside the app directory: when they change, write a file in the app directory, and the Fastly CLI builds the app again.
365
+
215
366
  ## ⚙️ Configuring `static-publish.rc.js`
216
367
 
217
368
  This file defines your compute-js-static-publish application's settings. A copy of this is also baked into the Wasm binary and loaded when running your Compute app locally or on the edge.
@@ -229,7 +380,8 @@ All fields are required unless specified otherwise.
229
380
  - `kvStore.kvStoreName` - The name of the KV Store used for publishing.
230
381
  - `defaultCollectionName` - Collection to serve when none is specified.
231
382
  - `publishId` - Unique prefix for all keys in the KV Store. Override only for advanced setups (e.g., multiple apps sharing the same KV Store).
232
- - `staticPublisherWorkingDir` - Directory to hold working files during publish.
383
+ - `staticPublisherWorkingDir` - Directory to hold working files during publish. The path is relative to the directory of `static-publish.rc.js`.
384
+ - `generatedFrom` - (optional) A record of how the app was made: the template, the version of this package, and the date. The scaffolder writes it. The app does not use it.
233
385
 
234
386
  #### Example: `static-publish.rc.js`
235
387
 
@@ -259,7 +411,8 @@ All fields are required unless specified otherwise.
259
411
  - `s3.endpoint` - (optional) The custom endpoint for the S3-compatible bucket.
260
412
  - `defaultCollectionName` - Collection to serve when none is specified.
261
413
  - `publishId` - Unique prefix for all keys in the bucket. Override only for advanced setups (e.g., multiple apps sharing the same bucket).
262
- - `staticPublisherWorkingDir` - Directory to hold working files during publish.
414
+ - `staticPublisherWorkingDir` - Directory to hold working files during publish. The path is relative to the directory of `static-publish.rc.js`.
415
+ - `generatedFrom` - (optional) A record of how the app was made: the template, the version of this package, and the date. The scaffolder writes it. The app does not use it.
263
416
 
264
417
  #### Example: `static-publish.rc.js`
265
418
 
@@ -297,6 +450,9 @@ const config = {
297
450
  return true; // include everything by default
298
451
  },
299
452
 
453
+ // Files to publish as hidden files (optional):
454
+ hiddenItems: ['/404.html', '/templates/'],
455
+
300
456
  // Override which compressed variants to create for each asset during publish (optional):
301
457
  contentCompression: ['br', 'gzip'],
302
458
 
@@ -330,7 +486,8 @@ You can override this file for a single `publish-content` command by specifying
330
486
  - `excludeDirs` - Array of directory names or regex patterns to exclude (default: `['./node_modules']`).
331
487
  - `excludeDotFiles` - Exclude dotfiles and dot-named directories (default: true).
332
488
  - `includeWellKnown` - Always include `.well-known` even if dotfiles are excluded (default: true).
333
- - `assetInclusionTest` - Function to determine inclusion and variant behavior per file.
489
+ - `assetInclusionTest` - Function to determine inclusion and variant behavior per file. Return `false` to leave the file out, `true` to include it, or `{ hidden: true }` to include it as a [hidden file](#hidden-files).
490
+ - `hiddenItems` - The files to publish as [hidden files](#hidden-files). The same format as `server.staticItems`, tested against the asset key (the path relative to `rootDir`): a directory that ends with `/`, an exact path, a glob pattern, or `'re:/<regex>/<flags>'` (default: none).
334
491
  - `contentCompression` - Array of compression formats to pre-generate (`['br', 'gzip']` by default).
335
492
  - `brotliQuality` - Brotli quality for the `br` variants, an integer from 0 to 11 (default: 11). Quality 11 gives the smallest files but is the slowest. Quality 10 is approximately 3 times faster, and its files are approximately 2% larger. If you change this value, variants that are already in storage are not compressed again.
336
493
  - `contentTypes` - Additional or override content type definitions.
@@ -343,7 +500,10 @@ You can override this file for a single `publish-content` command by specifying
343
500
  `'../site/public'`, set it to `'/public'`. The value starts with `/` and does not
344
501
  end with `/` (default: `''`). The scaffolder sets it from `--root-dir` and `--public-dir`.
345
502
  - `spaFile` - Path to a file to be used to serve in a SPA application.
346
- - `notFoundPageFile` - Path to a file to be used to serve as a 404 not found page.
503
+ - `notFoundPageFile` - Path to a file to be used to serve as a 404 not found page.
504
+ The server serves `spaFile` or `notFoundPageFile` only to a request that accepts HTML: its `Accept`
505
+ header is missing or empty, or has `text/html`, `text/*`, or `*/*` with a q-value that is not 0.
506
+ For other requests, `serveRequest()` returns `null`.
347
507
  - `autoIndex` - List of files to automatically use as index.
348
508
  - `autoExt` - List of extensions to automatically apply to a path and retry when
349
509
  the requested path is not found.
@@ -352,6 +512,33 @@ You can override this file for a single `publish-content` command by specifying
352
512
  - `allowedEncodings` - Specifies which compression formats the server is allowed
353
513
  to serve based on the client's `Accept-Encoding` header.
354
514
 
515
+ ### Hidden files
516
+
517
+ A hidden file is published, but the Publisher Server does not serve it for a request, also not through `autoExt` or `autoIndex`. Use hidden files for:
518
+
519
+ - The 404 page: a request for `/404.html` must not get the 404 page with status `200`. If the `spaFile` or the `notFoundPageFile` is hidden, the server still serves it as the fallback page.
520
+ - Files that your code reads, for example templates. Get them with `getMatchingAsset(key, { includeHidden: true })` (see [Using Published Assets in Your Code](#-using-published-assets-in-your-code)).
521
+
522
+ A file is hidden if `hiddenItems` selects it, or if `assetInclusionTest` returns `{ hidden: true }` for it:
523
+
524
+ ```js
525
+ const config = {
526
+ rootDir: '../public',
527
+ hiddenItems: ['/404.html', '/templates/'],
528
+ assetInclusionTest: (key) => key.endsWith('.tpl') ? { hidden: true } : true,
529
+ server: {
530
+ notFoundPageFile: '/404.html',
531
+ },
532
+ };
533
+ ```
534
+
535
+ `publish-content` and `collections list` show the number of hidden files.
536
+
537
+ > [!WARNING]
538
+ > **Hidden is not access control.** Hidden files are in storage (the KV Store or the bucket), the same as the other files, and code that asks for hidden files can serve them. Do not use hidden files for secrets.
539
+
540
+ A collection that has hidden files requires the `hidden` feature. An app that is built with a version earlier than 8.1.0 does not serve such a collection (8.0), or does not find its hidden files (earlier versions). Build and deploy your app with 8.1.0 or later before you publish hidden files.
541
+
355
542
  ## 📦 Collections (Publish, Preview, Promote)
356
543
 
357
544
  Collections are a powerful feature that allow you to publish and manage multiple versions of your site simultaneously. Each collection is a named set of:
@@ -363,7 +550,7 @@ Collections are a powerful feature that allow you to publish and manage multiple
363
550
  Collections are published using a `--collection-name`, and can be reused, updated, or deleted independently. For example, you can create a staging version of your site using:
364
551
 
365
552
  ```sh
366
- npx @fastly/compute-js-static-publish publish-content \
553
+ npx @fastly/compute-js-static-publish@beta publish-content \
367
554
  --collection-name=staging \
368
555
  --expires-in=7d \
369
556
  --config=./publish-content.config.js
@@ -371,6 +558,8 @@ npx @fastly/compute-js-static-publish publish-content \
371
558
 
372
559
  You can overwrite or republish any collection at any time. Old file hashes will be reused automatically where contents match.
373
560
 
561
+ A collection name must be a DNS label: lowercase `a-z`, `0-9`, and `-`, from 1 to 63 characters, with no `-` at the start or the end (for example `live`, `staging`, `pr-42`). Thus a name is safe in storage keys, in cookies, and in hostnames. If a CI tool makes collection names from branch names, it must convert them to this form (for example `feature/Foo_bar` to `feature-foo-bar`). A collection that was published before this rule continues to work, with a warning, but new collections must follow it.
562
+
374
563
  ### Expiration (Auto-cleanup)
375
564
 
376
565
  Collections can expire automatically:
@@ -420,9 +609,156 @@ addEventListener("fetch", event => {
420
609
  });
421
610
  ```
422
611
 
612
+ ### 👀 Previews: Collection Selection
613
+
614
+ `collectionSelection` in `static-publish.rc.js` chooses the collection that serves each request, for example to show a preview of a pull request. It is off by default: without it, every request gets the default collection.
615
+
616
+ ```js
617
+ const rc = {
618
+ // ...
619
+ collectionSelection: {
620
+ // Tried in order. The first source that gives a collection wins.
621
+ // If no source gives a collection, the default collection is used.
622
+ sources: [
623
+ { type: 'host', pattern: '{collection}.preview.example.com' },
624
+ { type: 'path', prefix: '/_preview/{collection}', sticky: 'cookie' },
625
+ { type: 'query', param: 'collection', sticky: 'cookie' },
626
+ { type: 'cookie', cookieName: 'publisher-collection',
627
+ activatePath: '/activate', resetPath: '/reset', maxAge: 604800 },
628
+ { type: 'header', name: 'x-publisher-collection' },
629
+ ],
630
+ // The collections that can be selected ('*' matches any characters). Default: any.
631
+ allow: ['pr-*', 'staging'],
632
+ // The selected collection does not exist or has expired:
633
+ // 'not-found' (default) gives a 404 response, 'default' serves the default collection.
634
+ onMissing: 'not-found',
635
+ // X-Robots-Tag: noindex on the responses of a selected collection. Default: true.
636
+ noindex: true,
637
+ },
638
+ };
639
+ ```
640
+
641
+ | Source | Reads | Notes |
642
+ |--------|-------|-------|
643
+ | `host` | The hostname, matched against `pattern` | Needs a wildcard domain and TLS for it. The pattern has one `{collection}` in one label, with fixed text around it if you want (`branch-{collection}.preview.example.com`). A host label has at most 63 characters. Make sure that your production hostname does not match the pattern. |
644
+ | `path` | A path prefix, which is removed before the file lookup | Works on `*.edgecompute.app`. Links that start with `/` lose the prefix, so use it with `sticky: 'cookie'`, or for a site with relative links. The links in HTML do not change. |
645
+ | `query` | A query parameter | Only the request that has it. Usually used with `sticky: 'cookie'`. |
646
+ | `cookie` | A cookie | Also serves the activate path (`/activate?collection=<name>&redirectTo=<path>`) and the reset path. |
647
+ | `header` | A request header | For tests, CI checks, and API clients. |
648
+
649
+ - `sticky: 'cookie'` on a `path` or `query` source: when the source matches, set the cookie of the `cookie` source, and redirect (`308`) to the URL without the prefix or the parameter. It needs a `cookie` source.
650
+ - A name must follow the [collection name rule](#-collections-publish-preview-promote) and match `allow`. Otherwise the source is skipped.
651
+ - Redirects go only to a path on the same site. `redirectTo` with another site redirects to `/`.
652
+ - The responses of a selected collection (not the default collection) get `X-Robots-Tag: noindex` (unless `noindex` is `false`). They get `Cache-Control: private` if the URL does not name the collection. See [Shared caches](#shared-caches).
653
+ - To find out if a selected collection exists, `PublisherServer` reads its index, also when the [response cache](#️-caching-responses-with-the-core-cache) has the response.
654
+
655
+ The `plain` app does this in `src/index.js`. Apps scaffolded before 8.1.0 do not. To add it to such an app, change `src/index.js`:
656
+
657
+ ```js
658
+ const selection = publisherServer.resolveCollection(request);
659
+ if (selection.response != null) {
660
+ return selection.response; // a redirect (sticky, activate, reset), or an error
661
+ }
662
+ const response = await publisherServer.serveRequest(request, {
663
+ collectionName: selection.collectionName, // null: the default collection
664
+ pathname: selection.pathname, // the path without the prefix of a path source
665
+ });
666
+ ```
667
+
668
+ To scaffold an app with collection selection, use the [`--collection-selection` flags](#options). To show a link to a collection, for example in CI, use `previewUrl()`. It uses the first source that can make a URL:
669
+
670
+ ```js
671
+ import { previewUrl } from '@fastly/compute-js-static-publish';
672
+ import rc from './static-publish.rc.js';
673
+
674
+ previewUrl('pr-42', 'https://example.edgecompute.app', rc.collectionSelection);
675
+ // with the sources above: 'https://pr-42.preview.example.com/'
676
+ ```
677
+
678
+ > [!WARNING]
679
+ > A preview is public to anyone who knows its name. Use `allow` to limit the collections that can be selected, and do not publish content that must stay private.
680
+
681
+ #### Shared caches
682
+
683
+ A shared cache, for example a CDN in front of your service, can store a response and give it to other visitors. The [response cache](#️-caching-responses-with-the-core-cache) of `PublisherServer` keeps the responses of each collection apart, so this section is only about shared caches. For a shared cache, the response of a collection that is not the default collection depends on how the request selects the collection:
684
+
685
+ | Source | Does the URL name the collection? | `Cache-Control` |
686
+ |--------|-----------------------------------|-----------------|
687
+ | `host`, `path`, `query` | Yes | As for the default collection. A shared cache can store the response. |
688
+ | `cookie`, `header` | No: the same URL can serve another collection | `private`. A shared cache does not store the response. |
689
+ | `path` or `query` with `sticky: 'cookie'` | No: after the redirect, the cookie selects the collection | `private` |
690
+
691
+ A response gets `private` also when your code gives `serveRequest()` a `collectionName` that the sources of the request do not select. For a `query` source, the shared cache must keep the query string in its cache key.
692
+
693
+ **Previews with a cookie or a header:** the default collection and the preview have the same URLs. A shared cache can store a response of the default collection, and give it to a visitor who has the preview cookie. That visitor then sees the default collection in place of the preview. If a shared cache is in front of your service, select previews with a `host` or `path` source.
694
+
695
+ **More than one site in one service:** you can serve one site from each collection. Select the collection with a `host` source, for example `{collection}.example.com`, so that a shared cache can store the responses of each site. Also set `noindex: false`, because otherwise each site that is not the default collection gets `X-Robots-Tag: noindex`. A collection that expires stops being served, so do not set an expiration time for these collections.
696
+
697
+ **Without `collectionSelection`:** if your code chooses the collection, for example with `collectionSelector.fromCookie()` and `setActiveCollectionName()`, or with the `collectionName` option, `PublisherServer` does not add `Cache-Control: private` or `X-Robots-Tag: noindex`. Your code must add them when the URL does not name the collection. Otherwise a shared cache can store a preview and give it to other visitors.
698
+
699
+ `serveRequest()` returns a normal `Response`. To use a different cache policy, change its headers in your code before you return it.
700
+
701
+ #### A preview for each pull request
702
+
703
+ A CI job can publish each pull request to its own collection, and remove it when the pull request closes. `--expires-in` stops serving a preview after that time, also if the second job does not run. But its index stays in storage until `clean --delete-expired-collections`, and its files stay until `clean`.
704
+
705
+ This GitHub Actions workflow publishes the collection `pr-<number>`, and, when the pull request closes, deletes the collection and runs `clean`. It needs the `FASTLY_API_TOKEN` secret (and, for the purge, the `FASTLY_SERVICE_ID` secret).
706
+
707
+ ```yaml
708
+ name: Preview
709
+ on:
710
+ pull_request:
711
+ types: [opened, synchronize, reopened, closed]
712
+
713
+ # clean must not run while a publish runs, so all jobs that change the same
714
+ # storage use one concurrency group. Use the same group in every workflow that
715
+ # publishes or cleans, for example the workflow that publishes `live`.
716
+ concurrency:
717
+ group: static-publish-storage
718
+ cancel-in-progress: false
719
+
720
+ jobs:
721
+ publish:
722
+ if: github.event.action != 'closed'
723
+ runs-on: ubuntu-latest
724
+ defaults:
725
+ run:
726
+ working-directory: compute-js
727
+ env:
728
+ FASTLY_API_TOKEN: ${{ secrets.FASTLY_API_TOKEN }}
729
+ FASTLY_SERVICE_ID: ${{ secrets.FASTLY_SERVICE_ID }}
730
+ steps:
731
+ - uses: actions/checkout@v7
732
+ - uses: actions/setup-node@v7
733
+ with:
734
+ node-version: 24
735
+ - run: npm ci
736
+ - run: npx @fastly/compute-js-static-publish@beta publish-content --collection-name=pr-${{ github.event.number }} --expires-in=7d
737
+
738
+ remove:
739
+ if: github.event.action == 'closed'
740
+ runs-on: ubuntu-latest
741
+ defaults:
742
+ run:
743
+ working-directory: compute-js
744
+ env:
745
+ FASTLY_API_TOKEN: ${{ secrets.FASTLY_API_TOKEN }}
746
+ FASTLY_SERVICE_ID: ${{ secrets.FASTLY_SERVICE_ID }}
747
+ steps:
748
+ - uses: actions/checkout@v7
749
+ - uses: actions/setup-node@v7
750
+ with:
751
+ node-version: 24
752
+ - run: npm ci
753
+ - run: npx @fastly/compute-js-static-publish@beta collections delete --collection-name=pr-${{ github.event.number }}
754
+ - run: npx @fastly/compute-js-static-publish@beta clean --delete-expired-collections
755
+ ```
756
+
757
+ For a pull request that never published, `collections delete` finds no collection and deletes nothing.
758
+
423
759
  ### 🔀 Selecting a Collection at Runtime
424
760
 
425
- The `collectionSelector` module provides helpers to extract a collection name from different parts of a request:
761
+ For previews, use [collection selection](#-previews-collection-selection). To select a collection in your own code, the `collectionSelector` module provides helpers to extract a collection name from different parts of a request:
426
762
 
427
763
  ```js
428
764
  collectionSelector.fromHostDomain(request, /^preview-([^\.]*)\./);
@@ -459,7 +795,7 @@ collectionSelector.fromConfigStore('my-config-store', 'collection-key');
459
795
  If you're happy with a preview or staging collection and want to make it live, use the `collections promote` command:
460
796
 
461
797
  ```sh
462
- npx @fastly/compute-js-static-publish collections promote \
798
+ npx @fastly/compute-js-static-publish@beta collections promote \
463
799
  --collection-name=staging
464
800
  --to=live
465
801
  ```
@@ -469,7 +805,7 @@ This copies all content and server settings from the `staging` collection to `li
469
805
  You can also specify a new expiration:
470
806
 
471
807
  ```sh
472
- npx @fastly/compute-js-static-publish collections promote \
808
+ npx @fastly/compute-js-static-publish@beta collections promote \
473
809
  --collection-name=preview-42 \
474
810
  --to=staging \
475
811
  --expires-in=7d
@@ -639,7 +975,7 @@ npm run fastly:clean
639
975
 
640
976
  These scripts run against the local and Fastly KV Stores respectively, and run the following command:
641
977
  ```
642
- npx @fastly/compute-js-static-publish clean --delete-expired-collections
978
+ npx @fastly/compute-js-static-publish@beta clean --delete-expired-collections
643
979
  ```
644
980
 
645
981
  This removes:
@@ -648,12 +984,15 @@ This removes:
648
984
  - Unused content blobs (no longer referenced)
649
985
  - Orphaned server config files
650
986
 
987
+ > [!WARNING]
988
+ > Do not run `clean` while `publish-content` can run for the same storage. `publish-content` writes the index of a collection after it uploads the files, so `clean` can delete files that the new index then refers to. In CI, put the jobs that publish and the job that cleans in the same `concurrency` group (see [A preview for each pull request](#a-preview-for-each-pull-request)).
989
+
651
990
  ### 🔍 Dry Run Mode
652
991
 
653
992
  Preview what will be deleted without making changes:
654
993
 
655
994
  ```sh
656
- npx @fastly/compute-js-static-publish clean --dry-run
995
+ npx @fastly/compute-js-static-publish@beta clean --dry-run
657
996
  ```
658
997
 
659
998
  > ⚠️ Cleanup never deletes the default collection and never deletes content that’s still in use.
@@ -705,6 +1044,39 @@ async function handleRequest(request) {
705
1044
  }
706
1045
  ```
707
1046
 
1047
+ ### Options of `serveRequest()`
1048
+
1049
+ `serveRequest(request, options)` takes these options. Without options, it works as above.
1050
+
1051
+ | Option | Description | Default |
1052
+ |--------|-------------|---------|
1053
+ | `collectionName` | The collection to serve, for this call only. `null` selects the default collection. | The active collection (see [Switching the active collection](#switching-the-active-collection)) |
1054
+ | `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 |
1055
+ | `fallback` | `false`: if no file matches, do not serve the SPA file or the 404 page. Return `null`. | `true` |
1056
+ | `healthCheck` | `false`: do not answer `/healthz`. | `true` |
1057
+
1058
+ `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.
1059
+
1060
+ `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:
1061
+
1062
+ ```js
1063
+ async function handleRequest(request) {
1064
+ const response = await publisherServer.serveRequest(request, { fallback: false });
1065
+ if (response) {
1066
+ return response;
1067
+ }
1068
+
1069
+ const url = new URL(request.url);
1070
+ if (url.pathname === '/api/hello') {
1071
+ return new Response(JSON.stringify({ greeting: "hi" }), {
1072
+ headers: { 'content-type': 'application/json' }
1073
+ });
1074
+ }
1075
+
1076
+ return (await publisherServer.serveFallback(request)) ?? new Response("Not Found", { status: 404 });
1077
+ }
1078
+ ```
1079
+
708
1080
  ### ⏱️ Measuring Performance with `Server-Timing`
709
1081
 
710
1082
  `PublisherServer` can report how long it spends reading from storage. To turn this on, give it the name of a request header:
@@ -752,17 +1124,18 @@ publisherServer.setResponseCache({ maxAge: 3600 });
752
1124
 
753
1125
  `maxAge` is in seconds. This is off by default.
754
1126
 
755
- `maxBodySize` sets the largest response, in bytes, to cache. The default is 8 MiB (`8 * 1024 * 1024`). A larger response is served from storage each time:
1127
+ `maxBodySize` sets the largest response, in bytes, to cache. The default is 16 MiB (`16 * 1024 * 1024`). A larger response is served from storage each time:
756
1128
 
757
1129
  ```js
758
- publisherServer.setResponseCache({ maxAge: 3600, maxBodySize: 16 * 1024 * 1024 });
1130
+ publisherServer.setResponseCache({ maxAge: 3600, maxBodySize: 4 * 1024 * 1024 });
759
1131
  ```
760
1132
 
761
1133
  - A response is cached by the publish ID, the collection, the path, and the client's `Accept-Encoding`. A cache hit does not read the settings, the index, or the file.
762
1134
  - A path that does not match a file is cached, too, so a missing path does not read the index again.
1135
+ - With the options of `serveRequest()`, the path in the key is the `pathname` option, and the collection is the `collectionName` option. A response with `fallback: false` has its own key. `serveFallback()` caches one response for each collection, for all paths.
763
1136
  - If several requests miss the same response at the same time, one request produces it, and the others wait for it.
764
1137
  - Only `200` and `404` responses are cached. Conditional requests (`304`) and `HEAD` requests are answered from the cached response.
765
- - Each cached response has the surrogate key `<publishId>-<collectionName>`. After you publish, `publish-content` purges this key (see [`--fastly-service-id`](#publish-content)), so the next request gets the new content.
1138
+ - Each cached response has the surrogate key `<publishId>-<collectionName>`. After you publish, `publish-content` purges this key (see [`--fastly-service-id`](#publish-content)), so the next request gets the new content. `collections promote` and `collections delete` purge the key of the collection that they change.
766
1139
 
767
1140
  `serveRequest()` uses the response cache automatically. If you call `getMatchingAsset()` and `serveAsset()` directly, wrap them in `serveCached()`. When a response is not cached yet, `serveCached()` calls your function to produce it, with a `GET` request that has no conditional headers:
768
1141
 
@@ -781,11 +1154,200 @@ The second argument identifies the response in the collection. If anything other
781
1154
 
782
1155
  Notes:
783
1156
 
784
- - A response is read completely before it is cached, so a request uses memory for one response, up to `maxBodySize`. Other requests that wait for the same response get it when it is cached.
1157
+ - 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.
785
1158
  - 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.
786
1159
  - 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.
787
1160
  - 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.
788
1161
 
1162
+ ## 🔥 Using Hono
1163
+
1164
+ `@fastly/compute-js-static-publish/hono` has middleware for [Hono](https://hono.dev/) apps. It serves the published files with `PublisherServer`, so a Hono app gets all the features of the server: `autoIndex`, `autoExt`, the compressed variants, `304` responses, the [response cache](#️-caching-responses-with-the-core-cache), `Server-Timing`, and [collection selection](#-previews-collection-selection).
1165
+
1166
+ ### The `hono` template
1167
+
1168
+ To scaffold a Hono app, add `--template hono` (in a managed project: `managed.template: 'hono'`):
1169
+
1170
+ ```sh
1171
+ npx @fastly/compute-js-static-publish@beta --template hono --root-dir=./public --kv-store-name=site-content
1172
+ ```
1173
+
1174
+ The app is TypeScript: `src/index.ts`, with code like the example below, and `tsconfig.json`. Add your own routes in `src/index.ts`. The build (`js-compute-runtime ./src/index.ts`) removes the types, but does not check them. To check the types, run `npx tsc` in the app. The app has `typescript` as a dev dependency.
1175
+
1176
+ ### Hono extensions
1177
+
1178
+ To add your own middleware and routes to the `hono` template, put modules in the extensions folder, `hono-extensions/`. In a managed project, this is the only way to add code, because the CLI generates the app. In an ejected app, you can also edit `src/index.ts`.
1179
+
1180
+ `scaffold --template hono` makes the folder next to the project file (managed) or next to `compute-js/` (ejected). To make it later, or to update it, run:
1181
+
1182
+ ```sh
1183
+ npx @fastly/compute-js-static-publish@beta template init
1184
+ ```
1185
+
1186
+ ```
1187
+ hono-extensions/
1188
+ ├── package.json # Your dependencies, and the peer dependencies on the packages that the app provides
1189
+ ├── tsconfig.json # For your editor
1190
+ ├── 10-auth.ts # A module
1191
+ ├── api.ts # A module
1192
+ ├── _example.ts # An example, not a module (the name starts with _)
1193
+ └── lib/ # Your helpers (not modules)
1194
+ ```
1195
+
1196
+ - **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.
1197
+ - **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.
1198
+ - **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):
1199
+
1200
+ ```
1201
+ selectCollection() → middleware → beforeFiles → serveStatic() → afterFiles → serveFallback()
1202
+ ```
1203
+
1204
+ - `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.
1205
+ - `beforeFiles`: before the published files.
1206
+ - `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.
1207
+
1208
+ 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:
1209
+
1210
+ ```ts
1211
+ // hono-extensions/10-header.ts
1212
+ import { defineExtension } from '@fastly/compute-js-static-publish/hono';
1213
+
1214
+ export default defineExtension((app, options?: { value?: string }) => {
1215
+ app.use('*', async (c, next) => {
1216
+ await next();
1217
+ c.header('x-site', options?.value ?? 'default');
1218
+ });
1219
+ });
1220
+ ```
1221
+
1222
+ ```ts
1223
+ // hono-extensions/api.ts
1224
+ import { defineExtension } from '@fastly/compute-js-static-publish/hono';
1225
+
1226
+ export default defineExtension({ bindings: { config: 'ConfigStore:site_config' } }, {
1227
+ middleware: (app) => {
1228
+ app.use('/api/*', async (c, next) => {
1229
+ await next();
1230
+ c.header('cache-control', 'no-store');
1231
+ });
1232
+ },
1233
+ beforeFiles: (app) => {
1234
+ app.get('/api/greeting', async (c) => c.json({ greeting: await c.env.config?.get('greeting') }));
1235
+ },
1236
+ afterFiles: (app) => {
1237
+ app.get('/blog/:slug', (c) => c.redirect(`/archive/${c.req.param('slug')}/`, 301));
1238
+ },
1239
+ });
1240
+ ```
1241
+
1242
+ **Options** come from `templateOptions.hono.extensions` in the project file (or in `static-publish.rc.js`), with the name of the module as the key. Each phase of a module gets the same options. The build shows a warning for options of a module that does not exist:
1243
+
1244
+ ```js
1245
+ templateOptions: {
1246
+ hono: {
1247
+ bindings: { config: 'ConfigStore:site_config' },
1248
+ extensions: { header: { value: 'my-site' } },
1249
+ },
1250
+ },
1251
+ ```
1252
+
1253
+ **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.
1254
+
1255
+ **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.
1256
+
1257
+ **The build** bundles the modules into `src/hono-extensions.generated.js` of the app (the `prebuild` [template hook](#-template-hooks)). The packages that the app provides stay imports, so that the app has one copy of each: the dependencies of the app (for example `hono` and `@fastly/hono-fastly-compute`), this package, and `fastly:*`. Thus, do not install them in the folder. `template init` writes them as peer dependencies in `hono-extensions/package.json`, with the versions that the app has. Install other packages in the folder (`npm install` in `hono-extensions/`), and the build bundles them.
1258
+
1259
+ - `build.hono.extensionsDir` sets another folder, relative to the project file (or to `static-publish.rc.js`). The default is `./hono-extensions`.
1260
+ - Without the folder, or without modules, the app has no extensions. `dev` and `deploy` of a managed project then show how to make the folder.
1261
+ - In a managed project, the files of the folder (without `node_modules/`) are part of the fingerprint, so a change to a module makes `deploy` deploy again.
1262
+ - Keep the code of the extensions in the folder. A module can import a file from outside the folder, and the build bundles it, but a change to that file does not change the fingerprint, and the watcher does not see it.
1263
+
1264
+ **`template init`** makes the folder with `package.json`, `tsconfig.json`, and the example. In a folder that exists, it updates only the peer dependencies, and adds the starter files that are missing. It never changes your modules. `--reset` writes the starter files again (it asks first, or needs `--force` with `--non-interactive`). `--check` changes nothing, and fails with `template-init-needed` if the folder is out of date, for example after an upgrade of this package; use it in CI.
1265
+
1266
+ **Watch:** `dev -- --watch` (managed) and `npm run dev:watch` (ejected) also watch the extensions folder, also if it does not exist yet. A change in the folder bundles the modules again, and then the Fastly CLI builds and restarts the app. If a module has an error, the watcher shows it and the app keeps the last modules that built.
1267
+
1268
+ **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.
1269
+
1270
+ - [`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.
1271
+ - [`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.
1272
+
1273
+ Each example takes its secrets from a Secret Store. For `dev`, `managed.fastlyToml` adds a local Secret Store that reads environment variables.
1274
+
1275
+ ### Hono in your own app
1276
+
1277
+ Add `hono` and `@fastly/hono-fastly-compute` to your app:
1278
+
1279
+ ```sh
1280
+ npm install hono @fastly/hono-fastly-compute
1281
+ ```
1282
+
1283
+ Then serve the files from your Hono app. Add your own routes before `serveStatic()` or after it:
1284
+
1285
+ ```js
1286
+ import { Hono } from 'hono';
1287
+ import { fire } from '@fastly/hono-fastly-compute';
1288
+ import { fromStaticPublishRc } from '@fastly/compute-js-static-publish/hono';
1289
+ import rc from '../static-publish.rc.js';
1290
+
1291
+ const { serveStatic, serveFallback, selectCollection } = fromStaticPublishRc(rc);
1292
+
1293
+ const app = new Hono();
1294
+
1295
+ // Select the collection of each request with collectionSelection in
1296
+ // static-publish.rc.js, for example for previews.
1297
+ app.use('*', selectCollection());
1298
+
1299
+ app.get('/api/hello', (c) => c.json({ hello: 'world' }));
1300
+
1301
+ // Serve the published files. If no file matches, the request goes to the next handler.
1302
+ app.use('*', serveStatic());
1303
+
1304
+ // When nothing matches, serve the SPA file or the 404 page.
1305
+ app.notFound(serveFallback());
1306
+
1307
+ fire(app);
1308
+ ```
1309
+
1310
+ `fire()` from [`@fastly/hono-fastly-compute`](https://hono.dev/docs/getting-started/fastly) runs the app on Fastly Compute. Use version 0.4.0 or later with `@fastly/js-compute` v4. To use a KV Store, a Config Store, or other resources from `c.env`, use `buildFire()` with bindings. Do not use `hono/service-worker`: by default, it sends each 404 response to `fetch()`, and Compute has no default backend.
1311
+
1312
+ `fromStaticPublishRc(rc)` returns:
1313
+
1314
+ - `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`.
1315
+ - `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.
1316
+ - `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.
1317
+ - `publisherServer`: the `PublisherServer`, to configure it. For example, `publisherServer.setResponseCache({ maxAge: 3600 })`.
1318
+
1319
+ If you make the `PublisherServer` yourself, use `fromPublisherServer(publisherServer)` in place of `fromStaticPublishRc(rc)`.
1320
+
1321
+ `serveStatic()` takes options like the `serveStatic()` of Hono:
1322
+
1323
+ | Option | Description |
1324
+ |---|---|
1325
+ | `root` | The directory that request paths are relative to, in the published files (after `publicDirPrefix`, if it is set). The default is `./`. A path that resolves outside `root` is not served. |
1326
+ | `path` | The path to serve, in place of the request path. For example, `./favicon.ico`. |
1327
+ | `rewriteRequestPath` | `(path, c) => string`. Changes the request path before it is resolved against `root`. |
1328
+ | `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. |
1329
+
1330
+ For example, to serve `/assets/*` from the `static` directory:
1331
+
1332
+ ```js
1333
+ app.use('/assets/*', serveStatic({ root: './static', rewriteRequestPath: (path) => path.replace(/^\/assets/, '') }));
1334
+ ```
1335
+
1336
+ `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.
1337
+
1338
+ In TypeScript, use `StaticPublisherVariables` for the variables of the app, so that `c.var.staticPublisher` has a type:
1339
+
1340
+ ```ts
1341
+ import { fromStaticPublishRc, type StaticPublisherVariables } from '@fastly/compute-js-static-publish/hono';
1342
+
1343
+ const app = new Hono<{ Variables: StaticPublisherVariables }>();
1344
+ app.get('/api/collection', (c) => c.json({ collection: c.var.staticPublisher.collectionName }));
1345
+ ```
1346
+
1347
+ The middleware imports only types from `hono`, so it does not add `hono` to your bundle. `hono` (v4) is an optional peer dependency of this package.
1348
+
1349
+ To move from `@fastly/hono-compute-js-static-publish`, see [MIGRATING.md](./MIGRATING.md).
1350
+
789
1351
  ## 📥 Using Published Assets in Your Code
790
1352
 
791
1353
  To access files you've published, use the `getMatchingAsset()` and `loadAssetVariant()` methods on `publisherServer`.
@@ -804,6 +1366,17 @@ if (asset != null) {
804
1366
  }
805
1367
  ```
806
1368
 
1369
+ `getMatchingAsset(key, options)` takes these options:
1370
+
1371
+ - `applyAuto` - Also try `autoExt` and `autoIndex`, as for a request (default: `false`). The second argument can also be a boolean, the value of `applyAuto`.
1372
+ - `includeHidden` - Also find [hidden files](#hidden-files) (default: `false`).
1373
+
1374
+ ```js
1375
+ const template = await publisherServer.getMatchingAsset('/templates/email.html', { includeHidden: true });
1376
+ ```
1377
+
1378
+ `getAssetEntryMap()` returns the whole index. The key of a hidden file in it is `hidden:` and then the asset key, for example `hidden:/404.html`.
1379
+
807
1380
  ### Load the File from KV Store:
808
1381
 
809
1382
  ```js
@@ -825,7 +1398,7 @@ You can stream `assetVariant.storageEntry.body` directly to a `Response`, or rea
825
1398
  ### Available Commands
826
1399
 
827
1400
  #### Outside a Compute App Directory
828
- - `npx @fastly/compute-js-static-publish@latest [options]` - Scaffold a new Compute app
1401
+ - `npx @fastly/compute-js-static-publish@beta [options]` - Scaffold a new Compute app
829
1402
 
830
1403
  #### Inside a Compute App Directory
831
1404
  - `publish-content` - Publish static files to storage (KV Store or S3-compatible storage) under a named collection
@@ -835,6 +1408,146 @@ You can stream `assetVariant.storageEntry.body` directly to a `Response`, or rea
835
1408
  - `collections promote` - Copy a collection to another name
836
1409
  - `collections update-expiration` - Modify expiration time for an existing collection
837
1410
 
1411
+ ### 🤖 Using the CLI in CI
1412
+
1413
+ These rules are for tools that run the CLI with no person present, for example a GitHub Actions workflow. They are part of the contract of the CLI: a change that breaks them comes only in a major release.
1414
+
1415
+ **Exit codes:**
1416
+
1417
+ | Code | Meaning |
1418
+ |------|---------|
1419
+ | `0` | Success. Also when there is nothing to do, for example when you publish the same content again, promote to a collection again, or delete a collection that does not exist. A failed purge after a successful publish is only a warning (see `purge.ok` in the JSON). |
1420
+ | `1` | The operation failed, for example storage cannot be reached, or the deploy failed. A retry can help. |
1421
+ | `2` | A usage or config error, for example an unknown option, a missing option, a collection name that breaks the rule, or a config file that cannot be loaded. A retry cannot help. |
1422
+
1423
+ **`--json`:** `publish-content`, `collections list`, `collections delete`, `collections promote`, `status`, `deploy` (in a managed project), and `--version` can write their result as one JSON object to stdout, at the end. All log lines then go to stderr, so that they still show in the CI log. With another command, `--json` is an error (`json-not-supported`).
1424
+
1425
+ ```sh
1426
+ npx @fastly/compute-js-static-publish@beta publish-content \
1427
+ --project-dir=./compute-js --collection-name=pr-42 --json > result.json
1428
+ ```
1429
+
1430
+ Each object has `schemaVersion` (now `1`). A new field keeps the version. A field is removed or changed only in a major release, with a new `schemaVersion`.
1431
+
1432
+ `publish-content --json`:
1433
+
1434
+ ```json
1435
+ {
1436
+ "schemaVersion": 1,
1437
+ "collection": "pr-42",
1438
+ "publishId": "default",
1439
+ "files": { "total": 352, "hidden": 2 },
1440
+ "storageItems": { "uploaded": 12, "reused": 340 },
1441
+ "expiresAt": "2026-12-01T00:00:00.000Z",
1442
+ "purge": {
1443
+ "ok": true,
1444
+ "serviceId": "SERVICE_ID",
1445
+ "environments": [ { "environment": "production", "result": "purged" } ]
1446
+ }
1447
+ }
1448
+ ```
1449
+
1450
+ - `files` counts the files in the index. `storageItems` counts the items in storage: each file, and each compressed variant that is kept. Thus `storageItems.uploaded` can be larger than `files.total`.
1451
+ - `expiresAt` is `null` if the collection does not expire.
1452
+ - `purge` is `null` if there was no purge (`--local`, or no Service ID). `purge.ok` is `false` if a purge failed. Then the visitors can get the old content from the cache until it expires. Each item of `environments` has a `result`: `purged`, `not-staged` (a `staging` purge, and the service has no staged version), or `failed` (with a `reason`).
1453
+
1454
+ `collections list --json`:
1455
+
1456
+ ```json
1457
+ {
1458
+ "schemaVersion": 1,
1459
+ "publishId": "default",
1460
+ "defaultCollection": "live",
1461
+ "collections": [
1462
+ {
1463
+ "name": "live", "isDefault": true,
1464
+ "publishedAt": "2026-11-01T00:00:00.000Z", "expiresAt": null, "expired": false,
1465
+ "requires": [ "hidden" ], "unsupported": [], "files": 352, "hidden": 2
1466
+ }
1467
+ ]
1468
+ }
1469
+ ```
1470
+
1471
+ `collections delete --json`. `deleted` is `false` with `"reason": "not-found"` if the collection does not exist (also exit `0`). `purge` is as in `publish-content`:
1472
+
1473
+ ```json
1474
+ { "schemaVersion": 1, "collection": "pr-42", "publishId": "default", "deleted": true, "purge": null }
1475
+ ```
1476
+
1477
+ `collections promote --json`. `expiresAt` is the expiration time of the target after the promote, or `null`:
1478
+
1479
+ ```json
1480
+ { "schemaVersion": 1, "from": "staging", "to": "live", "publishId": "default", "expiresAt": null }
1481
+ ```
1482
+
1483
+ `status --json` in a managed project. `needsDeploy` is `null` if it is not known (no API token):
1484
+
1485
+ ```json
1486
+ {
1487
+ "schemaVersion": 1,
1488
+ "mode": "managed",
1489
+ "serviceId": "SERVICE_ID",
1490
+ "staticPublishVersion": { "recorded": "8.1.0", "running": "8.1.0", "check": "same" },
1491
+ "fingerprint": { "current": "3f…", "deployed": "3f…", "deployedStaticPublishVersion": "8.1.0" },
1492
+ "activeVersion": 12,
1493
+ "domain": "example.edgecompute.app",
1494
+ "needsDeploy": false,
1495
+ "reasons": [],
1496
+ "previewUrls": [ { "type": "query", "url": "https://example.edgecompute.app/?collection={collection}" } ],
1497
+ "template": {
1498
+ "name": "hono",
1499
+ "provides": {
1500
+ "@fastly/hono-fastly-compute": "0.4.0",
1501
+ "@fastly/js-compute": "4.0.0",
1502
+ "hono": "4.13.14",
1503
+ "@fastly/compute-js-static-publish": "8.1.0"
1504
+ }
1505
+ }
1506
+ }
1507
+ ```
1508
+
1509
+ `template.provides` lists the packages that the app of the template provides to the folder of the template (for example `hono-extensions/`), with their versions.
1510
+
1511
+ In an ejected app, `status --json` gives `{ "schemaVersion": 1, "mode": "ejected", "serviceId": "SERVICE_ID" }`.
1512
+
1513
+ `deploy --json`. `deployed` is `false` with `"reason": "up-to-date"` if the active version already has this app:
1514
+
1515
+ ```json
1516
+ {
1517
+ "schemaVersion": 1,
1518
+ "deployed": true,
1519
+ "serviceId": "SERVICE_ID",
1520
+ "version": 13,
1521
+ "domain": "example.edgecompute.app",
1522
+ "fingerprint": "3f…",
1523
+ "staticPublishVersion": "8.1.0"
1524
+ }
1525
+ ```
1526
+
1527
+ `--version --json` gives `{ "schemaVersion": 1, "version": "8.1.0" }`.
1528
+
1529
+ **Errors:** with `--json`, stdout has one object, `{ "schemaVersion": 1, "error": { "code": "…", "message": "…" } }`. The error also goes to stderr. `message` is for people and can change. `code` is one of these values. A script can use it:
1530
+
1531
+ | Code | Exit code | Meaning |
1532
+ |------|-----------|---------|
1533
+ | `usage` | `2` | An unknown command or option, or a missing or incorrect option value |
1534
+ | `config-invalid` | `2` | `static-publish.rc.js`, `static-publish.project.js`, or `publish-content.config.js` cannot be loaded, or is not valid |
1535
+ | `collection-name-invalid` | `2` | A collection name breaks the [rule](#-collections-publish-preview-promote) |
1536
+ | `collection-not-found` | `2` | The command needs a collection that does not exist |
1537
+ | `project-dir-not-found` | `2` | `--project-dir` is not a directory, or has no config file |
1538
+ | `json-not-supported` | `2` | `--json` with a command that does not support it |
1539
+ | `credentials-missing` | `2` | An API token or S3 credentials are necessary, but not given |
1540
+ | `version-mismatch` | `2` | `managed.staticPublishVersion` is not the version of the CLI that runs |
1541
+ | `first-deploy-manual` | `2` | The first deploy of a managed project with S3 storage, with `--non-interactive` |
1542
+ | `version-not-published` | `2` | `eject` needs a version of this package that is on npm |
1543
+ | `template-init-needed` | `2` | `template init --check`: the folder of the template (for example `hono-extensions/`) is out of date. Run `template init` |
1544
+ | `deploy-failed` | `1` | The build or the deploy of the app failed |
1545
+ | `failed` | `1` | The operation failed, for example storage cannot be reached |
1546
+
1547
+ New codes can come in a minor release. Treat a code that you do not know by its exit code.
1548
+
1549
+ **Secrets:** give the Fastly API token in `FASTLY_API_TOKEN`, and S3 credentials in `S3_ACCESS_KEY_ID` and `S3_SECRET_ACCESS_KEY`. The CLI replaces the values of the token and the S3 secret access key with `[REDACTED]` in its output, also in errors and in the JSON.
1550
+
838
1551
  ### 🛠 App Scaffolding
839
1552
 
840
1553
  Run outside an existing Compute app directory:
@@ -843,12 +1556,12 @@ Run outside an existing Compute app directory:
843
1556
 
844
1557
  ```sh
845
1558
  # Using KV store storage
846
- npx @fastly/compute-js-static-publish@latest \
1559
+ npx @fastly/compute-js-static-publish@beta \
847
1560
  --root-dir=./public \
848
1561
  --kv-store-name=<site-content>
849
1562
 
850
1563
  # Using S3 storage (BETA)
851
- npx @fastly/compute-js-static-publish@latest \
1564
+ npx @fastly/compute-js-static-publish@beta \
852
1565
  --root-dir=./public \
853
1566
  --storage-mode=s3 \
854
1567
  --s3-region=<s3 region> \
@@ -859,13 +1572,15 @@ npx @fastly/compute-js-static-publish@latest \
859
1572
  #### Full options list
860
1573
 
861
1574
  ```sh
862
- npx @fastly/compute-js-static-publish@latest \
1575
+ npx @fastly/compute-js-static-publish@beta \
863
1576
  --root-dir=./public \
864
1577
  { [--storage-mode=kv-store] --kv-store-name=<site-content> | \
865
1578
  --storage-mode=s3 --s3-region=<s3 region> --s3-bucket=<bucket name> [--s3-endpoint=<endpoint>] } \
866
1579
  [--output=./compute-js] \
867
1580
  [--static-publisher-working-dir=<output>/static-publisher] \
868
1581
  [--publish-id=<prefix>] \
1582
+ [--default-collection-name=live] \
1583
+ [--template=plain|hono] \
869
1584
  [--static-dir=./public/static] \
870
1585
  [--spa=./public/spa.html] \
871
1586
  [--not-found-page=./public/404.html] \
@@ -896,10 +1611,13 @@ npx @fastly/compute-js-static-publish@latest \
896
1611
  - `--description`: Application description to insert into `fastly.toml`
897
1612
  - `--author`: Author to insert into `fastly.toml`
898
1613
  - `--service-id`: Optional existing Fastly Compute service ID
1614
+ - `--template`: The template of the app's code (default: `plain`). `plain` is a JavaScript app that calls `PublisherServer.serveRequest()` from a fetch event listener. `hono` is a TypeScript [Hono](https://hono.dev/) app (see [Using Hono](#-using-hono)).
1615
+ - `--managed`: Write only `static-publish.project.js` (a [managed project](#managed-projects)) in the current directory, in place of the app. `--output` is not used.
899
1616
 
900
1617
  **Used in building config files:**
901
1618
  - `--root-dir`: Required. Directory of static site content.
902
1619
  - `--publish-id`: Optional key prefix for KV entries (default: `'default'`).
1620
+ - `--default-collection-name`: The collection to serve when no collection is selected (default: `'live'`).
903
1621
  - `--public-dir`: **Deprecated.** A future version will remove it. Public files base directory, under `--root-dir` (default: same as `--root-dir`). Files that are under `--root-dir` but not under `--public-dir` are published, but requests cannot get them.
904
1622
  - `--static-dir`: One or more directories to serve with long cache TTLs.
905
1623
  - `--spa`: SPA fallback file path, from the current directory (e.g., `./public/spa.html`). The file must exist under `--root-dir`.
@@ -907,14 +1625,41 @@ npx @fastly/compute-js-static-publish@latest \
907
1625
  - `--auto-index`: List of filenames to use as index files.
908
1626
  - `--auto-ext`: Extensions to try when resolving URLs.
909
1627
 
1628
+ **Collection selection** (written as `collectionSelection` in `static-publish.rc.js`; see [Previews: Collection Selection](#-previews-collection-selection)):
1629
+ - `--collection-selection`: A source. Can be repeated; the sources are tried in the order of the flags.
1630
+ - `host:<pattern>`, for example `host:{collection}.preview.example.com`
1631
+ - `path:<prefix>[,sticky]`, for example `path:/_preview/{collection},sticky`
1632
+ - `query:<param>[,sticky]`, for example `query:collection,sticky`
1633
+ - `cookie[:<cookieName>][,maxAge=<seconds>][,activatePath=<path>][,resetPath=<path>]`
1634
+ - `header:<name>`, for example `header:x-publisher-collection`
1635
+ - `--collection-allow`: The collections that can be selected, for example `pr-*,staging`.
1636
+ - `--collection-on-missing`: `not-found` (default) or `default`.
1637
+ - `--collection-noindex`: `true` (default) or `false`.
1638
+
910
1639
  ### 🚀 Inside a Compute App Directory
911
1640
 
912
- Once you're in the scaffolded Compute app directory (with `static-publish.rc.js` present), you can run these subcommands:
1641
+ Once you're in the scaffolded Compute app directory (with `static-publish.rc.js` present), you can run these subcommands.
1642
+
1643
+ To run a subcommand from another directory, for example the root of your repo in CI, give the app directory with `--project-dir`:
1644
+
1645
+ ```sh
1646
+ npx @fastly/compute-js-static-publish@beta publish-content \
1647
+ --project-dir=./compute-js \
1648
+ --collection-name=staging
1649
+ ```
1650
+
1651
+ With `--project-dir`, all relative paths are relative to that directory: the paths in `static-publish.rc.js` and `publish-content.config.js`, and also the paths in the other options (for example `--config` and `--root-dir`). The directory must have a `static-publish.rc.js` (an app) or a `static-publish.project.js` (a [managed project](#managed-projects)). To scaffold an app in another directory, use `--output`.
1652
+
1653
+ To print the version of this package, run `npx @fastly/compute-js-static-publish@beta --version`. It works in any directory.
1654
+
1655
+ With `--non-interactive`, or when the `CI` environment variable is set, the CLI never asks for input: missing input is an error. `deploy` then also runs the Fastly CLI with `--non-interactive`. The output never shows the values of `--fastly-api-token`, `--s3-secret-access-key`, `FASTLY_API_TOKEN`, and `S3_SECRET_ACCESS_KEY`.
1656
+
1657
+ For `--json`, the exit codes, and the error codes, see [Using the CLI in CI](#-using-the-cli-in-ci).
913
1658
 
914
1659
  #### `publish-content`
915
1660
 
916
1661
  ```sh
917
- npx @fastly/compute-js-static-publish publish-content \
1662
+ npx @fastly/compute-js-static-publish@beta publish-content \
918
1663
  [--root-dir=./public] \
919
1664
  [--collection-name=preview-42] \
920
1665
  [--config=./publish-content.config.js] \
@@ -931,7 +1676,7 @@ npx @fastly/compute-js-static-publish publish-content \
931
1676
 
932
1677
  Publishes static files from your local root directory into a named collection, in the storage that `static-publish.rc.js` specifies: the Fastly KV Store, S3-compatible storage (BETA), or a local dev directory (`--local`, KV Store mode only).
933
1678
 
934
- Before it scans your files, the command lists the files that are already in storage. Files that already exist with the same hash are not compressed or uploaded again. With the KV Store, the command uploads the remaining files in batches.
1679
+ Before it scans your files, the command lists the files that are already in storage. Files that already exist with the same hash are not compressed or uploaded again. With the KV Store, a file larger than 20 MiB is stored in chunks, and the command uploads a chunk again if the chunk in storage does not have the correct size. Then the command uploads the remaining files in batches.
935
1680
 
936
1681
  After this process is complete, the PublisherServer object in the Compute application will see the updated index of files and updated server settings from the `publish-content.config.js` file.
937
1682
 
@@ -972,7 +1717,7 @@ After this process is complete, the PublisherServer object in the Compute applic
972
1717
  #### `clean`
973
1718
 
974
1719
  ```sh
975
- npx @fastly/compute-js-static-publish clean \
1720
+ npx @fastly/compute-js-static-publish@beta clean \
976
1721
  [--delete-expired-collections] \
977
1722
  [--dry-run]
978
1723
  ```
@@ -998,7 +1743,7 @@ This can include expired collection indexes and orphaned content assets.
998
1743
  #### `collections list`
999
1744
 
1000
1745
  ```sh
1001
- npx @fastly/compute-js-static-publish collections list
1746
+ npx @fastly/compute-js-static-publish@beta collections list
1002
1747
  ```
1003
1748
  Lists all collections currently published in storage.
1004
1749
 
@@ -1017,13 +1762,15 @@ Lists all collections currently published in storage.
1017
1762
  #### `collections promote`
1018
1763
 
1019
1764
  ```sh
1020
- npx @fastly/compute-js-static-publish collections promote \
1765
+ npx @fastly/compute-js-static-publish@beta collections promote \
1021
1766
  --collection-name=preview-42 \
1022
1767
  --to=live \
1023
1768
  [--expires-in=7d | --expires-at=2025-06-01T00:00Z | --expires-never]
1024
1769
  ```
1025
1770
  Copies an existing collection (content + config) to a new collection name.
1026
1771
 
1772
+ If a Service ID is found, the command then purges the surrogate key `<publishId>-<collectionName>` of the target collection, so that the service stops serving cached responses of the old content. This uses the same options as [`publish-content`](#publish-content).
1773
+
1027
1774
  ##### Options:
1028
1775
 
1029
1776
  - `--collection-name`: The name of the source collection to promote (required)
@@ -1043,6 +1790,11 @@ Copies an existing collection (content + config) to a new collection name.
1043
1790
 
1044
1791
  - `--fastly-api-token`: API token to use when publishing. If not set, the tool uses the **`FASTLY_API_TOKEN` environment variable**.
1045
1792
 
1793
+ **Purge Options:**
1794
+
1795
+ - `--fastly-service-id`: The Fastly Service ID to purge after promoting. If not set, the tool checks the `FASTLY_SERVICE_ID` environment variable, then `service_id` in `fastly.toml`. If none is found, the command skips the purge. The purge also needs an API token (see `--fastly-api-token`), also in S3 mode. With `--local`, there is no purge. If the purge fails, the command shows a warning and completes, because the collection is already promoted.
1796
+ - `--purge-environment`: The environments to purge: `production` (the default), `staging`, or both, as a comma-separated list. You can also repeat the option.
1797
+
1046
1798
  **S3 Storage Options (BETA):**
1047
1799
 
1048
1800
  - `--s3-access-key-id`, `--s3-secret-access-key`: Access key ID and secret access key for S3-compatible storage. If not set, the tool will check the `S3_ACCESS_KEY_ID` and `S3_SECRET_ACCESS_KEY` environment variables.
@@ -1050,7 +1802,7 @@ Copies an existing collection (content + config) to a new collection name.
1050
1802
  #### `collections update-expiration`
1051
1803
 
1052
1804
  ```sh
1053
- npx @fastly/compute-js-static-publish collections update-expiration \
1805
+ npx @fastly/compute-js-static-publish@beta collections update-expiration \
1054
1806
  --collection-name=preview-42 \
1055
1807
  --expires-in=3d | --expires-at=2025-06-01T00:00Z | --expires-never
1056
1808
  ```
@@ -1080,13 +1832,13 @@ Sets or updates the expiration time of an existing collection.
1080
1832
  #### `collections delete`
1081
1833
 
1082
1834
  ```sh
1083
- npx @fastly/compute-js-static-publish collections delete \
1835
+ npx @fastly/compute-js-static-publish@beta collections delete \
1084
1836
  --collection-name=preview-42
1085
1837
  ```
1086
1838
 
1087
1839
  Deletes a collection index from storage. The content files will remain as they may still be referenced by other collection indexes.
1088
1840
 
1089
- Use the `npx @fastly/compute-js-static-publish clean` command afterward to remove content files that are no longer referenced by any collection.
1841
+ Use the `npx @fastly/compute-js-static-publish@beta clean` command afterward to remove content files that are no longer referenced by any collection.
1090
1842
 
1091
1843
  If a Service ID is found, the command then purges the surrogate key `<publishId>-<collectionName>`, so that the service stops serving cached responses of the deleted collection. This uses the same options as [`publish-content`](#publish-content).
1092
1844
 
@@ -1149,14 +1901,17 @@ if (redirectResponse) {
1149
1901
 
1150
1902
  | Endpoint | Purpose | Query params | Result |
1151
1903
  |------------------------------------|------------------|------------------------------------------------------------------------------------------------|-------------------------------------------|
1152
- | activatePath (default `/activate`) | Set the cookie | `collection` (required) - name of the collection<br /> `redirectTo` (optional, `/` by default) | `302` redirect with a `Set-Cookie` header |
1153
- | resetPath (default `/reset`) | Clear the cookie | `redirectTo` (optional, `/` by default) | `302` redirect that expires the cookie |
1904
+ | activatePath (default `/activate`) | Set the cookie | `collection` (required) - name of the collection<br /> `redirectTo` (optional, `/` by default) | `308` redirect with a `Set-Cookie` header |
1905
+ | resetPath (default `/reset`) | Clear the cookie | `redirectTo` (optional, `/` by default) | `308` redirect that expires the cookie |
1154
1906
 
1155
1907
  If a visitor accesses `/activate?collection=blue&redirectTo=/preview`, the helper will issue a redirect and drop `publisher-collection=blue` into their cookie jar.
1156
1908
  - If someone forgets `?collection=?`? Then `/activate` replies with HTTP `400`.
1157
1909
 
1158
1910
  When the visitor hits `/reset`, the cookie is deleted.
1159
1911
 
1912
+ > [!NOTE]
1913
+ > The collection that the cookie selects is not in the URL. Add `Cache-Control: private` to the responses of a preview, so that a shared cache does not store them. See [Shared caches](#shared-caches). With [`collectionSelection`](#-previews-collection-selection), `PublisherServer` does this for you.
1914
+
1160
1915
  3. Safety flags are baked in
1161
1916
 
1162
1917
  - `HttpOnly` is on by default (configurable), to help avoid XSS issues.
@@ -1204,7 +1959,7 @@ async function handleRequest(event) {
1204
1959
 
1205
1960
  ## 📚 Next Steps
1206
1961
 
1207
- - View CLI command help: `npx @fastly/compute-js-static-publish --help`
1962
+ - View CLI command help: `npx @fastly/compute-js-static-publish@beta --help`
1208
1963
  - Use in CI to automate branch previews
1209
1964
  - Visit [https://developer.fastly.com](https://developer.fastly.com) for Compute platform docs
1210
1965
 
@@ -1212,6 +1967,8 @@ async function handleRequest(event) {
1212
1967
 
1213
1968
  To build the package, run `npm run build`. To run the tests, see [test/README.md](./test/README.md).
1214
1969
 
1970
+ In the code, its comments, and the docs for developers of this package, a **customer** is a developer who uses this package to publish a site, and a **visitor** is a person who opens the customer's site.
1971
+
1215
1972
  ## Issues
1216
1973
 
1217
1974
  If you encounter any non-security-related bug or unexpected behavior, please [file an issue][bug] using the bug report template.