@fastly/compute-js-static-publish 7.0.0-beta.1 → 7.0.0-beta.3

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 (84) hide show
  1. package/README.md +11 -3
  2. package/README.short.md +11 -3
  3. package/build/cli/commands/manage/clean.d.ts +2 -0
  4. package/build/cli/commands/manage/clean.d.ts.map +1 -0
  5. package/build/cli/commands/manage/clean.js +277 -0
  6. package/build/cli/commands/manage/collections/delete.d.ts +2 -0
  7. package/build/cli/commands/manage/collections/delete.d.ts.map +1 -0
  8. package/build/cli/commands/manage/collections/delete.js +180 -0
  9. package/build/cli/commands/manage/collections/index.d.ts.map +1 -0
  10. package/build/cli/commands/manage/collections/index.js +63 -0
  11. package/build/cli/commands/manage/collections/list.d.ts +2 -0
  12. package/build/cli/commands/manage/collections/list.d.ts.map +1 -0
  13. package/build/cli/commands/manage/collections/list.js +191 -0
  14. package/build/cli/commands/manage/collections/promote.d.ts +2 -0
  15. package/build/cli/commands/manage/collections/promote.d.ts.map +1 -0
  16. package/build/cli/commands/manage/collections/promote.js +247 -0
  17. package/build/cli/commands/manage/collections/update-expiration.d.ts +2 -0
  18. package/build/cli/commands/manage/collections/update-expiration.d.ts.map +1 -0
  19. package/build/cli/commands/manage/collections/update-expiration.js +215 -0
  20. package/build/cli/commands/manage/index.d.ts.map +1 -0
  21. package/build/cli/commands/{index.js → manage/index.js} +36 -34
  22. package/build/cli/commands/manage/publish-content.d.ts +2 -0
  23. package/build/cli/commands/manage/publish-content.d.ts.map +1 -0
  24. package/build/cli/commands/{publish-content.js → manage/publish-content.js} +186 -85
  25. package/build/cli/commands/{init-app.d.ts → scaffold/index.d.ts} +2 -2
  26. package/build/cli/commands/scaffold/index.d.ts.map +1 -0
  27. package/build/cli/commands/{init-app.js → scaffold/index.js} +80 -31
  28. package/build/cli/index.js +11 -3
  29. package/build/cli/util/api-token.d.ts.map +1 -0
  30. package/build/cli/{fastly-api → util}/api-token.js +8 -2
  31. package/build/cli/util/args.d.ts +16 -2
  32. package/build/cli/util/args.d.ts.map +1 -1
  33. package/build/cli/util/args.js +32 -6
  34. package/build/cli/util/config.d.ts.map +1 -1
  35. package/build/cli/util/config.js +19 -19
  36. package/build/cli/util/fastly-toml.d.ts +2 -0
  37. package/build/cli/util/fastly-toml.d.ts.map +1 -0
  38. package/build/cli/util/fastly-toml.js +15 -0
  39. package/build/cli/util/kv-store-items.d.ts +3 -2
  40. package/build/cli/util/kv-store-items.d.ts.map +1 -1
  41. package/build/cli/util/kv-store-items.js +7 -13
  42. package/build/cli/util/kv-store-local-server.d.ts +8 -0
  43. package/build/cli/util/kv-store-local-server.d.ts.map +1 -1
  44. package/build/cli/util/kv-store-local-server.js +76 -0
  45. package/build/cli/{fastly-api → util}/kv-store.d.ts +6 -6
  46. package/build/cli/util/kv-store.d.ts.map +1 -0
  47. package/build/cli/{fastly-api → util}/kv-store.js +4 -4
  48. package/build/cli/util/node.d.ts +2 -0
  49. package/build/cli/util/node.d.ts.map +1 -0
  50. package/build/cli/util/node.js +10 -0
  51. package/build/models/config/publish-content-config.d.ts +0 -2
  52. package/build/models/config/publish-content-config.d.ts.map +1 -1
  53. package/build/models/config/static-publish-rc.d.ts +1 -0
  54. package/build/models/config/static-publish-rc.d.ts.map +1 -1
  55. package/build/models/server/index.d.ts +5 -0
  56. package/build/models/server/index.d.ts.map +1 -0
  57. package/build/models/server/index.js +1 -0
  58. package/build/models/time/index.d.ts +8 -0
  59. package/build/models/time/index.d.ts.map +1 -0
  60. package/build/models/time/index.js +54 -0
  61. package/build/server/publisher-server/index.d.ts +2 -0
  62. package/build/server/publisher-server/index.d.ts.map +1 -1
  63. package/build/server/publisher-server/index.js +34 -3
  64. package/package.json +3 -2
  65. package/build/cli/commands/clean.d.ts +0 -2
  66. package/build/cli/commands/clean.d.ts.map +0 -1
  67. package/build/cli/commands/clean.js +0 -121
  68. package/build/cli/commands/collections/delete.d.ts +0 -2
  69. package/build/cli/commands/collections/delete.d.ts.map +0 -1
  70. package/build/cli/commands/collections/delete.js +0 -88
  71. package/build/cli/commands/collections/index.d.ts.map +0 -1
  72. package/build/cli/commands/collections/index.js +0 -52
  73. package/build/cli/commands/collections/list.d.ts +0 -2
  74. package/build/cli/commands/collections/list.d.ts.map +0 -1
  75. package/build/cli/commands/collections/list.js +0 -62
  76. package/build/cli/commands/index.d.ts.map +0 -1
  77. package/build/cli/commands/init-app.d.ts.map +0 -1
  78. package/build/cli/commands/publish-content.d.ts +0 -2
  79. package/build/cli/commands/publish-content.d.ts.map +0 -1
  80. package/build/cli/fastly-api/api-token.d.ts.map +0 -1
  81. package/build/cli/fastly-api/kv-store.d.ts.map +0 -1
  82. /package/build/cli/commands/{collections → manage/collections}/index.d.ts +0 -0
  83. /package/build/cli/commands/{index.d.ts → manage/index.d.ts} +0 -0
  84. /package/build/cli/{fastly-api → util}/api-token.d.ts +0 -0
package/README.md CHANGED
@@ -25,7 +25,8 @@ npx @fastly/compute-js-static-publish --root-dir=./public --kv-store-name=site-c
25
25
  ```sh
26
26
  cd compute-js
27
27
  npm install
28
- npm run start # preview locally
28
+ npm run dev:publish # 'publish' your files to the simulated local KV Store
29
+ npm run dev:start # preview locally
29
30
  ```
30
31
 
31
32
  Serves your app at `http://127.0.0.1:7676`, powered by a simulated KV Store.
@@ -36,8 +37,15 @@ When you're ready to go live, [create a free Fastly account](https://www.fastly.
36
37
 
37
38
  ```sh
38
39
  cd compute-js
39
- npm run publish-service # deploy the app (publish the "service")
40
- npm run publish-content # upload your static files (publish the "content")
40
+ npm run fastly:deploy # deploy the app
41
+ npm run fastly:publish # upload your static files
42
+ ```
43
+
44
+ In the future, unless you have further changes to make to your app itself, you can
45
+ upload further updates to your static files:
46
+ ```sh
47
+ cd compute-js
48
+ npm run fastly:publish # upload your static files
41
49
  ```
42
50
 
43
51
  ## Features
package/README.short.md CHANGED
@@ -25,7 +25,8 @@ npx @fastly/compute-js-static-publish --root-dir=./public --kv-store-name=site-c
25
25
  ```sh
26
26
  cd compute-js
27
27
  npm install
28
- npm run start # preview locally
28
+ npm run dev:publish # 'publish' your files to the simulated local KV Store
29
+ npm run dev:start # preview locally
29
30
  ```
30
31
 
31
32
  Serves your app at `http://127.0.0.1:7676`, powered by a simulated KV Store.
@@ -36,8 +37,15 @@ When you're ready to go live, [create a free Fastly account](https://www.fastly.
36
37
 
37
38
  ```sh
38
39
  cd compute-js
39
- npm run publish-service # deploy the app (publish the "service")
40
- npm run publish-content # upload your static files (publish the "content")
40
+ npm run fastly:deploy # deploy the app
41
+ npm run fastly:publish # upload your static files
42
+ ```
43
+
44
+ In the future, unless you have further changes to make to your app itself, you can
45
+ upload further updates to your static files:
46
+ ```sh
47
+ cd compute-js
48
+ npm run fastly:publish # upload your static files
41
49
  ```
42
50
 
43
51
  ## Features
@@ -0,0 +1,2 @@
1
+ export declare function action(actionArgs: string[]): Promise<void>;
2
+ //# sourceMappingURL=clean.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"clean.d.ts","sourceRoot":"","sources":["../../../../src/cli/commands/manage/clean.ts"],"names":[],"mappings":"AAsDA,wBAAsB,MAAM,CAAC,UAAU,EAAE,MAAM,EAAE,iBA6ShD"}
@@ -0,0 +1,277 @@
1
+ /*
2
+ * Copyright Fastly, Inc.
3
+ * Licensed under the MIT license. See LICENSE file for details.
4
+ */
5
+ import path from 'node:path';
6
+ import { isExpired } from '../../../models/time/index.js';
7
+ import { LoadConfigError, loadStaticPublisherRcFile } from '../../util/config.js';
8
+ import { getKvStoreEntry, getKVStoreKeys, kvStoreDeleteEntry } from '../../util/kv-store.js';
9
+ import { loadApiToken } from '../../util/api-token.js';
10
+ import { parseCommandLine } from '../../util/args.js';
11
+ import { readServiceId } from '../../util/fastly-toml.js';
12
+ import { doKvStoreItemsOperation } from "../../util/kv-store-items.js";
13
+ import { isNodeError } from '../../util/node.js';
14
+ import { getLocalKvStoreEntry, getLocalKVStoreKeys, localKvStoreDeleteEntry } from "../../util/kv-store-local-server.js";
15
+ function help() {
16
+ console.log(`\
17
+
18
+ Usage:
19
+ npx @fastly/compute-js-static-publish clean [options]
20
+
21
+ Description:
22
+ Cleans up expired or unreferenced items in the Fastly KV Store.
23
+ This includes expired collection indexes and orphaned content assets.
24
+
25
+ Options:
26
+ --delete-expired-collections If set, expired collection index files will be deleted.
27
+
28
+ --dry-run Show what would be deleted without performing any deletions.
29
+
30
+ Global Options:
31
+ --local Instead of working with the Fastly KV Store, operate on
32
+ local files that will be used to simulate the KV Store
33
+ with the local development environment.
34
+
35
+ --fastly-api-token=<token> Fastly API token for KV Store access.
36
+ If not set, the tool will check:
37
+ 1. FASTLY_API_TOKEN environment variable
38
+ 2. Logged-in Fastly CLI profile
39
+
40
+ -h, --help Show this help message and exit.
41
+ `);
42
+ }
43
+ export async function action(actionArgs) {
44
+ const optionDefinitions = [
45
+ { name: 'verbose', type: Boolean },
46
+ { name: 'delete-expired-collections', type: Boolean },
47
+ { name: 'dry-run', type: Boolean },
48
+ { name: 'local', type: Boolean },
49
+ { name: 'fastly-api-token', type: String, },
50
+ ];
51
+ const parsed = parseCommandLine(actionArgs, optionDefinitions);
52
+ if (parsed.needHelp) {
53
+ if (parsed.error != null) {
54
+ console.error(String(parsed.error));
55
+ console.error();
56
+ process.exitCode = 1;
57
+ }
58
+ help();
59
+ return;
60
+ }
61
+ const { verbose, ['delete-expired-collections']: deleteExpiredCollections, ['dry-run']: dryRun, local: localMode, ['fastly-api-token']: fastlyApiToken, } = parsed.commandLineOptions;
62
+ // compute-js-static-publisher cli is always run from the Compute application directory
63
+ // in other words, the directory that contains `fastly.toml`.
64
+ const computeAppDir = path.resolve();
65
+ // Check to see if we have a service ID listed in `fastly.toml`.
66
+ // If we do NOT, then we do not use the KV Store.
67
+ let serviceId;
68
+ try {
69
+ serviceId = readServiceId(path.resolve(computeAppDir, './fastly.toml'));
70
+ }
71
+ catch (err) {
72
+ if (isNodeError(err) && err.code === 'ENOENT') {
73
+ console.warn(`❌ ERROR: can't find 'fastly.toml'.`);
74
+ process.exitCode = 1;
75
+ return;
76
+ }
77
+ console.warn(`❌ ERROR: can't read or parse 'fastly.toml'.`);
78
+ process.exitCode = 1;
79
+ return;
80
+ }
81
+ console.log(`🧹 Cleaning KV Store entries...`);
82
+ // Verify targets
83
+ let fastlyApiContext = undefined;
84
+ if (localMode) {
85
+ console.log(` Working on local simulated KV Store...`);
86
+ }
87
+ else {
88
+ if (serviceId === null) {
89
+ console.log(`❌️ 'service_id' not set in 'fastly.toml' - Deploy your Compute app to Fastly before publishing.`);
90
+ process.exitCode = 1;
91
+ return;
92
+ }
93
+ const apiTokenResult = loadApiToken({ commandLine: fastlyApiToken });
94
+ if (apiTokenResult == null) {
95
+ console.error("❌ Fastly API Token not provided.");
96
+ console.error("Set the FASTLY_API_TOKEN environment variable to an API token that has write access to the KV Store.");
97
+ process.exitCode = 1;
98
+ return;
99
+ }
100
+ fastlyApiContext = { apiToken: apiTokenResult.apiToken };
101
+ console.log(`✔️ Fastly API Token: ${fastlyApiContext.apiToken.slice(0, 4)}${'*'.repeat(fastlyApiContext.apiToken.length - 4)} from '${apiTokenResult.source}'`);
102
+ console.log(` Working on the Fastly KV Store...`);
103
+ }
104
+ // #### load config
105
+ let staticPublisherRc;
106
+ try {
107
+ staticPublisherRc = await loadStaticPublisherRcFile();
108
+ }
109
+ catch (err) {
110
+ console.error("❌ Can't load static-publish.rc.js");
111
+ console.error("Run this from a compute-js-static-publish compute-js directory.");
112
+ if (err instanceof LoadConfigError) {
113
+ for (const error of err.errors) {
114
+ console.error(error);
115
+ }
116
+ }
117
+ process.exitCode = 1;
118
+ return;
119
+ }
120
+ const publishId = staticPublisherRc.publishId;
121
+ console.log(` | Publish ID: ${publishId}`);
122
+ const kvStoreName = staticPublisherRc.kvStoreName;
123
+ console.log(` | Using KV Store: ${kvStoreName}`);
124
+ const defaultCollectionName = staticPublisherRc.defaultCollectionName;
125
+ console.log(` | Default Collection Name: ${defaultCollectionName}`);
126
+ const staticPublisherWorkingDir = staticPublisherRc.staticPublisherWorkingDir;
127
+ console.log(` | Static publisher working directory: ${staticPublisherWorkingDir}`);
128
+ const storeFile = path.resolve(staticPublisherWorkingDir, `./kvstore.json`);
129
+ // ### KVStore Keys to delete
130
+ const kvKeysToDelete = new Set();
131
+ // ### List all indexes ###
132
+ const indexesPrefix = publishId + '_index_';
133
+ let indexKeys;
134
+ if (localMode) {
135
+ indexKeys = await getLocalKVStoreKeys(storeFile, indexesPrefix);
136
+ }
137
+ else {
138
+ indexKeys = await getKVStoreKeys(fastlyApiContext, kvStoreName, indexesPrefix);
139
+ }
140
+ if (indexKeys == null) {
141
+ throw new Error(`Can't query indexes in KV Store`);
142
+ }
143
+ // ### Go through the index files, make lists
144
+ const foundCollections = indexKeys.map(x => x.slice(indexesPrefix.length));
145
+ // All collection names that we are keeping
146
+ const liveCollections = new Set();
147
+ // All asset keys (hashes) that we are keeping
148
+ const assetsIdsInUse = new Set();
149
+ console.log('Processing collections:');
150
+ await doKvStoreItemsOperation(foundCollections.map(collection => ({
151
+ key: indexesPrefix + collection,
152
+ collection,
153
+ })), async ({ collection }, indexKey) => {
154
+ console.log(`Collection: ${collection}`);
155
+ let kvAssetsIndexResponse;
156
+ if (localMode) {
157
+ kvAssetsIndexResponse = await getLocalKvStoreEntry(storeFile, indexKey);
158
+ }
159
+ else {
160
+ kvAssetsIndexResponse = await getKvStoreEntry(fastlyApiContext, kvStoreName, indexKey);
161
+ }
162
+ if (!kvAssetsIndexResponse) {
163
+ throw new Error(`Can't load KV Store entry ${indexesPrefix + collection}`);
164
+ }
165
+ let indexMetadata = {};
166
+ if (kvAssetsIndexResponse.metadata != null) {
167
+ try {
168
+ indexMetadata = JSON.parse(kvAssetsIndexResponse.metadata);
169
+ }
170
+ catch {
171
+ }
172
+ }
173
+ let isLive = true;
174
+ if (indexMetadata.expirationTime == null) {
175
+ console.log(' Collection has no expiration time set');
176
+ }
177
+ else {
178
+ console.log(' ⏰ Expiration: ' + new Date(indexMetadata.expirationTime * 1000));
179
+ if (collection === defaultCollectionName) {
180
+ console.log(` ✅ Expiration time not enforced for default collection.`);
181
+ }
182
+ else if (isExpired(indexMetadata.expirationTime)) {
183
+ if (!deleteExpiredCollections) {
184
+ console.log(` ⚠️ Use --delete-expired-collections to delete expired collections.`);
185
+ }
186
+ else {
187
+ console.log(` 🗑️ Marking expired collection for deletion.`);
188
+ kvKeysToDelete.add(indexKey);
189
+ isLive = false;
190
+ }
191
+ }
192
+ }
193
+ if (!isLive) {
194
+ return;
195
+ }
196
+ liveCollections.add(collection);
197
+ const kvAssetsIndex = (await kvAssetsIndexResponse.response.json());
198
+ for (const [_assetKey, assetEntry] of Object.entries(kvAssetsIndex)) {
199
+ if (assetEntry.key.startsWith('sha256:')) {
200
+ assetsIdsInUse.add(`sha256_${assetEntry.key.slice('sha256:'.length)}`);
201
+ }
202
+ }
203
+ });
204
+ console.log('');
205
+ // ### List all settings ###
206
+ console.log('Enumerating settings:');
207
+ const settingsPrefix = publishId + '_settings_';
208
+ let settingsKeys;
209
+ if (localMode) {
210
+ settingsKeys = await getLocalKVStoreKeys(storeFile, settingsPrefix);
211
+ }
212
+ else {
213
+ settingsKeys = await getKVStoreKeys(fastlyApiContext, kvStoreName, settingsPrefix);
214
+ }
215
+ if (settingsKeys == null) {
216
+ throw new Error(`Can't query settings in KV Store`);
217
+ }
218
+ // If a settings object is found that doesn't match a live collection name then
219
+ // mark it for deletion
220
+ const foundSettingsCollections = settingsKeys.map(key => ({ key, name: key.slice(settingsPrefix.length) }));
221
+ for (const foundSettings of foundSettingsCollections) {
222
+ console.log(`Settings: ${foundSettings.name}`);
223
+ if (!liveCollections.has(foundSettings.name)) {
224
+ console.log(` 🗑️ Does not match a live index, marking for deletion.`);
225
+ kvKeysToDelete.add(foundSettings.key);
226
+ }
227
+ }
228
+ console.log('');
229
+ // ### Obtain the assets in the KV Store and find the ones that are not in use
230
+ console.log('Enumerating assets:');
231
+ const assetPrefix = publishId + '_files_';
232
+ let assetKeys;
233
+ if (localMode) {
234
+ assetKeys = await getLocalKVStoreKeys(storeFile, assetPrefix);
235
+ }
236
+ else {
237
+ assetKeys = await getKVStoreKeys(fastlyApiContext, kvStoreName, assetPrefix);
238
+ }
239
+ if (assetKeys == null) {
240
+ throw new Error(`Can't query assets in KV Store`);
241
+ }
242
+ for (const assetKey of assetKeys) {
243
+ let assetId = assetKey.slice(assetPrefix.length);
244
+ if (assetId.startsWith('sha256_')) {
245
+ assetId = assetId.slice(0, 'sha256_'.length + 64);
246
+ }
247
+ else {
248
+ // If we don't know what the prefix is, we ignore it
249
+ continue;
250
+ }
251
+ if (assetsIdsInUse.has(assetId)) {
252
+ console.log(` ${assetId}: in use`);
253
+ }
254
+ else {
255
+ kvKeysToDelete.add(assetKey);
256
+ console.log(` ${assetId}: not in use - ✅ marking for deletion`);
257
+ }
258
+ }
259
+ console.log('');
260
+ // ### Delete items that have been flagged
261
+ const items = [...kvKeysToDelete].map(key => ({ key }));
262
+ await doKvStoreItemsOperation(items, async (_, key) => {
263
+ if (dryRun) {
264
+ console.log(`[DRY RUN] Deleting item: ${key}`);
265
+ }
266
+ else {
267
+ console.log(`Deleting item from KV Store: ${key}`);
268
+ if (localMode) {
269
+ await localKvStoreDeleteEntry(storeFile, key);
270
+ }
271
+ else {
272
+ await kvStoreDeleteEntry(fastlyApiContext, kvStoreName, key);
273
+ }
274
+ }
275
+ });
276
+ console.log('✅ Completed.');
277
+ }
@@ -0,0 +1,2 @@
1
+ export declare function action(actionArgs: string[]): Promise<void>;
2
+ //# sourceMappingURL=delete.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"delete.d.ts","sourceRoot":"","sources":["../../../../../src/cli/commands/manage/collections/delete.ts"],"names":[],"mappings":"AAgDA,wBAAsB,MAAM,CAAC,UAAU,EAAE,MAAM,EAAE,iBA2KhD"}
@@ -0,0 +1,180 @@
1
+ /*
2
+ * Copyright Fastly, Inc.
3
+ * Licensed under the MIT license. See LICENSE file for details.
4
+ */
5
+ import path from 'node:path';
6
+ import { loadApiToken } from '../../../util/api-token.js';
7
+ import { parseCommandLine } from "../../../util/args.js";
8
+ import { LoadConfigError, loadStaticPublisherRcFile } from '../../../util/config.js';
9
+ import { readServiceId } from '../../../util/fastly-toml.js';
10
+ import { getKVStoreKeys, kvStoreDeleteEntry } from '../../../util/kv-store.js';
11
+ import { doKvStoreItemsOperation } from '../../../util/kv-store-items.js';
12
+ import { getLocalKVStoreKeys, localKvStoreDeleteEntry } from '../../../util/kv-store-local-server.js';
13
+ import { isNodeError } from '../../../util/node.js';
14
+ function help() {
15
+ console.log(`\
16
+
17
+ Usage:
18
+ npx @fastly/compute-js-static-publish collections delete --collection-name=<name> [options]
19
+
20
+ Description:
21
+ Deletes a collection index from the KV Store. The content files will remain but will no
22
+ longer be referenced.
23
+
24
+ Use the 'npx @fastly/compute-js-static-publish clean' command afterward to remove content
25
+ files that are no longer referenced by any collection.
26
+
27
+ Required:
28
+ --collection-name=<name> The name of the collection to delete
29
+
30
+ Global Options:
31
+ --local Instead of working with the Fastly KV Store, operate on
32
+ local files that will be used to simulate the KV Store
33
+ with the local development environment.
34
+
35
+ --fastly-api-token=<token> Fastly API token for KV Store access.
36
+ If not set, the tool will check:
37
+ 1. FASTLY_API_TOKEN environment variable
38
+ 2. Logged-in Fastly CLI profile
39
+
40
+ -h, --help Show this help message and exit.
41
+ `);
42
+ }
43
+ export async function action(actionArgs) {
44
+ const optionDefinitions = [
45
+ { name: 'verbose', type: Boolean },
46
+ { name: 'collection-name', type: String },
47
+ { name: 'local', type: Boolean },
48
+ { name: 'fastly-api-token', type: String, },
49
+ ];
50
+ const parsed = parseCommandLine(actionArgs, optionDefinitions);
51
+ if (parsed.needHelp) {
52
+ if (parsed.error != null) {
53
+ console.error(String(parsed.error));
54
+ console.error();
55
+ process.exitCode = 1;
56
+ }
57
+ help();
58
+ return;
59
+ }
60
+ const { verbose, ['collection-name']: collectionNameValue, ['fastly-api-token']: fastlyApiToken, local: localMode, } = parsed.commandLineOptions;
61
+ // compute-js-static-publisher cli is always run from the Compute application directory
62
+ // in other words, the directory that contains `fastly.toml`.
63
+ const computeAppDir = path.resolve();
64
+ if (collectionNameValue == null) {
65
+ console.error("❌ Required argument '--collection-name' not specified.");
66
+ process.exitCode = 1;
67
+ return;
68
+ }
69
+ // Check to see if we have a service ID listed in `fastly.toml`.
70
+ // If we do NOT, then we do not use the KV Store.
71
+ let serviceId;
72
+ try {
73
+ serviceId = readServiceId(path.resolve(computeAppDir, './fastly.toml'));
74
+ }
75
+ catch (err) {
76
+ if (isNodeError(err) && err.code === 'ENOENT') {
77
+ console.warn(`❌ ERROR: can't find 'fastly.toml'.`);
78
+ process.exitCode = 1;
79
+ return;
80
+ }
81
+ console.warn(`❌ ERROR: can't read or parse 'fastly.toml'.`);
82
+ process.exitCode = 1;
83
+ return;
84
+ }
85
+ console.log(`🧹 Cleaning KV Store entries...`);
86
+ // Verify targets
87
+ let fastlyApiContext = undefined;
88
+ if (localMode) {
89
+ console.log(` Working on local simulated KV Store...`);
90
+ }
91
+ else {
92
+ if (serviceId === null) {
93
+ console.log(`❌️ 'service_id' not set in 'fastly.toml' - Deploy your Compute app to Fastly before publishing.`);
94
+ process.exitCode = 1;
95
+ return;
96
+ }
97
+ const apiTokenResult = loadApiToken({ commandLine: fastlyApiToken });
98
+ if (apiTokenResult == null) {
99
+ console.error("❌ Fastly API Token not provided.");
100
+ console.error("Set the FASTLY_API_TOKEN environment variable to an API token that has write access to the KV Store.");
101
+ process.exitCode = 1;
102
+ return;
103
+ }
104
+ fastlyApiContext = { apiToken: apiTokenResult.apiToken };
105
+ console.log(`✔️ Fastly API Token: ${fastlyApiContext.apiToken.slice(0, 4)}${'*'.repeat(fastlyApiContext.apiToken.length - 4)} from '${apiTokenResult.source}'`);
106
+ console.log(` Working on the Fastly KV Store...`);
107
+ }
108
+ // #### load config
109
+ let staticPublisherRc;
110
+ try {
111
+ staticPublisherRc = await loadStaticPublisherRcFile();
112
+ }
113
+ catch (err) {
114
+ console.error("❌ Can't load static-publish.rc.js");
115
+ console.error("Run this from a compute-js-static-publish compute-js directory.");
116
+ if (err instanceof LoadConfigError) {
117
+ for (const error of err.errors) {
118
+ console.error(error);
119
+ }
120
+ }
121
+ process.exitCode = 1;
122
+ return;
123
+ }
124
+ const publishId = staticPublisherRc.publishId;
125
+ console.log(` | Publish ID: ${publishId}`);
126
+ const kvStoreName = staticPublisherRc.kvStoreName;
127
+ console.log(` | Using KV Store: ${kvStoreName}`);
128
+ const defaultCollectionName = staticPublisherRc.defaultCollectionName;
129
+ console.log(` | Default Collection Name: ${defaultCollectionName}`);
130
+ const staticPublisherWorkingDir = staticPublisherRc.staticPublisherWorkingDir;
131
+ console.log(` | Static publisher working directory: ${staticPublisherWorkingDir}`);
132
+ const storeFile = path.resolve(staticPublisherWorkingDir, `./kvstore.json`);
133
+ const collectionName = collectionNameValue;
134
+ if (collectionName === defaultCollectionName) {
135
+ console.error(`❌ Cannot delete default collection: ${collectionName}`);
136
+ process.exitCode = 1;
137
+ return;
138
+ }
139
+ console.log(`✔️ Collection to delete: ${collectionName}`);
140
+ // ### KVStore Keys to delete
141
+ const kvKeysToDelete = new Set();
142
+ // ### List all indexes ###
143
+ const indexesPrefix = publishId + '_index_';
144
+ let indexKeys;
145
+ if (localMode) {
146
+ indexKeys = await getLocalKVStoreKeys(storeFile, indexesPrefix);
147
+ }
148
+ else {
149
+ indexKeys = await getKVStoreKeys(fastlyApiContext, kvStoreName, indexesPrefix);
150
+ }
151
+ if (indexKeys == null) {
152
+ throw new Error(`Can't query indexes in KV Store`);
153
+ }
154
+ // ### Found collections ###
155
+ const foundCollections = indexKeys.map(key => ({ key, name: key.slice(indexesPrefix.length), }));
156
+ if (foundCollections.length === 0) {
157
+ console.log('No collections found.');
158
+ }
159
+ else {
160
+ console.log(`Found collections: ${foundCollections.map(x => `'${x.name}'`).join(', ')}`);
161
+ for (const collection of foundCollections) {
162
+ if (collection.name === collectionName) {
163
+ console.log(`Flagging collection '${collection.name}' for deletion: ${collection.key}`);
164
+ kvKeysToDelete.add(collection.key);
165
+ }
166
+ }
167
+ }
168
+ // ### Delete items that have been flagged
169
+ const items = [...kvKeysToDelete].map(key => ({ key }));
170
+ await doKvStoreItemsOperation(items, async (_, key) => {
171
+ console.log(`Deleting key from KV Store: ${key}`);
172
+ if (localMode) {
173
+ await localKvStoreDeleteEntry(storeFile, key);
174
+ }
175
+ else {
176
+ await kvStoreDeleteEntry(fastlyApiContext, kvStoreName, key);
177
+ }
178
+ });
179
+ console.log("✅ Completed.");
180
+ }
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../../src/cli/commands/manage/collections/index.ts"],"names":[],"mappings":"AA6CA,wBAAsB,MAAM,CAAC,UAAU,EAAE,MAAM,EAAE,iBA0BhD"}
@@ -0,0 +1,63 @@
1
+ /*
2
+ * Copyright Fastly, Inc.
3
+ * Licensed under the MIT license. See LICENSE file for details.
4
+ */
5
+ import { getCommandAndArgs } from '../../../util/args.js';
6
+ import * as deleteCommand from './delete.js';
7
+ import * as listCommand from './list.js';
8
+ import * as promoteCommand from './promote.js';
9
+ import * as updateExpirationCommand from './update-expiration.js';
10
+ function help() {
11
+ console.log(`\
12
+
13
+ Usage:
14
+ npx @fastly/compute-js-static-publish collections <sub-command> [options]
15
+
16
+ Description:
17
+ Manage named collections within a Compute application built with @fastly/compute-js-static-publish.
18
+
19
+ Available Subcommands:
20
+ list List all published collections
21
+ delete Delete a specific collection index
22
+ promote Copies an existing collection (content + config)
23
+ to a new collection name
24
+ update-expiration Modify expiration time for an existing collection
25
+
26
+ Global Options:
27
+ --local Instead of working with the Fastly KV Store, operate on
28
+ local files that will be used to simulate the KV Store
29
+ with the local development environment.
30
+
31
+ --fastly-api-token=<token> Fastly API token for KV Store access.
32
+ If not set, the tool will check:
33
+ 1. FASTLY_API_TOKEN environment variable
34
+ 2. Logged-in Fastly CLI profile
35
+
36
+ -h, --help Show this help message and exit.
37
+
38
+ Examples:
39
+ npx @fastly/compute-js-static-publish collections list
40
+ npx @fastly/compute-js-static-publish collections delete --collection-name=preview-42
41
+ `);
42
+ }
43
+ export async function action(actionArgs) {
44
+ const modes = {
45
+ 'delete': deleteCommand,
46
+ 'list': listCommand,
47
+ 'promote': promoteCommand,
48
+ 'update-expiration': updateExpirationCommand,
49
+ };
50
+ const commandAndArgs = getCommandAndArgs(actionArgs, modes);
51
+ if (commandAndArgs.needHelp) {
52
+ if (commandAndArgs.command != null) {
53
+ console.error(`Unknown subcommand: ${commandAndArgs.command}`);
54
+ console.error(`Specify one of: ${Object.keys(modes).join(', ')}`);
55
+ console.error();
56
+ process.exitCode = 1;
57
+ }
58
+ help();
59
+ return;
60
+ }
61
+ const { command, argv, } = commandAndArgs;
62
+ await modes[command].action(argv);
63
+ }
@@ -0,0 +1,2 @@
1
+ export declare function action(actionArgs: string[]): Promise<void>;
2
+ //# sourceMappingURL=list.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"list.d.ts","sourceRoot":"","sources":["../../../../../src/cli/commands/manage/collections/list.ts"],"names":[],"mappings":"AA0CA,wBAAsB,MAAM,CAAC,UAAU,EAAE,MAAM,EAAE,iBAsLhD"}