@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
@@ -0,0 +1,191 @@
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 { loadApiToken } from '../../../util/api-token.js';
8
+ import { parseCommandLine } from '../../../util/args.js';
9
+ import { LoadConfigError, loadStaticPublisherRcFile } from '../../../util/config.js';
10
+ import { readServiceId } from '../../../util/fastly-toml.js';
11
+ import { getKvStoreEntry, getKVStoreKeys } from '../../../util/kv-store.js';
12
+ import { isNodeError } from '../../../util/node.js';
13
+ import { getLocalKvStoreEntry, getLocalKVStoreKeys } from "../../../util/kv-store-local-server.js";
14
+ function help() {
15
+ console.log(`\
16
+
17
+ Usage:
18
+ npx @fastly/compute-js-static-publish collections list [options]
19
+
20
+ Description:
21
+ Lists all collections currently published in the KV Store.
22
+
23
+ Global Options:
24
+ --local Instead of working with the Fastly KV Store, operate on
25
+ local files that will be used to simulate the KV Store
26
+ with the local development environment.
27
+
28
+ --fastly-api-token=<token> Fastly API token for KV Store access.
29
+ If not set, the tool will check:
30
+ 1. FASTLY_API_TOKEN environment variable
31
+ 2. Logged-in Fastly CLI profile
32
+
33
+ -h, --help Show this help message and exit.
34
+ `);
35
+ }
36
+ export async function action(actionArgs) {
37
+ const optionDefinitions = [
38
+ { name: 'verbose', type: Boolean },
39
+ { name: 'local', type: Boolean },
40
+ { name: 'fastly-api-token', type: String, },
41
+ ];
42
+ const parsed = parseCommandLine(actionArgs, optionDefinitions);
43
+ if (parsed.needHelp) {
44
+ if (parsed.error != null) {
45
+ console.error(String(parsed.error));
46
+ console.error();
47
+ process.exitCode = 1;
48
+ }
49
+ help();
50
+ return;
51
+ }
52
+ const { verbose, local: localMode, ['fastly-api-token']: fastlyApiToken, } = parsed.commandLineOptions;
53
+ // compute-js-static-publisher cli is always run from the Compute application directory
54
+ // in other words, the directory that contains `fastly.toml`.
55
+ const computeAppDir = path.resolve();
56
+ // Check to see if we have a service ID listed in `fastly.toml`.
57
+ // If we do NOT, then we do not use the KV Store.
58
+ let serviceId;
59
+ try {
60
+ serviceId = readServiceId(path.resolve(computeAppDir, './fastly.toml'));
61
+ }
62
+ catch (err) {
63
+ if (isNodeError(err) && err.code === 'ENOENT') {
64
+ console.warn(`❌ ERROR: can't find 'fastly.toml'.`);
65
+ process.exitCode = 1;
66
+ return;
67
+ }
68
+ console.warn(`❌ ERROR: can't read or parse 'fastly.toml'.`);
69
+ process.exitCode = 1;
70
+ return;
71
+ }
72
+ console.log(`📃 Listing collections...`);
73
+ // Verify targets
74
+ let fastlyApiContext = undefined;
75
+ if (localMode) {
76
+ console.log(` Working on local simulated KV Store...`);
77
+ }
78
+ else {
79
+ if (serviceId === null) {
80
+ console.log(`❌️ 'service_id' not set in 'fastly.toml' - Deploy your Compute app to Fastly before publishing.`);
81
+ process.exitCode = 1;
82
+ return;
83
+ }
84
+ const apiTokenResult = loadApiToken({ commandLine: fastlyApiToken });
85
+ if (apiTokenResult == null) {
86
+ console.error("❌ Fastly API Token not provided.");
87
+ console.error("Set the FASTLY_API_TOKEN environment variable to an API token that has write access to the KV Store.");
88
+ process.exitCode = 1;
89
+ return;
90
+ }
91
+ fastlyApiContext = { apiToken: apiTokenResult.apiToken };
92
+ console.log(`✔️ Fastly API Token: ${fastlyApiContext.apiToken.slice(0, 4)}${'*'.repeat(fastlyApiContext.apiToken.length - 4)} from '${apiTokenResult.source}'`);
93
+ console.log(` Working on the Fastly KV Store...`);
94
+ }
95
+ // #### load config
96
+ let staticPublisherRc;
97
+ try {
98
+ staticPublisherRc = await loadStaticPublisherRcFile();
99
+ }
100
+ catch (err) {
101
+ console.error("❌ Can't load static-publish.rc.js");
102
+ console.error("Run this from a compute-js-static-publish compute-js directory.");
103
+ if (err instanceof LoadConfigError) {
104
+ for (const error of err.errors) {
105
+ console.error(error);
106
+ }
107
+ }
108
+ process.exitCode = 1;
109
+ return;
110
+ }
111
+ const publishId = staticPublisherRc.publishId;
112
+ console.log(` | Publish ID: ${publishId}`);
113
+ const kvStoreName = staticPublisherRc.kvStoreName;
114
+ console.log(` | Using KV Store: ${kvStoreName}`);
115
+ const defaultCollectionName = staticPublisherRc.defaultCollectionName;
116
+ console.log(` | Default Collection Name: ${defaultCollectionName}`);
117
+ const staticPublisherWorkingDir = staticPublisherRc.staticPublisherWorkingDir;
118
+ console.log(` | Static publisher working directory: ${staticPublisherWorkingDir}`);
119
+ const storeFile = path.resolve(staticPublisherWorkingDir, `./kvstore.json`);
120
+ // ### List all indexes ###
121
+ const indexesPrefix = publishId + '_index_';
122
+ let indexKeys;
123
+ if (localMode) {
124
+ indexKeys = await getLocalKVStoreKeys(storeFile, indexesPrefix);
125
+ }
126
+ else {
127
+ indexKeys = await getKVStoreKeys(fastlyApiContext, kvStoreName, indexesPrefix);
128
+ }
129
+ if (indexKeys == null) {
130
+ throw new Error(`❌ Can't query indexes in KV Store`);
131
+ }
132
+ // ### Found collections ###
133
+ const foundCollections = indexKeys.map(x => x.slice(indexesPrefix.length));
134
+ if (foundCollections.length === 0) {
135
+ console.log('No collections found.');
136
+ }
137
+ else {
138
+ console.log(`Found collections:`);
139
+ for (const collection of foundCollections) {
140
+ if (collection === defaultCollectionName) {
141
+ console.log(` ${collection} *DEFAULT*`);
142
+ }
143
+ else {
144
+ console.log(` ${collection}`);
145
+ }
146
+ const indexKey = indexesPrefix + collection;
147
+ let kvAssetsIndexResponse;
148
+ if (localMode) {
149
+ kvAssetsIndexResponse = await getLocalKvStoreEntry(storeFile, indexKey);
150
+ }
151
+ else {
152
+ kvAssetsIndexResponse = await getKvStoreEntry(fastlyApiContext, kvStoreName, indexKey);
153
+ }
154
+ if (kvAssetsIndexResponse == null) {
155
+ throw new Error(`❌ Can't load KV Store entry ${indexesPrefix + collection}`);
156
+ }
157
+ let indexMetadata;
158
+ if (kvAssetsIndexResponse.metadata != null) {
159
+ try {
160
+ indexMetadata = JSON.parse(kvAssetsIndexResponse.metadata);
161
+ }
162
+ catch {
163
+ }
164
+ }
165
+ if (indexMetadata == null) {
166
+ console.log(` No metadata found.`);
167
+ continue;
168
+ }
169
+ if (indexMetadata.publishedTime == null) {
170
+ console.log(' Published : unknown');
171
+ }
172
+ else {
173
+ console.log(` Published : ${new Date(indexMetadata.publishedTime * 1000)}`);
174
+ }
175
+ if (indexMetadata.expirationTime == null) {
176
+ console.log(' Expiration : not set');
177
+ }
178
+ else {
179
+ console.log(` Expiration : ${new Date(indexMetadata.expirationTime * 1000)}`);
180
+ if (collection === defaultCollectionName) {
181
+ console.log(` ✅ Expiration time not enforced for default collection.`);
182
+ }
183
+ else if (isExpired(indexMetadata.expirationTime)) {
184
+ console.log(` ⚠️ EXPIRED - Use 'clean --delete-expired-collections' to`);
185
+ console.log(` remove expired collections.`);
186
+ }
187
+ }
188
+ }
189
+ }
190
+ console.log("✅ Completed.");
191
+ }
@@ -0,0 +1,2 @@
1
+ export declare function action(actionArgs: string[]): Promise<void>;
2
+ //# sourceMappingURL=promote.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"promote.d.ts","sourceRoot":"","sources":["../../../../../src/cli/commands/manage/collections/promote.ts"],"names":[],"mappings":"AAkEA,wBAAsB,MAAM,CAAC,UAAU,EAAE,MAAM,EAAE,iBAyOhD"}
@@ -0,0 +1,247 @@
1
+ /*
2
+ * Copyright Fastly, Inc.
3
+ * Licensed under the MIT license. See LICENSE file for details.
4
+ */
5
+ import { calcExpirationTime } from '../../../../models/time/index.js';
6
+ import { LoadConfigError, loadStaticPublisherRcFile } from '../../../util/config.js';
7
+ import { getKvStoreEntry, kvStoreSubmitEntry, } from '../../../util/kv-store.js';
8
+ import { loadApiToken } from '../../../util/api-token.js';
9
+ import { parseCommandLine } from '../../../util/args.js';
10
+ import path from "node:path";
11
+ import { readServiceId } from "../../../util/fastly-toml.js";
12
+ import { isNodeError } from "../../../util/node.js";
13
+ import { getLocalKvStoreEntry, localKvStoreSubmitEntry } from "../../../util/kv-store-local-server.js";
14
+ import fs from "node:fs";
15
+ function help() {
16
+ console.log(`\
17
+
18
+ Usage:
19
+ npx @fastly/compute-js-static-publish collections promote
20
+ --collection-name=<name> \\
21
+ --to=name> \\
22
+ [options]
23
+
24
+ Description:
25
+ Copies an existing collection (content + config) to a new collection name.
26
+
27
+ Required:
28
+ --collection-name=<name> The name of the collection to promote
29
+ --to=<name> The name of the new (target) collection to create or overwrite
30
+
31
+ Expiration:
32
+ --expires-in=<duration> Expiration duration from now.
33
+ Examples: 3d, 12h, 15m, 1w
34
+
35
+ --expires-at=<timestamp> Absolute expiration in ISO 8601 format.
36
+ Example: 2025-05-01T00:00:00Z
37
+
38
+ --expires-never Prevent this collection from expiring.
39
+
40
+ ⚠ These three options are mutually exclusive.
41
+ Specify no more than one. If not provided, then the
42
+ existing expiration rule of the collection being
43
+ promoted is used.
44
+
45
+ Global Options:
46
+ --local Instead of working with the Fastly KV Store, operate on
47
+ local files that will be used to simulate the KV Store
48
+ with the local development environment.
49
+
50
+ --fastly-api-token=<token> Fastly API token for KV Store access.
51
+ If not set, the tool will check:
52
+ 1. FASTLY_API_TOKEN environment variable
53
+ 2. Logged-in Fastly CLI profile
54
+
55
+ -h, --help Show this help message and exit.
56
+ `);
57
+ }
58
+ export async function action(actionArgs) {
59
+ const optionDefinitions = [
60
+ { name: 'verbose', type: Boolean },
61
+ { name: 'collection-name', type: String },
62
+ { name: 'to', type: String },
63
+ { name: 'expires-in', type: String },
64
+ { name: 'expires-at', type: String },
65
+ { name: 'expires-never', type: Boolean },
66
+ { name: 'local', type: Boolean },
67
+ { name: 'fastly-api-token', type: String, },
68
+ ];
69
+ const parsed = parseCommandLine(actionArgs, optionDefinitions);
70
+ if (parsed.needHelp) {
71
+ if (parsed.error != null) {
72
+ console.error(String(parsed.error));
73
+ console.error();
74
+ process.exitCode = 1;
75
+ }
76
+ help();
77
+ return;
78
+ }
79
+ const { verbose, ['collection-name']: collectionNameValue, to: toCollectionNameValue, ['expires-in']: expiresIn, ['expires-at']: expiresAt, ['expires-never']: expiresNever, local: localMode, ['fastly-api-token']: fastlyApiToken, } = parsed.commandLineOptions;
80
+ // compute-js-static-publisher cli is always run from the Compute application directory
81
+ // in other words, the directory that contains `fastly.toml`.
82
+ const computeAppDir = path.resolve();
83
+ if (collectionNameValue == null) {
84
+ console.error("❌ Required argument '--collection-name' not specified.");
85
+ process.exitCode = 1;
86
+ return;
87
+ }
88
+ if (toCollectionNameValue == null) {
89
+ console.error("❌ Required argument '--to' not specified.");
90
+ process.exitCode = 1;
91
+ return;
92
+ }
93
+ let expirationTime;
94
+ try {
95
+ expirationTime = calcExpirationTime({ expiresIn, expiresAt, expiresNever });
96
+ }
97
+ catch (err) {
98
+ console.error(`❌ Cannot process expiration time`);
99
+ console.error(String(err));
100
+ process.exitCode = 1;
101
+ return;
102
+ }
103
+ // Check to see if we have a service ID listed in `fastly.toml`.
104
+ // If we do NOT, then we do not use the KV Store.
105
+ let serviceId;
106
+ try {
107
+ serviceId = readServiceId(path.resolve(computeAppDir, './fastly.toml'));
108
+ }
109
+ catch (err) {
110
+ if (isNodeError(err) && err.code === 'ENOENT') {
111
+ console.warn(`❌ ERROR: can't find 'fastly.toml'.`);
112
+ process.exitCode = 1;
113
+ return;
114
+ }
115
+ console.warn(`❌ ERROR: can't read or parse 'fastly.toml'.`);
116
+ process.exitCode = 1;
117
+ return;
118
+ }
119
+ console.log(`📃 Promoting collection...`);
120
+ // Verify targets
121
+ let fastlyApiContext = undefined;
122
+ if (localMode) {
123
+ console.log(` Working on local simulated KV Store...`);
124
+ }
125
+ else {
126
+ if (serviceId === null) {
127
+ console.log(`❌️ 'service_id' not set in 'fastly.toml' - Deploy your Compute app to Fastly before publishing.`);
128
+ process.exitCode = 1;
129
+ return;
130
+ }
131
+ const apiTokenResult = loadApiToken({ commandLine: fastlyApiToken });
132
+ if (apiTokenResult == null) {
133
+ console.error("❌ Fastly API Token not provided.");
134
+ console.error("Set the FASTLY_API_TOKEN environment variable to an API token that has write access to the KV Store.");
135
+ process.exitCode = 1;
136
+ return;
137
+ }
138
+ fastlyApiContext = { apiToken: apiTokenResult.apiToken };
139
+ console.log(`✔️ Fastly API Token: ${fastlyApiContext.apiToken.slice(0, 4)}${'*'.repeat(fastlyApiContext.apiToken.length - 4)} from '${apiTokenResult.source}'`);
140
+ console.log(` Working on the Fastly KV Store...`);
141
+ }
142
+ // #### load config
143
+ let staticPublisherRc;
144
+ try {
145
+ staticPublisherRc = await loadStaticPublisherRcFile();
146
+ }
147
+ catch (err) {
148
+ console.error("❌ Can't load static-publish.rc.js");
149
+ console.error("Run this from a compute-js-static-publish compute-js directory.");
150
+ if (err instanceof LoadConfigError) {
151
+ for (const error of err.errors) {
152
+ console.error(error);
153
+ }
154
+ }
155
+ process.exitCode = 1;
156
+ return;
157
+ }
158
+ const publishId = staticPublisherRc.publishId;
159
+ console.log(` | Publish ID: ${publishId}`);
160
+ const kvStoreName = staticPublisherRc.kvStoreName;
161
+ console.log(` | Using KV Store: ${kvStoreName}`);
162
+ const defaultCollectionName = staticPublisherRc.defaultCollectionName;
163
+ console.log(` | Default Collection Name: ${defaultCollectionName}`);
164
+ const staticPublisherWorkingDir = staticPublisherRc.staticPublisherWorkingDir;
165
+ console.log(` | Static publisher working directory: ${staticPublisherWorkingDir}`);
166
+ const storeFile = path.resolve(staticPublisherWorkingDir, `./kvstore.json`);
167
+ const sourceCollectionName = collectionNameValue;
168
+ console.log(`✔️ Collection to copy: ${sourceCollectionName}`);
169
+ const targetCollectionName = toCollectionNameValue;
170
+ console.log(`✔️ Collection to promote to: ${targetCollectionName}`);
171
+ if (expirationTime === undefined) {
172
+ console.log(`✔️ Not updating expiration timestamp.`);
173
+ }
174
+ else if (expirationTime === null) {
175
+ console.log(`✔️ Updating expiration timestamp: never`);
176
+ }
177
+ else {
178
+ console.log(`✔️ Updating expiration timestamp: ${new Date(expirationTime * 1000).toISOString()}`);
179
+ }
180
+ if (targetCollectionName === defaultCollectionName && expirationTime !== undefined) {
181
+ console.log(` ⚠️ NOTE: Expiration time not enforced for default collection.`);
182
+ }
183
+ const sourceCollectionIndexKey = `${publishId}_index_${sourceCollectionName}`;
184
+ const targetCollectionIndexKey = `${publishId}_index_${targetCollectionName}`;
185
+ const sourceCollectionSettingsKey = `${publishId}_settings_${collectionNameValue}`;
186
+ const targetCollectionSettingsKey = `${publishId}_settings_${targetCollectionName}`;
187
+ let indexEntryInfo, settingsEntryInfo;
188
+ if (localMode) {
189
+ [indexEntryInfo, settingsEntryInfo] = await Promise.all([
190
+ getLocalKvStoreEntry(storeFile, sourceCollectionIndexKey),
191
+ getLocalKvStoreEntry(storeFile, sourceCollectionSettingsKey),
192
+ ]);
193
+ }
194
+ else {
195
+ [indexEntryInfo, settingsEntryInfo] = await Promise.all([
196
+ getKvStoreEntry(fastlyApiContext, kvStoreName, sourceCollectionIndexKey),
197
+ getKvStoreEntry(fastlyApiContext, kvStoreName, sourceCollectionSettingsKey),
198
+ ]);
199
+ }
200
+ if (!indexEntryInfo) {
201
+ throw new Error(`Error querying index for '${collectionNameValue}' in KV Store`);
202
+ }
203
+ if (!settingsEntryInfo) {
204
+ throw new Error(`Error querying settings for '${collectionNameValue}' in KV Store`);
205
+ }
206
+ let indexMetadata = {};
207
+ if (indexEntryInfo.metadata != null) {
208
+ try {
209
+ indexMetadata = JSON.parse(indexEntryInfo.metadata);
210
+ }
211
+ catch {
212
+ }
213
+ }
214
+ if (indexMetadata.publishedTime == null) {
215
+ indexMetadata.publishedTime = Math.floor(Date.now() / 1000);
216
+ }
217
+ if (expirationTime !== undefined) {
218
+ if (expirationTime === null) {
219
+ delete indexMetadata.expirationTime;
220
+ }
221
+ else {
222
+ indexMetadata.expirationTime = expirationTime;
223
+ }
224
+ }
225
+ console.log(`Uploading to KV Store: '${targetCollectionName}'`);
226
+ if (localMode) {
227
+ const staticPublisherKvStoreContent = `${staticPublisherWorkingDir}/kv-store-content`;
228
+ fs.mkdirSync(staticPublisherKvStoreContent, { recursive: true });
229
+ const indexFileName = `index_${collectionNameValue}.json`;
230
+ const indexFilePath = path.resolve(staticPublisherKvStoreContent, indexFileName);
231
+ const indexBody = await indexEntryInfo.response.arrayBuffer();
232
+ fs.writeFileSync(indexFilePath, Buffer.from(indexBody));
233
+ await localKvStoreSubmitEntry(storeFile, targetCollectionIndexKey, path.relative(computeAppDir, indexFilePath), JSON.stringify(indexMetadata));
234
+ const settingsFileName = `settings_${collectionNameValue}.json`;
235
+ const settingsFilePath = path.resolve(staticPublisherKvStoreContent, settingsFileName);
236
+ const settingsBody = await settingsEntryInfo.response.arrayBuffer();
237
+ fs.writeFileSync(settingsFilePath, Buffer.from(settingsBody));
238
+ await localKvStoreSubmitEntry(storeFile, targetCollectionSettingsKey, path.relative(computeAppDir, settingsFilePath), undefined);
239
+ }
240
+ else {
241
+ await Promise.all([
242
+ kvStoreSubmitEntry(fastlyApiContext, kvStoreName, targetCollectionIndexKey, indexEntryInfo.response.body, JSON.stringify(indexMetadata)),
243
+ kvStoreSubmitEntry(fastlyApiContext, kvStoreName, targetCollectionSettingsKey, settingsEntryInfo.response.body, undefined),
244
+ ]);
245
+ }
246
+ console.log("✅ Completed.");
247
+ }
@@ -0,0 +1,2 @@
1
+ export declare function action(actionArgs: string[]): Promise<void>;
2
+ //# sourceMappingURL=update-expiration.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"update-expiration.d.ts","sourceRoot":"","sources":["../../../../../src/cli/commands/manage/collections/update-expiration.ts"],"names":[],"mappings":"AA8DA,wBAAsB,MAAM,CAAC,UAAU,EAAE,MAAM,EAAE,iBA2MhD"}
@@ -0,0 +1,215 @@
1
+ /*
2
+ * Copyright Fastly, Inc.
3
+ * Licensed under the MIT license. See LICENSE file for details.
4
+ */
5
+ import { calcExpirationTime } from '../../../../models/time/index.js';
6
+ import { LoadConfigError, loadStaticPublisherRcFile } from '../../../util/config.js';
7
+ import { getKvStoreEntry, kvStoreSubmitEntry, } from '../../../util/kv-store.js';
8
+ import { loadApiToken } from '../../../util/api-token.js';
9
+ import { parseCommandLine } from '../../../util/args.js';
10
+ import { readServiceId } from "../../../util/fastly-toml.js";
11
+ import { isNodeError } from "../../../util/node.js";
12
+ import path from "node:path";
13
+ import fs from "node:fs";
14
+ import { getLocalKvStoreEntry, localKvStoreSubmitEntry } from "../../../util/kv-store-local-server.js";
15
+ function help() {
16
+ console.log(`\
17
+
18
+ Usage:
19
+ npx @fastly/compute-js-static-publish collections update-expiration \\
20
+ --collection-name=<name> \\
21
+ [options]
22
+
23
+ Description:
24
+ Updates the expiration time of an existing collection.
25
+
26
+ Required:
27
+ --collection-name=<name> The name of the collection to modify
28
+
29
+ Expiration:
30
+ --expires-in=<duration> Expiration duration from now.
31
+ Examples: 3d, 12h, 15m, 1w
32
+
33
+ --expires-at=<timestamp> Absolute expiration in ISO 8601 format.
34
+ Example: 2025-05-01T00:00:00Z
35
+
36
+ --expires-never Prevent this collection from expiring.
37
+
38
+ ⚠ These three options are mutually exclusive.
39
+ Specify exactly one.
40
+
41
+ Global Options:
42
+ --local Instead of working with the Fastly KV Store, operate on
43
+ local files that will be used to simulate the KV Store
44
+ with the local development environment.
45
+
46
+ --fastly-api-token=<token> Fastly API token for KV Store access.
47
+ If not set, the tool will check:
48
+ 1. FASTLY_API_TOKEN environment variable
49
+ 2. Logged-in Fastly CLI profile
50
+
51
+ -h, --help Show this help message and exit.
52
+ `);
53
+ }
54
+ export async function action(actionArgs) {
55
+ const optionDefinitions = [
56
+ { name: 'verbose', type: Boolean },
57
+ { name: 'collection-name', type: String, },
58
+ { name: 'expires-in', type: String },
59
+ { name: 'expires-at', type: String },
60
+ { name: 'expires-never', type: Boolean },
61
+ { name: 'local', type: Boolean },
62
+ { name: 'fastly-api-token', type: String, },
63
+ ];
64
+ const parsed = parseCommandLine(actionArgs, optionDefinitions);
65
+ if (parsed.needHelp) {
66
+ if (parsed.error != null) {
67
+ console.error(String(parsed.error));
68
+ console.error();
69
+ process.exitCode = 1;
70
+ }
71
+ help();
72
+ return;
73
+ }
74
+ const { verbose, ['collection-name']: collectionNameValue, ['expires-in']: expiresIn, ['expires-at']: expiresAt, ['expires-never']: expiresNever, local: localMode, ['fastly-api-token']: fastlyApiToken, } = parsed.commandLineOptions;
75
+ // compute-js-static-publisher cli is always run from the Compute application directory
76
+ // in other words, the directory that contains `fastly.toml`.
77
+ const computeAppDir = path.resolve();
78
+ if (collectionNameValue == null) {
79
+ console.error("❌ Required argument '--collection-name' not specified.");
80
+ process.exitCode = 1;
81
+ return;
82
+ }
83
+ let expirationTime;
84
+ try {
85
+ expirationTime = calcExpirationTime({ expiresIn, expiresAt, expiresNever });
86
+ }
87
+ catch (err) {
88
+ console.error(`❌ Cannot process expiration time`);
89
+ console.error(String(err));
90
+ process.exitCode = 1;
91
+ return;
92
+ }
93
+ if (expirationTime === undefined) {
94
+ console.error("❌ Exactly one of '--expires-in', '--expires-at', or '--expires-never' is required.");
95
+ process.exitCode = 1;
96
+ return;
97
+ }
98
+ // Check to see if we have a service ID listed in `fastly.toml`.
99
+ // If we do NOT, then we do not use the KV Store.
100
+ let serviceId;
101
+ try {
102
+ serviceId = readServiceId(path.resolve(computeAppDir, './fastly.toml'));
103
+ }
104
+ catch (err) {
105
+ if (isNodeError(err) && err.code === 'ENOENT') {
106
+ console.warn(`❌ ERROR: can't find 'fastly.toml'.`);
107
+ process.exitCode = 1;
108
+ return;
109
+ }
110
+ console.warn(`❌ ERROR: can't read or parse 'fastly.toml'.`);
111
+ process.exitCode = 1;
112
+ return;
113
+ }
114
+ console.log(`📃 Promoting collection...`);
115
+ // Verify targets
116
+ let fastlyApiContext = undefined;
117
+ if (localMode) {
118
+ console.log(` Working on local simulated KV Store...`);
119
+ }
120
+ else {
121
+ if (serviceId === null) {
122
+ console.log(`❌️ 'service_id' not set in 'fastly.toml' - Deploy your Compute app to Fastly before publishing.`);
123
+ process.exitCode = 1;
124
+ return;
125
+ }
126
+ const apiTokenResult = loadApiToken({ commandLine: fastlyApiToken });
127
+ if (apiTokenResult == null) {
128
+ console.error("❌ Fastly API Token not provided.");
129
+ console.error("Set the FASTLY_API_TOKEN environment variable to an API token that has write access to the KV Store.");
130
+ process.exitCode = 1;
131
+ return;
132
+ }
133
+ fastlyApiContext = { apiToken: apiTokenResult.apiToken };
134
+ console.log(`✔️ Fastly API Token: ${fastlyApiContext.apiToken.slice(0, 4)}${'*'.repeat(fastlyApiContext.apiToken.length - 4)} from '${apiTokenResult.source}'`);
135
+ console.log(` Working on the Fastly KV Store...`);
136
+ }
137
+ // #### load config
138
+ let staticPublisherRc;
139
+ try {
140
+ staticPublisherRc = await loadStaticPublisherRcFile();
141
+ }
142
+ catch (err) {
143
+ console.error("❌ Can't load static-publish.rc.js");
144
+ console.error("Run this from a compute-js-static-publish compute-js directory.");
145
+ if (err instanceof LoadConfigError) {
146
+ for (const error of err.errors) {
147
+ console.error(error);
148
+ }
149
+ }
150
+ process.exitCode = 1;
151
+ return;
152
+ }
153
+ const publishId = staticPublisherRc.publishId;
154
+ console.log(` | Publish ID: ${publishId}`);
155
+ const kvStoreName = staticPublisherRc.kvStoreName;
156
+ console.log(` | Using KV Store: ${kvStoreName}`);
157
+ const defaultCollectionName = staticPublisherRc.defaultCollectionName;
158
+ console.log(` | Default Collection Name: ${defaultCollectionName}`);
159
+ const staticPublisherWorkingDir = staticPublisherRc.staticPublisherWorkingDir;
160
+ console.log(` | Static publisher working directory: ${staticPublisherWorkingDir}`);
161
+ const storeFile = path.resolve(staticPublisherWorkingDir, `./kvstore.json`);
162
+ const collectionName = collectionNameValue;
163
+ console.log(`✔️ Collection to update: ${collectionName}`);
164
+ if (expirationTime !== null) {
165
+ console.log(`✔️ Updating expiration timestamp: ${new Date(expirationTime * 1000).toISOString()}`);
166
+ }
167
+ else {
168
+ console.log(`✔️ Updating expiration timestamp: never`);
169
+ }
170
+ if (collectionName === defaultCollectionName && expirationTime != null) {
171
+ console.log(` ⚠️ NOTE: Expiration time not enforced for default collection.`);
172
+ }
173
+ const collectionIndexKey = `${publishId}_index_${collectionName}`;
174
+ let indexEntryInfo;
175
+ if (localMode) {
176
+ indexEntryInfo = await getLocalKvStoreEntry(storeFile, collectionIndexKey);
177
+ }
178
+ else {
179
+ indexEntryInfo = await getKvStoreEntry(fastlyApiContext, kvStoreName, collectionIndexKey);
180
+ }
181
+ if (!indexEntryInfo) {
182
+ throw new Error(`Error querying index for '${collectionNameValue}' in KV Store`);
183
+ }
184
+ let indexMetadata = {};
185
+ if (indexEntryInfo.metadata != null) {
186
+ try {
187
+ indexMetadata = JSON.parse(indexEntryInfo.metadata);
188
+ }
189
+ catch {
190
+ }
191
+ }
192
+ if (indexMetadata.publishedTime == null) {
193
+ indexMetadata.publishedTime = Math.floor(Date.now() / 1000);
194
+ }
195
+ if (expirationTime === null) {
196
+ delete indexMetadata.expirationTime;
197
+ }
198
+ else {
199
+ indexMetadata.expirationTime = expirationTime;
200
+ }
201
+ console.log(`Uploading to KV Store: '${collectionName}'`);
202
+ if (localMode) {
203
+ const staticPublisherKvStoreContent = `${staticPublisherWorkingDir}/kv-store-content`;
204
+ fs.mkdirSync(staticPublisherKvStoreContent, { recursive: true });
205
+ const indexFileName = `index_${collectionNameValue}.json`;
206
+ const indexFilePath = path.resolve(staticPublisherKvStoreContent, indexFileName);
207
+ const indexBody = await indexEntryInfo.response.arrayBuffer();
208
+ fs.writeFileSync(indexFilePath, Buffer.from(indexBody));
209
+ await localKvStoreSubmitEntry(storeFile, collectionIndexKey, path.relative(computeAppDir, indexFilePath), JSON.stringify(indexMetadata));
210
+ }
211
+ else {
212
+ await kvStoreSubmitEntry(fastlyApiContext, kvStoreName, collectionIndexKey, indexEntryInfo.response.body, JSON.stringify(indexMetadata));
213
+ }
214
+ console.log("✅ Completed.");
215
+ }
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/cli/commands/manage/index.ts"],"names":[],"mappings":"AAoDA,wBAAsB,MAAM,CAAC,UAAU,EAAE,MAAM,EAAE,iBAyBhD"}