@fastly/compute-js-static-publish 8.0.0-rc.1 → 8.0.0

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 (53) hide show
  1. package/build/cli/cli/commands/manage/clean.d.ts.map +1 -1
  2. package/build/cli/cli/commands/manage/clean.js +1 -0
  3. package/build/cli/cli/commands/manage/collections/delete.d.ts.map +1 -1
  4. package/build/cli/cli/commands/manage/collections/delete.js +39 -2
  5. package/build/cli/cli/commands/manage/collections/index.d.ts.map +1 -1
  6. package/build/cli/cli/commands/manage/collections/index.js +1 -0
  7. package/build/cli/cli/commands/manage/collections/list.d.ts.map +1 -1
  8. package/build/cli/cli/commands/manage/collections/list.js +10 -1
  9. package/build/cli/cli/commands/manage/collections/promote.d.ts.map +1 -1
  10. package/build/cli/cli/commands/manage/collections/promote.js +1 -0
  11. package/build/cli/cli/commands/manage/collections/update-expiration.d.ts.map +1 -1
  12. package/build/cli/cli/commands/manage/collections/update-expiration.js +1 -0
  13. package/build/cli/cli/commands/manage/index.d.ts.map +1 -1
  14. package/build/cli/cli/commands/manage/index.js +1 -0
  15. package/build/cli/cli/commands/manage/publish-content.d.ts.map +1 -1
  16. package/build/cli/cli/commands/manage/publish-content.js +69 -74
  17. package/build/cli/cli/commands/scaffold/index.d.ts.map +1 -1
  18. package/build/cli/cli/commands/scaffold/index.js +32 -13
  19. package/build/cli/cli/storage/s3-storage-provider.d.ts +1 -0
  20. package/build/cli/cli/storage/s3-storage-provider.d.ts.map +1 -1
  21. package/build/cli/cli/storage/s3-storage-provider.js +8 -4
  22. package/build/cli/cli/util/purge.d.ts +1 -0
  23. package/build/cli/cli/util/purge.d.ts.map +1 -1
  24. package/build/cli/cli/util/purge.js +21 -6
  25. package/build/cli/cli/util/service-id.js +1 -1
  26. package/build/cli/cli/util/variants.d.ts +7 -0
  27. package/build/cli/cli/util/variants.d.ts.map +1 -1
  28. package/build/cli/cli/util/variants.js +17 -0
  29. package/build/cli/models/config/publisher-server-config.d.ts +1 -0
  30. package/build/cli/models/config/publisher-server-config.d.ts.map +1 -1
  31. package/build/cli/models/server/index.d.ts +4 -0
  32. package/build/cli/models/server/index.d.ts.map +1 -1
  33. package/build/cli/models/server/index.js +34 -1
  34. package/build/server/models/config/publisher-server-config.d.ts +1 -0
  35. package/build/server/models/config/publisher-server-config.d.ts.map +1 -1
  36. package/build/server/models/server/index.d.ts +4 -0
  37. package/build/server/models/server/index.d.ts.map +1 -1
  38. package/build/server/models/server/index.js +34 -1
  39. package/build/server/server/collection-selector/from-cookie.d.ts.map +1 -1
  40. package/build/server/server/collection-selector/from-cookie.js +28 -2
  41. package/build/server/server/publisher-server/index.d.ts +0 -1
  42. package/build/server/server/publisher-server/index.d.ts.map +1 -1
  43. package/build/server/server/publisher-server/index.js +62 -52
  44. package/build/server/server/publisher-server/response-cache.d.ts +13 -0
  45. package/build/server/server/publisher-server/response-cache.d.ts.map +1 -1
  46. package/build/server/server/publisher-server/response-cache.js +54 -0
  47. package/build/server/server/storage/s3-storage-provider.d.ts +6 -1
  48. package/build/server/server/storage/s3-storage-provider.d.ts.map +1 -1
  49. package/build/server/server/storage/s3-storage-provider.js +12 -7
  50. package/build/server/server/util/body-length.d.ts +5 -0
  51. package/build/server/server/util/body-length.d.ts.map +1 -0
  52. package/build/server/server/util/body-length.js +63 -0
  53. package/package.json +3 -3
@@ -27,15 +27,15 @@ export function parsePurgeEnvironments(values) {
27
27
  }
28
28
  return result.length > 0 ? result : ['production'];
29
29
  }
30
- // Finds the service to purge after publishing, so that it stops serving cached
31
- // copies of the collection. Returns null, and logs why, if the purge is skipped.
32
- // Throws if a Service ID is found but an API token is not, so that this fails
33
- // before anything is uploaded.
30
+ // Finds the service to purge after a change to a collection, so that it stops
31
+ // serving cached copies of the collection. Returns null, and logs why, if the
32
+ // purge is skipped. Throws if a Service ID is found but an API token is not, so
33
+ // that a command can fail before it changes storage.
34
34
  export function loadPurgeTarget(params) {
35
35
  // Check the option even when the purge is skipped, so that a typo is reported.
36
36
  const environments = parsePurgeEnvironments(params.purgeEnvironments);
37
37
  if (params.localMode) {
38
- console.log(`- Local mode: will skip purge step after publish.`);
38
+ console.log(`- Local mode: will skip the purge.`);
39
39
  return null;
40
40
  }
41
41
  const serviceIdResult = loadServiceId({
@@ -43,7 +43,7 @@ export function loadPurgeTarget(params) {
43
43
  fastlyTomlPath: path.resolve(params.computeAppDir, 'fastly.toml'),
44
44
  });
45
45
  if (serviceIdResult == null) {
46
- console.log(`- Service ID not found (--fastly-service-id, FASTLY_SERVICE_ID, or fastly.toml). Will skip purge step after publish.`);
46
+ console.log(`- Service ID not found (--fastly-service-id, FASTLY_SERVICE_ID, or fastly.toml). Will skip the purge.`);
47
47
  return null;
48
48
  }
49
49
  console.log(`✔️ Service ID from ${serviceIdResult.source}: ${serviceIdResult.serviceId}`);
@@ -81,3 +81,18 @@ export async function purgeSurrogateKey(fastlyApiContext, fastlyServiceId, surro
81
81
  }
82
82
  return true;
83
83
  }
84
+ // Purges the cached responses of a collection in each environment of the purge
85
+ // target. A failed purge is a warning, because the change to storage is done.
86
+ export async function purgeCollection(purgeTarget, publishId, collectionName) {
87
+ const surrogateKey = `${publishId}-${collectionName}`;
88
+ for (const environment of purgeTarget.environments) {
89
+ console.log(`Purging surrogate key [${surrogateKey}] on service [${purgeTarget.serviceId}] (${environment})...`);
90
+ const purged = await purgeSurrogateKey(purgeTarget.fastlyApiContext, purgeTarget.serviceId, surrogateKey, true, environment);
91
+ if (purged) {
92
+ console.log('Purged');
93
+ }
94
+ else {
95
+ console.warn(`⚠️ Warning: Failed purging (${environment}). Cached copies may be served until they expire.`);
96
+ }
97
+ }
98
+ }
@@ -4,7 +4,7 @@
4
4
  */
5
5
  import fs from 'node:fs';
6
6
  import { readServiceId } from './fastly-toml.js';
7
- // Finds the Fastly Service ID to purge after publishing. Checks, in order:
7
+ // Finds the Fastly Service ID to purge after a change to a collection. Checks, in order:
8
8
  // 1. The command line (--fastly-service-id)
9
9
  // 2. The FASTLY_SERVICE_ID environment variable
10
10
  // 3. service_id in fastly.toml
@@ -1,5 +1,12 @@
1
1
  import { type ContentCompressionTypes } from '../../models/compression/index.js';
2
2
  import { type CompressOptions } from '../compression/index.js';
3
3
  export type Variants = 'original' | ContentCompressionTypes;
4
+ export declare class OncePerKey<T> {
5
+ private readonly promises;
6
+ run(key: string, fn: () => Promise<T>): {
7
+ promise: Promise<T>;
8
+ first: boolean;
9
+ };
10
+ }
4
11
  export declare function ensureVariantFileExists(variantFilePath: string, variant: Variants, file: string, verbose: boolean, compressOptions?: CompressOptions): Promise<void>;
5
12
  //# sourceMappingURL=variants.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"variants.d.ts","sourceRoot":"","sources":["../../../../src/cli/util/variants.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,KAAK,uBAAuB,EAAE,MAAM,mCAAmC,CAAC;AACjF,OAAO,EAAQ,KAAK,eAAe,EAAE,MAAM,yBAAyB,CAAC;AAGrE,MAAM,MAAM,QAAQ,GAAG,UAAU,GAAG,uBAAuB,CAAC;AAE5D,wBAAsB,uBAAuB,CAC3C,eAAe,EAAE,MAAM,EACvB,OAAO,EAAE,QAAQ,EACjB,IAAI,EAAE,MAAM,EACZ,OAAO,EAAE,OAAO,EAChB,eAAe,GAAE,eAAoB,iBA6BtC"}
1
+ {"version":3,"file":"variants.d.ts","sourceRoot":"","sources":["../../../../src/cli/util/variants.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,KAAK,uBAAuB,EAAE,MAAM,mCAAmC,CAAC;AACjF,OAAO,EAAQ,KAAK,eAAe,EAAE,MAAM,yBAAyB,CAAC;AAGrE,MAAM,MAAM,QAAQ,GAAG,UAAU,GAAG,uBAAuB,CAAC;AAK5D,qBAAa,UAAU,CAAC,CAAC;IACvB,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAiC;IAE1D,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,GAAG;QAAE,OAAO,EAAE,OAAO,CAAC,CAAC,CAAC,CAAC;QAAC,KAAK,EAAE,OAAO,CAAA;KAAE;CAShF;AAED,wBAAsB,uBAAuB,CAC3C,eAAe,EAAE,MAAM,EACvB,OAAO,EAAE,QAAQ,EACjB,IAAI,EAAE,MAAM,EACZ,OAAO,EAAE,OAAO,EAChB,eAAe,GAAE,eAAoB,iBA6BtC"}
@@ -5,6 +5,23 @@
5
5
  import fs from 'node:fs';
6
6
  import { algs } from '../compression/index.js';
7
7
  import { rootRelative } from './files.js';
8
+ // Runs an async function one time for each key. The first call for a key
9
+ // starts the function and stores its promise before it returns. Later calls
10
+ // for the same key, also concurrent calls, get the same promise.
11
+ export class OncePerKey {
12
+ constructor() {
13
+ this.promises = new Map();
14
+ }
15
+ run(key, fn) {
16
+ let promise = this.promises.get(key);
17
+ if (promise != null) {
18
+ return { promise, first: false };
19
+ }
20
+ promise = fn();
21
+ this.promises.set(key, promise);
22
+ return { promise, first: true };
23
+ }
24
+ }
8
25
  export async function ensureVariantFileExists(variantFilePath, variant, file, verbose, compressOptions = {}) {
9
26
  // Compress/prepare the asset if it doesn't already exist
10
27
  // We disregard chunked copies of the file and only check for the existence
@@ -1,5 +1,6 @@
1
1
  import { type ContentCompressionTypes } from '../compression/index.js';
2
2
  export type PublisherServerConfig = {
3
+ /** @deprecated A future version will remove this setting. */
3
4
  publicDirPrefix?: string;
4
5
  staticItems?: string[] | string | false | null;
5
6
  allowedEncodings?: ContentCompressionTypes[];
@@ -1 +1 @@
1
- {"version":3,"file":"publisher-server-config.d.ts","sourceRoot":"","sources":["../../../../src/models/config/publisher-server-config.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,KAAK,uBAAuB,EAAE,MAAM,yBAAyB,CAAC;AAGvE,MAAM,MAAM,qBAAqB,GAAG;IAGlC,eAAe,CAAC,EAAE,MAAM,CAAC;IAQzB,WAAW,CAAC,EAAE,MAAM,EAAE,GAAG,MAAM,GAAG,K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AAG,IAAI,CAAC;IAI3C,SAAS,CAAC,EAAE,MAAM,EAAE,GAAG,MAAM,GAAG,KAAK,GAAG,IAAI,CAAC;CAC9C,CAAC;AAEF,MAAM,MAAM,+BAA+B,GAAG;IAC5C,eAAe,EAAE,MAAM,CAAC;IACxB,WAAW,EAAE,MAAM,EAAE,CAAC;IACtB,gBAAgB,EAAE,uBAAuB,EAAE,CAAC;IAC5C,OAAO,EAAE,MAAM,GAAG,IAAI,CAAC;IACvB,gBAAgB,EAAE,MAAM,GAAG,IAAI,CAAC;IAChC,OAAO,EAAE,MAAM,EAAE,CAAC;IAClB,SAAS,EAAE,MAAM,EAAE,CAAC;CACrB,CAAC"}
@@ -1,7 +1,11 @@
1
1
  export type IndexMetadata = {
2
2
  publishedTime?: number;
3
3
  expirationTime?: number;
4
+ requires?: string[];
5
+ otherFields?: Record<string, string>;
4
6
  };
7
+ export declare const SUPPORTED_INDEX_FEATURES: readonly string[];
5
8
  export declare function encodeIndexMetadata(indexMetadata: IndexMetadata): Record<string, string>;
6
9
  export declare function decodeIndexMetadata(obj: Record<string, string> | undefined): IndexMetadata | null;
10
+ export declare function getUnsupportedIndexFeatures(indexMetadata: IndexMetadata, supportedFeatures?: readonly string[]): string[];
7
11
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/models/server/index.ts"],"names":[],"mappings":"AAOA,MAAM,MAAM,aAAa,GAAG;IAC1B,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,cAAc,CAAC,EAAE,MAAM,CAAC;CACzB,CAAC;AAEF,wBAAgB,mBAAmB,CAAC,aAAa,EAAE,aAAa,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAYxF;AAED,wBAAgB,mBAAmB,CAAC,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,SAAS,GAAG,aAAa,GAAG,IAAI,CAUjG"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/models/server/index.ts"],"names":[],"mappings":"AAOA,MAAM,MAAM,aAAa,GAAG;IAC1B,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,cAAc,CAAC,EAAE,MAAM,CAAC;IAIxB,QAAQ,CAAC,EAAE,MAAM,EAAE,CAAC;IAGpB,WAAW,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;CACtC,CAAC;AAMF,eAAO,MAAM,wBAAwB,EAAE,SAAS,MAAM,EAAO,CAAC;AAI9D,wBAAgB,mBAAmB,CAAC,aAAa,EAAE,aAAa,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAqBxF;AAED,wBAAgB,mBAAmB,CAAC,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,SAAS,GAAG,aAAa,GAAG,IAAI,CA2BjG;AAGD,wBAAgB,2BAA2B,CACzC,aAAa,EAAE,aAAa,EAC5B,iBAAiB,GAAE,SAAS,MAAM,EAA6B,GAC9D,MAAM,EAAE,CAEV"}
@@ -3,14 +3,28 @@
3
3
  * Licensed under the MIT license. See LICENSE file for details.
4
4
  */
5
5
  import { getMetadataFieldValue } from '../metadata/index.js';
6
+ // The features that this version of PublisherServer supports. A server does
7
+ // not serve a collection that requires a feature that is not in this list.
8
+ // A feature name must not contain a comma, because the metadata uses commas to
9
+ // separate the names. Use short kebab-case names, for example 'my-feature'.
10
+ export const SUPPORTED_INDEX_FEATURES = [];
11
+ const KNOWN_FIELDS = ['publishedTime', 'expirationTime', 'requires'];
6
12
  export function encodeIndexMetadata(indexMetadata) {
7
- const result = {};
13
+ const result = { ...indexMetadata.otherFields };
8
14
  if (indexMetadata.publishedTime != null && !isNaN(indexMetadata.publishedTime)) {
9
15
  result['publishedTime'] = String(indexMetadata.publishedTime);
10
16
  }
11
17
  if (indexMetadata.expirationTime != null && !isNaN(indexMetadata.expirationTime)) {
12
18
  result['expirationTime'] = String(indexMetadata.expirationTime);
13
19
  }
20
+ if (indexMetadata.requires != null && indexMetadata.requires.length > 0) {
21
+ for (const feature of indexMetadata.requires) {
22
+ if (feature.includes(',')) {
23
+ throw new Error(`Feature name '${feature}' must not contain a comma.`);
24
+ }
25
+ }
26
+ result['requires'] = indexMetadata.requires.join(',');
27
+ }
14
28
  return result;
15
29
  }
16
30
  export function decodeIndexMetadata(obj) {
@@ -19,8 +33,27 @@ export function decodeIndexMetadata(obj) {
19
33
  }
20
34
  const publishedTime = parseFloat(getMetadataFieldValue(obj, 'publishedTime'));
21
35
  const expirationTime = parseFloat(getMetadataFieldValue(obj, 'expirationTime'));
36
+ const requiresValue = getMetadataFieldValue(obj, 'requires');
37
+ const requires = requiresValue != null
38
+ ? String(requiresValue).split(',').map(x => x.trim()).filter(x => x !== '')
39
+ : [];
40
+ // S3 makes the metadata keys lowercase, so compare the keys without case.
41
+ const knownKeys = KNOWN_FIELDS.map(x => x.toLowerCase());
42
+ let otherFields;
43
+ for (const [key, value] of Object.entries(obj)) {
44
+ if (!knownKeys.includes(key.toLowerCase())) {
45
+ otherFields ??= {};
46
+ otherFields[key] = String(value);
47
+ }
48
+ }
22
49
  return {
23
50
  publishedTime: !isNaN(publishedTime) ? publishedTime : undefined,
24
51
  expirationTime: !isNaN(expirationTime) ? expirationTime : undefined,
52
+ requires: requires.length > 0 ? requires : undefined,
53
+ otherFields,
25
54
  };
26
55
  }
56
+ // Returns the features in requires that are not in supportedFeatures.
57
+ export function getUnsupportedIndexFeatures(indexMetadata, supportedFeatures = SUPPORTED_INDEX_FEATURES) {
58
+ return (indexMetadata.requires ?? []).filter(x => !supportedFeatures.includes(x));
59
+ }
@@ -1,5 +1,6 @@
1
1
  import { type ContentCompressionTypes } from '../compression/index.js';
2
2
  export type PublisherServerConfig = {
3
+ /** @deprecated A future version will remove this setting. */
3
4
  publicDirPrefix?: string;
4
5
  staticItems?: string[] | string | false | null;
5
6
  allowedEncodings?: ContentCompressionTypes[];
@@ -1 +1 @@
1
- {"version":3,"file":"publisher-server-config.d.ts","sourceRoot":"","sources":["../../../../src/models/config/publisher-server-config.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,KAAK,uBAAuB,EAAE,MAAM,yBAAyB,CAAC;AAGvE,MAAM,MAAM,qBAAqB,GAAG;IAGlC,eAAe,CAAC,EAAE,MAAM,CAAC;IAQzB,WAAW,CAAC,EAAE,MAAM,EAAE,GAAG,MAAM,GAAG,KAAK,GAAG,IAAI,CAAC;IAK/C,gBAAgB,CAAC,EAAE,uBAAuB,EAAE,CAAC;IAI7C,OAAO,CAAC,EAAE,MAAM,GAAG,KAAK,GAAG,IAAI,CAAC;IAIhC,gBAAgB,CAAC,EAAE,MAAM,GAAG,KAAK,GAAG,IAAI,CAAC;IAIzC,OAAO,CAAC,EAAE,MAAM,EAAE,GAAG,MAAM,GAAG,KAAK,GAAG,IAAI,CAAC;IAI3C,SAAS,CAAC,EAAE,MAAM,EAAE,GAAG,MAAM,GAAG,KAAK,GAAG,IAAI,CAAC;CAC9C,CAAC;AAEF,MAAM,MAAM,+BAA+B,GAAG;IAC5C,eAAe,EAAE,MAAM,CAAC;IACxB,WAAW,EAAE,MAAM,EAAE,CAAC;IACtB,gBAAgB,EAAE,uBAAuB,EAAE,CAAC;IAC5C,OAAO,EAAE,MAAM,GAAG,IAAI,CAAC;IACvB,gBAAgB,EAAE,MAAM,GAAG,IAAI,CAAC;IAChC,OAAO,EAAE,MAAM,EAAE,CAAC;IAClB,SAAS,EAAE,MAAM,EAAE,CAAC;CACrB,CAAC"}
1
+ {"version":3,"file":"publisher-server-config.d.ts","sourceRoot":"","sources":["../../../../src/models/config/publisher-server-config.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,KAAK,uBAAuB,EAAE,MAAM,yBAAyB,CAAC;AAGvE,MAAM,MAAM,qBAAqB,GAAG;IAGlC,6DAA6D;IAC7D,eAAe,CAAC,EAAE,MAAM,CAAC;IAQzB,WAAW,CAAC,EAAE,MAAM,EAAE,GAAG,MAAM,GAAG,KAAK,GAAG,IAAI,CAAC;IAK/C,gBAAgB,CAAC,EAAE,uBAAuB,EAAE,CAAC;IAI7C,OAAO,CAAC,EAAE,MAAM,GAAG,KAAK,GAAG,IAAI,CAAC;IAIhC,gBAAgB,CAAC,EAAE,MAAM,GAAG,KAAK,GAAG,IAAI,CAAC;IAIzC,OAAO,CAAC,EAAE,MAAM,EAAE,GAAG,MAAM,GAAG,KAAK,GAAG,IAAI,CAAC;IAI3C,SAAS,CAAC,EAAE,MAAM,EAAE,GAAG,MAAM,GAAG,KAAK,GAAG,IAAI,CAAC;CAC9C,CAAC;AAEF,MAAM,MAAM,+BAA+B,GAAG;IAC5C,eAAe,EAAE,MAAM,CAAC;IACxB,WAAW,EAAE,MAAM,EAAE,CAAC;IACtB,gBAAgB,EAAE,uBAAuB,EAAE,CAAC;IAC5C,OAAO,EAAE,MAAM,GAAG,IAAI,CAAC;IACvB,gBAAgB,EAAE,MAAM,GAAG,IAAI,CAAC;IAChC,OAAO,EAAE,MAAM,EAAE,CAAC;IAClB,SAAS,EAAE,MAAM,EAAE,CAAC;CACrB,CAAC"}
@@ -1,7 +1,11 @@
1
1
  export type IndexMetadata = {
2
2
  publishedTime?: number;
3
3
  expirationTime?: number;
4
+ requires?: string[];
5
+ otherFields?: Record<string, string>;
4
6
  };
7
+ export declare const SUPPORTED_INDEX_FEATURES: readonly string[];
5
8
  export declare function encodeIndexMetadata(indexMetadata: IndexMetadata): Record<string, string>;
6
9
  export declare function decodeIndexMetadata(obj: Record<string, string> | undefined): IndexMetadata | null;
10
+ export declare function getUnsupportedIndexFeatures(indexMetadata: IndexMetadata, supportedFeatures?: readonly string[]): string[];
7
11
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/models/server/index.ts"],"names":[],"mappings":"AAOA,MAAM,MAAM,aAAa,GAAG;IAC1B,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,cAAc,CAAC,EAAE,MAAM,CAAC;CACzB,CAAC;AAEF,wBAAgB,mBAAmB,CAAC,aAAa,EAAE,aAAa,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAYxF;AAED,wBAAgB,mBAAmB,CAAC,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,SAAS,GAAG,aAAa,GAAG,IAAI,CAUjG"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/models/server/index.ts"],"names":[],"mappings":"AAOA,MAAM,MAAM,aAAa,GAAG;IAC1B,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,cAAc,CAAC,EAAE,MAAM,CAAC;IAIxB,QAAQ,CAAC,EAAE,MAAM,EAAE,CAAC;IAGpB,WAAW,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;CACtC,CAAC;AAMF,eAAO,MAAM,wBAAwB,EAAE,SAAS,MAAM,EAAO,CAAC;AAI9D,wBAAgB,mBAAmB,CAAC,aAAa,EAAE,aAAa,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAqBxF;AAED,wBAAgB,mBAAmB,CAAC,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,SAAS,GAAG,aAAa,GAAG,IAAI,CA2BjG;AAGD,wBAAgB,2BAA2B,CACzC,aAAa,EAAE,aAAa,EAC5B,iBAAiB,GAAE,SAAS,MAAM,EAA6B,GAC9D,MAAM,EAAE,CAEV"}
@@ -3,14 +3,28 @@
3
3
  * Licensed under the MIT license. See LICENSE file for details.
4
4
  */
5
5
  import { getMetadataFieldValue } from '../metadata/index.js';
6
+ // The features that this version of PublisherServer supports. A server does
7
+ // not serve a collection that requires a feature that is not in this list.
8
+ // A feature name must not contain a comma, because the metadata uses commas to
9
+ // separate the names. Use short kebab-case names, for example 'my-feature'.
10
+ export const SUPPORTED_INDEX_FEATURES = [];
11
+ const KNOWN_FIELDS = ['publishedTime', 'expirationTime', 'requires'];
6
12
  export function encodeIndexMetadata(indexMetadata) {
7
- const result = {};
13
+ const result = { ...indexMetadata.otherFields };
8
14
  if (indexMetadata.publishedTime != null && !isNaN(indexMetadata.publishedTime)) {
9
15
  result['publishedTime'] = String(indexMetadata.publishedTime);
10
16
  }
11
17
  if (indexMetadata.expirationTime != null && !isNaN(indexMetadata.expirationTime)) {
12
18
  result['expirationTime'] = String(indexMetadata.expirationTime);
13
19
  }
20
+ if (indexMetadata.requires != null && indexMetadata.requires.length > 0) {
21
+ for (const feature of indexMetadata.requires) {
22
+ if (feature.includes(',')) {
23
+ throw new Error(`Feature name '${feature}' must not contain a comma.`);
24
+ }
25
+ }
26
+ result['requires'] = indexMetadata.requires.join(',');
27
+ }
14
28
  return result;
15
29
  }
16
30
  export function decodeIndexMetadata(obj) {
@@ -19,8 +33,27 @@ export function decodeIndexMetadata(obj) {
19
33
  }
20
34
  const publishedTime = parseFloat(getMetadataFieldValue(obj, 'publishedTime'));
21
35
  const expirationTime = parseFloat(getMetadataFieldValue(obj, 'expirationTime'));
36
+ const requiresValue = getMetadataFieldValue(obj, 'requires');
37
+ const requires = requiresValue != null
38
+ ? String(requiresValue).split(',').map(x => x.trim()).filter(x => x !== '')
39
+ : [];
40
+ // S3 makes the metadata keys lowercase, so compare the keys without case.
41
+ const knownKeys = KNOWN_FIELDS.map(x => x.toLowerCase());
42
+ let otherFields;
43
+ for (const [key, value] of Object.entries(obj)) {
44
+ if (!knownKeys.includes(key.toLowerCase())) {
45
+ otherFields ??= {};
46
+ otherFields[key] = String(value);
47
+ }
48
+ }
22
49
  return {
23
50
  publishedTime: !isNaN(publishedTime) ? publishedTime : undefined,
24
51
  expirationTime: !isNaN(expirationTime) ? expirationTime : undefined,
52
+ requires: requires.length > 0 ? requires : undefined,
53
+ otherFields,
25
54
  };
26
55
  }
56
+ // Returns the features in requires that are not in supportedFeatures.
57
+ export function getUnsupportedIndexFeatures(indexMetadata, supportedFeatures = SUPPORTED_INDEX_FEATURES) {
58
+ return (indexMetadata.requires ?? []).filter(x => !supportedFeatures.includes(x));
59
+ }
@@ -1 +1 @@
1
- {"version":3,"file":"from-cookie.d.ts","sourceRoot":"","sources":["../../../../src/server/collection-selector/from-cookie.ts"],"names":[],"mappings":"AAMA,OAAO,EACL,KAAK,4BAA4B,EACjC,KAAK,6BAA6B,EACnC,MAAM,kCAAkC,CAAC;AAE1C,MAAM,MAAM,4BAA4B,GAAG;IACzC,UAAU,EAAE,MAAM,CAAC;IACnB,YAAY,EAAE,MAAM,CAAC;IACrB,SAAS,EAAE,MAAM,CAAC;IAClB,cAAc,EAAE,OAAO,CAAC;IACxB,YAAY,EAAE,MAAM,GAAG,SAAS,CAAC;IACjC,UAAU,EAAE,MAAM,CAAC;CACpB,CAAC;AAEF,qBAAa,wBAAyB,YAAW,6BAA6B;;gBAEzD,UAAU,EAAE,MAAM;gBAClB,IAAI,EAAE,OAAO,CAAC,4BAA4B,CAAC;IAqBvD,IAAI,EAAE,4BAA4B,CAAC;IAEnC,iBAAiB,CAAC,OAAO,EAAE,OAAO,GAAG,4BAA4B;IAIjE,aAAa,CAAC,OAAO,EAAE,OAAO;CA+DtC;AAED,MAAM,WAAW,gBAAgB;IAC/B,cAAc,EAAE,4BAA4B,CAAC;IAC7C,gBAAgB,EAAE,QAAQ,GAAG,IAAI,CAAC;CACnC;AAED,wBAAgB,UAAU,CAAC,OAAO,EAAE,OAAO,EAAE,gBAAgB,CAAC,EAAE,MAAM,GAAG,4BAA4B,GAAG,gBAAgB,CAevH"}
1
+ {"version":3,"file":"from-cookie.d.ts","sourceRoot":"","sources":["../../../../src/server/collection-selector/from-cookie.ts"],"names":[],"mappings":"AAMA,OAAO,EACL,KAAK,4BAA4B,EACjC,KAAK,6BAA6B,EACnC,MAAM,kCAAkC,CAAC;AAyB1C,MAAM,MAAM,4BAA4B,GAAG;IACzC,UAAU,EAAE,MAAM,CAAC;IACnB,YAAY,EAAE,MAAM,CAAC;IACrB,SAAS,EAAE,MAAM,CAAC;IAClB,cAAc,EAAE,OAAO,CAAC;IACxB,YAAY,EAAE,MAAM,GAAG,SAAS,CAAC;IACjC,UAAU,EAAE,MAAM,CAAC;CACpB,CAAC;AAEF,qBAAa,wBAAyB,YAAW,6BAA6B;;gBAEzD,UAAU,EAAE,MAAM;gBAClB,IAAI,EAAE,OAAO,CAAC,4BAA4B,CAAC;IAqBvD,IAAI,EAAE,4BAA4B,CAAC;IAEnC,iBAAiB,CAAC,OAAO,EAAE,OAAO,GAAG,4BAA4B;IAIjE,aAAa,CAAC,OAAO,EAAE,OAAO;CAmEtC;AAED,MAAM,WAAW,gBAAgB;IAC/B,cAAc,EAAE,4BAA4B,CAAC;IAC7C,gBAAgB,EAAE,QAAQ,GAAG,IAAI,CAAC;CACnC;AAED,wBAAgB,UAAU,CAAC,OAAO,EAAE,OAAO,EAAE,gBAAgB,CAAC,EAAE,MAAM,GAAG,4BAA4B,GAAG,gBAAgB,CAevH"}
@@ -3,6 +3,28 @@
3
3
  * Licensed under the MIT license. See LICENSE file for details.
4
4
  */
5
5
  import { getCookieValue } from '../util/cookies.js';
6
+ // The characters that a cookie value can have (cookie-octet in RFC 6265):
7
+ // no controls, spaces, '"', ',', ';', or '\'.
8
+ const COOKIE_VALUE_PATTERN = /^[\x21\x23-\x2B\x2D-\x3A\x3C-\x5B\x5D-\x7E]+$/;
9
+ // The redirect target after activate or reset. Only a path on the same site
10
+ // is allowed; anything else gives '/'.
11
+ function getRedirectTo(url) {
12
+ const redirectTo = url.searchParams.get('redirectTo');
13
+ if (redirectTo == null || !redirectTo.startsWith('/') || redirectTo.startsWith('//') || redirectTo.startsWith('/\\')) {
14
+ return '/';
15
+ }
16
+ let target;
17
+ try {
18
+ target = new URL(redirectTo, url.origin);
19
+ }
20
+ catch {
21
+ return '/';
22
+ }
23
+ if (target.origin !== url.origin) {
24
+ return '/';
25
+ }
26
+ return target.pathname + target.search + target.hash;
27
+ }
6
28
  export class CookieCollectionSelector {
7
29
  constructor(optsOrCookieName) {
8
30
  let opts = optsOrCookieName;
@@ -33,7 +55,11 @@ export class CookieCollectionSelector {
33
55
  if (collectionName == null) {
34
56
  return new Response(`Missing required 'collection' query parameter.`, { status: 400 });
35
57
  }
36
- const redirectTo = url.searchParams.get('redirectTo') ?? '/';
58
+ // The value goes into Set-Cookie, so it must be a valid cookie value.
59
+ if (!COOKIE_VALUE_PATTERN.test(collectionName)) {
60
+ return new Response(`The 'collection' query parameter has characters that are not allowed.`, { status: 400 });
61
+ }
62
+ const redirectTo = getRedirectTo(url);
37
63
  const cookieSegments = [
38
64
  `${this.opts.cookieName}=${collectionName}`,
39
65
  ];
@@ -57,7 +83,7 @@ export class CookieCollectionSelector {
57
83
  });
58
84
  }
59
85
  if (url.pathname === this.opts.resetPath) {
60
- const redirectTo = url.searchParams.get('redirectTo') ?? '/';
86
+ const redirectTo = getRedirectTo(url);
61
87
  const cookieSegments = [
62
88
  `${this.opts.cookieName}=`,
63
89
  ];
@@ -45,7 +45,6 @@ export declare class PublisherServer {
45
45
  private findAssetVariantForAcceptEncodingsGroups;
46
46
  serveAsset(request: Request, asset: AssetEntry, init?: AssetInit): Promise<Response>;
47
47
  serveCached(request: Request, keyPath: string, produce: (request: Request) => Promise<Response | null>): Promise<Response | null>;
48
- private copyBodyToCache;
49
48
  private responseFromCache;
50
49
  serveRequest(request: Request): Promise<Response | null>;
51
50
  private serveRequestFromStorage;
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/server/publisher-server/index.ts"],"names":[],"mappings":"AAUA,OAAO,EACL,KAAK,eAAe,EACrB,MAAM,0CAA0C,CAAC;AAClD,OAAO,EACL,KAAK,+BAA+B,EACrC,MAAM,gDAAgD,CAAC;AACxD,OAAO,EACL,KAAK,uBAAuB,EAC7B,MAAM,mCAAmC,CAAC;AAC3C,OAAO,EACL,KAAK,UAAU,EACf,KAAK,aAAa,EAClB,KAAK,oBAAoB,EAE1B,MAAM,8BAA8B,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AM,EACf,OAAO,EAAE,CAAC,OAAO,EAAE,OAAO,KAAK,OAAO,CAAC,QAAQ,GAAG,IAAI,CAAC,GACtD,OAAO,CAAC,QAAQ,GAAG,IAAI,CAAC;IAmG3B,OAAO,CAAC,iBAAiB;IA4BnB,YAAY,CAAC,OAAO,EAAE,OAAO,GAAG,OAAO,CAAC,QAAQ,GAAG,IAAI,CAAC;YAsBhD,uBAAuB;CAwDtC"}
@@ -2,15 +2,17 @@
2
2
  * Copyright Fastly, Inc.
3
3
  * Licensed under the MIT license. See LICENSE file for details.
4
4
  */
5
+ /// <reference types="@fastly/js-compute" />
5
6
  import { CoreCache } from 'fastly:cache';
6
7
  import { decodeAssetVariantMetadata, } from '../../models/assets/index.js';
7
- import { decodeIndexMetadata, } from '../../models/server/index.js';
8
+ import { decodeIndexMetadata, getUnsupportedIndexFeatures } from '../../models/server/index.js';
8
9
  import { isExpired } from '../../models/time/index.js';
9
10
  import { loadStorageProviderFromStaticPublishRc, } from '../storage/storage-provider.js';
10
11
  import { checkIfModifiedSince, getIfModifiedSinceHeader } from './serve-preconditions/if-modified-since.js';
11
12
  import { checkIfNoneMatch, getIfNoneMatchHeader } from './serve-preconditions/if-none-match.js';
12
13
  import { ServerTiming } from '../util/server-timing.js';
13
- import { CACHEABLE_STATUSES, buildCacheFillRequest, buildResponseCacheKey, decodeCachedResponseMetadata, encodeCachedResponseMetadata, parseAcceptEncodingGroups, } from './response-cache.js';
14
+ import { CACHEABLE_STATUSES, DEFAULT_MAX_BODY_SIZE, buildCacheFillRequest, buildResponseCacheKey, decodeCachedResponseMetadata, encodeCachedResponseMetadata, parseAcceptEncodingGroups, readBodyUpTo, } from './response-cache.js';
15
+ import { checkBodyLength } from '../util/body-length.js';
14
16
  export function buildHeadersSubset(responseHeaders, keys) {
15
17
  const resultHeaders = new Headers();
16
18
  for (const value of keys) {
@@ -140,21 +142,28 @@ export class PublisherServer {
140
142
  this.assetEntryMapCache = null;
141
143
  return null;
142
144
  }
143
- let collectionIsExpired = false;
144
- if (this.activeCollectionName !== this.defaultCollectionName) {
145
- let metadata;
146
- const metadataText = indexFile.metadataText();
147
- if (metadataText != null) {
148
- try {
149
- metadata = JSON.parse(metadataText);
150
- }
151
- catch {
152
- }
153
- metadata = decodeIndexMetadata(metadata);
145
+ let metadata;
146
+ const metadataText = indexFile.metadataText();
147
+ if (metadataText != null) {
148
+ try {
149
+ metadata = JSON.parse(metadataText);
154
150
  }
155
- if (metadata != null) {
156
- collectionIsExpired = metadata.expirationTime != null && isExpired(metadata.expirationTime);
151
+ catch {
157
152
  }
153
+ metadata = decodeIndexMetadata(metadata);
154
+ }
155
+ // Do not serve a collection that needs a feature that this version does not
156
+ // support. This check applies to all collections, also the default collection.
157
+ const unsupportedFeatures = metadata != null ? getUnsupportedIndexFeatures(metadata) : [];
158
+ if (unsupportedFeatures.length > 0) {
159
+ console.error(`Collection at ${indexFileKey} requires features that this version of the server does not support: ${unsupportedFeatures.join(', ')}.`);
160
+ console.error(`Build and deploy the application with a newer version of @fastly/compute-js-static-publish.`);
161
+ this.assetEntryMapCache = null;
162
+ return null;
163
+ }
164
+ let collectionIsExpired = false;
165
+ if (this.activeCollectionName !== this.defaultCollectionName && metadata != null) {
166
+ collectionIsExpired = metadata.expirationTime != null && isExpired(metadata.expirationTime);
158
167
  }
159
168
  if (collectionIsExpired) {
160
169
  console.error(`Requested collection expired at ${indexFileKey}.`);
@@ -392,8 +401,11 @@ export class PublisherServer {
392
401
  if (preconditionResponse != null) {
393
402
  return preconditionResponse;
394
403
  }
395
- const storageEntry = assetVariant.storageEntry;
396
- return new Response(storageEntry.body, {
404
+ // If the body does not have the size in its metadata, the response must not
405
+ // look complete. An empty body throws here, and any other mismatch causes an
406
+ // error in the body stream, so that the client gets an incomplete response.
407
+ const body = await checkBodyLength(assetVariant.storageEntry.body, assetVariant.size, `File ${asset.key} (${assetVariant.contentEncoding ?? 'identity'})`);
408
+ return new Response(body, {
397
409
  status: init?.status ?? 200,
398
410
  headers,
399
411
  });
@@ -415,6 +427,10 @@ export class PublisherServer {
415
427
  const state = entry.state();
416
428
  if (!state.mustInsertOrUpdate()) {
417
429
  const metadata = state.found() && state.usable() ? decodeCachedResponseMetadata(entry.userMetadata()) : null;
430
+ if (metadata?.tooLarge) {
431
+ this.serverTiming?.add('cache', performance.now() - lookupStart, 'bypass');
432
+ return produce(request);
433
+ }
418
434
  if (metadata != null) {
419
435
  // age() is in milliseconds. A hit younger than the time since a purge proves the entry was refilled.
420
436
  this.serverTiming?.add('cache', performance.now() - lookupStart, `hit age=${Math.round(entry.age() / 1000)}s`);
@@ -457,45 +473,39 @@ export class PublisherServer {
457
473
  // Server-Timing describes one request, so it is not stored.
458
474
  headers.delete('Server-Timing');
459
475
  const metadata = { status: response.status, headers: [...headers] };
460
- const contentLength = Number(headers.get('Content-Length'));
461
- // Stream the body into the cache entry, and give the client (and any requests
462
- // waiting on this key) the entry's own stream as it fills. FastlyBody.append()
463
- // can take only host-backed streams, and the storage providers build their
464
- // bodies in JavaScript, so copy the chunks.
465
- const [writer, streamedEntry] = entry.insertAndStreamBack({
466
- ...insertOptions,
467
- userMetadata: encodeCachedResponseMetadata(metadata),
468
- length: Number.isInteger(contentLength) && headers.has('Content-Length') ? contentLength : undefined,
469
- });
470
- const copied = this.copyBodyToCache(response, writer);
471
- const cachedResponse = this.responseFromCache(request, metadata, streamedEntry.body());
472
- // A response without a body (HEAD, 304) does not keep the request running
473
- // until the copy finishes. If the copy is cut short, the entry can be stored
474
- // with a partial body, so wait for it.
475
- if (cachedResponse?.body == null) {
476
- await copied;
477
- }
478
- return cachedResponse;
479
- }
480
- async copyBodyToCache(response, writer) {
476
+ // Read the whole body before the insertion starts. After it starts, a body
477
+ // that is not complete is not safe: the requests that read the entry get
478
+ // a short body that ends as if it is complete. If the read fails (for example,
479
+ // serveAsset() finds a body that does not have the size in its metadata),
480
+ // cancel() stores nothing, and the next request fills the entry again.
481
+ let readResult;
481
482
  try {
482
- if (response.body != null) {
483
- const reader = response.body.getReader();
484
- for (;;) {
485
- const { done, value } = await reader.read();
486
- if (done) {
487
- break;
488
- }
489
- writer.append(value);
490
- }
491
- }
492
- writer.close();
483
+ readResult = await readBodyUpTo(response.body, this.responseCache.maxBodySize ?? DEFAULT_MAX_BODY_SIZE);
493
484
  }
494
485
  catch (err) {
495
- // Without close(), the cache treats the insertion as incomplete, so a
496
- // partial body is not kept. Readers of this entry get a stream error.
497
- console.error('Could not write the response to the cache:', err);
486
+ entry.cancel();
487
+ throw err;
488
+ }
489
+ if ('body' in readResult) {
490
+ // Too large to cache. Cache a marker, so that later requests do not read
491
+ // the body to find this again, and serve the body from storage.
492
+ const tooLargeMetadata = { tooLarge: true };
493
+ const writer = entry.insert({
494
+ ...insertOptions,
495
+ userMetadata: encodeCachedResponseMetadata(tooLargeMetadata),
496
+ length: 0,
497
+ });
498
+ writer.close();
499
+ return this.responseFromCache(request, metadata, readResult.body);
498
500
  }
501
+ const writer = entry.insert({
502
+ ...insertOptions,
503
+ userMetadata: encodeCachedResponseMetadata(metadata),
504
+ length: readResult.bytes.byteLength,
505
+ });
506
+ writer.append(readResult.bytes);
507
+ writer.close();
508
+ return this.responseFromCache(request, metadata, readResult.bytes);
499
509
  }
500
510
  responseFromCache(request, metadata, body) {
501
511
  if (metadata.notFound) {
@@ -1,11 +1,18 @@
1
1
  import { type ContentCompressionTypes } from '../../models/compression/index.js';
2
2
  export type ResponseCacheOptions = {
3
3
  maxAge: number;
4
+ maxBodySize?: number;
4
5
  };
6
+ export declare const DEFAULT_MAX_BODY_SIZE: number;
5
7
  export type CachedResponseMetadata = {
6
8
  notFound: true;
9
+ tooLarge?: false;
7
10
  } | {
8
11
  notFound?: false;
12
+ tooLarge: true;
13
+ } | {
14
+ notFound?: false;
15
+ tooLarge?: false;
9
16
  status: number;
10
17
  headers: [string, string][];
11
18
  };
@@ -14,6 +21,12 @@ export declare function parseAcceptEncodingGroups(headerValue: string, allowedEn
14
21
  export declare function acceptEncodingCacheKeyPart(request: Request): string;
15
22
  export declare function buildResponseCacheKey(publishId: string, collectionName: string, keyPath: string, request: Request): string;
16
23
  export declare function buildCacheFillRequest(request: Request): Request;
24
+ export type ReadBodyResult = {
25
+ bytes: Uint8Array<ArrayBuffer>;
26
+ } | {
27
+ body: ReadableStream<Uint8Array>;
28
+ };
29
+ export declare function readBodyUpTo(body: ReadableStream<Uint8Array> | null, maxLength: number): Promise<ReadBodyResult>;
17
30
  export declare function encodeCachedResponseMetadata(metadata: CachedResponseMetadata): string;
18
31
  export declare function decodeCachedResponseMetadata(buffer: ArrayBuffer): CachedResponseMetadata | null;
19
32
  //# sourceMappingURL=response-cache.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"response-cache.d.ts","sourceRoot":"","sources":["../../../../src/server/publisher-server/response-cache.ts"],"names":[],"mappings":"AAKA,OAAO,EACL,KAAK,uBAAuB,EAE7B,MAAM,mCAAmC,CAAC;AAE3C,MAAM,MAAM,oBAAoB,GAAG;IAIjC,MAAM,EAAE,MAAM,CAAC;CAChB,CAAC;AAIF,MAAM,MAAM,sBAAsB,GAC9B;IAAE,QAAQ,EAAE,IAAI,CAAA;CAAE,GAClB;IAAE,QAAQ,CAAC,EAAE,KAAK,CAAC;IAAC,MAAM,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,CAAC,MAAM,EAAE,MAAM,CAAC,EAAE,CAAA;CAAE,CAAC;AAItE,eAAO,MAAM,kBAAkB,EAAE,QAAQ,CAAC,MAAM,EAAE,CAAgB,CAAC;AAgBnE,wBAAgB,yBAAyB,CACvC,WAAW,EAAE,MAAM,EACnB,gBAAgB,EAAE,QAAQ,CAAC,uBAAuB,EAAE,CAAC,GACpD,uBAAuB,EAAE,EAAE,CA2C7B;AAOD,wBAAgB,0BAA0B,CAAC,OAAO,EAAE,OAAO,GAAG,MAAM,CAQnE;AAED,wBAAgB,qBAAqB,CACnC,SAAS,EAAE,MAAM,EACjB,cAAc,EAAE,MAAM,EACtB,OAAO,EAAE,MAAM,EACf,OA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