@fastly/compute-js-static-publish 1.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 (39) hide show
  1. package/.idea/compute-js-static-publish.iml +12 -0
  2. package/.idea/inspectionProfiles/Project_Default.xml +6 -0
  3. package/.idea/jsLibraryMappings.xml +6 -0
  4. package/.idea/misc.xml +6 -0
  5. package/.idea/modules.xml +8 -0
  6. package/.idea/vcs.xml +6 -0
  7. package/LICENSE +21 -0
  8. package/README.md +106 -0
  9. package/SECURITY.md +13 -0
  10. package/build/build-static.js +160 -0
  11. package/build/content-types.js +1 -0
  12. package/build/index.js +69 -0
  13. package/build/init-app.js +276 -0
  14. package/build/presets/implementations/create-react-app.js +35 -0
  15. package/build/presets/implementations/docusaurus.js +13 -0
  16. package/build/presets/implementations/gatsby.js +13 -0
  17. package/build/presets/implementations/next.js +13 -0
  18. package/build/presets/implementations/sveltekit.js +13 -0
  19. package/build/presets/implementations/vite.js +13 -0
  20. package/build/presets/index.js +16 -0
  21. package/build/presets/preset-base.js +1 -0
  22. package/package.json +43 -0
  23. package/resources/README.md +3 -0
  24. package/resources/default-content-types.cjs +105 -0
  25. package/resources/index.js +120 -0
  26. package/resources/webpack.config.js +111 -0
  27. package/src/build-static.ts +195 -0
  28. package/src/content-types.ts +7 -0
  29. package/src/index.ts +81 -0
  30. package/src/init-app.ts +330 -0
  31. package/src/presets/implementations/create-react-app.ts +34 -0
  32. package/src/presets/implementations/docusaurus.ts +13 -0
  33. package/src/presets/implementations/gatsby.ts +13 -0
  34. package/src/presets/implementations/next.ts +13 -0
  35. package/src/presets/implementations/sveltekit.ts +13 -0
  36. package/src/presets/implementations/vite.ts +13 -0
  37. package/src/presets/index.ts +18 -0
  38. package/src/presets/preset-base.ts +18 -0
  39. package/tsconfig.json +19 -0
@@ -0,0 +1,12 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <module type="JAVA_MODULE" version="4">
3
+ <component name="Go" enabled="true" />
4
+ <component name="NewModuleRootManager" inherit-compiler-output="true">
5
+ <exclude-output />
6
+ <content url="file://$MODULE_DIR$">
7
+ <excludeFolder url="file://$MODULE_DIR$/build" />
8
+ </content>
9
+ <orderEntry type="inheritedJdk" />
10
+ <orderEntry type="sourceFolder" forTests="false" />
11
+ </component>
12
+ </module>
@@ -0,0 +1,6 @@
1
+ <component name="InspectionProjectProfileManager">
2
+ <profile version="1.0">
3
+ <option name="myName" value="Project Default" />
4
+ <inspection_tool class="ES6PreferShortImport" enabled="false" level="WARNING" enabled_by_default="false" />
5
+ </profile>
6
+ </component>
@@ -0,0 +1,6 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <project version="4">
3
+ <component name="JavaScriptLibraryMappings">
4
+ <file url="file://$PROJECT_DIR$" libraries="{Node.js Core}" />
5
+ </component>
6
+ </project>
package/.idea/misc.xml ADDED
@@ -0,0 +1,6 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <project version="4">
3
+ <component name="ProjectRootManager">
4
+ <output url="file://$PROJECT_DIR$/out" />
5
+ </component>
6
+ </project>
@@ -0,0 +1,8 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <project version="4">
3
+ <component name="ProjectModuleManager">
4
+ <modules>
5
+ <module fileurl="file://$PROJECT_DIR$/.idea/compute-js-static-publish.iml" filepath="$PROJECT_DIR$/.idea/compute-js-static-publish.iml" />
6
+ </modules>
7
+ </component>
8
+ </project>
package/.idea/vcs.xml ADDED
@@ -0,0 +1,6 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <project version="4">
3
+ <component name="VcsDirectoryMappings">
4
+ <mapping directory="" vcs="Git" />
5
+ </component>
6
+ </project>
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2022 Fastly, Inc.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,106 @@
1
+ # Static Publisher for JavaScript on Compute@Edge
2
+
3
+ Using a static site generator to build your website? Do you simply need to serve some static files? With `compute-js-static-publish`, now you can deploy and serve everything from Fastly's blazing-fast [Compute@Edge](https://developer.fastly.com/learning/compute/).
4
+
5
+ ## How it works
6
+
7
+ You have some HTML files, along with some accompanying CSS, JavaScript, image, and font files in a directory. Perhaps you've used a framework or static site generator to build these files.
8
+
9
+ Assuming the root of your output directory is `./public`,
10
+
11
+ ### 1. Run `compute-js-static-publish`
12
+
13
+ ```shell
14
+ npx @fastly/compute-js-static-publish --public-dir=./public
15
+ ```
16
+
17
+ >This will generate a Compute@Edge application at `./compute-js`. It will add a default `./src/index.js` file that serves the static files from your project.
18
+
19
+ ### 2. Test your application using [Fastly's local development server](https://developer.fastly.com/learning/compute/testing/#running-a-local-testing-server)
20
+
21
+ ```shell
22
+ cd ./compute-js
23
+ npm install
24
+ fastly compute serve
25
+ ```
26
+
27
+ The build process will generate a `/src/statics.js` file (in `./compute-js`) that holds references to your project's public files.
28
+
29
+ ### 3. When you're ready to go live, [deploy your Compute@Edge service](https://developer.fastly.com/reference/cli/compute/publish/)
30
+
31
+ ```shell
32
+ fastly compute publish
33
+ ```
34
+
35
+ Each time you build your Compute@Edge project (by running `fastly compute serve` or `fastly compute publish`), `compute-js-static-publish` will scan your `./public` directory and regenerate `/src/statics.js`.
36
+
37
+ You can modify `/src/index.js` to suit your needs, such as adding your own API endpoints. This file will not be overwritten after it is created.
38
+
39
+ ## CLI options
40
+
41
+ Most arguments are optional, and if provided, override the defaults described below.
42
+
43
+ ```shell
44
+ npx @fastly/compute-js-static-publish \
45
+ --public-dir=./build \
46
+ --static-dir=./build/static \
47
+ --output=./compute-js \
48
+ --spa=./build/index.html
49
+ ```
50
+
51
+ Any configuration options will be written to a `static-publish.rc.js` file.
52
+
53
+ | Option | Default | Description |
54
+ |------------------|-------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
55
+ | `preset` | (None) | Apply default options from a specified preset. See ["Frameworks and Static Site Generators"](#usage-with-frameworks-and-static-site-generators). |
56
+ | `output` | `./compute-js` | The directory in which to create the Compute@Edge application. |
57
+ | `public-dir` | (None) | **Required**. The root of the directory that contains your website's public files. Files at this path will be served by the generated Compute@Edge application. |
58
+ | `static-dir` | (None) | A subdirectory of `--public-dir` that contains the website's static assets. Files at this path will be cached by the browser for 1 year. Use versioned or hashed filenames to avoid serving stale assets. |
59
+ | `auto-index` | `index.html,index.htm` | Handle request paths that end in `/` by appending these names (comma-separated), in the specified order. By default, if `/path/to/a/` is requested, attempt to serve `/path/to/a/index.html`, then `/path/to/a/index.htm`. |
60
+ | `auto-ext` | `.html,.htm` | Handle request paths that do not end in `/` by appending these extensions (comma-separated), in the specified order. By default, if `/path/to/a` is requested, attempt to serve `/path/to/a`, `/path/to/a.html`, then `/path/to/a.htm`. |
61
+ | `spa` | (None) | Serve this file when the request path does not match known paths – with a `200` status code. Useful for apps that use [client-side routing](https://create-react-app.dev/docs/deployment#serving-apps-with-client-side-routing). |
62
+ | `not-found-page` | `<public-dir>/404.html` | Serve this file when the request path does not match known paths – with a `404` status code. Useful for a custom 404 error page. |
63
+
64
+ On subsequent builds of your Compute@Edge application, `compute-js-static-publish` will run with a special flag, `build-static`, reading from stored configuration, then scanning the `--public-dir` directory to recreate `./src/statics.js`.
65
+
66
+ ### Fastly service options
67
+
68
+ These arguments are used to populate the `fastly.toml` and `package.json` files of your Compute@Edge application.
69
+
70
+ | Option | Default | Description |
71
+ |---------------|------------------------------------------------------------------|------------------------------------------------------------------------------|
72
+ | `name` | `name` from `package.json`, or `compute-js-static-site` | The name of your Compute@Edge application. |
73
+ | `description` | `description` from `package.json`, or `Compute@Edge static site` | The description of your Compute@Edge application. |
74
+ | `author` | `author` from `package.json`, or `you@example.com` | The author of your Compute@Edge application. |
75
+ | `service-id` | (None) | The ID of an existing Fastly WASM service for your Compute@Edge application. |
76
+
77
+
78
+ ## Usage with frameworks and static site generators
79
+
80
+ `compute-js-static-publish` supports preset defaults for a number of frameworks and static site generators:
81
+
82
+ | `--preset` | `--public-dir` | `--static-dir` | Notes |
83
+ |-------------------------------|----------------|------------------|-------------------------------------------------------------------------------------------------------------------------------------|
84
+ | `cra` (or `create-react-app`) | `./build` | `./build/static` | For apps written using [Create React App](https://create-react-app.dev). Checks for a dependency on `react-scripts`. |
85
+ | `cra-eject` | `./build` | `./build/static` | For apps written using Create React App, but which have since been ejected via `npm run eject`. Does not check for `react-scripts`. |
86
+ | `vite` | `./dist` | (None) | For apps written using [Vite](https://vitejs.dev). |
87
+ | `sveltekit` | `./dist` | (None) | For apps written using [SvelteKit](https://kit.svelte.dev). |
88
+ | `next` | `./out` | (None) | For apps written using [Next.js](https://nextjs.org), using `npm run export`. |
89
+ | `gatsby` | `./public` | (None) | For apps written using [Gatsby](https://www.gatsbyjs.com). |
90
+ | `docusaurus` | `./build` | (None) | For apps written using [Docusaurus](https://docusaurus.io) |
91
+
92
+ You may still override any of these options individually.
93
+
94
+ ## Issues
95
+
96
+ If you encounter any non-security-related bug or unexpected behavior, please [file an issue][bug].
97
+
98
+ [bug]: https://github.com/fastly/compute-js-static-publish/issues/new?labels=bug
99
+
100
+ ### Security issues
101
+
102
+ Please see our [SECURITY.md](./SECURITY.md) for guidance on reporting security-related issues.
103
+
104
+ ## License
105
+
106
+ [MIT](./LICENSE).
package/SECURITY.md ADDED
@@ -0,0 +1,13 @@
1
+ ## Report a security issue
2
+
3
+ The project team welcomes security reports and is committed to providing prompt attention to security issues. Security
4
+ issues should be reported privately via [Fastly’s security issue reporting process](https://www.fastly.com/security/report-security-issue).
5
+
6
+ ## Security advisories
7
+
8
+ Remediation of security vulnerabilities is prioritized by the project team. The project team endeavors to coordinate
9
+ remediation with third-party stakeholders, and is committed to transparency in the disclosure process. The team announces
10
+ security issues via [GitHub](https://github.com/fastly/compute-js-static-publish/releases) on a best-effort basis.
11
+
12
+ Note that communications related to security issues in Fastly-maintained OSS as described here are distinct from
13
+ [Fastly Security Advisories](https://www.fastly.com/security-advisories).
@@ -0,0 +1,160 @@
1
+ // This program builds static resources out of the files in the
2
+ // public folder to be served. It reads the name of the public
3
+ // folder from the static-publish.rc.js file.
4
+ // With create-react-app, this would be the ./build directory.
5
+ // This also reexports the "spa" value in the static-publish.rc.js
6
+ // file so that the C@E handler knows what file to serve up if
7
+ // the resource doesn't map to a file.
8
+ import * as fs from "fs";
9
+ import * as path from "path";
10
+ import * as url from "url";
11
+ function getFiles(results, dir) {
12
+ const entries = fs.readdirSync(dir, { withFileTypes: true });
13
+ for (const entry of entries) {
14
+ const name = path.resolve(dir, entry.name);
15
+ if (entry.isDirectory()) {
16
+ getFiles(results, name);
17
+ }
18
+ else {
19
+ results.push(name);
20
+ }
21
+ }
22
+ }
23
+ export async function buildStaticLoader() {
24
+ var _a, _b, _c, _d, _e, _f, _g, _h;
25
+ console.log("Building loader...");
26
+ let config;
27
+ try {
28
+ const staticPublishRcPath = path.resolve('./static-publish.rc.js');
29
+ config = (await import(staticPublishRcPath)).default;
30
+ }
31
+ catch (ex) {
32
+ console.error("❌ Can't load static-publish.rc.js");
33
+ console.error("Run this from a compute-js-static-publish compute-js directory.");
34
+ console.error("Error: ", String(ex));
35
+ process.exit(1);
36
+ }
37
+ const results = [];
38
+ getFiles(results, config.publicDir);
39
+ const outputDir = path.resolve();
40
+ const publicDirRoot = path.resolve(config.publicDir);
41
+ console.log(`Public directory '${publicDirRoot}'.`);
42
+ const staticDirs = (_a = config.staticDirs) !== null && _a !== void 0 ? _a : [];
43
+ if (staticDirs.length > 0) {
44
+ console.log(`Using static directories: ${staticDirs.join(', ')}`);
45
+ }
46
+ else {
47
+ console.log(`No static directories defined.`);
48
+ }
49
+ const staticRoots = staticDirs.map(dir => path.resolve(config.publicDir, dir));
50
+ const DEFAULT_EXCLUDE_DIRS = [
51
+ './node_modules'
52
+ ];
53
+ const excludeDirs = (_b = config.excludeDirs) !== null && _b !== void 0 ? _b : DEFAULT_EXCLUDE_DIRS;
54
+ if (excludeDirs.length > 0) {
55
+ console.log(`Using exclude directories: ${excludeDirs.join(', ')}`);
56
+ }
57
+ else {
58
+ console.log(`No exclude directories defined.`);
59
+ }
60
+ const excludeRoots = excludeDirs.map(dir => path.resolve(config.publicDir, dir));
61
+ // Load defaultContentTypes module
62
+ const __dirname = url.fileURLToPath(new URL('.', import.meta.url));
63
+ const defaultContentTypesJsSrcPath = path.resolve(__dirname, '../resources/default-content-types.cjs');
64
+ const defaultContentTypes = await import(defaultContentTypesJsSrcPath);
65
+ // Load content types
66
+ const finalContentTypes = defaultContentTypes.mergeContentTypes((_c = config.contentTypes) !== null && _c !== void 0 ? _c : []);
67
+ // Update the target file too, so webpack can see it.
68
+ const defaultContentTypesJsPath = path.resolve('./default-content-types.cjs');
69
+ fs.copyFileSync(defaultContentTypesJsSrcPath, defaultContentTypesJsPath);
70
+ const DEFAULT_INCLUDE_DIRS = [
71
+ './.well-known'
72
+ ];
73
+ const includeDirs = (_d = config.includeDirs) !== null && _d !== void 0 ? _d : DEFAULT_INCLUDE_DIRS;
74
+ if (includeDirs.length > 0) {
75
+ console.log(`Using include directories: ${includeDirs.join(', ')}`);
76
+ }
77
+ else {
78
+ console.log(`No include directories defined.`);
79
+ }
80
+ const includeRoots = includeDirs.map(dir => path.resolve(config.publicDir, dir));
81
+ const files = results
82
+ .filter(file => {
83
+ // Exclude files that come from C@E app dir
84
+ if (file.startsWith(outputDir)) {
85
+ return false;
86
+ }
87
+ // Include files that come from "included roots" dir
88
+ if (includeRoots.some(root => file.startsWith(root))) {
89
+ return true;
90
+ }
91
+ // Exclude files that are in directories that start with "."
92
+ if (file.indexOf('/.') !== -1) {
93
+ return false;
94
+ }
95
+ // Exclude files that come from "excluded roots" dir
96
+ if (excludeRoots.some(root => file.startsWith(root))) {
97
+ return false;
98
+ }
99
+ return true;
100
+ });
101
+ let fileContents = '';
102
+ for (const [index, file] of files.entries()) {
103
+ const relativeFilePath = path.relative('./src', file);
104
+ fileContents += `import file${index} from "${relativeFilePath}";\n`;
105
+ }
106
+ const knownAssets = {};
107
+ fileContents += `\nexport const assets = {\n`;
108
+ for (const [index, file] of files.entries()) {
109
+ const contentDef = defaultContentTypes.testFileContentType(finalContentTypes, file);
110
+ const filePath = file.slice(publicDirRoot.length);
111
+ const type = contentDef === null || contentDef === void 0 ? void 0 : contentDef.type;
112
+ const isStatic = staticRoots.some(root => file.startsWith(root));
113
+ knownAssets[filePath] = { contentType: type, isStatic };
114
+ if (contentDef != null) {
115
+ console.log(filePath + ': ' + JSON.stringify(type) + (isStatic ? ' [STATIC]' : ''));
116
+ }
117
+ else {
118
+ console.warn('Warning: Unknown file type ' + filePath + '...');
119
+ }
120
+ let content;
121
+ if (contentDef == null || contentDef.binary) {
122
+ content = 'Buffer.from(file' + index + ', "base64")';
123
+ }
124
+ else {
125
+ content = 'file' + index;
126
+ }
127
+ fileContents += ` ${JSON.stringify(filePath)}: { contentType: ${JSON.stringify(type)}, content: ${content}, isStatic: ${JSON.stringify(isStatic)} },\n`;
128
+ }
129
+ fileContents += '};\n';
130
+ let spaFile = (_e = config.spa) !== null && _e !== void 0 ? _e : false;
131
+ if (spaFile) {
132
+ console.log(`Application SPA file '${spaFile}'.`);
133
+ if (!knownAssets[spaFile] || knownAssets[spaFile].contentType !== 'text/html') {
134
+ console.warn(`'${spaFile}' does not exist or is not of type 'text/html'. Ignoring.`);
135
+ spaFile = false;
136
+ }
137
+ }
138
+ else {
139
+ console.log(`Application is not a SPA.`);
140
+ }
141
+ fileContents += `\nexport const spaFile = ${JSON.stringify(spaFile)};\n`;
142
+ let notFoundPageFile = (_f = config.notFoundPage) !== null && _f !== void 0 ? _f : false;
143
+ if (notFoundPageFile) {
144
+ console.log(`Application 'not found (404)' file '${notFoundPageFile}'.`);
145
+ if (!knownAssets[notFoundPageFile] || knownAssets[notFoundPageFile].contentType !== 'text/html') {
146
+ console.warn(`'${notFoundPageFile}' does not exist or is not of type 'text/html'. Ignoring.`);
147
+ notFoundPageFile = false;
148
+ }
149
+ }
150
+ else {
151
+ console.log(`Application specifies no 'not found (404)' page.`);
152
+ }
153
+ fileContents += `\nexport const notFoundPageFile = ${JSON.stringify(notFoundPageFile)};\n`;
154
+ let autoIndex = (_g = config.autoIndex) !== null && _g !== void 0 ? _g : null;
155
+ fileContents += `\nexport const autoIndex = ${JSON.stringify(autoIndex)};\n`;
156
+ let autoExt = (_h = config.autoExt) !== null && _h !== void 0 ? _h : null;
157
+ fileContents += `\nexport const autoExt = ${JSON.stringify(autoExt)};\n`;
158
+ fs.writeFileSync('./src/statics.js', fileContents);
159
+ console.log("🚀 Wrote static file loader for " + files.length + " file(s).");
160
+ }
@@ -0,0 +1 @@
1
+ export {};
package/build/index.js ADDED
@@ -0,0 +1,69 @@
1
+ #!/usr/bin/env node
2
+ import commandLineArgs from "command-line-args";
3
+ import { initApp } from "./init-app.js";
4
+ import { buildStaticLoader } from "./build-static.js";
5
+ const optionDefinitions = [
6
+ // (optional) Should be one of:
7
+ // - cra (or create-react-app)
8
+ // - vite
9
+ // - sveltekit
10
+ // - next
11
+ // - gatsby
12
+ // - docusaurus
13
+ { name: 'preset', type: String, },
14
+ { name: 'build-static', type: Boolean },
15
+ { name: 'output', alias: 'o', type: String, defaultValue: './compute-js', },
16
+ { name: 'public-dir', type: String, },
17
+ { name: 'static-dir', type: String, },
18
+ // List of files to automatically use as index, for example, index.html,index.htm
19
+ // If a request comes in but the route does not exist, we check the route
20
+ // plus a slash plus the items in this array.
21
+ {
22
+ name: 'auto-index',
23
+ type: (val) => {
24
+ if (val == null) {
25
+ return null;
26
+ }
27
+ const values = val
28
+ .split(',')
29
+ .map(x => x.trim())
30
+ .filter(x => x !== '');
31
+ return values.length > 0 ? values : null;
32
+ },
33
+ },
34
+ // List of extensions to apply to a path name, for example, if
35
+ // http://example.com/about is requested, we can respond with http://example.com/about.html
36
+ {
37
+ name: 'auto-ext',
38
+ type: (val) => {
39
+ if (val == null) {
40
+ return null;
41
+ }
42
+ const values = val
43
+ .split(',')
44
+ .map(x => x.trim())
45
+ .map(x => {
46
+ while (x.startsWith('.')) {
47
+ x = x.slice(1);
48
+ }
49
+ return '.' + x;
50
+ })
51
+ .filter(x => x !== '');
52
+ return values.length > 0 ? values : null;
53
+ },
54
+ },
55
+ { name: 'spa', type: String, },
56
+ { name: 'not-found-page', type: String, },
57
+ { name: 'name', type: String, },
58
+ { name: 'author', type: String, },
59
+ { name: 'description', type: String, },
60
+ // Fastly Service ID to be added to the fastly.toml that is generated.
61
+ { name: 'service-id', type: String },
62
+ ];
63
+ const commandLineValues = commandLineArgs(optionDefinitions);
64
+ console.log("Fastly Compute@Edge JavaScript Static Publisher");
65
+ if (commandLineValues['build-static']) {
66
+ await buildStaticLoader();
67
+ process.exit();
68
+ }
69
+ initApp(commandLineValues);