carlin 2.3.0 → 2.5.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 +132 -12
  2. package/package.json +2 -2
package/dist/index.mjs CHANGED
@@ -557,9 +557,15 @@ const uploadFileToS3 = async ({ bucket, contentType, file, filePath, key }) => {
557
557
  };
558
558
  /**
559
559
  * Get all files inside $directory.
560
+ *
561
+ * `dot: true` because a static site's dot directories are content: RFC 8615
562
+ * puts the files agents and clients fetch by convention under `.well-known/`,
563
+ * and glob skips a segment starting with a dot by default. Without it those
564
+ * files are absent from the deployed site and nothing reports it — the deploy
565
+ * succeeds, the path 404s.
560
566
  */
561
567
  const getAllFilesInsideADirectory = async ({ directory }) => {
562
- return (await glob(`${directory}/**/*`)).filter((item) => {
568
+ return (await glob(`${directory}/**/*`, { dot: true })).filter((item) => {
563
569
  return fs.lstatSync(item).isFile();
564
570
  });
565
571
  };
@@ -3586,6 +3592,76 @@ const APPEND_INDEX_HTML_HELPER = `function appendIndexHtml(request) {
3586
3592
  return request;
3587
3593
  }`;
3588
3594
  /**
3595
+ * `redirectToTrailingSlash` injected into every app-supplied viewer request
3596
+ * function, and the whole behavior of the `redirectToTrailingSlash` option.
3597
+ *
3598
+ * `appendIndexHtml` answers `/docs/guide` and `/docs/guide/` with the same
3599
+ * object, so every page of a site has a duplicate that search engines crawl and
3600
+ * have to de-duplicate, and nothing signals a link written without the trailing
3601
+ * slash. This helper serves the trailing slash form as `appendIndexHtml` does
3602
+ * and redirects the extension-less one to it, so a page answers on one URL.
3603
+ *
3604
+ * The query string is carried over verbatim — the values CloudFront exposes are
3605
+ * the ones the viewer sent, so re-encoding them would double-encode a
3606
+ * `?utm_content=a%20b`, and dropping them would break attribution on the
3607
+ * redirected request. A parameter sent without a value (`?flag`) is rebuilt as
3608
+ * `?flag=`, which every query string parser reads the same way.
3609
+ *
3610
+ * https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/functions-event-structure.html
3611
+ */
3612
+ const REDIRECT_TO_TRAILING_SLASH_HELPER = `function redirectToTrailingSlash(request) {
3613
+ var uri = request.uri;
3614
+
3615
+ if (uri.endsWith('/')) {
3616
+ request.uri += 'index.html';
3617
+ return request;
3618
+ }
3619
+
3620
+ if (uri.includes('.')) {
3621
+ return request;
3622
+ }
3623
+
3624
+ var querystring = '';
3625
+
3626
+ for (var name in request.querystring) {
3627
+ var parameter = request.querystring[name];
3628
+ var values = parameter.multiValue || [parameter];
3629
+
3630
+ for (var i = 0; i < values.length; i++) {
3631
+ querystring += (querystring ? '&' : '?') + name + '=' + values[i].value;
3632
+ }
3633
+ }
3634
+
3635
+ return {
3636
+ statusCode: 301,
3637
+ statusDescription: 'Moved Permanently',
3638
+ headers: { location: { value: uri + '/' + querystring } },
3639
+ };
3640
+ }`;
3641
+ /**
3642
+ * Code of the per-app function the `redirectToTrailingSlash` option creates.
3643
+ *
3644
+ * The redirect cannot go into the shared base stack function the
3645
+ * `appendIndexHtml` option associates: that one is imported by ARN by every
3646
+ * static app in the account, so changing it would redirect all of them at once,
3647
+ * on someone else's version bump. A per-app function keeps the choice with the
3648
+ * app, and costs no base stack update before the option can be used.
3649
+ */
3650
+ const REDIRECT_TO_TRAILING_SLASH_FUNCTION_CODE = `${REDIRECT_TO_TRAILING_SLASH_HELPER}
3651
+
3652
+ function handler(event) {
3653
+ return redirectToTrailingSlash(event.request);
3654
+ }
3655
+ `;
3656
+ /**
3657
+ * Helpers carlin makes available to an app-supplied function, in the order they
3658
+ * are injected. They count against the size budget of every function, so a
3659
+ * helper is added here only when it holds behavior an option of carlin also
3660
+ * provides — an app that supplies its own function can reach for it instead of
3661
+ * losing the option.
3662
+ */
3663
+ const INJECTED_HELPERS = [APPEND_INDEX_HTML_HELPER, REDIRECT_TO_TRAILING_SLASH_HELPER].join("\n\n");
3664
+ /**
3589
3665
  * The entry point CloudFront calls. A function whose code doesn't declare it
3590
3666
  * fails at deploy time with an opaque error, so it's checked at synth time.
3591
3667
  */
@@ -3599,19 +3675,19 @@ const readViewerRequestFunctionCode = ({ filePath }) => {
3599
3675
  return fs.readFileSync(resolvedPath, "utf8");
3600
3676
  };
3601
3677
  /**
3602
- * Composes the source of the per-app `AWS::CloudFront::Function`: the
3603
- * `appendIndexHtml` helper followed by the app code, which owns the `handler`.
3678
+ * Composes the source of the per-app `AWS::CloudFront::Function`: the injected
3679
+ * helpers followed by the app code, which owns the `handler`.
3604
3680
  */
3605
3681
  const getViewerRequestFunctionCode = ({ code }) => {
3606
3682
  if (!code.trim()) throw new Error("The viewer-request-function-code option points to an empty file.");
3607
3683
  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.");
3608
- const functionCode = `${APPEND_INDEX_HTML_HELPER}\n\n${code.trim()}\n`;
3684
+ const functionCode = `${INJECTED_HELPERS}\n\n${code.trim()}\n`;
3609
3685
  /**
3610
- * The helper counts against the app budget, so the size of the composed
3686
+ * The helpers count against the app budget, so the size of the composed
3611
3687
  * source is what CloudFront rejects.
3612
3688
  */
3613
3689
  const size = Buffer.byteLength(functionCode, "utf8");
3614
- 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.`);
3690
+ if (size > 10240) throw new Error(`The viewer request function is ${size} bytes, above the ${MAX_FUNCTION_SIZE_BYTES} bytes CloudFront allows. The helpers carlin injects count against this budget.`);
3615
3691
  return functionCode;
3616
3692
  };
3617
3693
  //#endregion
@@ -3719,7 +3795,7 @@ const getBucketStaticWebsiteTemplate = ({ spa }) => {
3719
3795
  } }
3720
3796
  };
3721
3797
  };
3722
- const getCloudFrontTemplate = ({ acm, aliases = [], appendIndexHtml, responseHeaders = [], responseHeadersPolicy, spa, hostedZoneName, viewerRequestFunctionCode }) => {
3798
+ const getCloudFrontTemplate = ({ acm, aliases = [], appendIndexHtml, redirectToTrailingSlash, responseHeaders = [], responseHeadersPolicy, spa, hostedZoneName, viewerRequestFunctionCode }) => {
3723
3799
  const template = {
3724
3800
  AWSTemplateFormatVersion: "2010-09-09",
3725
3801
  Resources: {
@@ -3913,7 +3989,28 @@ const getCloudFrontTemplate = ({ acm, aliases = [], appendIndexHtml, responseHea
3913
3989
  * https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/edge-function-restrictions-all.html
3914
3990
  */
3915
3991
  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.");
3916
- if (viewerRequestFunctionCode) template.Resources[CLOUDFRONT_VIEWER_REQUEST_FUNCTION_LOGICAL_ID] = {
3992
+ /**
3993
+ * The redirect is a mode of the index appending, not a behavior of its own:
3994
+ * it still serves `/docs/guide/` as `/docs/guide/index.html`, and only
3995
+ * changes what answers `/docs/guide`.
3996
+ */
3997
+ if (redirectToTrailingSlash && !appendIndexHtml) throw new Error("The redirect-to-trailing-slash option requires the append-index-html option. It changes how an extension-less URI is answered, so the index appending it redirects to has to be on.");
3998
+ /**
3999
+ * An extension-less URI of a SPA is a client route rather than a directory,
4000
+ * so redirecting it to a trailing slash would move every route of the app to
4001
+ * a URL its router doesn't produce.
4002
+ */
4003
+ if (redirectToTrailingSlash && spa) throw new Error("The redirect-to-trailing-slash and spa options are mutually exclusive. An extension-less URI of a SPA is a client route, not a directory, so redirecting it to a trailing slash changes the URL of every route.");
4004
+ /**
4005
+ * The redirect cannot go into the shared base stack function, which every
4006
+ * static app of the account imports by ARN, so it is deployed as a function
4007
+ * of this app instead.
4008
+ */
4009
+ const perAppFunctionCode = (() => {
4010
+ if (viewerRequestFunctionCode) return getViewerRequestFunctionCode({ code: viewerRequestFunctionCode });
4011
+ if (redirectToTrailingSlash) return REDIRECT_TO_TRAILING_SLASH_FUNCTION_CODE;
4012
+ })();
4013
+ if (perAppFunctionCode) template.Resources[CLOUDFRONT_VIEWER_REQUEST_FUNCTION_LOGICAL_ID] = {
3917
4014
  Type: "AWS::CloudFront::Function",
3918
4015
  Properties: {
3919
4016
  /**
@@ -3926,12 +4023,12 @@ const getCloudFrontTemplate = ({ acm, aliases = [], appendIndexHtml, responseHea
3926
4023
  Comment: { "Fn::Sub": ["Viewer request function for the ${Project} project.", { Project: { Ref: "Project" } }] },
3927
4024
  Runtime: FUNCTION_RUNTIME
3928
4025
  },
3929
- FunctionCode: getViewerRequestFunctionCode({ code: viewerRequestFunctionCode }),
4026
+ FunctionCode: perAppFunctionCode,
3930
4027
  AutoPublish: true
3931
4028
  }
3932
4029
  };
3933
4030
  const viewerRequestFunctionArn = (() => {
3934
- if (viewerRequestFunctionCode) return { "Fn::GetAtt": [CLOUDFRONT_VIEWER_REQUEST_FUNCTION_LOGICAL_ID, "FunctionMetadata.FunctionARN"] };
4031
+ if (perAppFunctionCode) return { "Fn::GetAtt": [CLOUDFRONT_VIEWER_REQUEST_FUNCTION_LOGICAL_ID, "FunctionMetadata.FunctionARN"] };
3935
4032
  if (appendIndexHtml) return { "Fn::ImportValue": BASE_STACK_CLOUDFRONT_FUNCTION_APPEND_INDEX_HTML_ARN_EXPORTED_NAME };
3936
4033
  })();
3937
4034
  if (viewerRequestFunctionArn) {
@@ -3957,12 +4054,13 @@ const getCloudFrontTemplate = ({ acm, aliases = [], appendIndexHtml, responseHea
3957
4054
  };
3958
4055
  return template;
3959
4056
  };
3960
- const getStaticAppTemplate = ({ acm, aliases, appendIndexHtml, cloudfront, responseHeaders, responseHeadersPolicy, spa, hostedZoneName, region, viewerRequestFunctionCode }) => {
4057
+ const getStaticAppTemplate = ({ acm, aliases, appendIndexHtml, cloudfront, redirectToTrailingSlash, responseHeaders, responseHeadersPolicy, spa, hostedZoneName, region, viewerRequestFunctionCode }) => {
3961
4058
  if (cloudfront) return getCloudFrontTemplate({
3962
4059
  acm,
3963
4060
  aliases,
3964
4061
  appendIndexHtml,
3965
4062
  cloudfront,
4063
+ redirectToTrailingSlash,
3966
4064
  responseHeaders,
3967
4065
  responseHeadersPolicy,
3968
4066
  spa,
@@ -4040,7 +4138,7 @@ const logPrefix$4 = "static-app";
4040
4138
  * 1. Upload static files to the host bucket S3.
4041
4139
  * 1. Remove old deployment versions. Keep only the 3 most recent ones.
4042
4140
  */
4043
- const deployStaticApp = async ({ acm, aliases, appendIndexHtml, buildFolder, cloudfront, responseHeaders, responseHeadersPolicy, spa, hostedZoneName, region, skipUpload, uploadSourceMaps, viewerRequestFunctionCode }) => {
4141
+ const deployStaticApp = async ({ acm, aliases, appendIndexHtml, buildFolder, cloudfront, redirectToTrailingSlash, responseHeaders, responseHeadersPolicy, spa, hostedZoneName, region, skipUpload, uploadSourceMaps, viewerRequestFunctionCode }) => {
4044
4142
  try {
4045
4143
  const { stackName } = await handleDeployInitialization({ logPrefix: logPrefix$4 });
4046
4144
  const params = { StackName: stackName };
@@ -4049,6 +4147,7 @@ const deployStaticApp = async ({ acm, aliases, appendIndexHtml, buildFolder, clo
4049
4147
  aliases,
4050
4148
  appendIndexHtml,
4051
4149
  cloudfront,
4150
+ redirectToTrailingSlash,
4052
4151
  responseHeaders,
4053
4152
  responseHeadersPolicy,
4054
4153
  spa,
@@ -4142,6 +4241,11 @@ const options$4 = {
4142
4241
  hidden: true,
4143
4242
  type: "string"
4144
4243
  },
4244
+ "redirect-to-trailing-slash": {
4245
+ default: false,
4246
+ describe: "Answer an extension-less request URI with a `301` to its trailing slash form instead of serving the page on both, so each page of the site has a single URL. Requires the `append-index-html` option.",
4247
+ type: "boolean"
4248
+ },
4145
4249
  "response-headers": {
4146
4250
  coerce: parseResponseHeaders,
4147
4251
  default: [],
@@ -4192,6 +4296,22 @@ const deployStaticAppCommand = {
4192
4296
  */
4193
4297
  if (!cloudfront && (hasResponseHeaders || responseHeadersPolicy)) throw new Error(`The ${hasResponseHeaders ? "response-headers" : "response-headers-policy"} option requires the cloudfront option.`);
4194
4298
  return true;
4299
+ }).check(({ appendIndexHtml, redirectToTrailingSlash, spa }) => {
4300
+ if (!redirectToTrailingSlash) return true;
4301
+ /**
4302
+ * The redirect is a mode of the index appending, not a behavior of
4303
+ * its own: it still serves `/docs/guide/` as
4304
+ * `/docs/guide/index.html`, and only changes what answers
4305
+ * `/docs/guide`.
4306
+ */
4307
+ if (!appendIndexHtml) throw new Error("The redirect-to-trailing-slash option requires the append-index-html option. It changes how an extension-less URI is answered, so the index appending it redirects to has to be on.");
4308
+ /**
4309
+ * An extension-less URI of a SPA is a client route rather than a
4310
+ * directory, so redirecting it to a trailing slash would move every
4311
+ * route of the app to a URL its router doesn't produce.
4312
+ */
4313
+ if (spa) throw new Error("The redirect-to-trailing-slash and spa options are mutually exclusive. An extension-less URI of a SPA is a client route, not a directory, so redirecting it to a trailing slash changes the URL of every route.");
4314
+ return true;
4195
4315
  }).check(({ appendIndexHtml, cloudfront, viewerRequestFunctionCode }) => {
4196
4316
  if (!viewerRequestFunctionCode) return true;
4197
4317
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "carlin",
3
- "version": "2.3.0",
3
+ "version": "2.5.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.14.0",
61
60
  "@ttoss/read-config-file": "^2.3.0",
61
+ "@ttoss/cloudformation": "^0.14.0",
62
62
  "@ttoss/config": "^1.38.0"
63
63
  },
64
64
  "devDependencies": {