@fastly/compute-js-static-publish 8.0.0 โ†’ 8.0.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 (48) hide show
  1. package/CHANGELOG.md +544 -0
  2. package/DOCUMENTATION.md +1243 -0
  3. package/MIGRATING.md +128 -0
  4. package/README.md +9 -2
  5. package/README.short.md +9 -2
  6. package/build/cli/cli/commands/manage/collections/promote.d.ts.map +1 -1
  7. package/build/cli/cli/commands/manage/collections/promote.js +43 -4
  8. package/build/cli/cli/commands/manage/publish-content.d.ts.map +1 -1
  9. package/build/cli/cli/commands/manage/publish-content.js +13 -16
  10. package/build/cli/cli/commands/scaffold/index.d.ts.map +1 -1
  11. package/build/cli/cli/commands/scaffold/index.js +51 -31
  12. package/build/cli/cli/storage/kv-store-local-provider.d.ts +1 -0
  13. package/build/cli/cli/storage/kv-store-local-provider.d.ts.map +1 -1
  14. package/build/cli/cli/storage/kv-store-local-provider.js +4 -1
  15. package/build/cli/cli/storage/kv-store-provider.d.ts +2 -1
  16. package/build/cli/cli/storage/kv-store-provider.d.ts.map +1 -1
  17. package/build/cli/cli/storage/kv-store-provider.js +17 -6
  18. package/build/cli/cli/storage/s3-storage-provider.d.ts +1 -0
  19. package/build/cli/cli/storage/s3-storage-provider.d.ts.map +1 -1
  20. package/build/cli/cli/storage/s3-storage-provider.js +8 -2
  21. package/build/cli/cli/storage/storage-provider.d.ts +4 -0
  22. package/build/cli/cli/storage/storage-provider.d.ts.map +1 -1
  23. package/build/cli/cli/storage/storage-provider.js +32 -0
  24. package/build/cli/cli/util/api-token.d.ts +2 -1
  25. package/build/cli/cli/util/api-token.d.ts.map +1 -1
  26. package/build/cli/cli/util/api-token.js +38 -3
  27. package/build/cli/cli/util/kv-store-items.d.ts +1 -0
  28. package/build/cli/cli/util/kv-store-items.d.ts.map +1 -1
  29. package/build/cli/cli/util/kv-store-items.js +16 -40
  30. package/build/cli/cli/util/progress.d.ts +11 -0
  31. package/build/cli/cli/util/progress.d.ts.map +1 -0
  32. package/build/cli/cli/util/progress.js +32 -0
  33. package/build/cli/cli/util/purge.d.ts +9 -1
  34. package/build/cli/cli/util/purge.d.ts.map +1 -1
  35. package/build/cli/cli/util/purge.js +16 -8
  36. package/build/cli/cli/util/s3.d.ts +10 -4
  37. package/build/cli/cli/util/s3.d.ts.map +1 -1
  38. package/build/cli/cli/util/s3.js +13 -35
  39. package/build/server/server/publisher-server/accept-html.d.ts +2 -0
  40. package/build/server/server/publisher-server/accept-html.d.ts.map +1 -0
  41. package/build/server/server/publisher-server/accept-html.js +50 -0
  42. package/build/server/server/publisher-server/index.d.ts +1 -0
  43. package/build/server/server/publisher-server/index.d.ts.map +1 -1
  44. package/build/server/server/publisher-server/index.js +31 -13
  45. package/build/server/server/publisher-server/response-cache.d.ts +3 -0
  46. package/build/server/server/publisher-server/response-cache.d.ts.map +1 -1
  47. package/build/server/server/publisher-server/response-cache.js +24 -1
  48. package/package.json +6 -3
@@ -0,0 +1,1243 @@
1
+ # Static Publisher for JavaScript on Fastly Compute
2
+
3
+ > NOTE: `@fastly/compute-js-static-publish` is provided as a Fastly Labs product. Visit the [Fastly Labs](https://www.fastlylabs.com/) site for terms of use.
4
+
5
+ > [!NOTE]
6
+ > v8 adds Beta support for S3-compatible storage, such as Fastly [Object Storage](https://www.fastly.com/products/storage). For more details, see the [S3-compatible storage](#-using-s3-compatible-storage-beta) section.
7
+
8
+ > [!NOTE]
9
+ > These docs are for v7 or newer, a major rewrite that adds powerful new features such as named collections.
10
+ > If you're looking for v6, please check out the [v6 branch](https://github.com/fastly/compute-js-static-publish/tree/v6).
11
+
12
+ > [!WARNING]
13
+ > v7 and newer no longer support module assets. If you require this feature, consider using [v6](https://github.com/fastly/compute-js-static-publish/tree/v6).
14
+
15
+ ## ๐Ÿ“– Table of Contents
16
+
17
+ - [โœจ Key Features](#-key-features)
18
+ - [๐Ÿ Quick Start](#-quick-start)
19
+ - [๐Ÿ“ฆ Fastly KV Store](#-using-the-fastly-kv-store)
20
+ - [๐ŸŽ S3 Compatible Storage](#-using-s3-compatible-storage-beta) (Beta)
21
+ - [โš™๏ธ Configuring `static-publish.rc.js`](#๏ธ-configuring-static-publishrcjs)
22
+ - [๐Ÿงพ Config for Publishing and Server: `publish-content.config.js`](#-config-for-publishing-and-server-publish-contentconfigjs)
23
+ - [๐Ÿ“ฆ Collections (Publish, Preview, Promote)](#-collections-publish-preview-promote)
24
+ - [๐Ÿงน Cleaning Up](#-cleaning-up)
25
+ - [๐Ÿ”„ Content Compression](#-content-compression)
26
+ - [๐Ÿงฉ Using PublisherServer in Custom Apps](#-using-publisherserver-in-custom-apps)
27
+ - [๐Ÿ“ฅ Using Published Assets in Your Code](#-using-published-assets-in-your-code)
28
+ - [๐Ÿ“š CLI Reference](#-cli-reference)
29
+ - [๐Ÿ“• Appendix](#-appendix)
30
+ - [๐Ÿ“š Next Steps](#-next-steps)
31
+
32
+ Serve static websites and web apps at the edge — no backends and no CDN invalidation delays.
33
+
34
+ `@fastly/compute-js-static-publish` helps you deploy and serve static files using [Fastly Compute](https://developer.fastly.com/learning/compute/) for fast, cacheable, and content-addressed delivery. The library can be configured to store your data in either of the following:
35
+ * Fastly [Key Value Store](https://www.fastly.com/products/kv-store)
36
+ * S3-compatible storage, such as Fastly [Object Storage](https://www.fastly.com/products/storage) (Beta)
37
+
38
+ ## โœจ Key Features
39
+
40
+ - ๐Ÿ“ฆ Easy to scaffold and deploy
41
+ - ๐Ÿš€ Content stored using hashed keys, in Fastly KV Store or S3-compatible storage (Beta) including Fastly Object Storage
42
+ - ๐Ÿ” Publish new content without needing to deploy new Wasm binaries
43
+ - ๐Ÿ—‚ Organize releases into named collections which can be previewed (e.g. `live`, `staging`, `preview-123`)
44
+ - ๐Ÿงผ Cleanup tools to remove expired or orphaned files
45
+ - โš™๏ธ Configurable per-collection server configurations (e.g. fallback files)
46
+ - ๐Ÿ”’ Supports Brotli/gzip compression, conditional GET, and long cache TTLs
47
+
48
+ ---
49
+
50
+ ## ๐Ÿ Quick Start
51
+
52
+ ### ๐Ÿ“ฆ Using the Fastly KV Store
53
+
54
+ #### 1. Scaffold a Compute App
55
+
56
+ Create a directory for your project, place your static files in `./public`, then type:
57
+
58
+ ```sh
59
+ npx @fastly/compute-js-static-publish@latest \
60
+ --root-dir=./public \
61
+ --kv-store-name=site-content
62
+ ```
63
+
64
+ You get a Compute app in `./compute-js` with:
65
+
66
+ - `fastly.toml` (service config)
67
+ - `src/index.js` (entry point)
68
+ - `static-publish.rc.js` (app config)
69
+ - `publish-content.config.js` (publish-time / runtime behavior)
70
+
71
+ Once the application is scaffolded, install dependencies:
72
+
73
+ ```sh
74
+ cd compute-js
75
+ npm install
76
+ ```
77
+
78
+ #### 2. Preview Locally
79
+
80
+ Type the following — no Fastly account or service required yet!
81
+
82
+ ```sh
83
+ npm run dev:publish
84
+ npm run dev:start
85
+ ```
86
+
87
+ Fastly's [local development environment](https://www.fastly.com/documentation/guides/compute/testing/#running-a-local-testing-server) serves your static website at `http://127.0.0.1:7676`, powered by a simulated KV Store.
88
+
89
+ #### 3. Deploy Your App
90
+
91
+ Ready to go live? All you need is a [free Fastly account](https://www.fastly.com/signup/?tier=free)!
92
+
93
+ ```sh
94
+ npm run fastly:deploy
95
+ ```
96
+
97
+ The command publishes your Compute app and creates the KV Store. (No content uploaded yet!)
98
+
99
+ #### 4. Publish Content
100
+
101
+ ```sh
102
+ npm run fastly:publish
103
+ ```
104
+
105
+ This command uploads your static files to the KV Store and applies the server config. Your website is now up and live!
106
+
107
+ `fastly:publish` needs a Fastly API token that can write to the KV Store. Set the `FASTLY_API_TOKEN` environment variable, or add `-- --fastly-api-token=<token>`. The command does not read the token of your Fastly CLI profile. If you are logged in with the Fastly CLI, you can give it that token:
108
+
109
+ ```sh
110
+ FASTLY_API_TOKEN=$(npx fastly auth token) npm run fastly:publish
111
+ ```
112
+
113
+ ### ๐ŸŽ Using S3 Compatible Storage (Beta)
114
+
115
+ #### 1. Scaffold a Compute App
116
+
117
+ Create a directory for your project, place your static files in `./public`, then type:
118
+
119
+ ```sh
120
+ npx @fastly/compute-js-static-publish@latest \
121
+ --root-dir=./public \
122
+ --storage-mode=s3 \
123
+ --s3-region=<s3 region> \
124
+ --s3-bucket=<bucket name>
125
+ ```
126
+
127
+ > [!NOTE]
128
+ > 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
+ > ```sh
131
+ > npx @fastly/compute-js-static-publish@latest \
132
+ > --root-dir=./public \
133
+ > --storage-mode=s3 \
134
+ > --s3-region=us-east-1 \
135
+ > --s3-bucket=my-static-content-bucket \
136
+ > --s3-endpoint=https://us-east-1.object.fastlystorage.app
137
+ > ```
138
+ >
139
+ > 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).
140
+
141
+ You get a Compute app in `./compute-js` with:
142
+
143
+ - `fastly.toml` (service config)
144
+ - `src/index.js` (entry point)
145
+ - `static-publish.rc.js` (app config)
146
+ - `publish-content.config.js` (publish-time / runtime behavior)
147
+
148
+ Once the application is scaffolded, install dependencies:
149
+
150
+ ```sh
151
+ cd compute-js
152
+ npm install
153
+ ```
154
+
155
+ #### 2. Publish your content to S3-compatible storage
156
+
157
+ Before publishing your content, your S3-compatible bucket must already exist.
158
+
159
+ > [!TIP]
160
+ > If you're using Fastly Object Storage, [create your Fastly account](https://www.fastly.com/signup/?tier=free) if you haven't already, and then follow the [Object Storage quick start](https://www.fastly.com/documentation/guides/platform/object-storage/object-storage-quick-start/) to set up your bucket.
161
+
162
+ Type the following:
163
+
164
+ ```sh
165
+ npm run s3:publish
166
+ ```
167
+
168
+ #### 3. Preview Locally
169
+
170
+ Type the following to preview your site locally:
171
+
172
+ ```sh
173
+ npm run dev:start
174
+ ```
175
+
176
+ Fastly's [local development environment](https://www.fastly.com/documentation/guides/compute/testing/#running-a-local-testing-server) serves your static website at `http://127.0.0.1:7676`. Your content is fetched from S3-compatible storage.
177
+
178
+ #### 4. Deploy Your App
179
+
180
+ Ready to go live? All you need is a [free Fastly account](https://www.fastly.com/signup/?tier=free)!
181
+
182
+ ```sh
183
+ npm run fastly:deploy
184
+ ```
185
+
186
+ The app reads the S3 credentials from the Secret Store that has the resource link name `S3_CREDENTIALS` on your service.
187
+
188
+ When the Fastly CLI creates a new service, it creates a Secret Store named `S3_CREDENTIALS`, links it to the service with the same name, and prompts you for the values `S3_ACCESS_KEY_ID` and `S3_SECRET_ACCESS_KEY`.
189
+
190
+ ---
191
+
192
+ ## ๐Ÿ—‚ Project Layout
193
+
194
+ Here's what your project might look like after scaffolding:
195
+
196
+ ```
197
+ my-project/
198
+ โ”œโ”€โ”€ public/ # Your static site files (HTML, CSS, JS, etc.)
199
+ โ”‚ โ”œโ”€โ”€ index.html
200
+ โ”‚ โ”œโ”€โ”€ scripts.js
201
+ โ”‚ โ”œโ”€โ”€ styles.css
202
+ โ”‚ โ””โ”€โ”€ (... other static files ...)
203
+ โ””โ”€โ”€ compute-js/ # The scaffolded Compute application
204
+ โ”œโ”€โ”€ fastly.toml # Fastly service configuration
205
+ โ”œโ”€โ”€ package.json # Scaffolded package metadata
206
+ โ”œโ”€โ”€ package-lock.json # Dependency lockfile
207
+ โ”œโ”€โ”€ .gitignore # Ignores build artifacts by default
208
+ โ”œโ”€โ”€ static-publish.rc.js # App config
209
+ โ”œโ”€โ”€ publish-content.config.js # Publishing / runtime config
210
+ โ”œโ”€โ”€ static-publisher/ # โš ๏ธ Do not commit - generated content for local dev and publishing
211
+ โ”‚ โ”œโ”€โ”€ kvstore.json # Simulates KV Store content for local preview
212
+ โ”‚ โ””โ”€โ”€ kv-store-content/ # Preprocessed and compressed files for KV upload
213
+ โ””โ”€โ”€ src/
214
+ โ””โ”€โ”€ index.js # Your Compute app entry point
215
+ ```
216
+
217
+ ## โš™๏ธ Configuring `static-publish.rc.js`
218
+
219
+ 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.
220
+
221
+ > [!NOTE]
222
+ > Making changes to this file requires rebuilding the Compute app, since a copy of it is baked into the Wasm binary.
223
+
224
+ ### Using the Fastly KV Store
225
+
226
+ #### Fields:
227
+
228
+ All fields are required unless specified otherwise.
229
+
230
+ - `storageMode` - Specifies the storage mode. Set to `'kv-store'`.
231
+ - `kvStore.kvStoreName` - The name of the KV Store used for publishing.
232
+ - `defaultCollectionName` - Collection to serve when none is specified.
233
+ - `publishId` - Unique prefix for all keys in the KV Store. Override only for advanced setups (e.g., multiple apps sharing the same KV Store).
234
+ - `staticPublisherWorkingDir` - Directory to hold working files during publish.
235
+
236
+ #### Example: `static-publish.rc.js`
237
+
238
+ ```js
239
+ const rc = {
240
+ storageMode: 'kv-store',
241
+ kvStore: {
242
+ kvStoreName: 'site-content',
243
+ },
244
+ defaultCollectionName: 'live',
245
+ publishId: 'default',
246
+ staticPublisherWorkingDir: './static-publisher',
247
+ };
248
+
249
+ export default rc;
250
+ ```
251
+
252
+ ### Using S3-compatible storage (BETA)
253
+
254
+ #### Fields:
255
+
256
+ All fields are required unless specified otherwise.
257
+
258
+ - `storageMode` - Specifies the storage mode. Set to `'s3'`.
259
+ - `s3.region` - The region of the S3-compatible bucket.
260
+ - `s3.bucket` - The name of the S3-compatible bucket.
261
+ - `s3.endpoint` - (optional) The custom endpoint for the S3-compatible bucket.
262
+ - `defaultCollectionName` - Collection to serve when none is specified.
263
+ - `publishId` - Unique prefix for all keys in the bucket. Override only for advanced setups (e.g., multiple apps sharing the same bucket).
264
+ - `staticPublisherWorkingDir` - Directory to hold working files during publish.
265
+
266
+ #### Example: `static-publish.rc.js`
267
+
268
+ ```js
269
+ const rc = {
270
+ storageMode: 's3',
271
+ s3: {
272
+ region: 'us-east-1',
273
+ bucket: 'my-site-content',
274
+ },
275
+ defaultCollectionName: 'live',
276
+ publishId: 'default',
277
+ staticPublisherWorkingDir: './static-publisher',
278
+ };
279
+
280
+ export default rc;
281
+ ```
282
+
283
+ ## ๐Ÿงพ Config for Publishing and Server: `publish-content.config.js`
284
+
285
+ This file is included as part of the scaffolding. Every time you publish content, the publish settings in this file are used for publishing the content, and the server settings are taken from this file and saved as the settings used by the server for that collection.
286
+
287
+ ```js
288
+ const config = {
289
+ // these paths are relative to compute-js dir
290
+ rootDir: '../public',
291
+
292
+ // Include/exclude filters (optional):
293
+ excludeDirs: ['node_modules'],
294
+ excludeDotFiles: true,
295
+ includeWellKnown: true,
296
+
297
+ // Advanced filtering (optional):
298
+ assetInclusionTest: (key, contentType) => {
299
+ return true; // include everything by default
300
+ },
301
+
302
+ // Override which compressed variants to create for each asset during publish (optional):
303
+ contentCompression: ['br', 'gzip'],
304
+
305
+ // Brotli quality, 0 to 11 (optional, default 11):
306
+ brotliQuality: 11,
307
+
308
+ // Content type definitions/overrides (optional):
309
+ contentTypes: [
310
+ { test: /\.custom$/, contentType: 'application/x-custom', text: false },
311
+ ],
312
+
313
+ // Server settings
314
+ server: {
315
+ spaFile: '/spa.html',
316
+ notFoundPageFile: '/404.html',
317
+ autoIndex: ['index.html'],
318
+ autoExt: ['.html'],
319
+ staticItems: ['/static/', '/assets/'],
320
+ allowedEncodings: ['br', 'gzip'],
321
+ }
322
+ };
323
+
324
+ export default config;
325
+ ```
326
+
327
+ You can override this file for a single `publish-content` command by specifying an alternative using `--config` on the command line.
328
+
329
+ ### Fields:
330
+
331
+ - `rootDir` - Directory to scan for content, relative to this file (required).
332
+ - `excludeDirs` - Array of directory names or regex patterns to exclude (default: `['./node_modules']`).
333
+ - `excludeDotFiles` - Exclude dotfiles and dot-named directories (default: true).
334
+ - `includeWellKnown` - Always include `.well-known` even if dotfiles are excluded (default: true).
335
+ - `assetInclusionTest` - Function to determine inclusion and variant behavior per file.
336
+ - `contentCompression` - Array of compression formats to pre-generate (`['br', 'gzip']` by default).
337
+ - `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.
338
+ - `contentTypes` - Additional or override content type definitions.
339
+
340
+ - `server` - Server runtime config that contains the following fields:
341
+ - `publicDirPrefix` - **Deprecated.** A future version will remove it.
342
+ A prefix that the Publisher Server adds to the path of each
343
+ request, to get the asset key. Use it if the files to serve are in a subdirectory
344
+ of `rootDir`. For example, if `rootDir` is `'../site'` and the files to serve are in
345
+ `'../site/public'`, set it to `'/public'`. The value starts with `/` and does not
346
+ end with `/` (default: `''`). The scaffolder sets it from `--root-dir` and `--public-dir`.
347
+ - `spaFile` - Path to a file to be used to serve in a SPA application.
348
+ - `notFoundPageFile` - Path to a file to be used to serve as a 404 not found page.
349
+ The server serves `spaFile` or `notFoundPageFile` only to a request that accepts HTML: its `Accept`
350
+ header is missing or empty, or has `text/html`, `text/*`, or `*/*` with a q-value that is not 0.
351
+ For other requests, `serveRequest()` returns `null`.
352
+ - `autoIndex` - List of files to automatically use as index.
353
+ - `autoExt` - List of extensions to automatically apply to a path and retry when
354
+ the requested path is not found.
355
+ - `staticItems` - Directories to specify as containing 'static' files. The
356
+ Publisher Server will serve files from these directories with a long TTL.
357
+ - `allowedEncodings` - Specifies which compression formats the server is allowed
358
+ to serve based on the client's `Accept-Encoding` header.
359
+
360
+ ## ๐Ÿ“ฆ Collections (Publish, Preview, Promote)
361
+
362
+ 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
+
364
+ - Static files
365
+ - Server configuration (e.g., fallback file, static directories, etc.)
366
+ - An index file that maps paths to those hashes
367
+
368
+ 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:
369
+
370
+ ```sh
371
+ npx @fastly/compute-js-static-publish publish-content \
372
+ --collection-name=staging \
373
+ --expires-in=7d \
374
+ --config=./publish-content.config.js
375
+ ```
376
+
377
+ You can overwrite or republish any collection at any time. Old file hashes will be reused automatically where contents match.
378
+
379
+ ### Expiration (Auto-cleanup)
380
+
381
+ Collections can expire automatically:
382
+
383
+ - Expired collections are ignored by the server and return 404s
384
+ - A request for a collection other than the default collection that is expired or not published gets a plain-text 404 that names the collection. The response cache does not store it, so the collection is served as soon as you publish it. If the default collection is not published, the server returns a 500.
385
+ - The default collection never expires
386
+ - Expiration limits can be modified (shortened, extended, reenstated) using `collections update-expiration`
387
+ - They are cleaned up by `clean --delete-expired-collections`
388
+
389
+ ```sh
390
+ --expires-in=3d # relative (e.g. 1h, 2d, 1w)
391
+ --expires-at=2025-05-01T12:00Z # absolute (ISO 8601)
392
+ --expires-never # the collection never expires
393
+ ```
394
+
395
+ *(Only one of **`--expires-in`**, **`--expires-at`**, or **`--expires-never`** may be specified)*
396
+
397
+ ### Switching the active collection
398
+
399
+ By default, the server app serves assets from the "default collection", named in `static-publish.rc.js` under `defaultCollectionName`. To switch the active collection, you add custom code to your Compute app that calls `publisherServer.setActiveCollectionName(name)`:
400
+
401
+ ```js
402
+ publisherServer.setActiveCollectionName("preview-42");
403
+ ```
404
+
405
+ Pass `null` to select the default collection.
406
+
407
+ If the app turns on sandbox reuse, Compute can use a sandbox for more than one request (see [Sandbox lifecycle](https://www.fastly.com/documentation/guides/compute/developer-guides/sandbox-lifecycle/)), and the active collection stays set until you change it. Thus, call `setActiveCollectionName()` for each request, also when the request does not select a collection.
408
+
409
+ #### Example: Subdomain-based Routing
410
+
411
+ In the following example, assume that the Compute application is hosted using a wildcard domain `*.example.com`. A request for `preview-pr-123.example.com` would activate the collection `'pr-123'`.
412
+
413
+ ```js
414
+ import { PublisherServer, collectionSelector } from '@fastly/compute-js-static-publish';
415
+ import rc from '../static-publish.rc.js';
416
+
417
+ const publisherServer = PublisherServer.fromStaticPublishRc(rc);
418
+
419
+ addEventListener("fetch", event => {
420
+ const request = event.request;
421
+ const collectionName = collectionSelector.fromHostDomain(request, /^preview-([^\.]*)\./);
422
+ publisherServer.setActiveCollectionName(collectionName); // null selects the default collection
423
+
424
+ event.respondWith(publisherServer.serveRequest(request));
425
+ });
426
+ ```
427
+
428
+ ### ๐Ÿ”€ Selecting a Collection at Runtime
429
+
430
+ The `collectionSelector` module provides helpers to extract a collection name from different parts of a request:
431
+
432
+ ```js
433
+ collectionSelector.fromHostDomain(request, /^preview-([^\.]*)\./);
434
+ ```
435
+
436
+ #### From the Request URL
437
+
438
+ ```js
439
+ collectionSelector.fromRequestUrl(request, url => url.pathname.split('/')[2]);
440
+ ```
441
+
442
+ #### With a Custom Request Matcher
443
+
444
+ ```js
445
+ collectionSelector.fromRequest(request, req => req.headers.get('x-collection') ?? 'live');
446
+ ```
447
+
448
+ #### From a Cookie
449
+
450
+ See [fromCookie](#fromcookie) for details on this feature.
451
+
452
+ ```js
453
+ const { collectionName, redirectResponse } = collectionSelector.fromCookie(request);
454
+ ```
455
+
456
+ #### From a Fastly Config Store
457
+
458
+ ```js
459
+ collectionSelector.fromConfigStore('my-config-store', 'collection-key');
460
+ ```
461
+
462
+ ### ๐Ÿš€ Promoting a Collection
463
+
464
+ If you're happy with a preview or staging collection and want to make it live, use the `collections promote` command:
465
+
466
+ ```sh
467
+ npx @fastly/compute-js-static-publish collections promote \
468
+ --collection-name=staging
469
+ --to=live
470
+ ```
471
+
472
+ This copies all content and server settings from the `staging` collection to `live`.
473
+
474
+ You can also specify a new expiration:
475
+
476
+ ```sh
477
+ npx @fastly/compute-js-static-publish collections promote \
478
+ --collection-name=preview-42 \
479
+ --to=staging \
480
+ --expires-in=7d
481
+ ```
482
+
483
+ > [!NOTE]
484
+ > The collection denoted by `defaultCollectionName` is exempt from expiration.
485
+
486
+ ## ๐Ÿ›  Development โ†’ Production Workflow
487
+
488
+ ### Using the KV Store
489
+
490
+ #### Local development
491
+
492
+ During development, the local development server (`npm run dev:start`) runs against assets loaded into the simulated KV Store provided by the local development environment.
493
+
494
+ Prior to starting the server, publish the content to the simulated KV Store:
495
+
496
+ ```sh
497
+ npm run dev:publish # 'publish' your files to the simulated local KV Store
498
+ npm run dev:start # preview locally
499
+ ```
500
+
501
+ This simulates publishing by writing to `kvstore.json` instead of uploading to the actual KV Store. You can preview your site at `http://127.0.0.1:7676` - no Fastly account or service required.
502
+
503
+ Note that for local development, you will have to stop and restart the local development server each time you publish updates to your content.
504
+
505
+ To publish to an alternative collection name, use the following command and then restart the local development server:
506
+
507
+ ```sh
508
+ npm run dev:publish -- --collection-name=preview-123
509
+ ```
510
+
511
+ #### Production
512
+
513
+ When you're ready for production:
514
+
515
+ 1. [Create a free Fastly account](https://www.fastly.com/signup/?tier=free) if you haven't already.
516
+ 2. Run `npm run fastly:deploy`
517
+ - This builds your Compute app into a Wasm binary
518
+ - Deploys it to a new or existing Fastly Compute service
519
+ - If creating a new service:
520
+ - you'll be prompted for backend info - **you can skip this**, as no backend is needed (all content is served from KV)
521
+ - KV Store will be created if necessary and automatically linked to your new service.
522
+
523
+ Once deployed, publish content like so:
524
+
525
+ ```sh
526
+ npm run fastly:publish
527
+ ```
528
+
529
+ `fastly:publish` needs a Fastly API token that can write to the KV Store. Set the `FASTLY_API_TOKEN` environment variable, or add `-- --fastly-api-token=<token>`. The command does not read the token of your Fastly CLI profile. If you are logged in with the Fastly CLI, you can give it that token:
530
+
531
+ ```sh
532
+ FASTLY_API_TOKEN=$(npx fastly auth token) npm run fastly:publish
533
+ ```
534
+
535
+ This:
536
+
537
+ - Uses the default collection name
538
+ - Uploads static files to the KV Store
539
+ - Stores server configuration for the collection
540
+
541
+ > [!TIP]
542
+ > Upload to a specific collection by specifying the collection name when publishing content:
543
+ > ```sh
544
+ > npm run fastly:publish -- --collection-name=preview-42
545
+ > ```
546
+
547
+ **No Wasm redeploy needed** unless you:
548
+
549
+ - Modify `src/index.js` - such as when you update your custom routing logic (e.g. collection selection) or
550
+ - Change `static-publish.rc.js`
551
+
552
+ If you do need to rebuild and redeploy the Compute app, simply run:
553
+
554
+ ```sh
555
+ npm run fastly:deploy
556
+ ```
557
+
558
+ ### Using S3-compatible storage (BETA)
559
+
560
+ #### Local development
561
+
562
+ During development, the local development server (`npm run dev:start`) runs against assets published to S3-compatible storage.
563
+
564
+ In this mode, the content in the S3-compatible storage can be updated independent of the Compute application running in the local development server.
565
+
566
+ Before publishing your content, your S3-compatible bucket must already exist.
567
+
568
+ > [!TIP]
569
+ > If you're using Fastly Object Storage, [create your Fastly account](https://www.fastly.com/signup/?tier=free) if you haven't already, and then follow the [Object Storage quick start](https://www.fastly.com/documentation/guides/platform/object-storage/object-storage-quick-start/) to set up your bucket.
570
+
571
+ Publish your content by typing:
572
+
573
+ ```sh
574
+ npm run s3:publish
575
+ ```
576
+
577
+ Then start the local development server:
578
+
579
+ ```sh
580
+ npm run dev:start
581
+ ```
582
+
583
+ #### Production
584
+
585
+ When you're ready for production:
586
+
587
+ 1. [Create a free Fastly account](https://www.fastly.com/signup/?tier=free) if you haven't already.
588
+ 2. Run `npm run fastly:deploy`
589
+ - This builds your Compute app into a Wasm binary
590
+ - Deploys it to a new or existing Fastly Compute service
591
+ - If creating a new service, the Fastly CLI uses the `[setup]` section of `fastly.toml`:
592
+ - It creates the backend `s3_storage`. It prompts you for the hostname and the port of the backend.
593
+ The default values are the hostname of your S3 endpoint and 443. Press Enter to accept them.
594
+ - It creates the Secret Store `S3_CREDENTIALS` and prompts you for the values of
595
+ `S3_ACCESS_KEY_ID` and `S3_SECRET_ACCESS_KEY`. Use credentials that can read the bucket.
596
+ - It links the backend and the Secret Store to your new service.
597
+ - If you deploy to an existing service, the Fastly CLI does not use the `[setup]` section.
598
+ Add the backend and the Secret Store to the service yourself, with the same names.
599
+
600
+ Once deployed, publish content like so:
601
+
602
+ ```sh
603
+ npm run s3:publish
604
+ ```
605
+
606
+ After the deploy, `fastly.toml` has the service ID, so `s3:publish` also purges the service's cache. For this purge, set `FASTLY_API_TOKEN` (or add `-- --fastly-api-token=<token>`) in addition to the S3 credentials. Without it, `s3:publish` stops with an error before it uploads files.
607
+
608
+ This:
609
+
610
+ - Uses the default collection name
611
+ - Uploads static files to the S3-compatible bucket
612
+ - Stores server configuration for the collection
613
+
614
+ > [!TIP]
615
+ > Upload to a specific collection by specifying the collection name when publishing content:
616
+ > ```sh
617
+ > npm run s3:publish -- --collection-name=preview-42
618
+ > ```
619
+
620
+ **No Wasm redeploy needed** unless you:
621
+
622
+ - Modify `src/index.js` - such as when you update your custom routing logic (e.g. collection selection) or
623
+ - Change `static-publish.rc.js`
624
+
625
+ If you do need to rebuild and redeploy the Compute app, simply run:
626
+
627
+ ```sh
628
+ npm run fastly:deploy
629
+ ```
630
+
631
+ ## ๐Ÿงน Cleaning Up
632
+
633
+ Every time you publish, old files are left behind for safety. **However, files with the same content will be re-used across collections and publishing events.** They are only stored once in the KV Store using their content hash as a key. This ensures that unchanged files aren't duplicated, keeping storage efficient and deduplicated.
634
+
635
+ Over time, however, collections may expire, old versions of files will be left behind, and some assets in the KV Store will no longer be referenced by any live collection. To avoid bloat, use:
636
+
637
+ ```sh
638
+ npm run dev:clean
639
+ ```
640
+ and
641
+ ```sh
642
+ npm run fastly:clean
643
+ ```
644
+
645
+ These scripts run against the local and Fastly KV Stores respectively, and run the following command:
646
+ ```
647
+ npx @fastly/compute-js-static-publish clean --delete-expired-collections
648
+ ```
649
+
650
+ This removes:
651
+
652
+ - Expired collection index files (only if `--delete-expired-collections` is passed)
653
+ - Unused content blobs (no longer referenced)
654
+ - Orphaned server config files
655
+
656
+ ### ๐Ÿ” Dry Run Mode
657
+
658
+ Preview what will be deleted without making changes:
659
+
660
+ ```sh
661
+ npx @fastly/compute-js-static-publish clean --dry-run
662
+ ```
663
+
664
+ > โš ๏ธ Cleanup never deletes the default collection and never deletes content thatโ€™s still in use.
665
+
666
+ ## ๐Ÿ”„ Content Compression
667
+
668
+ This project supports pre-compressing and serving assets in Brotli and Gzip formats. Compression is controlled at two different stages:
669
+
670
+ - **During publishing**, the `contentCompression` field in the `publish` section of `publish-content.config.js` defines which compressed variants (e.g., `br`, `gzip`) should be generated and uploaded to storage.
671
+
672
+ Assets are stored in multiple formats (uncompressed + compressed) if configured. A compressed variant is uploaded and used only if it is smaller than the original. (For very small files, the compressed variant is often larger.) If a variant is already in storage, it is not compressed or uploaded again. Files are compressed in parallel on the Node.js thread pool. By default, the CLI sets `UV_THREADPOOL_SIZE` to the number of CPU cores (minimum 4, maximum 16). To use a different value, set `UV_THREADPOOL_SIZE` yourself. To make compression faster, you can also set a lower `brotliQuality`. The following file types are compressed by default:
673
+
674
+ - Text-based: `.html`, `.js`, `.css`, `.svg`, `.json`, `.txt`, `.xml`, `.map`
675
+ - Certain binary formats: `.bmp`, `.tar`
676
+
677
+ - **At runtime**, the `allowedEncodings` field in the `server` section of `publish-content.config.js` specifies which compression formats the server is allowed to serve based on the client's `Accept-Encoding` header.
678
+
679
+ `PublisherServer` will serve the smallest appropriate version based on the `Accept-Encoding` header.
680
+
681
+ ## ๐Ÿงฉ Using PublisherServer in Custom Apps
682
+
683
+ You can combine PublisherServer with custom logic to support APIs, authentication, redirects, or A/B testing. Handle your own routes before you call `serveRequest()`.
684
+
685
+ `serveRequest()` returns `null` for a method other than `GET` or `HEAD`, and when no file matches and no SPA file or 404 page applies. If `publish-content.config.js` sets a 404 page or an SPA file, `serveRequest()` serves that page for each path that has no file. Thus, code after `serveRequest()` does not run for those requests.
686
+
687
+ ```js
688
+ import { PublisherServer } from '@fastly/compute-js-static-publish';
689
+ import rc from '../static-publish.rc.js';
690
+
691
+ const publisherServer = PublisherServer.fromStaticPublishRc(rc);
692
+
693
+ addEventListener("fetch", event => {
694
+ event.respondWith(handleRequest(event.request));
695
+ });
696
+
697
+ async function handleRequest(request) {
698
+ // Add your custom logic here, before serveRequest()
699
+ const url = new URL(request.url);
700
+ if (url.pathname === '/api/hello') {
701
+ return new Response(JSON.stringify({ greeting: "hi" }), {
702
+ headers: { 'content-type': 'application/json' }
703
+ });
704
+ }
705
+
706
+ const response = await publisherServer.serveRequest(request);
707
+ if (response != null) {
708
+ return response;
709
+ }
710
+
711
+ return new Response("Not Found", { status: 404 });
712
+ }
713
+ ```
714
+
715
+ ### โฑ๏ธ Measuring Performance with `Server-Timing`
716
+
717
+ `PublisherServer` can report how long it spends reading from storage. To turn this on, give it the name of a request header:
718
+
719
+ ```js
720
+ publisherServer.setServerTimingRequestHeader('X-Publisher-Server-Timing');
721
+ ```
722
+
723
+ A request that has this header gets a [`Server-Timing`](https://www.w3.org/TR/server-timing/) response header. Requests without it are not affected. This is off by default.
724
+
725
+ ```
726
+ Server-Timing: settings;dur=12.3, index;dur=40.1, index-body;dur=31.0, index-parse;dur=24.2, asset;dur=11.4
727
+ ```
728
+
729
+ | Name | Duration of |
730
+ |------|-------------|
731
+ | `settings` | Reading and parsing the collection's settings |
732
+ | `index` | Reading the collection's index, until the response headers arrive |
733
+ | `index-body` | Reading the body of the index |
734
+ | `index-parse` | Parsing the index |
735
+ | `asset` | Reading the file, until the response headers arrive. Can appear more than one time, one time for each variant that is tried. |
736
+ | `cache` | Looking up the response cache, if it is on (see [Caching Responses with the Core Cache](#๏ธ-caching-responses-with-the-core-cache)). `desc` is `hit` (with the age of the cached response, for example `hit age=42s`), `miss`, or `bypass`. |
737
+
738
+ An entry is missing if `PublisherServer` did not read that item for this request, for example because the item is cached in memory, or because the response came from the response cache.
739
+
740
+ `serveRequest()` starts the measurements for each request. If you call `getMatchingAsset()` and `serveAsset()` directly, call `beginRequest()` first:
741
+
742
+ ```js
743
+ publisherServer.beginRequest(request);
744
+ const asset = await publisherServer.getMatchingAsset(pathname);
745
+ if (asset != null) {
746
+ return publisherServer.serveAsset(request, asset);
747
+ }
748
+ ```
749
+
750
+ Any client can send the request header. Choose a name that is not easy to guess if you do not want to show these timings to the public.
751
+
752
+ ### ๐Ÿ—„๏ธ Caching Responses with the Core Cache
753
+
754
+ To serve a file, `PublisherServer` reads the collection's settings, the collection's index, and the file. Fastly can cache these reads, but `PublisherServer` must still parse the index for each request, and the index of a large site is large. To skip this work, `PublisherServer` can cache whole responses with the Fastly [Core Cache](https://www.fastly.com/documentation/guides/concepts/cache/) API:
755
+
756
+ ```js
757
+ publisherServer.setResponseCache({ maxAge: 3600 });
758
+ ```
759
+
760
+ `maxAge` is in seconds. This is off by default.
761
+
762
+ `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:
763
+
764
+ ```js
765
+ publisherServer.setResponseCache({ maxAge: 3600, maxBodySize: 4 * 1024 * 1024 });
766
+ ```
767
+
768
+ - 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.
769
+ - A path that does not match a file is cached, too, so a missing path does not read the index again.
770
+ - If several requests miss the same response at the same time, one request produces it, and the others wait for it.
771
+ - Only `200` and `404` responses are cached. Conditional requests (`304`) and `HEAD` requests are answered from the cached response.
772
+ - 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.
773
+
774
+ `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:
775
+
776
+ ```js
777
+ publisherServer.beginRequest(request);
778
+ const response = await publisherServer.serveCached(request, pathname, async (fillRequest) => {
779
+ const asset = await publisherServer.getMatchingAsset(pathname);
780
+ if (asset == null) {
781
+ return null; // not found; this result is cached, too
782
+ }
783
+ return publisherServer.serveAsset(fillRequest, asset);
784
+ });
785
+ ```
786
+
787
+ The second argument identifies the response in the collection. If anything other than the path and `Accept-Encoding` changes your response, include it in this value.
788
+
789
+ Notes:
790
+
791
+ - 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.
792
+ - 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.
793
+ - 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.
794
+ - 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.
795
+
796
+ ## ๐Ÿ“ฅ Using Published Assets in Your Code
797
+
798
+ To access files you've published, use the `getMatchingAsset()` and `loadAssetVariant()` methods on `publisherServer`.
799
+
800
+ ### Access Metadata for a File:
801
+
802
+ ```js
803
+ const asset = await publisherServer.getMatchingAsset('/index.html');
804
+ if (asset != null) {
805
+ // Asset exists with that path
806
+ asset.contentType; // e.g., 'text/html'
807
+ asset.lastModifiedTime; // Unix timestamp
808
+ asset.size; // Size in bytes of the base version
809
+ asset.hash; // SHA256 hash of base version
810
+ asset.variants; // Available variants (e.g., ['gzip'])
811
+ }
812
+ ```
813
+
814
+ ### Load the File from KV Store:
815
+
816
+ ```js
817
+ const assetVariant = await publisherServer.loadAssetVariant(asset, null); // pass 'gzip' or 'br' for compressed
818
+
819
+ assetVariant.storageEntry; // Storage entry (type StorageEntry defined in './src/storage/storage-provider.ts')
820
+ assetVariant.size; // Size of the variant
821
+ assetVariant.hash; // SHA256 of the variant
822
+ assetVariant.contentEncoding; // 'gzip', 'br', or null
823
+ assetVariant.numChunks; // Number of chunks (for large files)
824
+ ```
825
+
826
+ You can stream `assetVariant.storageEntry.body` directly to a `Response`, or read it using `.text()`, `.json()`, or `.arrayBuffer()` depending on its content type.
827
+
828
+ ---
829
+
830
+ ## ๐Ÿ“š CLI Reference
831
+
832
+ ### Available Commands
833
+
834
+ #### Outside a Compute App Directory
835
+ - `npx @fastly/compute-js-static-publish@latest [options]` - Scaffold a new Compute app
836
+
837
+ #### Inside a Compute App Directory
838
+ - `publish-content` - Publish static files to storage (KV Store or S3-compatible storage) under a named collection
839
+ - `clean` - Delete expired and unreferenced entries in storage
840
+ - `collections list` - List all published collections
841
+ - `collections delete` - Delete a specific collection index
842
+ - `collections promote` - Copy a collection to another name
843
+ - `collections update-expiration` - Modify expiration time for an existing collection
844
+
845
+ ### ๐Ÿ›  App Scaffolding
846
+
847
+ Run outside an existing Compute app directory:
848
+
849
+ #### Minimum required options
850
+
851
+ ```sh
852
+ # Using KV store storage
853
+ npx @fastly/compute-js-static-publish@latest \
854
+ --root-dir=./public \
855
+ --kv-store-name=<site-content>
856
+
857
+ # Using S3 storage (BETA)
858
+ npx @fastly/compute-js-static-publish@latest \
859
+ --root-dir=./public \
860
+ --storage-mode=s3 \
861
+ --s3-region=<s3 region> \
862
+ --s3-bucket=<bucket name> \
863
+ [--s3-endpoint=<endpoint>]
864
+ ```
865
+
866
+ #### Full options list
867
+
868
+ ```sh
869
+ npx @fastly/compute-js-static-publish@latest \
870
+ --root-dir=./public \
871
+ { [--storage-mode=kv-store] --kv-store-name=<site-content> | \
872
+ --storage-mode=s3 --s3-region=<s3 region> --s3-bucket=<bucket name> [--s3-endpoint=<endpoint>] } \
873
+ [--output=./compute-js] \
874
+ [--static-publisher-working-dir=<output>/static-publisher] \
875
+ [--publish-id=<prefix>] \
876
+ [--static-dir=./public/static] \
877
+ [--spa=./public/spa.html] \
878
+ [--not-found-page=./public/404.html] \
879
+ [--auto-index=index.html,index.htm] \
880
+ [--auto-ext=.html,.htm] \
881
+ [--name=my-site] \
882
+ [--description='My Compute static site'] \
883
+ [--author='you@example.com'] \
884
+ [--service-id=your-fastly-service-id]
885
+ ```
886
+
887
+ #### Options:
888
+
889
+ **Used to generate the Compute app:**
890
+ - `--storage-mode`: Specifies the storage mode. Must be either `kv-store` or `s3` (default: `kv-store`).
891
+
892
+ If `--storage-mode=kv-store`:
893
+ - `--kv-store-name`: Required. Name of KV Store to use.
894
+
895
+ If `--storage-mode=s3`:
896
+ - `--s3-region`: Required. Region of the S3-compatible bucket.
897
+ - `--s3-bucket`: Required. Name of the S3-compatible bucket.
898
+ - `--s3-endpoint`: Optional. Custom endpoint of the S3-compatible bucket, if necessary.
899
+
900
+ - `--output`: Compute app destination (default: `./compute-js`)
901
+ - `--static-publisher-working-dir`: Directory to hold working files (default: `<output>/static-publisher`).
902
+ - `--name`: Application name to insert into `fastly.toml`
903
+ - `--description`: Application description to insert into `fastly.toml`
904
+ - `--author`: Author to insert into `fastly.toml`
905
+ - `--service-id`: Optional existing Fastly Compute service ID
906
+
907
+ **Used in building config files:**
908
+ - `--root-dir`: Required. Directory of static site content.
909
+ - `--publish-id`: Optional key prefix for KV entries (default: `'default'`).
910
+ - `--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.
911
+ - `--static-dir`: One or more directories to serve with long cache TTLs.
912
+ - `--spa`: SPA fallback file path, from the current directory (e.g., `./public/spa.html`). The file must exist under `--root-dir`.
913
+ - `--not-found-page`: 404 fallback file path, from the current directory (e.g., `./public/404.html`). The file must exist under `--root-dir`. If you do not set it, the scaffolder uses `404.html` in `--root-dir` if that file exists.
914
+ - `--auto-index`: List of filenames to use as index files.
915
+ - `--auto-ext`: Extensions to try when resolving URLs.
916
+
917
+ ### ๐Ÿš€ Inside a Compute App Directory
918
+
919
+ Once you're in the scaffolded Compute app directory (with `static-publish.rc.js` present), you can run these subcommands:
920
+
921
+ #### `publish-content`
922
+
923
+ ```sh
924
+ npx @fastly/compute-js-static-publish publish-content \
925
+ [--root-dir=./public] \
926
+ [--collection-name=preview-42] \
927
+ [--config=./publish-content.config.js] \
928
+ [--expires-in=7d | --expires-at=2025-05-01T12:00Z | --expires-never] \
929
+ [--overwrite-existing] \
930
+ [--brotli-quality=<0-11>] \
931
+ [--local] \
932
+ [--fastly-api-token=...] \
933
+ [--fastly-service-id=...] \
934
+ [--purge-environment=production,staging] \
935
+ [--s3-access-key-id=... --s3-secret-access-key=...] \
936
+ [--verbose]
937
+ ```
938
+
939
+ 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).
940
+
941
+ 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.
942
+
943
+ 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.
944
+
945
+ ##### Options:
946
+
947
+ - `--collection-name`: Name of the collection to create/update (default: value in `static-publish.rc.js`)
948
+ - `--config`: Path to a config file to configure server behavior for this collection (default: `./publish-content.config.js`)
949
+ - `--root-dir`: Source directory to read files from (overrides value in `publish-content.config.js`)
950
+ - `--overwrite-existing`: Always upload all files, even if they are already in storage. `--kv-overwrite` is an alias.
951
+ - `--brotli-quality`: Brotli quality for the `br` variants, an integer from 0 to 11. Overrides `brotliQuality` in `publish-content.config.js`. This is useful in CI, where the config file is generated at each run.
952
+ - `--fastly-service-id`: The Fastly Service ID to purge after publishing. The command purges the surrogate key `<publishId>-<collectionName>`, so that the service stops serving cached copies of the collection's settings, index, files, and responses (see [response cache](#๏ธ-caching-responses-with-the-core-cache)). If not set, the tool will check:
953
+ - **`FASTLY_SERVICE_ID` environment variable**
954
+ - `service_id` in `fastly.toml`
955
+
956
+ If none is found, the command skips the purge. The purge also needs an API token (see `--fastly-api-token`). With `--local`, there is no purge. If the purge fails, the command shows a warning and completes, because the content is already published.
957
+ - `--purge-environment`: The environments to purge: `production` (the default), `staging`, or both, as a comma-separated list (`--purge-environment=production,staging`). You can also repeat the option. Purge `staging` if you test the collection on a [staged service version](https://www.fastly.com/documentation/guides/getting-started/services/working-with-staging/), because a purge without it does not clear the staging cache. If the service has no staged version, there is nothing to purge in `staging`. The API then gives the same error as for a service ID that is not correct, so the command shows a message for both causes, not a warning.
958
+ - `--verbose`: Verbose mode. When enabled, the command logs a line for each file that the command scans, and for each upload. Without this option, the command logs the progress after each 1,000 files or uploads.
959
+
960
+ **Expiration:**
961
+
962
+ - `--expires-in`: Time-to-live from now (e.g. `1h`, `2d`, `1w`)
963
+ - `--expires-at`: Absolute expiration time (ISO format: `2025-05-01T12:00Z`)
964
+ - `--expires-never`: Collection never expires
965
+
966
+ *At most one of **`--expires-in`**, **`--expires-at`**, or **`--expires-never`** may be specified*
967
+
968
+ **KV Store Options:**
969
+
970
+ - `--local`: Instead of working with the Fastly KV Store, operate on local files that will be used to simulate the KV Store with the local development environment. KV Store mode only. In S3 mode, `--local` is an error, because there is no local simulation of S3 storage.
971
+
972
+ - `--fastly-api-token`: API token to use when publishing. If not set, the tool uses the **`FASTLY_API_TOKEN` environment variable**.
973
+
974
+ **S3 Storage Options (BETA):**
975
+
976
+ - `--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.
977
+ - `--s3-upload-concurrency`: Number of objects to upload at the same time, from 1 to 256 (default: 64). Each upload keeps its file in memory, so a site with many large files can need a lower value.
978
+
979
+ #### `clean`
980
+
981
+ ```sh
982
+ npx @fastly/compute-js-static-publish clean \
983
+ [--delete-expired-collections] \
984
+ [--dry-run]
985
+ ```
986
+
987
+ Cleans up expired or unreferenced items in storage (KV Store or S3-compatible storage).
988
+ This can include expired collection indexes and orphaned content assets.
989
+
990
+ ##### Options:
991
+
992
+ - `--delete-expired-collections`: If set, expired collection index files will be deleted.
993
+ - `--dry-run`: Show what would be deleted without performing any deletions.
994
+
995
+ **KV Store Options:**
996
+
997
+ - `--local`: Instead of working with the Fastly KV Store, operate on local files that will be used to simulate the KV Store with the local development environment. KV Store mode only. In S3 mode, `--local` is an error, because there is no local simulation of S3 storage.
998
+
999
+ - `--fastly-api-token`: API token to use when publishing. If not set, the tool uses the **`FASTLY_API_TOKEN` environment variable**.
1000
+
1001
+ **S3 Storage Options (BETA):**
1002
+
1003
+ - `--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.
1004
+
1005
+ #### `collections list`
1006
+
1007
+ ```sh
1008
+ npx @fastly/compute-js-static-publish collections list
1009
+ ```
1010
+ Lists all collections currently published in storage.
1011
+
1012
+ ##### Options:
1013
+
1014
+ **KV Store Options:**
1015
+
1016
+ - `--local`: Instead of working with the Fastly KV Store, operate on local files that will be used to simulate the KV Store with the local development environment. KV Store mode only. In S3 mode, `--local` is an error, because there is no local simulation of S3 storage.
1017
+
1018
+ - `--fastly-api-token`: API token to use when publishing. If not set, the tool uses the **`FASTLY_API_TOKEN` environment variable**.
1019
+
1020
+ **S3 Storage Options (BETA):**
1021
+
1022
+ - `--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.
1023
+
1024
+ #### `collections promote`
1025
+
1026
+ ```sh
1027
+ npx @fastly/compute-js-static-publish collections promote \
1028
+ --collection-name=preview-42 \
1029
+ --to=live \
1030
+ [--expires-in=7d | --expires-at=2025-06-01T00:00Z | --expires-never]
1031
+ ```
1032
+ Copies an existing collection (content + config) to a new collection name.
1033
+
1034
+ 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).
1035
+
1036
+ ##### Options:
1037
+
1038
+ - `--collection-name`: The name of the source collection to promote (required)
1039
+ - `--to`: The name of the new (target) collection to create or overwrite (required)
1040
+
1041
+ **Expiration:**
1042
+
1043
+ - `--expires-in`: Time-to-live from now (e.g. `1h`, `2d`, `1w`)
1044
+ - `--expires-at`: Absolute expiration time (ISO format)
1045
+ - `--expires-never`: Collection never expires
1046
+
1047
+ *At most one of **`--expires-in`**, **`--expires-at`**, or **`--expires-never`** may be specified*. If not provided, then the existing expiration rule of the collection being promoted is used.
1048
+
1049
+ **KV Store Options:**
1050
+
1051
+ - `--local`: Instead of working with the Fastly KV Store, operate on local files that will be used to simulate the KV Store with the local development environment. KV Store mode only. In S3 mode, `--local` is an error, because there is no local simulation of S3 storage.
1052
+
1053
+ - `--fastly-api-token`: API token to use when publishing. If not set, the tool uses the **`FASTLY_API_TOKEN` environment variable**.
1054
+
1055
+ **Purge Options:**
1056
+
1057
+ - `--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.
1058
+ - `--purge-environment`: The environments to purge: `production` (the default), `staging`, or both, as a comma-separated list. You can also repeat the option.
1059
+
1060
+ **S3 Storage Options (BETA):**
1061
+
1062
+ - `--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.
1063
+
1064
+ #### `collections update-expiration`
1065
+
1066
+ ```sh
1067
+ npx @fastly/compute-js-static-publish collections update-expiration \
1068
+ --collection-name=preview-42 \
1069
+ --expires-in=3d | --expires-at=2025-06-01T00:00Z | --expires-never
1070
+ ```
1071
+ Sets or updates the expiration time of an existing collection.
1072
+
1073
+ ##### Options:
1074
+ - `--collection-name`: The name of the collection to update (required)
1075
+
1076
+ **Expiration:**
1077
+
1078
+ - `--expires-in`: Time-to-live from now (e.g. `1h`, `2d`, `1w`)
1079
+ - `--expires-at`: Absolute expiration time (ISO format)
1080
+ - `--expires-never`: Collection never expires
1081
+
1082
+ *Exactly one of **`--expires-in`**, **`--expires-at`**, or **`--expires-never`** must be specified*
1083
+
1084
+ **KV Store Options:**
1085
+
1086
+ - `--local`: Instead of working with the Fastly KV Store, operate on local files that will be used to simulate the KV Store with the local development environment. KV Store mode only. In S3 mode, `--local` is an error, because there is no local simulation of S3 storage.
1087
+
1088
+ - `--fastly-api-token`: API token to use when publishing. If not set, the tool uses the **`FASTLY_API_TOKEN` environment variable**.
1089
+
1090
+ **S3 Storage Options (BETA):**
1091
+
1092
+ - `--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.
1093
+
1094
+ #### `collections delete`
1095
+
1096
+ ```sh
1097
+ npx @fastly/compute-js-static-publish collections delete \
1098
+ --collection-name=preview-42
1099
+ ```
1100
+
1101
+ Deletes a collection index from storage. The content files will remain as they may still be referenced by other collection indexes.
1102
+
1103
+ Use the `npx @fastly/compute-js-static-publish clean` command afterward to remove content files that are no longer referenced by any collection.
1104
+
1105
+ 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).
1106
+
1107
+ ##### Options:
1108
+
1109
+ - `--collection-name`: The name of the collection to delete (required)
1110
+
1111
+ - `--fastly-service-id`: The Fastly Service ID to purge after deleting. 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`). With `--local`, there is no purge. If the purge fails, the command shows a warning and completes, because the collection is already deleted.
1112
+
1113
+ - `--purge-environment`: The environments to purge: `production` (the default), `staging`, or both, as a comma-separated list. You can also repeat the option.
1114
+
1115
+ **KV Store Options:**
1116
+
1117
+ - `--local`: Instead of working with the Fastly KV Store, operate on local files that will be used to simulate the KV Store with the local development environment. KV Store mode only. In S3 mode, `--local` is an error, because there is no local simulation of S3 storage.
1118
+
1119
+ - `--fastly-api-token`: API token to use when publishing. If not set, the tool uses the **`FASTLY_API_TOKEN` environment variable**.
1120
+
1121
+ **S3 Storage Options (BETA):**
1122
+
1123
+ - `--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.
1124
+
1125
+ ---
1126
+
1127
+ ## ๐Ÿ“• Appendix
1128
+
1129
+ ### fromCookie
1130
+
1131
+ `collectionSelector.fromCookie` is a utility function that enables the use of a browser
1132
+ cookie to select the active collection.
1133
+
1134
+ ```js
1135
+ import { collectionSelector } from '@fastly/compute-js-static-publish';
1136
+
1137
+ const { collectionName, redirectResponse } =
1138
+ collectionSelector.fromCookie(request, {
1139
+ // Everything here is optional โ€“ these are just examples
1140
+ cookieName: 'publisher-collection', // default
1141
+ activatePath: '/activate', // default
1142
+ resetPath: '/reset', // default
1143
+ cookieHttpOnly: true, // default
1144
+ cookieMaxAge: 60 * 60 * 24 * 7, // 7-days. default is `null`, never expires.
1145
+ cookiePath: '/', // default
1146
+ });
1147
+
1148
+ if (redirectResponse) {
1149
+ // honor the redirect
1150
+ return redirectResponse;
1151
+ }
1152
+
1153
+ // `collectionName` now holds the active collection (or `null` if none)
1154
+ ```
1155
+
1156
+ #### What it does, in plain English
1157
+
1158
+ 1. Reads a cookie
1159
+
1160
+ It looks for a cookie named cookieName (default `publisher-collection`) and hands you the value as `collectionName`.
1161
+
1162
+ 2. Handles two helper endpoints for you
1163
+
1164
+ | Endpoint | Purpose | Query params | Result |
1165
+ |------------------------------------|------------------|------------------------------------------------------------------------------------------------|-------------------------------------------|
1166
+ | activatePath (default `/activate`) | Set the cookie | `collection` (required) - name of the collection<br /> `redirectTo` (optional, `/` by default) | `302` redirect with a `Set-Cookie` header |
1167
+ | resetPath (default `/reset`) | Clear the cookie | `redirectTo` (optional, `/` by default) | `302` redirect that expires the cookie |
1168
+
1169
+ If a visitor accesses `/activate?collection=blue&redirectTo=/preview`, the helper will issue a redirect and drop `publisher-collection=blue` into their cookie jar.
1170
+ - If someone forgets `?collection=?`? Then `/activate` replies with HTTP `400`.
1171
+
1172
+ When the visitor hits `/reset`, the cookie is deleted.
1173
+
1174
+ 3. Safety flags are baked in
1175
+
1176
+ - `HttpOnly` is on by default (configurable), to help avoid XSS issues.
1177
+ - `Secure` is automatically added on HTTPS requests.
1178
+ - `SameSite=Lax` is always set โ€“ reasonable default for previews.
1179
+
1180
+ #### Option reference
1181
+
1182
+ | Option | Type | Default | Notes |
1183
+ |------------------|-------------------|--------------------------|------------------------------------------------|
1184
+ | `cookieName` | string | `'publisher-collection'` | Name of the cookie to read/write |
1185
+ | `activatePath` | string | `'/activate'` | Path that sets the cookie |
1186
+ | `resetPath` | string | `'/reset'` | Path that clears the cookie |
1187
+ | `cookieHttpOnly` | boolean | `true` | Turn off if the client-side needs to read it |
1188
+ | `cookieMaxAge` | number\|undefined | `undefined` | Seconds until expiry; omit for session cookies |
1189
+ | `cookiePath` | string | `'/'` | Path attribute in the cookie |
1190
+
1191
+ #### Example
1192
+
1193
+ `fromCookie` can be dropped into a Fastly Compute app:
1194
+
1195
+ ```js
1196
+ async function handleRequest(event) {
1197
+ const request = event.request;
1198
+
1199
+ // --- Cookie handling starts here
1200
+ const { collectionName, redirectResponse } = collectionSelector.fromCookie(request);
1201
+ if (redirectResponse) {
1202
+ // obey redirect first
1203
+ return redirectResponse;
1204
+ }
1205
+ publisherServer.setActiveCollectionName(collectionName); // null selects the default collection
1206
+ // --- Cookie handling ends here
1207
+
1208
+ // Regular routing follows...
1209
+ const response = await publisherServer.serveRequest(request);
1210
+ if (response != null) {
1211
+ return response;
1212
+ }
1213
+ return new Response('Not found', { status: 404 });
1214
+ }
1215
+ ```
1216
+
1217
+ ---
1218
+
1219
+ ## ๐Ÿ“š Next Steps
1220
+
1221
+ - View CLI command help: `npx @fastly/compute-js-static-publish --help`
1222
+ - Use in CI to automate branch previews
1223
+ - Visit [https://developer.fastly.com](https://developer.fastly.com) for Compute platform docs
1224
+
1225
+ ## Development
1226
+
1227
+ To build the package, run `npm run build`. To run the tests, see [test/README.md](./test/README.md).
1228
+
1229
+ 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.
1230
+
1231
+ ## Issues
1232
+
1233
+ If you encounter any non-security-related bug or unexpected behavior, please [file an issue][bug] using the bug report template.
1234
+
1235
+ [bug]: https://github.com/fastly/compute-js-static-publish/issues/new?labels=bug
1236
+
1237
+ ### Security issues
1238
+
1239
+ Please see our [SECURITY.md](SECURITY.md) for guidance on reporting security-related issues.
1240
+
1241
+ ## License
1242
+
1243
+ [MIT](./LICENSE).