carlin 2.1.0 → 2.2.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 (2) hide show
  1. package/dist/index.mjs +130 -7
  2. package/package.json +2 -2
package/dist/index.mjs CHANGED
@@ -3544,12 +3544,82 @@ const getResponseHeadersPolicyConfig = ({ responseHeaders }) => {
3544
3544
  };
3545
3545
  };
3546
3546
  //#endregion
3547
+ //#region src/deploy/staticApp/viewerRequestFunction.ts
3548
+ /**
3549
+ * Maximum size of a CloudFront Function, in bytes.
3550
+ *
3551
+ * https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/cloudfront-function-quotas.html
3552
+ */
3553
+ const MAX_FUNCTION_SIZE_BYTES = 10 * 1024;
3554
+ /**
3555
+ * https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/writing-function-code.html
3556
+ */
3557
+ const FUNCTION_RUNTIME = "cloudfront-js-2.0";
3558
+ /**
3559
+ * `appendIndexHtml` injected into every app-supplied viewer request function.
3560
+ *
3561
+ * A cache behavior takes a single viewer request function, so an app that
3562
+ * supplies its own cannot also associate the shared `AppendIndexDotHtml` of the
3563
+ * base stack. Composing the two by concatenating their sources would not work
3564
+ * either: both would declare `handler`, and the later declaration would win
3565
+ * silently, dropping one of the behaviors.
3566
+ *
3567
+ * Injecting the logic as a named helper instead leaves a single `handler` in the
3568
+ * composed source and makes the order explicit at the call site, which is where
3569
+ * it matters — a function rewriting `/docs/x` to `/docs/x.md` must run before
3570
+ * the index appending, one rewriting `/docs/x` to `/x/docs` after it.
3571
+ *
3572
+ * The body is the base stack `AppendIndexDotHtml` function
3573
+ * (`getCloudFrontTemplate.ts`) with the event unwrapping removed, so both
3574
+ * behave the same. `tests/unit/deploy/staticApp/viewerRequestFunction.test.ts`
3575
+ * asserts they don't drift.
3576
+ */
3577
+ const APPEND_INDEX_HTML_HELPER = `function appendIndexHtml(request) {
3578
+ var uri = request.uri;
3579
+ if (uri.endsWith('/')) {
3580
+ request.uri += 'index.html';
3581
+ } else if (!uri.includes('.')) {
3582
+ request.uri += '/index.html';
3583
+ }
3584
+ return request;
3585
+ }`;
3586
+ /**
3587
+ * The entry point CloudFront calls. A function whose code doesn't declare it
3588
+ * fails at deploy time with an opaque error, so it's checked at synth time.
3589
+ */
3590
+ const HANDLER_DECLARATION_REGEX = /function\s+handler\s*\(/;
3591
+ /**
3592
+ * Reads the file the `viewerRequestFunctionCode` option points to.
3593
+ */
3594
+ const readViewerRequestFunctionCode = ({ filePath }) => {
3595
+ const resolvedPath = path.resolve(filePath);
3596
+ if (!fs.existsSync(resolvedPath)) throw new Error(`The viewer-request-function-code option points to "${filePath}", which doesn't exist.`);
3597
+ return fs.readFileSync(resolvedPath, "utf8");
3598
+ };
3599
+ /**
3600
+ * Composes the source of the per-app `AWS::CloudFront::Function`: the
3601
+ * `appendIndexHtml` helper followed by the app code, which owns the `handler`.
3602
+ */
3603
+ const getViewerRequestFunctionCode = ({ code }) => {
3604
+ if (!code.trim()) throw new Error("The viewer-request-function-code option points to an empty file.");
3605
+ if (!HANDLER_DECLARATION_REGEX.test(code)) throw new Error("The viewer request function code must declare a `function handler(event)`, which is the entry point CloudFront calls.");
3606
+ const functionCode = `${APPEND_INDEX_HTML_HELPER}\n\n${code.trim()}\n`;
3607
+ /**
3608
+ * The helper counts against the app budget, so the size of the composed
3609
+ * source is what CloudFront rejects.
3610
+ */
3611
+ const size = Buffer.byteLength(functionCode, "utf8");
3612
+ if (size > 10240) throw new Error(`The viewer request function is ${size} bytes, above the ${MAX_FUNCTION_SIZE_BYTES} bytes CloudFront allows. The \`appendIndexHtml\` helper carlin injects counts against this budget.`);
3613
+ return functionCode;
3614
+ };
3615
+ //#endregion
3547
3616
  //#region src/deploy/staticApp/staticApp.template.ts
3548
3617
  const PACKAGE_VERSION = getPackageVersion();
3549
3618
  const STATIC_APP_BUCKET_LOGICAL_ID = "StaticBucket";
3550
3619
  const CLOUDFRONT_DISTRIBUTION_LOGICAL_ID = "CloudFrontDistribution";
3551
3620
  const CLOUDFRONT_ORIGIN_ACCESS_CONTROL_LOGICAL_ID = "OriginAccessControl";
3552
3621
  const CLOUDFRONT_RESPONSE_HEADERS_POLICY_LOGICAL_ID = "ResponseHeadersPolicy";
3622
+ const CLOUDFRONT_VIEWER_REQUEST_FUNCTION_LOGICAL_ID = "ViewerRequestFunction";
3553
3623
  const ROUTE_53_RECORD_SET_GROUP_LOGICAL_ID = "Route53RecordSetGroup";
3554
3624
  const ERROR_DOCUMENT = "404/index.html";
3555
3625
  /**
@@ -3637,7 +3707,7 @@ const getBucketStaticWebsiteTemplate = ({ spa }) => {
3637
3707
  } }
3638
3708
  };
3639
3709
  };
3640
- const getCloudFrontTemplate = ({ acm, aliases = [], appendIndexHtml, responseHeaders = [], responseHeadersPolicy, spa, hostedZoneName }) => {
3710
+ const getCloudFrontTemplate = ({ acm, aliases = [], appendIndexHtml, responseHeaders = [], responseHeadersPolicy, spa, hostedZoneName, viewerRequestFunctionCode }) => {
3641
3711
  const template = {
3642
3712
  AWSTemplateFormatVersion: "2010-09-09",
3643
3713
  Resources: {
@@ -3819,7 +3889,37 @@ const getCloudFrontTemplate = ({ acm, aliases = [], appendIndexHtml, responseHea
3819
3889
  [`Alias${index}URL`]: { Value: `https://${alias}` }
3820
3890
  };
3821
3891
  }, {});
3822
- if (appendIndexHtml) {
3892
+ /**
3893
+ * A cache behavior takes a single viewer request function, so the app
3894
+ * supplied one replaces the shared base stack one instead of being appended
3895
+ * to it. `appendIndexHtml` is available to the app code as a helper, which is
3896
+ * why the two options are mutually exclusive.
3897
+ *
3898
+ * https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/edge-function-restrictions-all.html
3899
+ */
3900
+ if (appendIndexHtml && viewerRequestFunctionCode) throw new Error("The append-index-html and viewer-request-function-code options are mutually exclusive. A cache behavior takes a single viewer request function. Call `appendIndexHtml(request)` from your function instead, which carlin injects for you.");
3901
+ if (viewerRequestFunctionCode) template.Resources[CLOUDFRONT_VIEWER_REQUEST_FUNCTION_LOGICAL_ID] = {
3902
+ Type: "AWS::CloudFront::Function",
3903
+ Properties: {
3904
+ /**
3905
+ * Function names must be unique per AWS account. Static app deploys are
3906
+ * always in us-east-1, so the stack name cannot collide with a
3907
+ * same-named stack in another region.
3908
+ */
3909
+ Name: { Ref: "AWS::StackName" },
3910
+ FunctionConfig: {
3911
+ Comment: { "Fn::Sub": ["Viewer request function for the ${Project} project.", { Project: { Ref: "Project" } }] },
3912
+ Runtime: FUNCTION_RUNTIME
3913
+ },
3914
+ FunctionCode: getViewerRequestFunctionCode({ code: viewerRequestFunctionCode }),
3915
+ AutoPublish: true
3916
+ }
3917
+ };
3918
+ const viewerRequestFunctionArn = (() => {
3919
+ if (viewerRequestFunctionCode) return { "Fn::GetAtt": [CLOUDFRONT_VIEWER_REQUEST_FUNCTION_LOGICAL_ID, "FunctionMetadata.FunctionARN"] };
3920
+ if (appendIndexHtml) return { "Fn::ImportValue": BASE_STACK_CLOUDFRONT_FUNCTION_APPEND_INDEX_HTML_ARN_EXPORTED_NAME };
3921
+ })();
3922
+ if (viewerRequestFunctionArn) {
3823
3923
  if (!template.Resources["CloudFrontDistribution"].Properties) template.Resources[CLOUDFRONT_DISTRIBUTION_LOGICAL_ID].Properties = {};
3824
3924
  template.Resources[CLOUDFRONT_DISTRIBUTION_LOGICAL_ID].Properties.DistributionConfig.DefaultCacheBehavior.FunctionAssociations = [(
3825
3925
  /**
@@ -3827,7 +3927,7 @@ const getCloudFrontTemplate = ({ acm, aliases = [], appendIndexHtml, responseHea
3827
3927
  */
3828
3928
  {
3829
3929
  EventType: "viewer-request",
3830
- FunctionARN: { "Fn::ImportValue": BASE_STACK_CLOUDFRONT_FUNCTION_APPEND_INDEX_HTML_ARN_EXPORTED_NAME }
3930
+ FunctionARN: viewerRequestFunctionArn
3831
3931
  })];
3832
3932
  }
3833
3933
  /**
@@ -3842,7 +3942,7 @@ const getCloudFrontTemplate = ({ acm, aliases = [], appendIndexHtml, responseHea
3842
3942
  };
3843
3943
  return template;
3844
3944
  };
3845
- const getStaticAppTemplate = ({ acm, aliases, appendIndexHtml, cloudfront, responseHeaders, responseHeadersPolicy, spa, hostedZoneName, region }) => {
3945
+ const getStaticAppTemplate = ({ acm, aliases, appendIndexHtml, cloudfront, responseHeaders, responseHeadersPolicy, spa, hostedZoneName, region, viewerRequestFunctionCode }) => {
3846
3946
  if (cloudfront) return getCloudFrontTemplate({
3847
3947
  acm,
3848
3948
  aliases,
@@ -3852,7 +3952,8 @@ const getStaticAppTemplate = ({ acm, aliases, appendIndexHtml, cloudfront, respo
3852
3952
  responseHeadersPolicy,
3853
3953
  spa,
3854
3954
  hostedZoneName,
3855
- region
3955
+ region,
3956
+ viewerRequestFunctionCode
3856
3957
  });
3857
3958
  return getBucketStaticWebsiteTemplate({ spa });
3858
3959
  };
@@ -3924,7 +4025,7 @@ const logPrefix$4 = "static-app";
3924
4025
  * 1. Upload static files to the host bucket S3.
3925
4026
  * 1. Remove old deployment versions. Keep only the 3 most recent ones.
3926
4027
  */
3927
- const deployStaticApp = async ({ acm, aliases, appendIndexHtml, buildFolder, cloudfront, responseHeaders, responseHeadersPolicy, spa, hostedZoneName, region, skipUpload, uploadSourceMaps }) => {
4028
+ const deployStaticApp = async ({ acm, aliases, appendIndexHtml, buildFolder, cloudfront, responseHeaders, responseHeadersPolicy, spa, hostedZoneName, region, skipUpload, uploadSourceMaps, viewerRequestFunctionCode }) => {
3928
4029
  try {
3929
4030
  const { stackName } = await handleDeployInitialization({ logPrefix: logPrefix$4 });
3930
4031
  const params = { StackName: stackName };
@@ -3937,7 +4038,8 @@ const deployStaticApp = async ({ acm, aliases, appendIndexHtml, buildFolder, clo
3937
4038
  responseHeadersPolicy,
3938
4039
  spa,
3939
4040
  hostedZoneName,
3940
- region
4041
+ region,
4042
+ viewerRequestFunctionCode: viewerRequestFunctionCode ? readViewerRequestFunctionCode({ filePath: viewerRequestFunctionCode }) : void 0
3941
4043
  });
3942
4044
  const bucket = await getStaticAppBucket({ stackName });
3943
4045
  /**
@@ -4056,6 +4158,10 @@ const options$4 = {
4056
4158
  describe: "Upload source map (`.map`) files to S3. They are excluded by default because the bucket is public and source maps expose the application source.",
4057
4159
  require: false,
4058
4160
  type: "boolean"
4161
+ },
4162
+ "viewer-request-function-code": {
4163
+ describe: "Path to a file whose code runs as the CloudFront viewer request function of the distribution. The file must declare a `function handler(event)`, and may call the `appendIndexHtml(request)` helper carlin injects.",
4164
+ type: "string"
4059
4165
  }
4060
4166
  };
4061
4167
  const deployStaticAppCommand = {
@@ -4071,6 +4177,23 @@ const deployStaticAppCommand = {
4071
4177
  */
4072
4178
  if (!cloudfront && (hasResponseHeaders || responseHeadersPolicy)) throw new Error(`The ${hasResponseHeaders ? "response-headers" : "response-headers-policy"} option requires the cloudfront option.`);
4073
4179
  return true;
4180
+ }).check(({ appendIndexHtml, cloudfront, viewerRequestFunctionCode }) => {
4181
+ if (!viewerRequestFunctionCode) return true;
4182
+ /**
4183
+ * A cache behavior takes a single viewer request function, and the
4184
+ * shared base stack one is what append-index-html associates. The app
4185
+ * supplied function gets the same behavior by calling the
4186
+ * `appendIndexHtml` helper carlin injects.
4187
+ *
4188
+ * https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/edge-function-restrictions-all.html
4189
+ */
4190
+ if (appendIndexHtml) throw new Error("The append-index-html and viewer-request-function-code options are mutually exclusive. A cache behavior takes a single viewer request function. Call `appendIndexHtml(request)` from your function instead, which carlin injects for you.");
4191
+ /**
4192
+ * The function is associated to a cache behavior, so a bucket only
4193
+ * deploy has nothing to attach it to.
4194
+ */
4195
+ if (!cloudfront) throw new Error("The viewer-request-function-code option requires the cloudfront option.");
4196
+ return true;
4074
4197
  }).middleware(() => {
4075
4198
  AWS.config.region = CLOUDFRONT_REGION;
4076
4199
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "carlin",
3
- "version": "2.1.0",
3
+ "version": "2.2.0",
4
4
  "description": "",
5
5
  "keywords": [],
6
6
  "homepage": "https://ttoss.dev/docs/carlin/",
@@ -57,8 +57,8 @@
57
57
  "ts-node": "^10.9.2",
58
58
  "uglify-js": "^3.19.3",
59
59
  "yargs": "^17.7.2",
60
- "@ttoss/cloudformation": "^0.13.11",
61
60
  "@ttoss/config": "^1.37.17",
61
+ "@ttoss/cloudformation": "^0.13.11",
62
62
  "@ttoss/read-config-file": "^2.2.20"
63
63
  },
64
64
  "devDependencies": {