@fastly/compute-js-static-publish 8.0.0-beta.2 → 8.0.0-beta.21

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 (113) hide show
  1. package/README.md +19 -5
  2. package/README.short.md +19 -5
  3. package/build/cli/cli/commands/manage/clean.d.ts.map +1 -1
  4. package/build/cli/cli/commands/manage/clean.js +17 -24
  5. package/build/cli/cli/commands/manage/collections/delete.d.ts.map +1 -1
  6. package/build/cli/cli/commands/manage/collections/delete.js +13 -23
  7. package/build/cli/cli/commands/manage/collections/index.d.ts.map +1 -1
  8. package/build/cli/cli/commands/manage/collections/index.js +7 -15
  9. package/build/cli/cli/commands/manage/collections/list.d.ts.map +1 -1
  10. package/build/cli/cli/commands/manage/collections/list.js +12 -22
  11. package/build/cli/cli/commands/manage/collections/promote.d.ts.map +1 -1
  12. package/build/cli/cli/commands/manage/collections/promote.js +12 -22
  13. package/build/cli/cli/commands/manage/collections/update-expiration.d.ts.map +1 -1
  14. package/build/cli/cli/commands/manage/collections/update-expiration.js +12 -22
  15. package/build/cli/cli/commands/manage/index.d.ts.map +1 -1
  16. package/build/cli/cli/commands/manage/index.js +7 -15
  17. package/build/cli/cli/commands/manage/publish-content.d.ts.map +1 -1
  18. package/build/cli/cli/commands/manage/publish-content.js +201 -92
  19. package/build/cli/cli/commands/scaffold/index.d.ts.map +1 -1
  20. package/build/cli/cli/commands/scaffold/index.js +54 -32
  21. package/build/cli/cli/compression/brotli.d.ts +2 -1
  22. package/build/cli/cli/compression/brotli.d.ts.map +1 -1
  23. package/build/cli/cli/compression/brotli.js +15 -4
  24. package/build/cli/cli/compression/gzip.d.ts +2 -1
  25. package/build/cli/cli/compression/gzip.d.ts.map +1 -1
  26. package/build/cli/cli/compression/gzip.js +8 -4
  27. package/build/cli/cli/compression/index.d.ts +4 -1
  28. package/build/cli/cli/compression/index.d.ts.map +1 -1
  29. package/build/cli/cli/index.js +8 -0
  30. package/build/cli/cli/storage/kv-store-local-provider.d.ts +3 -5
  31. package/build/cli/cli/storage/kv-store-local-provider.d.ts.map +1 -1
  32. package/build/cli/cli/storage/kv-store-local-provider.js +3 -8
  33. package/build/cli/cli/storage/kv-store-provider.d.ts +4 -5
  34. package/build/cli/cli/storage/kv-store-provider.d.ts.map +1 -1
  35. package/build/cli/cli/storage/kv-store-provider.js +38 -66
  36. package/build/cli/cli/storage/s3-storage-provider.d.ts +6 -6
  37. package/build/cli/cli/storage/s3-storage-provider.d.ts.map +1 -1
  38. package/build/cli/cli/storage/s3-storage-provider.js +54 -51
  39. package/build/cli/cli/storage/storage-provider.d.ts +9 -8
  40. package/build/cli/cli/storage/storage-provider.d.ts.map +1 -1
  41. package/build/cli/cli/storage/storage-provider.js +13 -0
  42. package/build/cli/cli/util/api-token.d.ts.map +1 -1
  43. package/build/cli/cli/util/api-token.js +0 -28
  44. package/build/cli/cli/util/config.d.ts.map +1 -1
  45. package/build/cli/cli/util/config.js +8 -1
  46. package/build/cli/cli/util/content-types.d.ts.map +1 -1
  47. package/build/cli/cli/util/content-types.js +5 -2
  48. package/build/cli/cli/util/kv-store-items.d.ts +12 -0
  49. package/build/cli/cli/util/kv-store-items.d.ts.map +1 -1
  50. package/build/cli/cli/util/kv-store-items.js +49 -0
  51. package/build/cli/cli/util/kv-store.d.ts +6 -0
  52. package/build/cli/cli/util/kv-store.d.ts.map +1 -1
  53. package/build/cli/cli/util/kv-store.js +39 -2
  54. package/build/cli/cli/util/purge.d.ts +19 -0
  55. package/build/cli/cli/util/purge.d.ts.map +1 -0
  56. package/build/cli/cli/util/purge.js +83 -0
  57. package/build/cli/cli/util/retryable.d.ts +2 -1
  58. package/build/cli/cli/util/retryable.d.ts.map +1 -1
  59. package/build/cli/cli/util/retryable.js +34 -1
  60. package/build/cli/cli/util/s3-credentials.d.ts +11 -0
  61. package/build/cli/cli/util/s3-credentials.d.ts.map +1 -0
  62. package/build/cli/cli/util/s3-credentials.js +38 -0
  63. package/build/cli/cli/util/s3.d.ts +1 -1
  64. package/build/cli/cli/util/s3.d.ts.map +1 -1
  65. package/build/cli/cli/util/s3.js +1 -1
  66. package/build/cli/cli/util/service-id.d.ts +10 -0
  67. package/build/cli/cli/util/service-id.d.ts.map +1 -0
  68. package/build/cli/cli/util/service-id.js +27 -0
  69. package/build/cli/cli/util/variants.d.ts +2 -1
  70. package/build/cli/cli/util/variants.d.ts.map +1 -1
  71. package/build/cli/cli/util/variants.js +8 -4
  72. package/build/cli/models/assets/index.js +1 -1
  73. package/build/cli/models/config/publish-content-config.d.ts +2 -0
  74. package/build/cli/models/config/publish-content-config.d.ts.map +1 -1
  75. package/build/cli/models/config/s3-storage-config.d.ts +1 -0
  76. package/build/cli/models/config/s3-storage-config.d.ts.map +1 -1
  77. package/build/cli/models/config/s3-storage-config.js +1 -0
  78. package/build/cli/models/config/static-publish-rc.d.ts +1 -0
  79. package/build/cli/models/config/static-publish-rc.d.ts.map +1 -1
  80. package/build/cli/models/config/static-publish-rc.js +3 -1
  81. package/build/cli/models/metadata/index.js +1 -1
  82. package/build/server/models/assets/index.js +1 -1
  83. package/build/server/models/config/publish-content-config.d.ts +2 -0
  84. package/build/server/models/config/publish-content-config.d.ts.map +1 -1
  85. package/build/server/models/config/s3-storage-config.d.ts +1 -0
  86. package/build/server/models/config/s3-storage-config.d.ts.map +1 -1
  87. package/build/server/models/config/s3-storage-config.js +1 -0
  88. package/build/server/models/config/static-publish-rc.d.ts +1 -0
  89. package/build/server/models/config/static-publish-rc.d.ts.map +1 -1
  90. package/build/server/models/config/static-publish-rc.js +3 -1
  91. package/build/server/models/metadata/index.js +1 -1
  92. package/build/server/server/index.d.ts +1 -1
  93. package/build/server/server/index.d.ts.map +1 -1
  94. package/build/server/server/index.js +1 -1
  95. package/build/server/server/publisher-server/index.d.ts +14 -0
  96. package/build/server/server/publisher-server/index.d.ts.map +1 -1
  97. package/build/server/server/publisher-server/index.js +178 -54
  98. package/build/server/server/publisher-server/response-cache.d.ts +19 -0
  99. package/build/server/server/publisher-server/response-cache.d.ts.map +1 -0
  100. package/build/server/server/publisher-server/response-cache.js +106 -0
  101. package/build/server/server/storage/s3-storage-provider.d.ts +16 -15
  102. package/build/server/server/storage/s3-storage-provider.d.ts.map +1 -1
  103. package/build/server/server/storage/s3-storage-provider.js +131 -60
  104. package/build/server/server/storage/storage-provider.d.ts +2 -2
  105. package/build/server/server/storage/storage-provider.d.ts.map +1 -1
  106. package/build/server/server/storage/storage-provider.js +2 -1
  107. package/build/server/server/util/server-timing.d.ts +7 -0
  108. package/build/server/server/util/server-timing.d.ts.map +1 -0
  109. package/build/server/server/util/server-timing.js +34 -0
  110. package/package.json +9 -8
  111. package/build/cli/cli/util/aws-credentials.d.ts +0 -12
  112. package/build/cli/cli/util/aws-credentials.d.ts.map +0 -1
  113. package/build/cli/cli/util/aws-credentials.js +0 -67
@@ -12,7 +12,9 @@ import { LoadConfigError, loadPublishContentConfigFile, loadStaticPublisherRcFil
12
12
  import { applyDefaults } from '../../util/data.js';
13
13
  import { calculateFileSizeAndHash, enumerateFiles, rootRelative } from '../../util/files.js';
14
14
  import { ensureVariantFileExists } from '../../util/variants.js';
15
- import { loadStorageProviderFromStaticPublishRc, StorageProviderBatch, } from '../../storage/storage-provider.js';
15
+ import { concurrentMap } from '../../util/retryable.js';
16
+ import { loadPurgeTarget, purgeSurrogateKey } from '../../util/purge.js';
17
+ import { getStorageKeysByHexPrefix, loadStorageProviderFromStaticPublishRc, StorageProviderBatch, } from '../../storage/storage-provider.js';
16
18
  // Storage key format:
17
19
  // <publishId>_index_<preview_id>.json
18
20
  // <publishId>_settings_<preview_id>.json
@@ -42,8 +44,26 @@ Optional:
42
44
  --root-dir=<dir> Directory to publish from. Overrides the config file setting.
43
45
  Default: rootDir from publish-content.config.js
44
46
 
47
+ --fastly-api-token=<token> Fastly API token for KV Store or cache access.
48
+ If not set, the tool uses the FASTLY_API_TOKEN
49
+ environment variable.
50
+
51
+ --fastly-service-id=<id> Fastly Service ID to purge after publishing (not with --local).
52
+ If not set, the tool will check:
53
+ 1. FASTLY_SERVICE_ID environment variable
54
+ 2. service_id in fastly.toml
55
+ If none is found, the purge is skipped.
56
+
57
+ --purge-environment=<env> Environment to purge: production, staging, or a
58
+ comma-separated list of both. Can be repeated.
59
+ Default: production
60
+
45
61
  --overwrite-existing Always overwrite existing entries in storage, even if unchanged.
46
62
 
63
+ --brotli-quality=<0-11> Brotli quality for the 'br' variants. Overrides
64
+ brotliQuality in the config file.
65
+ Default: brotliQuality from publish-content.config.js, or 11
66
+
47
67
  Expiration:
48
68
  --expires-in=<duration> Expiration duration from now.
49
69
  Examples: 3d, 12h, 15m, 1w
@@ -61,25 +81,16 @@ KV Store Options:
61
81
  local files that will be used to simulate the KV Store
62
82
  with the local development environment.
63
83
 
64
- --fastly-api-token=<token> Fastly API token for KV Store access.
65
- If not set, the tool will check:
66
- 1. FASTLY_API_TOKEN environment variable
67
- 2. Logged-in Fastly CLI profile
68
-
69
84
  --kv-overwrite Alias for --overwrite-existing.
70
85
 
71
- S3 Storage Options:
72
- --aws-access-key-id=<key> AWS Access Key ID and Secret Access Key used to
73
- --aws-secret-access-key=<key> interface with S3.
74
- If not set, the tool will check:
75
- 1. AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY
76
- environment variables
77
- 2. The aws credentials file, see below
86
+ S3 Storage Options (BETA):
87
+ --s3-access-key-id=<id> Access Key ID and Secret Access Key used to
88
+ --s3-secret-access-key=<key> interface with S3 or compatible storage.
89
+ If not set, the tool will check the S3_ACCESS_KEY_ID
90
+ and S3_SECRET_ACCESS_KEY environment variables.
78
91
 
79
- --aws-profile=<profile> Profile within the aws credentials file.
80
- If not set, the tool will check:
81
- 1. AWS_PROFILE environment variable
82
- 2. The default profile, if set
92
+ --s3-upload-concurrency=<1-256> Number of objects to upload at the same time.
93
+ Default: 64
83
94
 
84
95
  Global Options:
85
96
  -h, --help Show this help message and exit.
@@ -98,15 +109,18 @@ export async function action(actionArgs) {
98
109
  { name: 'collection-name', type: String, },
99
110
  { name: 'root-dir', type: String, },
100
111
  { name: 'overwrite-existing', type: Boolean },
112
+ { name: 'brotli-quality', type: String },
101
113
  { name: 'expires-in', type: String },
102
114
  { name: 'expires-at', type: String },
103
115
  { name: 'expires-never', type: Boolean },
104
116
  { name: 'local', type: Boolean },
105
117
  { name: 'fastly-api-token', type: String, },
118
+ { name: 'fastly-service-id', type: String, },
119
+ { name: 'purge-environment', type: String, multiple: true, },
106
120
  { name: 'kv-overwrite', type: Boolean },
107
- { name: 'aws-profile', type: String, },
108
- { name: 'aws-access-key-id', type: String, },
109
- { name: 'aws-secret-access-key', type: String, },
121
+ { name: 's3-access-key-id', type: String, },
122
+ { name: 's3-secret-access-key', type: String, },
123
+ { name: 's3-upload-concurrency', type: String, },
110
124
  ];
111
125
  const parsed = parseCommandLine(actionArgs, optionDefinitions);
112
126
  if (parsed.needHelp) {
@@ -118,7 +132,17 @@ export async function action(actionArgs) {
118
132
  help();
119
133
  return;
120
134
  }
121
- const { verbose, config: configFilePathValue, ['collection-name']: collectionNameValue, ['root-dir']: rootDir, ['overwrite-existing']: _overwriteExisting, ['expires-in']: expiresIn, ['expires-at']: expiresAt, ['expires-never']: expiresNever, local: localMode, ['fastly-api-token']: fastlyApiToken, ['kv-overwrite']: _kvOverwrite, ['aws-profile']: awsProfile, ['aws-access-key-id']: awsAccessKeyId, ['aws-secret-access-key']: awsSecretAccessKey, } = parsed.commandLineOptions;
135
+ const { verbose, config: configFilePathValue, ['collection-name']: collectionNameValue, ['root-dir']: rootDir, ['overwrite-existing']: _overwriteExisting, ['brotli-quality']: brotliQualityValue, ['expires-in']: expiresIn, ['expires-at']: expiresAt, ['expires-never']: expiresNever, local: localMode, ['fastly-api-token']: fastlyApiToken, ['fastly-service-id']: fastlyServiceId, ['purge-environment']: purgeEnvironmentValues, ['kv-overwrite']: _kvOverwrite, ['s3-access-key-id']: s3AccessKeyId, ['s3-secret-access-key']: s3SecretAccessKey, ['s3-upload-concurrency']: s3UploadConcurrencyValue, } = parsed.commandLineOptions;
136
+ let s3UploadConcurrency;
137
+ if (s3UploadConcurrencyValue !== undefined) {
138
+ if (typeof s3UploadConcurrencyValue !== 'string' || !/^\d+$/.test(s3UploadConcurrencyValue) ||
139
+ Number(s3UploadConcurrencyValue) < 1 || Number(s3UploadConcurrencyValue) > 256) {
140
+ console.error(`❌ --s3-upload-concurrency must be an integer from 1 to 256.`);
141
+ process.exitCode = 1;
142
+ return;
143
+ }
144
+ s3UploadConcurrency = Number(s3UploadConcurrencyValue);
145
+ }
122
146
  const overwriteExisting = _overwriteExisting ?? _kvOverwrite;
123
147
  // compute-js-static-publisher cli is always run from the Compute application directory
124
148
  // in other words, the directory that contains `fastly.toml`.
@@ -155,6 +179,17 @@ export async function action(actionArgs) {
155
179
  process.exitCode = 1;
156
180
  return;
157
181
  }
182
+ // --brotli-quality overrides brotliQuality in the config file.
183
+ let brotliQualitySource = 'config';
184
+ if (brotliQualityValue !== undefined) {
185
+ if (typeof brotliQualityValue !== 'string' || !/^\d+$/.test(brotliQualityValue) || Number(brotliQualityValue) > 11) {
186
+ console.error(`❌ --brotli-quality must be an integer from 0 to 11.`);
187
+ process.exitCode = 1;
188
+ return;
189
+ }
190
+ publishContentConfig.brotliQuality = Number(brotliQualityValue);
191
+ brotliQualitySource = '--brotli-quality';
192
+ }
158
193
  const publicDirRoot = path.resolve(rootDir != null ? rootDir : publishContentConfig.rootDir);
159
194
  if ((computeAppDir + '/').startsWith(publicDirRoot + '/')) {
160
195
  if (verbose) {
@@ -174,6 +209,9 @@ export async function action(actionArgs) {
174
209
  return;
175
210
  }
176
211
  console.log(`✔️ Public directory '${rootRelative(publicDirRoot)}'.`);
212
+ if (publishContentConfig.brotliQuality != null) {
213
+ console.log(`✔️ Brotli quality: ${publishContentConfig.brotliQuality} (from ${brotliQualitySource})`);
214
+ }
177
215
  const publishId = staticPublisherRc.publishId;
178
216
  console.log(` | Publish ID: ${publishId}`);
179
217
  const defaultCollectionName = staticPublisherRc.defaultCollectionName;
@@ -187,9 +225,9 @@ export async function action(actionArgs) {
187
225
  computeAppDir,
188
226
  localMode,
189
227
  fastlyApiToken,
190
- awsProfile,
191
- awsAccessKeyId,
192
- awsSecretAccessKey,
228
+ s3AccessKeyId,
229
+ s3SecretAccessKey,
230
+ s3UploadConcurrency,
193
231
  });
194
232
  }
195
233
  catch (err) {
@@ -198,6 +236,22 @@ export async function action(actionArgs) {
198
236
  process.exitCode = 1;
199
237
  return;
200
238
  }
239
+ // Purge target: checked now, so that a missing API token fails before anything is uploaded.
240
+ let purgeTarget;
241
+ try {
242
+ purgeTarget = loadPurgeTarget({
243
+ localMode: localMode ?? false,
244
+ computeAppDir,
245
+ fastlyServiceId,
246
+ fastlyApiToken,
247
+ purgeEnvironments: purgeEnvironmentValues,
248
+ });
249
+ }
250
+ catch (err) {
251
+ console.error(String(err));
252
+ process.exitCode = 1;
253
+ return;
254
+ }
201
255
  // Load content types
202
256
  const contentTypes = mergeContentTypes(publishContentConfig.contentTypes);
203
257
  // #### Collect all file paths
@@ -248,15 +302,38 @@ export async function action(actionArgs) {
248
302
  // and for serving using the local development server.
249
303
  const storageContentDir = `${staticPublisherWorkingDir}/storage-content`;
250
304
  fs.mkdirSync(storageContentDir, { recursive: true });
251
- // A list of items in storage at the end of the publishing.
252
- // Includes items that already exist as well. 'write' signifies
253
- // that the item is to be written
305
+ // The items to write to storage.
254
306
  const batch = new StorageProviderBatch();
255
307
  // Assets included in the publishing, keyed by asset key
256
308
  const assetsIndex = {};
257
- const baseHashToVariantMetadatasMap = new Map();
309
+ const baseHashToVariantKeepMap = new Map();
310
+ // #### Keys that are already in storage
311
+ // The key of a file is the hash of its content. If the key exists, storage
312
+ // already has the same content. Thus we do not compress, hash, or upload it again.
313
+ // In local mode, a key can refer to a working file that was deleted, so we do not list.
314
+ // All the keys that the scan looks for start with `<publishId>_files_sha256_` and a hex
315
+ // hash, so we list them in 16 parts at the same time.
316
+ let existingKeys;
317
+ if (!overwriteExisting && !localMode) {
318
+ console.log(`🔎 Listing files that are already in storage...`);
319
+ const listStart = Date.now();
320
+ existingKeys = new Set(await getStorageKeysByHexPrefix(storageProvider, `${publishId}_files_sha256_`) ?? []);
321
+ console.log(`✅ Found ${existingKeys.size} key(s) in ${((Date.now() - listStart) / 1000).toFixed(1)} s.`);
322
+ }
323
+ let existingVariantCount = 0;
324
+ function isVariantInStorage(variantKey, numChunks) {
325
+ if (existingKeys == null || !existingKeys.has(variantKey)) {
326
+ return false;
327
+ }
328
+ for (let chunkIndex = 1; chunkIndex < numChunks; chunkIndex++) {
329
+ if (!existingKeys.has(`${variantKey}_${chunkIndex}`)) {
330
+ return false;
331
+ }
332
+ }
333
+ return true;
334
+ }
258
335
  // #### Iterate files
259
- for (const file of files) {
336
+ const fileResults = await concurrentMap(files, async (file) => {
260
337
  // #### asset key
261
338
  const assetKey = file.slice(publicDirRoot.length)
262
339
  // in Windows, assetKey will otherwise end up as \path\file.html
@@ -285,24 +362,28 @@ export async function action(actionArgs) {
285
362
  includeAsset = true;
286
363
  }
287
364
  if (!includeAsset) {
288
- continue;
365
+ return;
289
366
  }
290
367
  // #### Base file size, hash, last modified time
291
368
  const { size: baseSize, hash: baseHash } = await calculateFileSizeAndHash(file);
292
369
  console.log(`📄 File '${rootRelative(file)}' - ${baseSize} bytes, sha256: ${baseHash}`);
293
370
  const stats = fs.statSync(file);
294
371
  const lastModifiedTime = Math.floor((stats.mtime).getTime() / 1000);
295
- // #### Metadata per variant
296
- let variantMetadatas = baseHashToVariantMetadatasMap.get(baseHash);
297
- if (variantMetadatas == null) {
298
- variantMetadatas = new Map();
299
- baseHashToVariantMetadatasMap.set(baseHash, variantMetadatas);
372
+ // #### Keep flag per variant
373
+ let variantKeeps = baseHashToVariantKeepMap.get(baseHash);
374
+ if (variantKeeps == null) {
375
+ variantKeeps = new Map();
376
+ baseHashToVariantKeepMap.set(baseHash, variantKeeps);
300
377
  }
378
+ // We know the number of chunks of the original before we read it. For a
379
+ // compressed variant, we know it only if the original fits in one chunk.
380
+ const baseNumChunks = storageProvider.calculateNumChunks(baseSize);
301
381
  const variantsToKeep = [];
302
382
  const variants = [
303
383
  'original',
304
384
  ...contentCompression,
305
385
  ];
386
+ const batchItems = [];
306
387
  for (const variant of variants) {
307
388
  let variantKey = `${publishId}_files_sha256_${baseHash}`;
308
389
  let variantFilename = `${baseHash}`;
@@ -311,78 +392,92 @@ export async function action(actionArgs) {
311
392
  variantFilename = `${variantFilename}_${variant}`;
312
393
  }
313
394
  const variantFilePath = path.resolve(storageContentDir, variantFilename);
314
- let variantMetadata = variantMetadatas.get(variant);
315
- if (variantMetadata != null) {
316
- console.log(` 🏃‍♂️ Asset "${variantKey}" is identical to an item we already know about, reusing existing copy.`);
395
+ let keep = variantKeeps.get(variant);
396
+ if (keep != null) {
397
+ if (verbose) {
398
+ console.log(` 🏃‍♂️ Asset "${variantKey}" is identical to an item we already know about, reusing existing copy.`);
399
+ }
400
+ }
401
+ else if ((variant === 'original' || baseNumChunks === 1) &&
402
+ isVariantInStorage(variantKey, variant === 'original' ? baseNumChunks : 1)) {
403
+ if (verbose) {
404
+ console.log(` ・ Asset found in storage with key "${variantKey}".`);
405
+ }
406
+ existingVariantCount++;
407
+ // We upload a compressed variant only if it is smaller than the
408
+ // original. Thus if it is in storage, the index keeps it.
409
+ keep = true;
410
+ variantKeeps.set(variant, keep);
317
411
  }
318
412
  else {
319
- if (!overwriteExisting) {
320
- const assetVariantMetadata = await storageProvider.getExistingAssetVariant(variantKey);
321
- if (assetVariantMetadata != null) {
322
- console.log(` ・ Asset found in storage with key "${variantKey}".`);
323
- // And we already know its hash and size.
324
- variantMetadata = Object.assign(assetVariantMetadata, { existsInKvStore: true });
325
- }
413
+ await ensureVariantFileExists(variantFilePath, variant, file, verbose, { brotliQuality: publishContentConfig.brotliQuality });
414
+ let contentEncoding, hash, size;
415
+ if (variant === 'original') {
416
+ contentEncoding = undefined;
417
+ hash = baseHash;
418
+ size = baseSize;
326
419
  }
327
- if (variantMetadata == null) {
328
- await ensureVariantFileExists(variantFilePath, variant, file);
329
- if (localMode) {
330
- console.log(` ・ Prepping asset for storage with key "${variantKey}".`);
331
- }
332
- let contentEncoding, hash, size;
333
- if (variant === 'original') {
334
- contentEncoding = undefined;
335
- hash = baseHash;
336
- size = baseSize;
337
- }
338
- else {
339
- contentEncoding = variant;
340
- ({ hash, size } = await calculateFileSizeAndHash(variantFilePath));
341
- }
420
+ else {
421
+ contentEncoding = variant;
422
+ ({ hash, size } = await calculateFileSizeAndHash(variantFilePath));
423
+ }
424
+ // Only keep variants whose file size actually ends up smaller than
425
+ // what we started with. Do not upload the other variants.
426
+ keep = variant === 'original' || size < baseSize;
427
+ variantKeeps.set(variant, keep);
428
+ if (keep) {
342
429
  const numChunks = storageProvider.calculateNumChunks(size);
343
- variantMetadata = {
344
- contentEncoding,
345
- size,
430
+ const metadataJson = {
431
+ size: String(size),
346
432
  hash,
347
- numChunks: numChunks > 1 ? numChunks : undefined,
348
- existsInKvStore: false,
349
433
  };
434
+ if (contentEncoding != null) {
435
+ metadataJson.contentEncoding = contentEncoding;
436
+ }
437
+ if (numChunks > 1) {
438
+ metadataJson.numChunks = String(numChunks);
439
+ }
440
+ batchItems.push({
441
+ size,
442
+ key: variantKey,
443
+ filePath: variantFilePath,
444
+ metadataJson,
445
+ });
350
446
  }
351
- variantMetadatas.set(variant, variantMetadata);
352
- const metadataJson = {
353
- size: String(variantMetadata.size),
354
- hash: variantMetadata.hash,
355
- };
356
- if (variantMetadata.contentEncoding != null) {
357
- metadataJson.contentEncoding = variantMetadata.contentEncoding;
358
- }
359
- if (variantMetadata.numChunks != null) {
360
- metadataJson.numChunks = String(variantMetadata.numChunks);
447
+ else if (verbose) {
448
+ console.log(` ・ Variant "${variantKey}" is not smaller than the original, not uploading.`);
361
449
  }
362
- batch.add({
363
- write: !variantMetadata.existsInKvStore,
364
- size: variantMetadata.size,
365
- key: variantKey,
366
- filePath: variantFilePath,
367
- metadataJson,
368
- });
369
450
  }
370
- // Only keep variants whose file size actually ends up smaller than
371
- // what we started with.
372
- if (variant !== 'original' && variantMetadata.size < baseSize) {
451
+ if (variant !== 'original' && keep) {
373
452
  variantsToKeep.push(variant);
374
453
  }
375
454
  }
376
- assetsIndex[assetKey] = {
377
- key: `sha256:${baseHash}`,
378
- size: baseSize,
379
- contentType: contentTypeTestResult.contentType,
380
- lastModifiedTime,
381
- variants: variantsToKeep,
455
+ return {
456
+ assetKey,
457
+ asset: {
458
+ key: `sha256:${baseHash}`,
459
+ size: baseSize,
460
+ contentType: contentTypeTestResult.contentType,
461
+ lastModifiedTime,
462
+ variants: variantsToKeep,
463
+ },
464
+ batchItems,
382
465
  };
466
+ });
467
+ for (const result of fileResults) {
468
+ if (result == null) {
469
+ continue;
470
+ }
471
+ assetsIndex[result.assetKey] = result.asset;
472
+ for (const batchItem of result.batchItems) {
473
+ batch.add(batchItem);
474
+ }
383
475
  }
384
476
  console.log(`✅ Scan complete.`);
385
- await storageProvider.applyBatch(batch);
477
+ if (existingKeys != null) {
478
+ console.log(` | ${existingVariantCount} variant(s) already in storage, ${batch.storageProviderBatchEntries.length} to upload.`);
479
+ }
480
+ await storageProvider.applyBatch(batch, { existingKeys });
386
481
  // #### INDEX FILE
387
482
  console.log(`🗂️ Saving Index...`);
388
483
  const indexFileKey = `${publishId}_index_${collectionName}`;
@@ -458,5 +553,19 @@ export async function action(actionArgs) {
458
553
  const settingsFilePath = path.resolve(storageContentDir, settingsFileName);
459
554
  await storageProvider.submitStorageEntry(settingsFileKey, settingsFilePath, JSON.stringify(serverSettings));
460
555
  console.log(`✅ Settings have been saved.`);
556
+ if (purgeTarget != null) {
557
+ const surrogateKey = `${publishId}-${collectionName}`;
558
+ for (const environment of purgeTarget.environments) {
559
+ console.log(`Purging surrogate key [${surrogateKey}] on service [${purgeTarget.serviceId}] (${environment})...`);
560
+ const purged = await purgeSurrogateKey(purgeTarget.fastlyApiContext, purgeTarget.serviceId, surrogateKey, true, environment);
561
+ if (purged) {
562
+ console.log('Purged');
563
+ }
564
+ else {
565
+ // The content is published. Only the cached copies may be stale until they expire.
566
+ console.warn(`⚠️ Warning: Failed purging (${environment}). Cached copies may be served until they expire.`);
567
+ }
568
+ }
569
+ }
461
570
  console.log(`🎉 Completed.`);
462
571
  }
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../../src/cli/commands/scaffold/index.ts"],"names":[],"mappings":"AAsEA,MAAM,MAAM,cAAc,GAAG;IAC3B,SAAS,EAAE,MAAM,GAAG,SAAS,CAAC;IAC9B,OAAO,EAAE,MAAM,GAAG,SAAS,CAAC;IAC5B,SAAS,EAAE,MAAM,GAAG,SAAS,CAAC;IAC9B,UAAU,EAAE,MAAM,EAAE,CAAC;IACrB,yBAAyB,EAAE,MAAM,GAAG,SAAS,CAAC;IAC9C,GAAG,EAAE,MAAM,GAAG,SAAS,CAAC;IACxB,YAAY,EAAE,MAAM,GAAG,SAAS,CAAC;IACjC,SAAS,EAAE,MAAM,EAAE,CAAC;IACpB,OAAO,EAAE,MAAM,EAAE,CAAC;IAClB,IAAI,EAAE,MAAM,GAAG,SAAS,CAAC;IACzB,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC;IAC3B,WAAW,EAAE,MAAM,GAAG,SAAS,CAAC;IAChC,SAAS,EAAE,MAAM,GAAG,SAAS,CAAC;IAC9B,SAAS,EAAE,MAAM,GAAG,SAAS,CAAC;IAC9B,WAAW,EAAE,MAAM,GAAG,SAAS,CAAC;IAChC,WAAW,EAAE,MAAM,GAAG,SAAS,CAAC;IAChC,QAAQ,EAAE,MAAM,GAAG,SAAS,CAAC;IAC7B,QAAQ,EAAE,MAAM,GAAG,SAAS,CAAC;IAC7B,UAAU,EAAE,MAAM,GAAG,SAAS,CAAC;CAChC,CAAC;AA0TF,wBAAsB,MAAM,CAAC,UAAU,EAAE,MAAM,EAAE,iBAopBhD"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../../src/cli/commands/scaffold/index.ts"],"names":[],"mappings":"AAuEA,MAAM,MAAM,cAAc,GAAG;IAC3B,SAAS,EAAE,MAAM,GAAG,SAAS,CAAC;IAC9B,OAAO,EAAE,MAAM,GAAG,SAAS,CAAC;IAC5B,SAAS,EAAE,MAAM,GAAG,SAAS,CAAC;IAC9B,UAAU,EAAE,MAAM,EAAE,CAAC;IACrB,yBAAyB,EAAE,MAAM,GAAG,SAAS,CAAC;IAC9C,GAAG,EAAE,MAAM,GAAG,SAAS,CAAC;IACxB,YAAY,EAAE,MAAM,GAAG,SAAS,CAAC;IACjC,SAAS,EAAE,MAAM,EAAE,CAAC;IACpB,OAAO,EAAE,MAAM,EAAE,CAAC;IAClB,IAAI,EAAE,MAAM,GAAG,SAAS,CAAC;IACzB,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC;IAC3B,WAAW,EAAE,MAAM,GAAG,SAAS,CAAC;IAChC,SAAS,EAAE,MAAM,GAAG,SAAS,CAAC;IAC9B,SAAS,EAAE,MAAM,GAAG,SAAS,CAAC;IAC9B,WAAW,EAAE,MAAM,GAAG,SAAS,CAAC;IAChC,WAAW,EAAE,MAAM,GAAG,SAAS,CAAC;IAChC,QAAQ,EAAE,MAAM,GAAG,SAAS,CAAC;IAC7B,QAAQ,EAAE,MAAM,GAAG,SAAS,CAAC;IAC7B,UAAU,EAAE,MAAM,GAAG,SAAS,CAAC;CAChC,CAAC;AA0TF,wBAAsB,MAAM,CAAC,UAAU,EAAE,MAAM,EAAE,iBAyqBhD"}
@@ -12,7 +12,7 @@ import * as fs from 'node:fs';
12
12
  import { parseCommandLine } from '../../util/args.js';
13
13
  import { dotRelative, rootRelative } from '../../util/files.js';
14
14
  import { findComputeJsStaticPublisherVersion } from '../../util/package.js';
15
- import { resolveS3Hostname } from '../../util/s3.js';
15
+ import { findHostnameForAwsS3RegionAndBucket } from '../../util/s3.js';
16
16
  function help() {
17
17
  console.log(`\
18
18
 
@@ -26,8 +26,9 @@ Description:
26
26
  management mode.
27
27
 
28
28
  Options:
29
- --storage-mode <mode> (required) Storage mode for content storage.
30
- Can be "kv-store" or "s3".
29
+ --storage-mode <mode> Storage mode for content storage.
30
+ Can be "kv-store" or "s3" (BETA).
31
+ (default: kv-store)
31
32
  If --storage-mode=kv-store, then:
32
33
  --kv-store-name <name> (required) Name of the KV Store.
33
34
 
@@ -39,8 +40,8 @@ Options:
39
40
  --root-dir <path> (required) Path to static content (e.g., ./public)
40
41
  -o, --output <dir> Output directory for Compute app (default: ./compute-js)
41
42
  --static-publisher-working-dir <dir> Working directory for build artifacts (default: <output>/static-publisher)
42
- --publish-id <id> Advanced. Prefix for KV keys (default: "default")
43
43
  (default: ./compute-js/static-publisher)
44
+ --publish-id <id> Advanced. Prefix for KV keys (default: "default")
44
45
 
45
46
  Compute Service Metadata:
46
47
  --name <name> App name (for fastly.toml)
@@ -201,7 +202,7 @@ function buildOptions(packageJson, commandLineOptions) {
201
202
  }
202
203
  }
203
204
  {
204
- let autoExt = [];
205
+ let autoExt;
205
206
  const autoExtValue = commandLineOptions['auto-ext'];
206
207
  const asArray = Array.isArray(autoExtValue) ? autoExtValue : [autoExtValue];
207
208
  if (asArray.every((x) => typeof x === 'string')) {
@@ -334,8 +335,8 @@ function processPublicDirToken(filepath, publicDir) {
334
335
  export async function action(actionArgs) {
335
336
  const optionDefinitions = [
336
337
  { name: 'verbose', type: Boolean },
337
- // Required. Storage mode for content storage. Can be "kv-store" or "s3".
338
- { name: 'storage-mode', type: String, },
338
+ // Storage mode for content storage. Can be "kv-store" or "s3".
339
+ { name: 'storage-mode', type: String, defaultValue: 'kv-store', },
339
340
  // If storage-mode=kv-store, then:
340
341
  // Required. The name of a Fastly KV Store to hold the content assets.
341
342
  // It is also added to the fastly.toml that is generated.
@@ -504,6 +505,7 @@ export async function action(actionArgs) {
504
505
  else if (!fs.existsSync(spaFilename)) {
505
506
  console.log(`⚠️ Warning: Ignoring specified SPA file '${SPA}' does not exist.`);
506
507
  console.log(` * ${rootRelative(spaFilename)} does not exist.`);
508
+ spaFilename = undefined;
507
509
  }
508
510
  }
509
511
  const NOT_FOUND_PAGE = options.notFoundPage;
@@ -520,6 +522,7 @@ export async function action(actionArgs) {
520
522
  else if (!fs.existsSync(notFoundPageFilename)) {
521
523
  console.log(`⚠️ Warning: Ignoring specified Not Found file '${NOT_FOUND_PAGE}' as it does not exist.`);
522
524
  console.log(` * ${rootRelative(notFoundPageFilename)} does not exist.`);
525
+ notFoundPageFilename = undefined;
523
526
  }
524
527
  }
525
528
  const autoIndex = options.autoIndex;
@@ -540,7 +543,7 @@ export async function action(actionArgs) {
540
543
  const fastlyServiceId = options.serviceId;
541
544
  const storageMode = options.storageMode;
542
545
  if (!(storageMode === 'kv-store' || storageMode === 's3')) {
543
- console.error(`❌ required parameter --storage-mode must be set to 'kv-store' or 's3'.`);
546
+ console.error(`❌ parameter --storage-mode must be set to 'kv-store' or 's3'.`);
544
547
  process.exitCode = 1;
545
548
  return;
546
549
  }
@@ -569,7 +572,11 @@ export async function action(actionArgs) {
569
572
  }
570
573
  let s3Endpoint = options.s3Endpoint;
571
574
  if (s3Endpoint == null || s3Endpoint === '') {
572
- s3Endpoint = await resolveS3Hostname(s3Region, s3Bucket);
575
+ // If endpoint is not presented, we assume it's from AWS,
576
+ // and ask the SDK what the hostname would be.
577
+ // This is required because we need to add the hostname as a
578
+ // backend in the Compute service.
579
+ s3Endpoint = await findHostnameForAwsS3RegionAndBucket(s3Region, s3Bucket);
573
580
  if (s3Endpoint) {
574
581
  console.log('✅ S3 endpoint resolved:', s3Endpoint);
575
582
  }
@@ -614,7 +621,7 @@ export async function action(actionArgs) {
614
621
  console.log('KV Store Name :', kvStoreName);
615
622
  }
616
623
  else if (storageMode === 's3') {
617
- console.log('Storage Name : S3-compatible storage');
624
+ console.log('Storage Name : S3 (or compatible) storage (BETA)');
618
625
  console.log('S3 Region :', s3Region);
619
626
  console.log('S3 Bucket :', s3Bucket);
620
627
  console.log('S3 Endpoint :', String(s3EndpointUrl));
@@ -662,7 +669,7 @@ export async function action(actionArgs) {
662
669
  packageJsonScripts['fastly:publish'] = 'npx @fastly/compute-js-static-publish publish-content';
663
670
  }
664
671
  else if (storageMode === 's3') {
665
- packageJsonScripts['publish'] = 'npx @fastly/compute-js-static-publish publish-content --local';
672
+ packageJsonScripts['s3:publish'] = 'npx @fastly/compute-js-static-publish publish-content';
666
673
  }
667
674
  resourceFiles['package.json'] = JSON.stringify({
668
675
  name,
@@ -671,11 +678,11 @@ export async function action(actionArgs) {
671
678
  author,
672
679
  type: 'module',
673
680
  devDependencies: {
674
- "@fastly/cli": "^12.0.0",
681
+ "@fastly/cli": "^16.0.0",
675
682
  '@fastly/compute-js-static-publish': computeJsStaticPublisherVersion,
676
683
  },
677
684
  dependencies: {
678
- '@fastly/js-compute': '^3.26.0',
685
+ '@fastly/js-compute': '^4.0.0',
679
686
  },
680
687
  engines: {
681
688
  node: '>=20.11.0',
@@ -689,10 +696,15 @@ export async function action(actionArgs) {
689
696
  if (storageMode === 'kv-store') {
690
697
  const localServerKvStorePath = dotRelative(computeJsDir, path.resolve(staticPublisherWorkingDir, 'kvstore.json'));
691
698
  fastlyTomlLocalServer = /* language=text */ `\
699
+ [local_server]
700
+
692
701
  [local_server.kv_stores]
693
702
  ${kvStoreName} = { file = "${localServerKvStorePath}", format = "json" }
694
703
  `;
695
704
  fastlyTomlSetup = /* language=text */ `\
705
+ [setup]
706
+
707
+ [setup.kv_stores]
696
708
  [setup.kv_stores.${kvStoreName}]
697
709
  `;
698
710
  // kvstore.json
@@ -700,24 +712,37 @@ ${kvStoreName} = { file = "${localServerKvStorePath}", format = "json" }
700
712
  }
701
713
  else if (storageMode === 's3') {
702
714
  fastlyTomlLocalServer = /* language=text */ `\
715
+ [local_server]
716
+
703
717
  [local_server.secret_stores]
704
- [[local_server.secret_stores.AWS_CREDENTIALS]]
705
- key = "AWS_ACCESS_KEY_ID"
706
- env = "AWS_ACCESS_KEY_ID"
707
- [[local_server.secret_stores.AWS_CREDENTIALS]]
708
- key = "AWS_SECRET_ACCESS_KEY"
709
- env = "AWS_SECRET_ACCESS_KEY"
718
+ [[local_server.secret_stores.S3_CREDENTIALS]]
719
+ key = "S3_ACCESS_KEY_ID"
720
+ env = "S3_ACCESS_KEY_ID"
721
+ [[local_server.secret_stores.S3_CREDENTIALS]]
722
+ key = "S3_SECRET_ACCESS_KEY"
723
+ env = "S3_SECRET_ACCESS_KEY"
710
724
 
711
725
  [local_server.backends]
712
- [local_server.backends.aws]
726
+ [local_server.backends.s3_storage]
713
727
  url = "${String(s3EndpointUrl)}"
714
728
  override_host = "${s3EndpointUrl.hostname}"
715
729
  `;
716
730
  fastlyTomlSetup = /* language=text */ `\
717
- [setup.backends.aws]
731
+ [setup]
732
+
733
+ [setup.backends]
734
+ [setup.backends.s3_storage]
718
735
  address = "${s3EndpointUrl.hostname}"
719
736
  description = "S3 API endpoint"
720
737
  port = 443
738
+ [setup.secret_stores]
739
+ [setup.secret_stores.S3_CREDENTIALS]
740
+ description = "Credentials for S3 storage"
741
+ [setup.secret_stores.S3_CREDENTIALS.items]
742
+ [setup.secret_stores.S3_CREDENTIALS.items.S3_ACCESS_KEY_ID]
743
+ description = "Access Key ID"
744
+ [setup.secret_stores.S3_CREDENTIALS.items.S3_SECRET_ACCESS_KEY]
745
+ description = "Secret Access Key"
721
746
  `;
722
747
  }
723
748
  resourceFiles['fastly.toml'] = /* language=text */ `\
@@ -824,7 +849,8 @@ const config = {
824
849
  // excludeDotFiles: true,
825
850
  // includeWellKnown: true,
826
851
  // assetInclusionTest: (assetKey) => true,
827
- // contentCompression: [ 'br', 'gzip' ],
852
+ // contentCompression: [ 'br', 'gzip' ],
853
+ // brotliQuality: 11,
828
854
  // contentTypes: [
829
855
  // { test: /.custom$/, contentType: 'application/x-custom', text: false },
830
856
  // ],
@@ -906,25 +932,21 @@ To publish your content to your S3-compatible bucket
906
932
  Bucket: ${s3Bucket}
907
933
  Endpoint: ${String(s3EndpointUrl)}
908
934
 
909
- Using an AWS profile set with "aws configure", type:
910
- cd ${COMPUTE_JS_DIR}
911
- AWS_PROFILE=xxxx npm run publish
912
-
913
- Using AWS IAM credentials, type:
935
+ Using an access key ID and secret access key for S3, type:
914
936
  cd ${COMPUTE_JS_DIR}
915
- AWS_ACCESS_KEY_ID=xxxx AWS_SECRET_ACCESS_KEY=xxxx npm run publish
937
+ S3_ACCESS_KEY_ID=xxxx S3_SECRET_ACCESS_KEY=xxxx npm run s3:publish
916
938
 
917
939
  To run your Compute application locally
918
940
 
919
941
  Run the following commands:
920
942
  cd ${COMPUTE_JS_DIR}
921
- AWS_ACCESS_KEY_ID=xxxx AWS_SECRET_ACCESS_KEY=xxxx npm run dev:start
943
+ S3_ACCESS_KEY_ID=xxxx S3_SECRET_ACCESS_KEY=xxxx npm run dev:start
922
944
 
923
945
  To build and deploy to your Compute service:
924
946
 
925
- Create a Secret Store in your account named AWS_CREDENTIALS, and set the following values:
926
- AWS_ACCESS_KEY_ID: xxxx
927
- AWS_SECRET_ACCESS_KEY: xxxx
947
+ Create a Secret Store in your account named S3_CREDENTIALS, and set the following values:
948
+ S3_ACCESS_KEY_ID: xxxx
949
+ S3_SECRET_ACCESS_KEY: xxxx
928
950
 
929
951
  Run the following commands:
930
952
  cd ${COMPUTE_JS_DIR}
@@ -1,3 +1,4 @@
1
+ import type { CompressOptions } from './index.js';
1
2
  export declare const key = "br";
2
- export declare function compressTo(src: string, dest: string): Promise<void>;
3
+ export declare function compressTo(src: string, dest: string, options?: CompressOptions): Promise<void>;
3
4
  //# sourceMappingURL=brotli.d.ts.map