@fastly/compute-js-static-publish 4.2.1 → 5.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +50 -50
- package/build/cli/commands/build-static.js +49 -49
- package/build/cli/commands/clean-kv-store.d.ts +3 -0
- package/build/cli/commands/clean-kv-store.d.ts.map +1 -0
- package/build/cli/commands/clean-kv-store.js +54 -0
- package/build/cli/commands/init-app.js +11 -11
- package/build/cli/index.js +9 -9
- package/build/cli/load-config.js +9 -9
- package/build/cli/presets/preset-base.d.ts +1 -1
- package/build/cli/presets/preset-base.d.ts.map +1 -1
- package/build/cli/util/fastly-api.js +1 -1
- package/build/cli/util/kv-store.d.ts +16 -0
- package/build/cli/util/kv-store.d.ts.map +1 -0
- package/build/cli/util/kv-store.js +108 -0
- package/build/compute-js.d.ts +1 -1
- package/build/compute-js.d.ts.map +1 -1
- package/build/compute-js.js +1 -1
- package/build/server/assets/content-asset-kv-store.d.ts +18 -0
- package/build/server/assets/content-asset-kv-store.d.ts.map +1 -0
- package/build/server/assets/content-asset-kv-store.js +67 -0
- package/build/server/assets/content-asset-wasm-inline.js +1 -1
- package/build/server/assets/content-assets.js +1 -1
- package/build/server/kv-store/inline-store-entry.d.ts +25 -0
- package/build/server/kv-store/inline-store-entry.d.ts.map +1 -0
- package/build/server/kv-store/inline-store-entry.js +100 -0
- package/build/types/config-normalized.d.ts +1 -1
- package/build/types/config.d.ts +1 -1
- package/build/types/content-assets.d.ts +6 -6
- package/build/types/content-assets.d.ts.map +1 -1
- package/build/util/metadata.d.ts +1 -1
- package/build/util/metadata.d.ts.map +1 -1
- package/build/util/metadata.js +4 -4
- package/package.json +2 -2
- package/resources/statics-metadata.d.ts +1 -1
package/README.md
CHANGED
|
@@ -5,7 +5,7 @@ Using a static site generator to build your website? Do you simply need to serve
|
|
|
5
5
|
## New! Version 4
|
|
6
6
|
|
|
7
7
|
Version 4 of this tool has some awesome new features:
|
|
8
|
-
- Support for serving files from Fastly's [
|
|
8
|
+
- Support for serving files from Fastly's [KV Store](#kv-store) instead of/alongside bundling them into the Wasm module.
|
|
9
9
|
- Scaffolded applications no longer use a bundler by default (Webpack is optional).
|
|
10
10
|
- Brotli and Gzip compression.
|
|
11
11
|
- Support for returning `304 Not Modified` status based on `If-None-Match` and `If-Modified-Since` request headers.
|
|
@@ -63,7 +63,7 @@ Once your application is scaffolded, `@fastly/compute-js-static-publish` integra
|
|
|
63
63
|
running as part of your build process.
|
|
64
64
|
|
|
65
65
|
The files you have configured to be included (`--root-dir`) are enumerated and prepared. Their contents are included into
|
|
66
|
-
your Wasm binary (or made available via [
|
|
66
|
+
your Wasm binary (or made available via [KV Store](#kv-store), if so configured). This process is called "publishing".
|
|
67
67
|
|
|
68
68
|
Once the files are published, they are available to the other source files in the Compute@Edge application. For example,
|
|
69
69
|
the stock application runs the [PublisherServer](#publisherserver) class to serve these files.
|
|
@@ -77,11 +77,11 @@ If the files in `--root-dir` have changed, then a new set of files will be publi
|
|
|
77
77
|
### Content Compression
|
|
78
78
|
|
|
79
79
|
During publishing, this tool supports pre-compression of content. By default, your assets are compressed using the Brotli
|
|
80
|
-
and gzip algorithms, and then stored alongside the original files in your Wasm binary (or [
|
|
80
|
+
and gzip algorithms, and then stored alongside the original files in your Wasm binary (or [KV Store](#kv-store)).
|
|
81
81
|
|
|
82
|
-
> Note: By default, pre-compressed content assets are not generated when the
|
|
82
|
+
> Note: By default, pre-compressed content assets are not generated when the KV Store is not used.
|
|
83
83
|
This is done to prevent the inclusion multiple of copies of each asset from making the Wasm binary too large.
|
|
84
|
-
If you want to pre-compress assets when not using
|
|
84
|
+
If you want to pre-compress assets when not using KV Store, add a value for 'contentCompression' to your
|
|
85
85
|
`static-publish.rc.js` file.
|
|
86
86
|
|
|
87
87
|
## CLI options
|
|
@@ -138,13 +138,13 @@ Note that the files referenced by `--spa` and `--not-found-page` do not necessar
|
|
|
138
138
|
|
|
139
139
|
These arguments are used to populate the `fastly.toml` and `package.json` files of your Compute@Edge application.
|
|
140
140
|
|
|
141
|
-
| Option
|
|
142
|
-
|
|
143
|
-
| `name`
|
|
144
|
-
| `description`
|
|
145
|
-
| `author`
|
|
146
|
-
| `service-id`
|
|
147
|
-
| `
|
|
141
|
+
| Option | Default | Description |
|
|
142
|
+
|-----------------|------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
|
|
143
|
+
| `name` | `name` from `package.json`, or `compute-js-static-site` | The name of your Compute@Edge application. |
|
|
144
|
+
| `description` | `description` from `package.json`, or `Compute@Edge static site` | The description of your Compute@Edge application. |
|
|
145
|
+
| `author` | `author` from `package.json`, or `you@example.com` | The author of your Compute@Edge application. |
|
|
146
|
+
| `service-id` | (None) | The ID of an existing Fastly WASM service for your Compute@Edge application. |
|
|
147
|
+
| `kv-store-name` | (None) | The name of an existing [Fastly KV Store](https://developer.fastly.com/learning/concepts/data-stores/#kv-stores) to hold the content assets. In addition to already existing, it must be linked to the service specified by `--service-id`. |
|
|
148
148
|
|
|
149
149
|
## Usage with frameworks and static site generators
|
|
150
150
|
|
|
@@ -176,7 +176,7 @@ You may still override any of these options individually.
|
|
|
176
176
|
This server handles the following automatically:
|
|
177
177
|
|
|
178
178
|
* Maps the path of your request to a path under `--public-dir` and serves the content of the asset
|
|
179
|
-
* Sources the content from the content packaged in the Wasm binary, or from the [
|
|
179
|
+
* Sources the content from the content packaged in the Wasm binary, or from the [KV Store](#kv-store), if configured.
|
|
180
180
|
* Applies long-lived cache headers to files served from `--static-dir` directories. Files under these directories will be cached by the browser for 1 year. (Use versioned or hashed filenames to avoid serving stale assets.)
|
|
181
181
|
* Performs Brotli and gzip compression as requested by the `Accept-Encoding` headers.
|
|
182
182
|
* Provides `Last-Modified` and `ETag` response headers, and uses them with `If-Modified-Since` and `If-None-Match` request headers to produce `304 Not Modified` responses.
|
|
@@ -231,58 +231,58 @@ ID of the service. The `fastly compute publish` will deploy to the service ident
|
|
|
231
231
|
To specify the service at the time you are scaffolding the project (for example, if you are running this tool and deploying
|
|
232
232
|
as part of a CI process), specify the `--service-id` command line argument to populate `fastly.toml` with this value.
|
|
233
233
|
|
|
234
|
-
## Using the
|
|
234
|
+
## Using the KV Store (BETA) <a name="kv-store"></a>
|
|
235
235
|
|
|
236
|
-
Starting with v4, it's now possible to upload assets to and serve them from a [Fastly
|
|
236
|
+
Starting with v4, it's now possible to upload assets to and serve them from a [Fastly KV Store](https://developer.fastly.com/learning/concepts/data-stores/#kv-stores).
|
|
237
237
|
|
|
238
|
-
You can enable the use of
|
|
238
|
+
You can enable the use of KV Store with `@fastly/compute-js-static-publish` as you scaffold your application, or
|
|
239
239
|
at any later time.
|
|
240
240
|
|
|
241
|
-
At the time you enable the use of
|
|
241
|
+
At the time you enable the use of KV Store:
|
|
242
242
|
|
|
243
243
|
* Your Fastly service must already exist. See [Associating your project with a Fastly Service](#associating-your-project-with-a-fastly-service) above.
|
|
244
244
|
|
|
245
|
-
* Your
|
|
246
|
-
As of this writing, to create the
|
|
247
|
-
or the Fastly [
|
|
248
|
-
Once the
|
|
245
|
+
* Your KV Store must already exist under the same Fastly account, and be linked to the service.
|
|
246
|
+
As of this writing, to create the KV Store you will need to use either the Fastly CLI [fastly kv-store create](https://developer.fastly.com/reference/cli/kv-store/create/)
|
|
247
|
+
or the Fastly [KV Store API](https://developer.fastly.com/reference/api/services/resources/kv-store/#create-store).
|
|
248
|
+
Once the KV Store is created, you must be link it to your Fastly service using the [Resource API](https://developer.fastly.com/reference/api/services/resource/#create-resource).
|
|
249
249
|
|
|
250
250
|
```shell
|
|
251
|
-
# Create
|
|
252
|
-
$ curl -i -X POST "https://api.fastly.com/resources/stores/
|
|
251
|
+
# Create a KV Store
|
|
252
|
+
$ curl -i -X POST "https://api.fastly.com/resources/stores/kv" -H "Fastly-Key: YOUR_FASTLY_TOKEN" -H "Content-Type: application/json" -H "Accept: application/json" -d '{"name":"example-store"}'
|
|
253
253
|
|
|
254
|
-
# Link the
|
|
255
|
-
$ curl -i -X POST "https://api.fastly.com/service/YOUR_FASTLY_SERVICE_ID/version/YOUR_FASTLY_SERVICE_VERSION/resource" -H "Fastly-Key: YOUR_FASTLY_TOKEN" -H "Content-Type: application/x-www-form-urlencoded" -H "Accept: application/json" -d "name=example-store-service-a&resource_id=
|
|
254
|
+
# Link the KV Store to a service
|
|
255
|
+
$ curl -i -X POST "https://api.fastly.com/service/YOUR_FASTLY_SERVICE_ID/version/YOUR_FASTLY_SERVICE_VERSION/resource" -H "Fastly-Key: YOUR_FASTLY_TOKEN" -H "Content-Type: application/x-www-form-urlencoded" -H "Accept: application/json" -d "name=example-store-service-a&resource_id=YOUR_KV_STORE_ID"
|
|
256
256
|
```
|
|
257
257
|
|
|
258
|
-
Once the
|
|
259
|
-
file under the `
|
|
258
|
+
Once the KV Store is created and linked to your service, add its name to your `static-publish.rc.js`
|
|
259
|
+
file under the `kvStoreName` key.
|
|
260
260
|
|
|
261
|
-
To specify the
|
|
262
|
-
deploying as part of a CI process), specify the `--service-id` and `--
|
|
261
|
+
To specify the KV Store at the time you are scaffolding the project (for example, if you are running this tool and
|
|
262
|
+
deploying as part of a CI process), specify the `--service-id` and `--kv-store-name` command line arguments to populate
|
|
263
263
|
the respective files with these values.
|
|
264
264
|
|
|
265
265
|
After you have done the above steps, go ahead and build your application as normal. If you use `fastly compute build --verbose`
|
|
266
|
-
(or run `npm run build` directly), you should see output in your logs saying that files are being sent to the
|
|
266
|
+
(or run `npm run build` directly), you should see output in your logs saying that files are being sent to the KV Store.
|
|
267
267
|
|
|
268
|
-
The `statics-metadata.js` file should now show `"type": "
|
|
268
|
+
The `statics-metadata.js` file should now show `"type": "kv-store"` for content assets.
|
|
269
269
|
Your Wasm binary should also be smaller, as the content of the files are no longer inlined in the build artifact.
|
|
270
|
-
You can deploy this and run it from Fastly, and the referenced files will be served from
|
|
270
|
+
You can deploy this and run it from Fastly, and the referenced files will be served from KV Store.
|
|
271
271
|
|
|
272
|
-
You will also see entries in `fastly.toml` that represent the local
|
|
272
|
+
You will also see entries in `fastly.toml` that represent the local KV Store.
|
|
273
273
|
These enable the site to also run correctly when served using the local development environment.
|
|
274
274
|
|
|
275
|
-
### Cleaning unused items from
|
|
275
|
+
### Cleaning unused items from KV Store
|
|
276
276
|
|
|
277
|
-
The files that are uploaded to the
|
|
277
|
+
The files that are uploaded to the KV Store are submitted using keys of the following format:
|
|
278
278
|
|
|
279
279
|
`<publish-id>:<asset-path>_<alg>_<hash>`
|
|
280
280
|
|
|
281
281
|
For example:
|
|
282
282
|
`12345abcde67890ABCDE00:/public/index.html_br_aeed29478691e67f6d5s36b4ded20c17e9eae437614617067a8751882368b965`
|
|
283
283
|
|
|
284
|
-
Using such
|
|
285
|
-
This enables to detect whether an unchanged file already exists in the
|
|
284
|
+
Using such a key ensures that whenever the file contents are identical, the same key will be generated.
|
|
285
|
+
This enables to detect whether an unchanged file already exists in the KV Store, avoiding having to re-submit
|
|
286
286
|
files that have not changed. If the file contents have changed, then a new hash is generated. This ensures that
|
|
287
287
|
even during the brief amount of time between deploys, any request served by a prior version will still serve the same
|
|
288
288
|
corresponding previous version of the content.
|
|
@@ -292,12 +292,12 @@ However, this system never deletes files automatically. After many deployments,
|
|
|
292
292
|
`@fastly/compute-js-static-publish` includes a feature to delete these old versions of the files that are no longer being
|
|
293
293
|
used. To run it, type the following command:
|
|
294
294
|
|
|
295
|
-
`npx @fastly/compute-js-static-publish --clean-
|
|
295
|
+
`npx @fastly/compute-js-static-publish --clean-kv-store`
|
|
296
296
|
|
|
297
|
-
It works by scanning `statics-metadata.js` for all currently-used
|
|
298
|
-
keys in the configured
|
|
297
|
+
It works by scanning `statics-metadata.js` for all currently-used keys. Then it enumerates all the existing
|
|
298
|
+
keys in the configured KV Store and that belong to this application (can do so by narrowing down all keys to the ones
|
|
299
299
|
that begin with the "publish id"). If any of the keys is not in the list of currently-used keys, then a request is made
|
|
300
|
-
to delete that
|
|
300
|
+
to delete that KV Store value.
|
|
301
301
|
|
|
302
302
|
And that's it! It should be possible to run this task to clean up once in a while.
|
|
303
303
|
|
|
@@ -309,8 +309,8 @@ And that's it! It should be possible to run this task to clean up once in a whil
|
|
|
309
309
|
except for those that are excluded using some of the following features. Files outside this root cannot be
|
|
310
310
|
included in the publishing.
|
|
311
311
|
|
|
312
|
-
* `
|
|
313
|
-
to Fastly
|
|
312
|
+
* `kvStoreName` - Set this value to the _name_ of an existing KV Store to enable uploading of content assets
|
|
313
|
+
to Fastly KV Store. See [Using the KV Store](#kv-store) for more information.
|
|
314
314
|
|
|
315
315
|
* `excludeDirs` - Specifies names of files and directories within `rootDir` to exclude from the publishing. Each entry can
|
|
316
316
|
be a string or a JavaScript `RegExp` object. Every file and directory under `rootDir` is checked against each entry of
|
|
@@ -332,19 +332,19 @@ And that's it! It should be possible to run this task to clean up once in a whil
|
|
|
332
332
|
the [asset key](#asset-keys), as well as its content type (MIME type string). You may return one of three values from
|
|
333
333
|
this function:
|
|
334
334
|
* Boolean `true` - Include the file as a content asset in this publishing. Upload the file to and serve it from the
|
|
335
|
-
|
|
335
|
+
KV Store if KV Store mode is enabled, or include the contents of the file in the Wasm binary if KV Store
|
|
336
336
|
mode is not enabled.
|
|
337
337
|
* String `"inline"` - Include the file as a content asset in this publishing. Include the contents of the file in the
|
|
338
|
-
Wasm binary, regardless of whether
|
|
338
|
+
Wasm binary, regardless of whether KV Store mode is enabled.
|
|
339
339
|
* Boolean `false` - Do not include this file as a content asset in this publishing.
|
|
340
340
|
|
|
341
341
|
If you do not provide a function, then every file will be included in this publishing as a content asset, and their
|
|
342
|
-
contents will be uploaded to and served from the
|
|
343
|
-
binary if
|
|
342
|
+
contents will be uploaded to and served from the KV Store if KV Store mode is enabled, or included in the Wasm
|
|
343
|
+
binary if KV Store mode is not enabled.
|
|
344
344
|
|
|
345
345
|
* `contentCompression` - During the publishing, the tool will pre-generate compressed versions of content assets in these
|
|
346
346
|
formats and make them available to the Publisher Server or your application. Default value is [ 'br' | 'gzip' ] if
|
|
347
|
-
|
|
347
|
+
KV Store is enabled, or [] if KV Store is not enabled.
|
|
348
348
|
|
|
349
349
|
* `moduleAssetInclusionTest` - Optionally specify a test function that can be run against each enumerated asset during
|
|
350
350
|
the publishing, to determine whether to include the asset as a module asset. For every file, this function is passed
|
|
@@ -426,7 +426,7 @@ binary contents of an asset.
|
|
|
426
426
|
|
|
427
427
|
The data of each content asset can exist in one of two stores:
|
|
428
428
|
* Inline Store - this is a data store that exists within the Wasm binary.
|
|
429
|
-
* Fastly
|
|
429
|
+
* Fastly KV Store - Fastly's distributed edge data store. Data can be placed here without impacting the size of
|
|
430
430
|
your Wasm binary.
|
|
431
431
|
|
|
432
432
|
Your application can stream the contents of these assets to a visitor, or read from the stream itself and access its
|
|
@@ -453,7 +453,7 @@ import { contentAssets } from './statics';
|
|
|
453
453
|
const asset = contentAssets.getAsset('/public/index.html');
|
|
454
454
|
|
|
455
455
|
// 'wasm-inline' if object's data is 'inlined' into Wasm binary
|
|
456
|
-
// '
|
|
456
|
+
// 'kv-store' if object's data exists in Fastly KV Store
|
|
457
457
|
asset.type;
|
|
458
458
|
|
|
459
459
|
// Get the "store entry"
|
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
//
|
|
6
6
|
// statics-metadata.js
|
|
7
7
|
//
|
|
8
|
-
//
|
|
8
|
+
// kvStoreName: string - Name of KV Store, or null if not used.
|
|
9
9
|
// contentAssetMetadataMap: Map<string, ContentAssetMetadataMapEntry> - mapping of asset keys to their metadata
|
|
10
10
|
// - key: string - assetKey, the filename relative to root dir (e.g., /public/foo/index.html)
|
|
11
11
|
// - value: ContentAssetMetadataMapEntry - metadata for asset
|
|
@@ -19,12 +19,12 @@
|
|
|
19
19
|
// - compressedFileInfos: Map<string, FileInfo> - information about any compressed versions
|
|
20
20
|
// - key: string - compression algorithm name (e.g., "gzip", "br", etc.)
|
|
21
21
|
// - value: FileInfo - information about the compressed version of the file
|
|
22
|
-
// - type: string - where the data is available. Usually 'wasm-inline' or '
|
|
22
|
+
// - type: string - where the data is available. Usually 'wasm-inline' or 'kv-store'.
|
|
23
23
|
// FileInfo structure
|
|
24
24
|
// - hash: string - SHA-256 hash of file
|
|
25
25
|
// - size: number - file size in bytes
|
|
26
26
|
// - staticFilePath: string - path to file in local filesystem, relative to root dir
|
|
27
|
-
// -
|
|
27
|
+
// - kvStoreKey: string - KV Store key, present only for items in KV Store
|
|
28
28
|
//
|
|
29
29
|
// statics.js
|
|
30
30
|
// imports statics-metadata.js and adds utilities for working with the content assets, as well as
|
|
@@ -65,32 +65,32 @@ import { calculateFileSizeAndHash } from "../util/hash.js";
|
|
|
65
65
|
import { getFiles } from "../util/files.js";
|
|
66
66
|
import { generateOrLoadPublishId } from "../util/publish-id.js";
|
|
67
67
|
import { loadApiKey } from "../util/fastly-api.js";
|
|
68
|
-
import {
|
|
68
|
+
import { kvStoreEntryExists, kvStoreSubmitFile } from "../util/kv-store.js";
|
|
69
69
|
import { mergeContentTypes, testFileContentType } from "../../util/content-types.js";
|
|
70
70
|
import { algs } from "../compression/index.js";
|
|
71
|
-
async function
|
|
72
|
-
for (const {
|
|
73
|
-
if (await
|
|
74
|
-
// Already exists in
|
|
75
|
-
console.log(`✔️ Asset already exists in
|
|
71
|
+
async function uploadFilesToKVStore(fastlyApiContext, kvStoreName, kvStoreItems) {
|
|
72
|
+
for (const { kvStoreKey, staticFilePath, text } of kvStoreItems) {
|
|
73
|
+
if (await kvStoreEntryExists(fastlyApiContext, kvStoreName, kvStoreKey)) {
|
|
74
|
+
// Already exists in KV Store
|
|
75
|
+
console.log(`✔️ Asset already exists in KV Store with key "${kvStoreKey}".`);
|
|
76
76
|
}
|
|
77
77
|
else {
|
|
78
|
-
// Upload to
|
|
78
|
+
// Upload to KV Store
|
|
79
79
|
const fileData = fs.readFileSync(staticFilePath);
|
|
80
|
-
await
|
|
81
|
-
console.log(`✔️ Submitted ${text ? 'text' : 'binary'} asset "${staticFilePath}" to
|
|
80
|
+
await kvStoreSubmitFile(fastlyApiContext, kvStoreName, kvStoreKey, fileData);
|
|
81
|
+
console.log(`✔️ Submitted ${text ? 'text' : 'binary'} asset "${staticFilePath}" to KV Store with key "${kvStoreKey}".`);
|
|
82
82
|
}
|
|
83
83
|
}
|
|
84
84
|
}
|
|
85
|
-
function
|
|
85
|
+
function writeKVStoreEntriesToFastlyToml(kvStoreName, kvStoreItems) {
|
|
86
86
|
let fastlyToml = fs.readFileSync('./fastly.toml', 'utf-8');
|
|
87
87
|
let before = '';
|
|
88
88
|
let after = '';
|
|
89
|
-
const tableMarker = `[[local_server.
|
|
89
|
+
const tableMarker = `[[local_server.kv_stores.${kvStoreName}]]`;
|
|
90
90
|
const startPos = fastlyToml.indexOf(tableMarker);
|
|
91
91
|
if (startPos === -1) {
|
|
92
|
-
//
|
|
93
|
-
if (fastlyToml.indexOf(
|
|
92
|
+
// KV Store decl not in fastly.toml yet
|
|
93
|
+
if (fastlyToml.indexOf(kvStoreName) !== -1) {
|
|
94
94
|
// don't do this!
|
|
95
95
|
console.error("Don't do this!");
|
|
96
96
|
throw "No";
|
|
@@ -120,10 +120,10 @@ function writeObjectStoreEntriesToFastlyToml(objectStoreName, objectStoreItems)
|
|
|
120
120
|
}
|
|
121
121
|
}
|
|
122
122
|
let tablesToml = '';
|
|
123
|
-
for (const {
|
|
123
|
+
for (const { kvStoreKey, staticFilePath } of kvStoreItems) {
|
|
124
124
|
// Probably, JSON.stringify is wrong, but it should do its job
|
|
125
125
|
tablesToml += tableMarker + '\n';
|
|
126
|
-
tablesToml += 'key = ' + JSON.stringify(
|
|
126
|
+
tablesToml += 'key = ' + JSON.stringify(kvStoreKey) + '\n';
|
|
127
127
|
tablesToml += 'path = ' + JSON.stringify(path.relative('./', staticFilePath)) + '\n';
|
|
128
128
|
tablesToml += '\n';
|
|
129
129
|
}
|
|
@@ -153,9 +153,9 @@ export async function buildStaticLoader(commandLineValues) {
|
|
|
153
153
|
const outputDir = path.resolve();
|
|
154
154
|
const publicDirRoot = path.resolve(config.rootDir);
|
|
155
155
|
console.log(`✔️ Public directory '${publicDirRoot}'.`);
|
|
156
|
-
const
|
|
156
|
+
const kvStoreName = config.kvStoreName;
|
|
157
157
|
let fastlyApiContext = null;
|
|
158
|
-
if (
|
|
158
|
+
if (kvStoreName != null) {
|
|
159
159
|
// TODO: load api key from command line
|
|
160
160
|
const apiKeyResult = loadApiKey();
|
|
161
161
|
if (apiKeyResult == null) {
|
|
@@ -165,12 +165,12 @@ export async function buildStaticLoader(commandLineValues) {
|
|
|
165
165
|
return;
|
|
166
166
|
}
|
|
167
167
|
fastlyApiContext = { apiToken: apiKeyResult.apiToken };
|
|
168
|
-
console.log(`✔️ Using
|
|
168
|
+
console.log(`✔️ Using KV Store mode, with KV Store: ${kvStoreName}`);
|
|
169
169
|
console.log(`✔️ Fastly API Token: ${fastlyApiContext.apiToken.slice(0, 4)}${'*'.repeat(fastlyApiContext.apiToken.length - 4)} from '${apiKeyResult.source}'`);
|
|
170
170
|
}
|
|
171
171
|
else {
|
|
172
172
|
if (displayFrameworkWarnings) {
|
|
173
|
-
console.log(`✔️ Not using
|
|
173
|
+
console.log(`✔️ Not using KV Store mode.`);
|
|
174
174
|
}
|
|
175
175
|
}
|
|
176
176
|
const excludeDirs = config.excludeDirs;
|
|
@@ -260,8 +260,8 @@ export async function buildStaticLoader(commandLineValues) {
|
|
|
260
260
|
};
|
|
261
261
|
});
|
|
262
262
|
console.log("🚀 Preparing content assets ...");
|
|
263
|
-
if (
|
|
264
|
-
console.log(`⚠️ Notice: By default, pre-compressed content assets are not generated when
|
|
263
|
+
if (kvStoreName == null && configRaw != null && !("contentCompression" in configRaw)) {
|
|
264
|
+
console.log(`⚠️ Notice: By default, pre-compressed content assets are not generated when KV Store is not used.`);
|
|
265
265
|
console.log(" If you want to pre-compress assets, add a value for 'contentCompression' to your static-publish.rc.js.");
|
|
266
266
|
}
|
|
267
267
|
// Create "static content" dir that will be used to hold a copy of static files.
|
|
@@ -271,12 +271,12 @@ export async function buildStaticLoader(commandLineValues) {
|
|
|
271
271
|
fs.mkdirSync(staticContentDir, { recursive: true });
|
|
272
272
|
// Build content assets metadata
|
|
273
273
|
const contentAssetMetadataMap = {};
|
|
274
|
-
//
|
|
275
|
-
const
|
|
274
|
+
// KV Store items to upload
|
|
275
|
+
const kvStoreItems = [];
|
|
276
276
|
let contentItems = 0;
|
|
277
277
|
const counts = {
|
|
278
278
|
inline: 0,
|
|
279
|
-
|
|
279
|
+
kvStore: 0,
|
|
280
280
|
excluded: 0,
|
|
281
281
|
};
|
|
282
282
|
for (const assetInfo of assetInfos) {
|
|
@@ -299,7 +299,7 @@ export async function buildStaticLoader(commandLineValues) {
|
|
|
299
299
|
},
|
|
300
300
|
};
|
|
301
301
|
let metadata;
|
|
302
|
-
const isInline =
|
|
302
|
+
const isInline = kvStoreName == null || assetInfo.inline;
|
|
303
303
|
const staticContentFilePath = `${staticContentDir}/file${contentItems}.${assetInfo.text ? 'txt' : 'bin'}`;
|
|
304
304
|
async function prepareCompressedVersions(contentCompressions, func) {
|
|
305
305
|
for (const alg of contentCompression) {
|
|
@@ -339,50 +339,50 @@ export async function buildStaticLoader(commandLineValues) {
|
|
|
339
339
|
counts.inline++;
|
|
340
340
|
}
|
|
341
341
|
else {
|
|
342
|
-
// For
|
|
342
|
+
// For KV Store mode, we don't need to make a copy of the original file
|
|
343
343
|
const staticFilePath = file;
|
|
344
|
-
// Use the hash as part of the
|
|
344
|
+
// Use the hash as part of the key name. This avoids having to
|
|
345
345
|
// re-upload a file if it already exists.
|
|
346
|
-
const
|
|
347
|
-
|
|
348
|
-
|
|
346
|
+
const kvStoreKey = `${publishId}:${assetKey}_${hash}`;
|
|
347
|
+
kvStoreItems.push({
|
|
348
|
+
kvStoreKey,
|
|
349
349
|
staticFilePath,
|
|
350
350
|
text,
|
|
351
351
|
});
|
|
352
352
|
const compressedFileInfos = {};
|
|
353
353
|
await prepareCompressedVersions(contentCompression, (alg, staticFilePath, hash, size) => {
|
|
354
|
-
const
|
|
355
|
-
compressedFileInfos[alg] = { staticFilePath,
|
|
356
|
-
|
|
357
|
-
|
|
354
|
+
const kvStoreKey = `${publishId}:${assetKey}_${alg}_${hash}`;
|
|
355
|
+
compressedFileInfos[alg] = { staticFilePath, kvStoreKey, hash, size };
|
|
356
|
+
kvStoreItems.push({
|
|
357
|
+
kvStoreKey,
|
|
358
358
|
staticFilePath,
|
|
359
359
|
text,
|
|
360
360
|
});
|
|
361
361
|
});
|
|
362
362
|
metadata = {
|
|
363
363
|
...entryBase,
|
|
364
|
-
type: '
|
|
364
|
+
type: 'kv-store',
|
|
365
365
|
fileInfo: {
|
|
366
366
|
...entryBase.fileInfo,
|
|
367
367
|
staticFilePath,
|
|
368
|
-
|
|
368
|
+
kvStoreKey,
|
|
369
369
|
},
|
|
370
370
|
compressedFileInfos,
|
|
371
371
|
};
|
|
372
|
-
counts.
|
|
372
|
+
counts.kvStore++;
|
|
373
373
|
}
|
|
374
374
|
contentAssetMetadataMap[assetKey] = metadata;
|
|
375
375
|
}
|
|
376
|
-
if (
|
|
377
|
-
await
|
|
378
|
-
|
|
376
|
+
if (kvStoreName != null) {
|
|
377
|
+
await uploadFilesToKVStore(fastlyApiContext, kvStoreName, kvStoreItems);
|
|
378
|
+
writeKVStoreEntriesToFastlyToml(kvStoreName, kvStoreItems);
|
|
379
379
|
}
|
|
380
|
-
console.log("✅ Prepared " + (counts.inline + counts.
|
|
380
|
+
console.log("✅ Prepared " + (counts.inline + counts.kvStore) + " content asset(s):");
|
|
381
381
|
if (counts.inline > 0) {
|
|
382
382
|
console.log(" " + counts.inline + " inline");
|
|
383
383
|
}
|
|
384
|
-
if (counts.
|
|
385
|
-
console.log(" " + counts.
|
|
384
|
+
if (counts.kvStore > 0) {
|
|
385
|
+
console.log(" " + counts.kvStore + " KV Store");
|
|
386
386
|
}
|
|
387
387
|
// Build statics-metadata.js
|
|
388
388
|
let metadataFileContents = `/*
|
|
@@ -390,7 +390,7 @@ export async function buildStaticLoader(commandLineValues) {
|
|
|
390
390
|
*/
|
|
391
391
|
|
|
392
392
|
`;
|
|
393
|
-
metadataFileContents += `\nexport const
|
|
393
|
+
metadataFileContents += `\nexport const kvStoreName = ${JSON.stringify(kvStoreName)};\n`;
|
|
394
394
|
metadataFileContents += `\nexport const contentAssetMetadataMap = {\n`;
|
|
395
395
|
for (const [key, value] of Object.entries(contentAssetMetadataMap)) {
|
|
396
396
|
metadataFileContents += ` ${JSON.stringify(key)}: ${JSON.stringify(value)},\n`;
|
|
@@ -415,7 +415,7 @@ export async function buildStaticLoader(commandLineValues) {
|
|
|
415
415
|
`;
|
|
416
416
|
fileContents += 'import { ContentAssets, ModuleAssets, PublisherServer } from "@fastly/compute-js-static-publish";\n\n';
|
|
417
417
|
fileContents += 'import "@fastly/compute-js-static-publish/build/compute-js";\n\n';
|
|
418
|
-
fileContents += 'import {
|
|
418
|
+
fileContents += 'import { kvStoreName, contentAssetMetadataMap } from "./statics-metadata";\n';
|
|
419
419
|
// Add import statements for assets that are modules and that need to be statically imported.
|
|
420
420
|
const staticImportModuleNumbers = {};
|
|
421
421
|
let staticImportModuleNumber = 0;
|
|
@@ -511,7 +511,7 @@ export async function buildStaticLoader(commandLineValues) {
|
|
|
511
511
|
autoIndex,
|
|
512
512
|
};
|
|
513
513
|
fileContents += `\nexport const serverConfig = ${JSON.stringify(serverConfig, null, 2)};\n`;
|
|
514
|
-
fileContents += '\nexport const contentAssets = new ContentAssets(contentAssetMetadataMap, {
|
|
514
|
+
fileContents += '\nexport const contentAssets = new ContentAssets(contentAssetMetadataMap, {kvStoreName});';
|
|
515
515
|
fileContents += '\nexport const moduleAssets = new ModuleAssets(moduleAssetsMap);\n';
|
|
516
516
|
fileContents += '\nlet server = null;';
|
|
517
517
|
fileContents += '\nexport function getServer() {' +
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"clean-kv-store.d.ts","sourceRoot":"","sources":["../../../src/cli/commands/clean-kv-store.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,mBAAmB,CAAC;AAc5D,wBAAsB,YAAY,CAAC,iBAAiB,EAAE,kBAAkB,iBAgEvE"}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import path from 'path';
|
|
2
|
+
import { generateOrLoadPublishId } from "../util/publish-id.js";
|
|
3
|
+
import { loadConfigFile } from "../load-config.js";
|
|
4
|
+
import { getKVStoreKeys, kvStoreDeleteFile } from "../util/kv-store.js";
|
|
5
|
+
import { loadApiKey } from "../util/fastly-api.js";
|
|
6
|
+
import { getKVStoreKeysFromMetadata } from "../../util/metadata.js";
|
|
7
|
+
export async function cleanKVStore(commandLineValues) {
|
|
8
|
+
const { publishId } = generateOrLoadPublishId();
|
|
9
|
+
const errors = [];
|
|
10
|
+
const { normalized: config } = await loadConfigFile(errors);
|
|
11
|
+
if (config == null) {
|
|
12
|
+
console.error("❌ Can't load static-publish.rc.js");
|
|
13
|
+
console.error("Run this from a compute-js-static-publish compute-js directory.");
|
|
14
|
+
for (const error of errors) {
|
|
15
|
+
console.error(error);
|
|
16
|
+
}
|
|
17
|
+
process.exitCode = 1;
|
|
18
|
+
return;
|
|
19
|
+
}
|
|
20
|
+
let fastlyApiContext = null;
|
|
21
|
+
const apiKeyResult = loadApiKey();
|
|
22
|
+
if (apiKeyResult == null) {
|
|
23
|
+
console.error("❌ Fastly API Token not provided.");
|
|
24
|
+
console.error("Specify one on the command line, or use the FASTLY_API_TOKEN environment variable.");
|
|
25
|
+
process.exitCode = 1;
|
|
26
|
+
return;
|
|
27
|
+
}
|
|
28
|
+
fastlyApiContext = { apiToken: apiKeyResult.apiToken };
|
|
29
|
+
const staticsMetadata = await import(path.resolve('./src/statics-metadata.js'));
|
|
30
|
+
const { kvStoreName, contentAssetMetadataMap } = staticsMetadata;
|
|
31
|
+
if (kvStoreName == null) {
|
|
32
|
+
console.error("❌ KV Store not specified.");
|
|
33
|
+
console.error("This only has meaning in KV Store mode.");
|
|
34
|
+
process.exitCode = 1;
|
|
35
|
+
return;
|
|
36
|
+
}
|
|
37
|
+
// TODO: Enable getting kvStoreName and publishId from command line
|
|
38
|
+
// These are the items that are currently in the KV Store and that belong to this publish ID.
|
|
39
|
+
const items = ((await getKVStoreKeys(fastlyApiContext, kvStoreName)) ?? [])
|
|
40
|
+
.filter(x => x.startsWith(`${publishId}:`));
|
|
41
|
+
// These are the items that are currently are being used.
|
|
42
|
+
const keys = getKVStoreKeysFromMetadata(contentAssetMetadataMap);
|
|
43
|
+
// So these are the items that we should be deleting.
|
|
44
|
+
const itemsToDelete = items.filter(x => !keys.has(x));
|
|
45
|
+
console.log("Publish ID: " + publishId);
|
|
46
|
+
console.log("KV Store contains " + items.length + " item(s) for this publish ID.");
|
|
47
|
+
console.log("Current site metadata contains " + keys.size + " item(s) (including compressed alternates).");
|
|
48
|
+
console.log("Number of items to delete: " + itemsToDelete.length);
|
|
49
|
+
for (const [index, item] of itemsToDelete.entries()) {
|
|
50
|
+
console.log("Deleting item [" + (index + 1) + "]: " + item);
|
|
51
|
+
await kvStoreDeleteFile(fastlyApiContext, kvStoreName, item);
|
|
52
|
+
}
|
|
53
|
+
console.log("✅ Completed.");
|
|
54
|
+
}
|
|
@@ -19,7 +19,7 @@ const defaultOptions = {
|
|
|
19
19
|
name: 'compute-js-static-site',
|
|
20
20
|
description: 'Compute@Edge static site',
|
|
21
21
|
serviceId: undefined,
|
|
22
|
-
|
|
22
|
+
kvStoreName: undefined,
|
|
23
23
|
};
|
|
24
24
|
// Current directory of this program that's running.
|
|
25
25
|
const __dirname = url.fileURLToPath(new URL('.', import.meta.url));
|
|
@@ -156,11 +156,11 @@ function processCommandLineArgs(commandLineValues) {
|
|
|
156
156
|
serviceId = serviceIdValue;
|
|
157
157
|
}
|
|
158
158
|
}
|
|
159
|
-
let
|
|
159
|
+
let kvStoreName;
|
|
160
160
|
{
|
|
161
|
-
const
|
|
162
|
-
if (
|
|
163
|
-
|
|
161
|
+
const kvStoreNameValue = commandLineValues['kv-store-name'];
|
|
162
|
+
if (kvStoreNameValue == null || typeof kvStoreNameValue === 'string') {
|
|
163
|
+
kvStoreName = kvStoreNameValue;
|
|
164
164
|
}
|
|
165
165
|
}
|
|
166
166
|
return {
|
|
@@ -175,7 +175,7 @@ function processCommandLineArgs(commandLineValues) {
|
|
|
175
175
|
author,
|
|
176
176
|
description,
|
|
177
177
|
serviceId,
|
|
178
|
-
|
|
178
|
+
kvStoreName,
|
|
179
179
|
};
|
|
180
180
|
}
|
|
181
181
|
function pickKeys(keys, object) {
|
|
@@ -254,7 +254,7 @@ export function initApp(commandLineValues) {
|
|
|
254
254
|
...options,
|
|
255
255
|
...(preset != null ? preset.defaultOptions : {}),
|
|
256
256
|
...pickKeys(['author', 'name', 'description'], (packageJson ?? {})),
|
|
257
|
-
...pickKeys(['rootDir', 'publicDir', 'staticDirs', 'spa', 'notFoundPage', 'autoIndex', 'autoExt', 'author', 'name', 'description', 'serviceId', '
|
|
257
|
+
...pickKeys(['rootDir', 'publicDir', 'staticDirs', 'spa', 'notFoundPage', 'autoIndex', 'autoExt', 'author', 'name', 'description', 'serviceId', 'kvStoreName'], commandLineAppOptions),
|
|
258
258
|
};
|
|
259
259
|
if (preset != null) {
|
|
260
260
|
if (!preset.check(packageJson, options)) {
|
|
@@ -365,7 +365,7 @@ export function initApp(commandLineValues) {
|
|
|
365
365
|
const name = options.name;
|
|
366
366
|
const description = options.description;
|
|
367
367
|
const fastlyServiceId = options.serviceId;
|
|
368
|
-
const
|
|
368
|
+
const kvStoreName = options.kvStoreName;
|
|
369
369
|
function rootRelative(itemPath) {
|
|
370
370
|
if (itemPath == null) {
|
|
371
371
|
return null;
|
|
@@ -385,7 +385,7 @@ export function initApp(commandLineValues) {
|
|
|
385
385
|
console.log('author :', author);
|
|
386
386
|
console.log('description :', description);
|
|
387
387
|
console.log('Service ID :', fastlyServiceId ?? '(None)');
|
|
388
|
-
console.log('
|
|
388
|
+
console.log('KV Store Name :', kvStoreName ?? '(None)');
|
|
389
389
|
console.log('');
|
|
390
390
|
if (useWebpack) {
|
|
391
391
|
console.log('Creating project with Webpack.');
|
|
@@ -514,12 +514,12 @@ ${fastlyServiceId != null ? `service_id = "${fastlyServiceId}"
|
|
|
514
514
|
/** @type {import('@fastly/compute-js-static-publish').StaticPublisherConfig} */
|
|
515
515
|
const config = {
|
|
516
516
|
rootDir: ${JSON.stringify(rootDirRel)},
|
|
517
|
-
${(
|
|
517
|
+
${(kvStoreName != null ? 'kvStoreName: ' + JSON.stringify(kvStoreName) : '// kvStoreName: false')},
|
|
518
518
|
// excludeDirs: [ './node_modules' ],
|
|
519
519
|
// excludeDotFiles: true,
|
|
520
520
|
// includeWellKnown: true,
|
|
521
521
|
// contentAssetInclusionTest: (filename) => true,
|
|
522
|
-
// contentCompression: [ 'br', 'gzip' ], // For this config value, default is [] if
|
|
522
|
+
// contentCompression: [ 'br', 'gzip' ], // For this config value, default is [] if kvStoreName is null.
|
|
523
523
|
// moduleAssetInclusionTest: (filename) => false,
|
|
524
524
|
// contentTypes: [
|
|
525
525
|
// { test: /.custom$/, contentType: 'application/x-custom', text: false },
|