@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,111 @@
1
+ const path = require("path");
2
+ const webpack = require("webpack");
3
+ const { ProvidePlugin } = webpack;
4
+
5
+ let config;
6
+ try {
7
+ config = require("./static-publish.rc.js");
8
+ } catch {
9
+ console.error('Error loading static-publish.rc.js');
10
+ process.exit(1);
11
+ }
12
+
13
+ let defaultContentTypes;
14
+ try {
15
+ defaultContentTypes = require("./default-content-types.cjs");
16
+ } catch {
17
+ console.error('Error loading default-content-types.cjs');
18
+ process.exit(1);
19
+ }
20
+
21
+ const contentTypes = defaultContentTypes.mergeContentTypes(config.contentTypes ?? []);
22
+
23
+ const srcDir = path.resolve('./src');
24
+ const srcNodeModulesDir = path.resolve('./node_modules');
25
+ const publicDir = path.resolve(config.publicDir);
26
+
27
+ if (publicDir.startsWith(path.resolve())) {
28
+ // If public dir is INSIDE the compute-js app dir, results may be weird
29
+ console.warn('⚠️ public files directory is inside of the Compute@Edge app directory.');
30
+ console.warn('This is an unsupported scenario and you may experience trouble.');
31
+ console.warn('');
32
+ }
33
+
34
+ module.exports = {
35
+ entry: "./src/index.js",
36
+ optimization: {
37
+ minimize: false
38
+ },
39
+ target: "webworker",
40
+ output: {
41
+ filename: "index.js",
42
+ path: path.resolve(__dirname, "bin"),
43
+ libraryTarget: "this",
44
+ },
45
+ module: {
46
+ // Asset modules are modules that allow the use asset files (fonts, icons, etc)
47
+ // without additional configuration or dependencies.
48
+ rules: [
49
+ // asset/source exports the source code of the asset.
50
+ // Usage: e.g., import notFoundPage from "./page_404.html"
51
+ {
52
+ test: (file) => {
53
+ if(!file.startsWith(publicDir + '/')) {
54
+ return false;
55
+ }
56
+ if(file.startsWith(srcDir + '/')) {
57
+ return false;
58
+ }
59
+ if(file.startsWith(srcNodeModulesDir + '/')) {
60
+ return false;
61
+ }
62
+ // If content type is known, and it's known not to be binary.
63
+ const result = defaultContentTypes.testFileContentType(contentTypes, file);
64
+ return result != null && !result.binary;
65
+ },
66
+ type: "asset/source",
67
+ },
68
+ // asset/inline exports the raw bytes of the asset.
69
+ // We base64 encode them here
70
+ {
71
+ test: (file) => {
72
+ if(!file.startsWith(publicDir + '/')) {
73
+ return false;
74
+ }
75
+ if(file.startsWith(srcDir + '/')) {
76
+ return false;
77
+ }
78
+ if(file.startsWith(srcNodeModulesDir + '/')) {
79
+ return false;
80
+ }
81
+ // If content type unknown, or it's known to be binary.
82
+ const result = defaultContentTypes.testFileContentType(contentTypes, file);
83
+ return result == null || result.binary;
84
+ },
85
+ type: "asset/inline",
86
+ generator: {
87
+ /**
88
+ * @param {Buffer} content
89
+ * @returns {string}
90
+ */
91
+ dataUrl: content => {
92
+ return content.toString('base64');
93
+ },
94
+ }
95
+ },
96
+ ],
97
+ },
98
+ plugins: [
99
+ // Polyfills go here.
100
+ // Used for, e.g., any cross-platform WHATWG,
101
+ // or core nodejs modules needed for your application.
102
+ new ProvidePlugin({
103
+ Buffer: [ "buffer", "Buffer" ],
104
+ }),
105
+ ],
106
+ resolve: {
107
+ fallback: {
108
+ "buffer": require.resolve("buffer/"),
109
+ },
110
+ },
111
+ };
@@ -0,0 +1,195 @@
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
+
5
+ // With create-react-app, this would be the ./build directory.
6
+
7
+ // This also reexports the "spa" value in the static-publish.rc.js
8
+ // file so that the C@E handler knows what file to serve up if
9
+ // the resource doesn't map to a file.
10
+
11
+ import * as fs from "fs";
12
+ import * as path from "path";
13
+ import * as url from "url";
14
+ import { ContentTypeDef } from "./content-types.js";
15
+
16
+ function getFiles(results: string[], dir: string) {
17
+ const entries = fs.readdirSync(dir, { withFileTypes: true });
18
+ for (const entry of entries) {
19
+ const name = path.resolve(dir, entry.name);
20
+ if (entry.isDirectory()) {
21
+ getFiles(results, name);
22
+ } else {
23
+ results.push(name);
24
+ }
25
+ }
26
+ }
27
+
28
+ export async function buildStaticLoader() {
29
+
30
+ console.log("Building loader...");
31
+
32
+ let config: any;
33
+ try {
34
+ const staticPublishRcPath = path.resolve('./static-publish.rc.js');
35
+ config = (await import(staticPublishRcPath)).default;
36
+ } catch(ex) {
37
+ console.error("❌ Can't load static-publish.rc.js");
38
+ console.error("Run this from a compute-js-static-publish compute-js directory.");
39
+ console.error("Error: ", String(ex));
40
+ process.exit(1);
41
+ }
42
+
43
+ const results: string[] = [];
44
+ getFiles(results, config.publicDir);
45
+
46
+ const outputDir = path.resolve();
47
+
48
+ const publicDirRoot = path.resolve(config.publicDir);
49
+
50
+ console.log(`Public directory '${publicDirRoot}'.`);
51
+
52
+ const staticDirs: string[] = config.staticDirs ?? [];
53
+ if (staticDirs.length > 0) {
54
+ console.log(`Using static directories: ${staticDirs.join(', ')}`);
55
+ } else {
56
+ console.log(`No static directories defined.`);
57
+ }
58
+ const staticRoots = staticDirs.map(
59
+ dir => path.resolve(config.publicDir, dir)
60
+ );
61
+
62
+ const DEFAULT_EXCLUDE_DIRS = [
63
+ './node_modules'
64
+ ];
65
+
66
+ const excludeDirs: string[] = config.excludeDirs ?? DEFAULT_EXCLUDE_DIRS;
67
+ if (excludeDirs.length > 0) {
68
+ console.log(`Using exclude directories: ${excludeDirs.join(', ')}`);
69
+ } else {
70
+ console.log(`No exclude directories defined.`);
71
+ }
72
+ const excludeRoots = excludeDirs.map(
73
+ dir => path.resolve(config.publicDir, dir)
74
+ );
75
+
76
+ // Load defaultContentTypes module
77
+ const __dirname = url.fileURLToPath(new URL('.', import.meta.url));
78
+ const defaultContentTypesJsSrcPath = path.resolve(__dirname, '../resources/default-content-types.cjs');
79
+ const defaultContentTypes = await import(defaultContentTypesJsSrcPath);
80
+
81
+ // Load content types
82
+ const finalContentTypes: ContentTypeDef[] = defaultContentTypes.mergeContentTypes(config.contentTypes ?? []);
83
+
84
+ // Update the target file too, so webpack can see it.
85
+ const defaultContentTypesJsPath = path.resolve('./default-content-types.cjs');
86
+ fs.copyFileSync(defaultContentTypesJsSrcPath, defaultContentTypesJsPath);
87
+
88
+ const DEFAULT_INCLUDE_DIRS = [
89
+ './.well-known'
90
+ ];
91
+
92
+ const includeDirs: string[] = config.includeDirs ?? DEFAULT_INCLUDE_DIRS;
93
+ if (includeDirs.length > 0) {
94
+ console.log(`Using include directories: ${includeDirs.join(', ')}`);
95
+ } else {
96
+ console.log(`No include directories defined.`);
97
+ }
98
+ const includeRoots = includeDirs.map(
99
+ dir => path.resolve(config.publicDir, dir)
100
+ );
101
+
102
+ const files = results
103
+ .filter(file => {
104
+ // Exclude files that come from C@E app dir
105
+ if(file.startsWith(outputDir)) {
106
+ return false;
107
+ }
108
+ // Include files that come from "included roots" dir
109
+ if(includeRoots.some(root => file.startsWith(root))) {
110
+ return true;
111
+ }
112
+ // Exclude files that are in directories that start with "."
113
+ if(file.indexOf('/.') !== -1) {
114
+ return false;
115
+ }
116
+ // Exclude files that come from "excluded roots" dir
117
+ if(excludeRoots.some(root => file.startsWith(root))) {
118
+ return false;
119
+ }
120
+ return true;
121
+ });
122
+
123
+ let fileContents = '';
124
+
125
+ for (const [index, file] of files.entries()) {
126
+ const relativeFilePath = path.relative('./src', file);
127
+ fileContents += `import file${index} from "${relativeFilePath}";\n`;
128
+ }
129
+
130
+ const knownAssets: Record<string, {contentType: string, isStatic:boolean}> = {};
131
+
132
+ fileContents += `\nexport const assets = {\n`;
133
+
134
+ for (const [index, file] of files.entries()) {
135
+ const contentDef = defaultContentTypes.testFileContentType(finalContentTypes, file);
136
+ const filePath = file.slice(publicDirRoot.length);
137
+ const type = contentDef?.type;
138
+ const isStatic = staticRoots.some(root => file.startsWith(root));
139
+ knownAssets[filePath] = { contentType: type, isStatic };
140
+
141
+ if (contentDef != null) {
142
+ console.log(filePath + ': ' + JSON.stringify(type) + (isStatic ? ' [STATIC]' : ''));
143
+ } else {
144
+ console.warn('Warning: Unknown file type ' + filePath + '...');
145
+ }
146
+
147
+ let content;
148
+ if (contentDef == null || contentDef.binary) {
149
+ content = 'Buffer.from(file' + index + ', "base64")';
150
+ } else {
151
+ content = 'file' + index;
152
+ }
153
+
154
+ fileContents += ` ${JSON.stringify(filePath)}: { contentType: ${JSON.stringify(type)}, content: ${content}, isStatic: ${JSON.stringify(isStatic)} },\n`;
155
+ }
156
+
157
+ fileContents += '};\n';
158
+
159
+ let spaFile: string | false = config.spa ?? false;
160
+ if(spaFile) {
161
+ console.log(`Application SPA file '${spaFile}'.`);
162
+ if(!knownAssets[spaFile] || knownAssets[spaFile].contentType !== 'text/html') {
163
+ console.warn(`'${spaFile}' does not exist or is not of type 'text/html'. Ignoring.`);
164
+ spaFile = false;
165
+ }
166
+ } else {
167
+ console.log(`Application is not a SPA.`);
168
+ }
169
+
170
+ fileContents += `\nexport const spaFile = ${JSON.stringify(spaFile)};\n`;
171
+
172
+ let notFoundPageFile: string | false = config.notFoundPage ?? false;
173
+ if(notFoundPageFile) {
174
+ console.log(`Application 'not found (404)' file '${notFoundPageFile}'.`);
175
+ if(!knownAssets[notFoundPageFile] || knownAssets[notFoundPageFile].contentType !== 'text/html') {
176
+ console.warn(`'${notFoundPageFile}' does not exist or is not of type 'text/html'. Ignoring.`);
177
+ notFoundPageFile = false;
178
+ }
179
+ } else {
180
+ console.log(`Application specifies no 'not found (404)' page.`);
181
+ }
182
+
183
+ fileContents += `\nexport const notFoundPageFile = ${JSON.stringify(notFoundPageFile)};\n`;
184
+
185
+ let autoIndex: string | false = config.autoIndex ?? null;
186
+ fileContents += `\nexport const autoIndex = ${JSON.stringify(autoIndex)};\n`;
187
+
188
+ let autoExt: string | false = config.autoExt ?? null;
189
+ fileContents += `\nexport const autoExt = ${JSON.stringify(autoExt)};\n`;
190
+
191
+ fs.writeFileSync('./src/statics.js', fileContents);
192
+
193
+ console.log("🚀 Wrote static file loader for " + files.length + " file(s).");
194
+
195
+ }
@@ -0,0 +1,7 @@
1
+ type TestFn = (name: string) => boolean;
2
+
3
+ export type ContentTypeDef = {
4
+ test: RegExp | TestFn,
5
+ type: string,
6
+ binary?: boolean,
7
+ };
package/src/index.ts ADDED
@@ -0,0 +1,81 @@
1
+ #!/usr/bin/env node
2
+
3
+ import commandLineArgs, { OptionDefinition } from "command-line-args";
4
+
5
+ import { initApp } from "./init-app.js";
6
+ import { buildStaticLoader } from "./build-static.js";
7
+
8
+ const optionDefinitions: OptionDefinition[] = [
9
+ // (optional) Should be one of:
10
+ // - cra (or create-react-app)
11
+ // - vite
12
+ // - sveltekit
13
+ // - next
14
+ // - gatsby
15
+ // - docusaurus
16
+ { name: 'preset', type: String, },
17
+
18
+ { name: 'build-static', type: Boolean },
19
+ { name: 'output', alias: 'o', type: String, defaultValue: './compute-js', },
20
+ { name: 'public-dir', type: String, },
21
+ { name: 'static-dir', type: String, },
22
+
23
+ // List of files to automatically use as index, for example, index.html,index.htm
24
+ // If a request comes in but the route does not exist, we check the route
25
+ // plus a slash plus the items in this array.
26
+ {
27
+ name: 'auto-index',
28
+ type: (val: string | null) => {
29
+ if(val == null) {
30
+ return null;
31
+ }
32
+ const values = val
33
+ .split(',')
34
+ .map(x => x.trim())
35
+ .filter(x => x !== '');
36
+ return values.length > 0 ? values : null;
37
+ },
38
+ },
39
+
40
+ // List of extensions to apply to a path name, for example, if
41
+ // http://example.com/about is requested, we can respond with http://example.com/about.html
42
+ {
43
+ name: 'auto-ext',
44
+ type: (val: string | null) => {
45
+ if(val == null) {
46
+ return null;
47
+ }
48
+ const values = val
49
+ .split(',')
50
+ .map(x => x.trim())
51
+ .map(x => {
52
+ while(x.startsWith('.')) {
53
+ x = x.slice(1);
54
+ }
55
+ return '.' + x;
56
+ })
57
+ .filter(x => x !== '');
58
+ return values.length > 0 ? values : null;
59
+ },
60
+ },
61
+
62
+ { name: 'spa', type: String, },
63
+ { name: 'not-found-page', type: String, },
64
+ { name: 'name', type: String, },
65
+ { name: 'author', type: String, },
66
+ { name: 'description', type: String, },
67
+
68
+ // Fastly Service ID to be added to the fastly.toml that is generated.
69
+ { name: 'service-id', type: String },
70
+ ];
71
+
72
+ const commandLineValues = commandLineArgs(optionDefinitions);
73
+
74
+ console.log("Fastly Compute@Edge JavaScript Static Publisher");
75
+
76
+ if (commandLineValues['build-static']) {
77
+ await buildStaticLoader();
78
+ process.exit();
79
+ }
80
+
81
+ initApp(commandLineValues);