@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,276 @@
1
+ // This program creates a Compute@Edge JavaScript application
2
+ // in a subfolder named compute-js.
3
+ // This project can be served using fastly compute serve
4
+ // or deployed to a Compute@Edge service using fastly compute publish.
5
+ import * as child_process from "child_process";
6
+ import * as path from "path";
7
+ import * as fs from "fs";
8
+ import * as url from 'url';
9
+ import { presets } from './presets/index.js';
10
+ const defaultOptions = {
11
+ 'public-dir': undefined,
12
+ 'static-dir': undefined,
13
+ spa: undefined,
14
+ 'not-found-page': '[public-dir]/404.html',
15
+ 'auto-index': ['index.html', 'index.htm'],
16
+ 'auto-ext': ['.html', '.htm'],
17
+ author: 'you@example.com',
18
+ name: 'compute-js-static-site',
19
+ description: 'Compute@Edge static site',
20
+ 'service-id': undefined,
21
+ };
22
+ function pickKeys(keys, object) {
23
+ const result = {};
24
+ for (const key of keys) {
25
+ if (object[key] !== undefined) {
26
+ result[key] = object[key];
27
+ }
28
+ }
29
+ return result;
30
+ }
31
+ function applyPublicDir(optionValue, publicDir) {
32
+ if (optionValue == null) {
33
+ return optionValue;
34
+ }
35
+ return optionValue.replace('[public-dir]', publicDir);
36
+ }
37
+ export function initApp(commandLineValues) {
38
+ var _a;
39
+ let options = defaultOptions;
40
+ let preset = null;
41
+ const presetName = (_a = commandLineValues['preset']) !== null && _a !== void 0 ? _a : 'none';
42
+ if (presetName !== 'none') {
43
+ const presetClass = presets[presetName];
44
+ if (presetClass == null) {
45
+ console.error('Unknown preset name.');
46
+ console.error("--preset must be one of: none, " + (Object.keys(presets).join(', ')));
47
+ process.exit(1);
48
+ return;
49
+ }
50
+ preset = new presetClass();
51
+ }
52
+ let packageJson;
53
+ try {
54
+ const packageJsonText = fs.readFileSync("./package.json", "utf-8");
55
+ packageJson = JSON.parse(packageJsonText);
56
+ }
57
+ catch (_b) {
58
+ console.log("Can't read/parse package.json in current directory, making no assumptions!");
59
+ packageJson = null;
60
+ }
61
+ options = {
62
+ ...options,
63
+ ...(preset != null ? preset.defaultOptions : {}),
64
+ ...pickKeys(['author', 'name', 'description'], packageJson !== null && packageJson !== void 0 ? packageJson : {}),
65
+ ...pickKeys(['public-dir', 'static-dir', 'spa', 'not-found-page', 'auto-index', 'auto-ext', 'author', 'name', 'description', 'service-id'], commandLineValues)
66
+ };
67
+ if (preset != null) {
68
+ if (!preset.check(packageJson, options)) {
69
+ console.log("Failed preset check.");
70
+ process.exit(1);
71
+ return;
72
+ }
73
+ }
74
+ const COMPUTE_JS_DIR = commandLineValues.output;
75
+ const computeJsDir = path.resolve(COMPUTE_JS_DIR);
76
+ const PUBLIC_DIR = options['public-dir'];
77
+ if (PUBLIC_DIR == null) {
78
+ console.error("❌ required parameter --public-dir not provided.");
79
+ process.exit(1);
80
+ return;
81
+ }
82
+ const publicDir = path.resolve(PUBLIC_DIR);
83
+ const BUILD_STATIC_DIR = applyPublicDir(options['static-dir'], PUBLIC_DIR);
84
+ const buildStaticDir = BUILD_STATIC_DIR != null ? path.resolve(BUILD_STATIC_DIR) : null;
85
+ const spa = applyPublicDir(options['spa'], PUBLIC_DIR);
86
+ const notFoundPage = applyPublicDir(options['not-found-page'], PUBLIC_DIR);
87
+ const autoIndex = options['auto-index'];
88
+ const autoExt = options['auto-ext'];
89
+ let spaFilename = spa;
90
+ // Specifically check for null instead of undefined
91
+ if (spa === null) {
92
+ spaFilename = path.resolve(publicDir, './index.html');
93
+ let rel = path.relative(path.resolve(), spaFilename);
94
+ if (!rel.startsWith('..')) {
95
+ rel = './' + rel;
96
+ }
97
+ console.log('--spa provided with no value, assuming ' + rel);
98
+ }
99
+ if (spaFilename != null) {
100
+ spaFilename = path.resolve(spaFilename);
101
+ if (!spaFilename.startsWith(publicDir)) {
102
+ console.error(`❌ SPA file '${spaFilename}' not inside public directory!`);
103
+ process.exit(1);
104
+ return;
105
+ }
106
+ }
107
+ let notFoundPageFilename = notFoundPage;
108
+ // Specifically check for null instead of undefined
109
+ if (notFoundPage === null) {
110
+ notFoundPageFilename = path.resolve(publicDir, './404.html');
111
+ let rel = path.relative(path.resolve(), notFoundPageFilename);
112
+ if (!rel.startsWith('..')) {
113
+ rel = './' + rel;
114
+ }
115
+ console.log('--not-found-page provided with no value, assuming ' + rel);
116
+ }
117
+ if (notFoundPageFilename != null) {
118
+ notFoundPageFilename = path.resolve(notFoundPageFilename);
119
+ if (!notFoundPageFilename.startsWith(publicDir)) {
120
+ console.error(`❌ --not-found-page file '${notFoundPageFilename}' not inside public directory!`);
121
+ process.exit(1);
122
+ return;
123
+ }
124
+ }
125
+ const exists = fs.existsSync(computeJsDir);
126
+ if (exists) {
127
+ console.error(`❌ '${COMPUTE_JS_DIR}' directory already exists!`);
128
+ process.exit(1);
129
+ return;
130
+ }
131
+ const author = options['author'];
132
+ const name = options['name'];
133
+ const description = options['description'];
134
+ const fastlyServiceId = options['service-id'];
135
+ let spaRel = spaFilename != null ? path.relative(path.resolve(), spaFilename) : null;
136
+ if (spaRel != null && !spaRel.startsWith('..')) {
137
+ spaRel = './' + spaRel;
138
+ }
139
+ let notFoundRel = notFoundPageFilename != null ? path.relative(path.resolve(), notFoundPageFilename) : null;
140
+ if (notFoundRel != null && !notFoundRel.startsWith('..')) {
141
+ notFoundRel = './' + notFoundRel;
142
+ }
143
+ console.log('');
144
+ console.log('Public Dir :', PUBLIC_DIR);
145
+ console.log('Static Dir :', BUILD_STATIC_DIR !== null && BUILD_STATIC_DIR !== void 0 ? BUILD_STATIC_DIR : '(None)');
146
+ console.log('SPA :', spaRel != null ? spaRel : '(None)');
147
+ console.log('404 Page :', notFoundRel != null ? notFoundRel : '(None)');
148
+ console.log('Auto-Index :', autoIndex != null ? autoIndex : '(None)');
149
+ console.log('Auto-Ext :', autoExt != null ? autoExt : '(None)');
150
+ console.log('name :', name);
151
+ console.log('author :', author);
152
+ console.log('description :', description);
153
+ console.log('Service ID :', fastlyServiceId);
154
+ console.log('');
155
+ console.log("Initializing Compute@Edge Application in " + computeJsDir + "...");
156
+ fs.mkdirSync(computeJsDir);
157
+ fs.mkdirSync(path.resolve(computeJsDir, './src'));
158
+ // .gitignore
159
+ const gitIgnoreContent = `\
160
+ /node_modules
161
+ /bin
162
+ /pkg
163
+ /src/statics.js
164
+ `;
165
+ const gitIgnorePath = path.resolve(computeJsDir, '.gitignore');
166
+ fs.writeFileSync(gitIgnorePath, gitIgnoreContent, "utf-8");
167
+ // package.json
168
+ // language=JSON
169
+ const packageJsonContent = `\
170
+ {
171
+ "name": ${JSON.stringify(name)},
172
+ "description": ${JSON.stringify(description)},
173
+ "author": ${JSON.stringify(author)},
174
+ "devDependencies": {
175
+ "@fastly/expressly": "^1.0.0-alpha.7",
176
+ "@fastly/js-compute": "^0.3.0",
177
+ "buffer": "^6.0.3",
178
+ "core-js": "^3.19.1",
179
+ "webpack": "^5.64.0",
180
+ "webpack-cli": "^4.9.1"
181
+ },
182
+ "engines": {
183
+ "node": "^16"
184
+ },
185
+ "license": "MIT",
186
+ "private": true,
187
+ "main": "src/index.js",
188
+ "scripts": {
189
+ "build": "js-compute-runtime bin/index.js bin/main.wasm",
190
+ "deploy": "npm run build && fastly compute deploy",
191
+ "prebuild": "npx @fastly/compute-js-static-publish --build-static && webpack"
192
+ },
193
+ "version": "0.2.1"
194
+ }
195
+ `;
196
+ const packageJsonPath = path.resolve(computeJsDir, 'package.json');
197
+ fs.writeFileSync(packageJsonPath, packageJsonContent, "utf-8");
198
+ // fastly.toml
199
+ // language=toml
200
+ const fastlyTomlContent = `\
201
+ # This file describes a Fastly Compute@Edge package. To learn more visit:
202
+ # https://developer.fastly.com/reference/fastly-toml/
203
+
204
+ authors = [ "${author}" ]
205
+ description = "${description}"
206
+ language = "javascript"
207
+ manifest_version = 2
208
+ name = "${name}"
209
+ service_id = "${fastlyServiceId}"
210
+ `;
211
+ const fastlyTomlPath = path.resolve(computeJsDir, 'fastly.toml');
212
+ fs.writeFileSync(fastlyTomlPath, fastlyTomlContent, "utf-8");
213
+ // static-publish.rc.js
214
+ const publicDirRel = path.relative(computeJsDir, publicDir);
215
+ const staticDirs = [];
216
+ if (buildStaticDir != null) {
217
+ staticDirs.push(buildStaticDir);
218
+ }
219
+ const staticDirsRel = [];
220
+ for (const staticDir of staticDirs) {
221
+ const rel = path.relative(publicDir, staticDir);
222
+ if (rel.startsWith('../')) {
223
+ // we can't have a path outside the public dir, so we ignore it
224
+ console.warn(`Specified static dir '${staticDir}' is not inside public directory, ignoring...`);
225
+ continue;
226
+ }
227
+ staticDirsRel.push('./' + rel);
228
+ }
229
+ let spaFileRel = false;
230
+ if (spaFilename != null) {
231
+ spaFileRel = '/' + path.relative(publicDir, spaFilename);
232
+ }
233
+ let notFoundFileRel = false;
234
+ if (notFoundPageFilename != null) {
235
+ notFoundFileRel = '/' + path.relative(publicDir, notFoundPageFilename);
236
+ }
237
+ const staticPublishJsContent = `\
238
+ module.exports = {
239
+ publicDir: ${JSON.stringify(publicDirRel)},
240
+ excludeDirs: [ './node_modules' ],
241
+ includeDirs: [ './.well-known' ],
242
+ staticDirs: ${JSON.stringify(staticDirsRel)},
243
+ spa: ${JSON.stringify(spaFileRel)},
244
+ notFoundPage: ${JSON.stringify(notFoundFileRel)},
245
+ autoIndex: ${JSON.stringify(autoIndex)},
246
+ autoExt: ${JSON.stringify(autoExt)},
247
+ };`;
248
+ const staticPublishJsonPath = path.resolve(computeJsDir, 'static-publish.rc.js');
249
+ fs.writeFileSync(staticPublishJsonPath, staticPublishJsContent, "utf-8");
250
+ // Copy resource files
251
+ const __dirname = url.fileURLToPath(new URL('.', import.meta.url));
252
+ // webpack.config.js
253
+ const webpackConfigJsSrcPath = path.resolve(__dirname, '../resources/webpack.config.js');
254
+ const webpackConfigJsPath = path.resolve(computeJsDir, 'webpack.config.js');
255
+ fs.copyFileSync(webpackConfigJsSrcPath, webpackConfigJsPath);
256
+ // src/index.js
257
+ const indexJsSrcPath = path.resolve(__dirname, '../resources/index.js');
258
+ const indexJsPath = path.resolve(computeJsDir, './src/index.js');
259
+ fs.copyFileSync(indexJsSrcPath, indexJsPath);
260
+ console.log("🚀 Compute@Edge application created!");
261
+ console.log('Installing dependencies...');
262
+ console.log(`npm --prefix ${COMPUTE_JS_DIR} install`);
263
+ child_process.spawnSync('npm', ['--prefix', COMPUTE_JS_DIR, 'install'], { stdio: 'inherit' });
264
+ console.log('');
265
+ console.log('');
266
+ console.log('To run your Compute@Edge application locally:');
267
+ console.log('');
268
+ console.log(' cd ' + COMPUTE_JS_DIR);
269
+ console.log(' fastly compute serve');
270
+ console.log('');
271
+ console.log('To build and deploy to your Compute@Edge service:');
272
+ console.log('');
273
+ console.log(' cd ' + COMPUTE_JS_DIR);
274
+ console.log(' fastly compute publish');
275
+ console.log('');
276
+ }
@@ -0,0 +1,35 @@
1
+ export class CreateReactAppPreset {
2
+ constructor() {
3
+ this.name = 'Create React App';
4
+ this.defaultOptions = {
5
+ 'public-dir': './build',
6
+ 'static-dir': '[public-dir]/static',
7
+ name: 'my-create-react-app',
8
+ description: 'Compute@Edge static site from create-react-app',
9
+ };
10
+ }
11
+ check(packageJson) {
12
+ var _a;
13
+ if (packageJson == null) {
14
+ console.error("❌ Can't read/parse package.json");
15
+ console.error("Run this from a create-react-app project directory.");
16
+ return false;
17
+ }
18
+ if (((_a = packageJson === null || packageJson === void 0 ? void 0 : packageJson.dependencies) === null || _a === void 0 ? void 0 : _a['react-scripts']) == null) {
19
+ console.error("❌ Can't find react-scripts in dependencies");
20
+ console.error("Run this from a create-react-app project directory.");
21
+ console.log("If this is a project created with create-react-app and has since been ejected, specify preset cra-eject to skip this check.");
22
+ return false;
23
+ }
24
+ return true;
25
+ }
26
+ }
27
+ export class CreateReactAppEjectedPreset extends CreateReactAppPreset {
28
+ constructor() {
29
+ super(...arguments);
30
+ this.name = 'Create React App (Ejected)';
31
+ }
32
+ check() {
33
+ return true;
34
+ }
35
+ }
@@ -0,0 +1,13 @@
1
+ export class DocusaurusPreset {
2
+ constructor() {
3
+ this.name = 'Docusaurus';
4
+ this.defaultOptions = {
5
+ 'public-dir': './build',
6
+ name: 'my-docusaurus-app',
7
+ description: 'Compute@Edge static site from docusaurus',
8
+ };
9
+ }
10
+ check() {
11
+ return true;
12
+ }
13
+ }
@@ -0,0 +1,13 @@
1
+ export class GatsbyPreset {
2
+ constructor() {
3
+ this.name = 'Gatsby';
4
+ this.defaultOptions = {
5
+ 'public-dir': './public',
6
+ name: 'my-gatsby-app',
7
+ description: 'Compute@Edge static site from Gatsby',
8
+ };
9
+ }
10
+ check() {
11
+ return true;
12
+ }
13
+ }
@@ -0,0 +1,13 @@
1
+ export class NextJsPreset {
2
+ constructor() {
3
+ this.name = 'Next.js';
4
+ this.defaultOptions = {
5
+ 'public-dir': './out',
6
+ name: 'my-next-app',
7
+ description: 'Compute@Edge static site from Next.js',
8
+ };
9
+ }
10
+ check() {
11
+ return true;
12
+ }
13
+ }
@@ -0,0 +1,13 @@
1
+ export class SvelteKitPreset {
2
+ constructor() {
3
+ this.name = 'SvelteKit';
4
+ this.defaultOptions = {
5
+ 'public-dir': './dist',
6
+ name: 'my-sveltekit-app',
7
+ description: 'Compute@Edge static site from SvelteKit',
8
+ };
9
+ }
10
+ check() {
11
+ return true;
12
+ }
13
+ }
@@ -0,0 +1,13 @@
1
+ export class VitePreset {
2
+ constructor() {
3
+ this.name = 'Vite';
4
+ this.defaultOptions = {
5
+ 'public-dir': './dist',
6
+ name: 'my-vite-app',
7
+ description: 'Compute@Edge static site from Vite',
8
+ };
9
+ }
10
+ check() {
11
+ return true;
12
+ }
13
+ }
@@ -0,0 +1,16 @@
1
+ import { CreateReactAppPreset, CreateReactAppEjectedPreset } from './implementations/create-react-app.js';
2
+ import { VitePreset } from './implementations/vite.js';
3
+ import { SvelteKitPreset } from './implementations/sveltekit.js';
4
+ import { NextJsPreset } from './implementations/next.js';
5
+ import { GatsbyPreset } from './implementations/gatsby.js';
6
+ import { DocusaurusPreset } from './implementations/docusaurus.js';
7
+ export const presets = {
8
+ 'cra': CreateReactAppPreset,
9
+ 'create-react-app': CreateReactAppPreset,
10
+ 'cra-eject': CreateReactAppEjectedPreset,
11
+ 'vite': VitePreset,
12
+ 'sveltekit': SvelteKitPreset,
13
+ 'next': NextJsPreset,
14
+ 'gatsby': GatsbyPreset,
15
+ 'docusaurus': DocusaurusPreset,
16
+ };
@@ -0,0 +1 @@
1
+ export {};
package/package.json ADDED
@@ -0,0 +1,43 @@
1
+ {
2
+ "name": "@fastly/compute-js-static-publish",
3
+ "type": "module",
4
+ "version": "1.0.0",
5
+ "description": "Static Publisher for Compute@Edge JavaScript",
6
+ "main": "./build/index.js",
7
+ "scripts": {
8
+ "prepack": "npm run build",
9
+ "build": "tsc",
10
+ "test": "echo \"Error: no test specified\" && exit 1"
11
+ },
12
+ "bin": {
13
+ "compute-js-static-publish": "./build/index.js",
14
+ "compute-js-build-static-loader": "./build/build-static.js"
15
+ },
16
+ "repository": {
17
+ "type": "git",
18
+ "url": "git+https://github.com/fastly/compute-js-static-publish.git"
19
+ },
20
+ "keywords": [
21
+ "compute-js",
22
+ "javascript",
23
+ "static",
24
+ "serve"
25
+ ],
26
+ "author": "Katsuyuki Omuro <komuro@fastly.com>",
27
+ "license": "MIT",
28
+ "bugs": {
29
+ "url": "https://github.com/fastly/compute-js-static-publish/issues"
30
+ },
31
+ "homepage": "https://github.com/fastly/compute-js-static-publish#readme",
32
+ "dependencies": {
33
+ "command-line-args": "^5.2.1",
34
+ "typescript": "^4.7.4"
35
+ },
36
+ "devDependencies": {
37
+ "@types/command-line-args": "^5.2.0",
38
+ "@types/node": "^18.0.0"
39
+ },
40
+ "engines": {
41
+ "node": ">=14.8"
42
+ }
43
+ }
@@ -0,0 +1,3 @@
1
+ ## Resources
2
+
3
+ The files in this directory are copied into the output folder.
@@ -0,0 +1,105 @@
1
+ const defaultContentTypes = [
2
+ // Text formats
3
+ { test: /.txt$/, type: 'text/plain', binary: false },
4
+ { test: /.htm(l)?$/, type: 'text/html', binary: false },
5
+ { test: /.xml$/, type: 'application/xml', binary: false },
6
+ { test: /.json$/, type: 'application/json', binary: false },
7
+ { test: /.map$/, type: 'application/json', binary: false },
8
+ { test: /.js$/, type: 'application/javascript', binary: false },
9
+ { test: /.css$/, type: 'text/css', binary: false },
10
+ { test: /.svg$/, type: 'image/svg+xml', binary: false },
11
+
12
+ // Binary formats
13
+ { test: /.bmp$/, type: 'image/bmp', binary: true },
14
+ { test: /.png$/, type: 'image/png', binary: true },
15
+ { test: /.gif$/, type: 'image/gif', binary: true },
16
+ { test: /.jp(e)?g$/, type: 'image/jpeg', binary: true },
17
+ { test: /.ico$/, type: 'image/vnd.microsoft.icon', binary: true },
18
+ { test: /.tif(f)?$/, type: 'image/png', binary: true },
19
+ { test: /.aac$/, type: 'audio/aac', binary: true },
20
+ { test: /.mp3$/, type: 'audio/mpeg', binary: true },
21
+ { test: /.avi$/, type: 'video/x-msvideo', binary: true },
22
+ { test: /.mp4$/, type: 'video/mp4', binary: true },
23
+ { test: /.mpeg$/, type: 'video/mpeg', binary: true },
24
+ { test: /.webm$/, type: 'video/webm', binary: true },
25
+ { test: /.pdf$/, type: 'application/pdf', binary: true },
26
+ { test: /.tar$/, type: 'application/x-tar', binary: true },
27
+ { test: /.zip$/, type: 'application/zip', binary: true },
28
+ { test: /.eot$/, type: 'application/vnd.ms-fontobject', binary: true },
29
+ { test: /.otf$/, type: 'font/otf', binary: true },
30
+ { test: /.ttf$/, type: 'font/ttf', binary: true },
31
+ { test: /.woff$/, type: 'font/woff', binary: true },
32
+ { test: /.woff2$/, type: 'font/woff2', binary: true },
33
+ ];
34
+
35
+ function mergeContentTypes(contentTypes) {
36
+
37
+ const finalContentTypes = [];
38
+
39
+ if(!Array.isArray(contentTypes)) {
40
+ console.warn('contentTypes not an array, ignoring.');
41
+ } else {
42
+
43
+ for (const [index, contentType] of contentTypes.entries()) {
44
+ let invalid = false;
45
+
46
+ if(
47
+ typeof contentType.test !== 'function' &&
48
+ !(contentType.test instanceof RegExp)
49
+ ) {
50
+ console.warn(`Ignoring contentTypes[${index}]: 'test' must be a function or regular expression.`);
51
+ invalid = true;
52
+ }
53
+
54
+ if(typeof contentType.type !== 'string' || contentType.type.indexOf('/') === -1) {
55
+ console.warn(`Ignoring contentTypes[${index}]: 'type' must be a string representing a MIME type.`);
56
+ invalid = true;
57
+ }
58
+
59
+ if('binary' in contentType && typeof contentType.binary !== 'boolean') {
60
+ console.warn(`Ignoring contentTypes[${index}]: optional 'binary' must be a boolean value.`);
61
+ invalid = true;
62
+ }
63
+
64
+ if(!invalid) {
65
+ const contentTypeDef = {
66
+ test: contentType.test,
67
+ type: contentType.type,
68
+ };
69
+ if(contentType.binary != null) {
70
+ contentTypeDef.binary = contentType.binary;
71
+ }
72
+ finalContentTypes.push(contentTypeDef);
73
+ }
74
+ }
75
+ }
76
+
77
+ console.log('Applying ' + finalContentTypes.length + ' custom content type(s).');
78
+
79
+ for (const contentType of defaultContentTypes) {
80
+ finalContentTypes.push(contentType);
81
+ }
82
+
83
+ return finalContentTypes;
84
+ }
85
+
86
+ function testFileContentType(contentTypes, file) {
87
+ for (const contentType of contentTypes) {
88
+ let matched = false;
89
+ if(contentType.test instanceof RegExp) {
90
+ matched = contentType.test.test(file);
91
+ } else {
92
+ // should be a function
93
+ matched = contentType.test(file);
94
+ }
95
+ if(matched) {
96
+ return { type: contentType.type, binary: Boolean(contentType.binary) };
97
+ }
98
+ }
99
+ return null;
100
+ }
101
+
102
+ module.exports = {
103
+ mergeContentTypes,
104
+ testFileContentType,
105
+ };
@@ -0,0 +1,120 @@
1
+ /// <reference types="@fastly/js-compute" />
2
+
3
+ import { Router } from '@fastly/expressly';
4
+ import { assets, spaFile, notFoundPageFile, autoIndex, autoExt } from './statics';
5
+
6
+ const router = new Router();
7
+
8
+ function getMatchingRequestPath(path) {
9
+ // If the path being looked up does not end in a slash, it has to
10
+ // match exactly one of the assets
11
+ if(!path.endsWith('/')) {
12
+
13
+ if(path in assets) {
14
+ return path;
15
+ }
16
+
17
+ // try auto-ext
18
+ if(autoExt != null) {
19
+ for (const extEntry of autoExt) {
20
+ let pathWithExt = path + extEntry;
21
+ if(pathWithExt in assets) {
22
+ return pathWithExt;
23
+ }
24
+ }
25
+ }
26
+
27
+ return null;
28
+
29
+ }
30
+
31
+ // try auto-index
32
+ if(autoIndex != null) {
33
+ for (const indexEntry of autoIndex) {
34
+ let indexPath = path + indexEntry;
35
+ if(indexPath in assets) {
36
+ return indexPath;
37
+ }
38
+ }
39
+ }
40
+
41
+ return null;
42
+ }
43
+
44
+ function requestAcceptsTextHtml(req) {
45
+ const accept = (req.headers.get('Accept') ?? '')
46
+ .split(',')
47
+ .map(x => x.split(';')[0]);
48
+ if(!accept.includes('text/html') && !accept.includes('*/*') && accept.includes('*')) {
49
+ return false;
50
+ }
51
+ return true;
52
+ }
53
+
54
+ router.get("*", (req, res) => {
55
+ const assetPath = getMatchingRequestPath(req.urlObj.pathname);
56
+ if(assetPath == null) {
57
+ return;
58
+ }
59
+ const staticFile = assets[assetPath];
60
+
61
+ // Aggressive caching for static files, and no caching for everything else.
62
+ // https://create-react-app.dev/docs/production-build/#static-file-caching
63
+ const headers = {
64
+ 'Cache-Control': staticFile.isStatic ? 'max-age=31536000' : 'no-cache',
65
+ };
66
+ if(staticFile.contentType != null) {
67
+ headers['Content-Type'] = staticFile.contentType;
68
+ }
69
+ res.send(new Response(staticFile.content, {
70
+ status: 200,
71
+ headers,
72
+ }));
73
+ });
74
+
75
+ // TODO: If you need to handle any API routes, add them here.
76
+ // router.get("/api/endpoint", (req, res) => {
77
+ // res.send("foo");
78
+ // });
79
+
80
+ // If this is a SPA, then return index.html for HTML requests
81
+ router.get("*", (req, res) => {
82
+ if(!spaFile) {
83
+ return;
84
+ }
85
+ if(!requestAcceptsTextHtml(req)) {
86
+ return;
87
+ }
88
+
89
+ const staticFile = assets[spaFile];
90
+ res.send(new Response(staticFile.content, {
91
+ status: 200,
92
+ headers: {
93
+ 'Cache-Control': 'no-cache',
94
+ 'Content-Type': 'text/html',
95
+ }
96
+ }));
97
+ });
98
+
99
+ router.all("*", (req, res) => {
100
+ if(notFoundPageFile && requestAcceptsTextHtml(req)) {
101
+ const staticFile = assets[notFoundPageFile];
102
+ res.send(new Response(staticFile.content, {
103
+ status: 404,
104
+ headers: {
105
+ 'Cache-Control': 'no-cache',
106
+ 'Content-Type': 'text/html',
107
+ }
108
+ }));
109
+ return;
110
+ }
111
+
112
+ res.send(new Response("404 Not Found", {
113
+ status: 404,
114
+ headers: {
115
+ 'Content-Type': 'text/plain',
116
+ },
117
+ }));
118
+ });
119
+
120
+ router.listen();