@fastly/compute-js-static-publish 4.0.0-alpha.4 → 4.1.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 (102) hide show
  1. package/README.md +51 -27
  2. package/build/cli/commands/build-static.d.ts.map +1 -1
  3. package/build/cli/commands/build-static.js +5 -4
  4. package/build/cli/commands/clean-object-store.d.ts.map +1 -1
  5. package/build/cli/commands/init-app.d.ts.map +1 -1
  6. package/build/cli/commands/init-app.js +0 -1
  7. package/build/cli/index.js +2 -0
  8. package/build/cli/presets/implementations/astro.d.ts +7 -0
  9. package/build/cli/presets/implementations/astro.d.ts.map +1 -0
  10. package/build/cli/presets/implementations/astro.js +23 -0
  11. package/build/cli/presets/implementations/vue.d.ts +7 -0
  12. package/build/cli/presets/implementations/vue.d.ts.map +1 -0
  13. package/build/cli/presets/implementations/vue.js +24 -0
  14. package/build/cli/presets/index.d.ts.map +1 -1
  15. package/build/cli/presets/index.js +4 -0
  16. package/build/compute-js.d.ts +3 -0
  17. package/build/compute-js.d.ts.map +1 -0
  18. package/build/compute-js.js +2 -0
  19. package/build/server/assets/asset-manager.d.ts +1 -0
  20. package/build/server/assets/asset-manager.d.ts.map +1 -1
  21. package/build/server/assets/asset-manager.js +3 -0
  22. package/build/server/assets/content-asset-object-store.d.ts +18 -0
  23. package/build/server/assets/content-asset-object-store.d.ts.map +1 -0
  24. package/build/server/assets/content-asset-object-store.js +67 -0
  25. package/build/server/assets/content-asset-wasm-inline.d.ts +17 -0
  26. package/build/server/assets/content-asset-wasm-inline.d.ts.map +1 -0
  27. package/build/server/assets/content-asset-wasm-inline.js +48 -0
  28. package/build/server/assets/content-assets-runtime.d.ts +2 -0
  29. package/build/server/assets/content-assets-runtime.d.ts.map +1 -0
  30. package/build/server/assets/content-assets.d.ts +33 -21
  31. package/build/server/assets/content-assets.d.ts.map +1 -1
  32. package/build/server/assets/content-assets.js +39 -85
  33. package/build/types/content-assets.d.ts +23 -7
  34. package/build/types/content-assets.d.ts.map +1 -1
  35. package/build/util/metadata.js +1 -1
  36. package/package.json +1 -1
  37. package/build/assets/asset-manager.d.ts +0 -7
  38. package/build/assets/asset-manager.d.ts.map +0 -1
  39. package/build/assets/asset-manager.js +0 -11
  40. package/build/assets/content-assets.d.ts +0 -29
  41. package/build/assets/content-assets.d.ts.map +0 -1
  42. package/build/assets/content-assets.js +0 -88
  43. package/build/assets/module-assets.d.ts +0 -23
  44. package/build/assets/module-assets.d.ts.map +0 -1
  45. package/build/assets/module-assets.js +0 -45
  46. package/build/cli/build-static.d.ts +0 -3
  47. package/build/cli/build-static.d.ts.map +0 -1
  48. package/build/cli/build-static.js +0 -524
  49. package/build/cli/clean-object-store.d.ts +0 -2
  50. package/build/cli/clean-object-store.d.ts.map +0 -1
  51. package/build/cli/cli.d.ts +0 -3
  52. package/build/cli/cli.d.ts.map +0 -1
  53. package/build/cli/cli.js +0 -77
  54. package/build/cli/init-app.d.ts +0 -3
  55. package/build/cli/init-app.d.ts.map +0 -1
  56. package/build/cli/init-app.js +0 -283
  57. package/build/presets/implementations/create-react-app.d.ts +0 -16
  58. package/build/presets/implementations/create-react-app.d.ts.map +0 -1
  59. package/build/presets/implementations/create-react-app.js +0 -34
  60. package/build/presets/implementations/docusaurus.d.ts +0 -11
  61. package/build/presets/implementations/docusaurus.d.ts.map +0 -1
  62. package/build/presets/implementations/docusaurus.js +0 -13
  63. package/build/presets/implementations/gatsby.d.ts +0 -11
  64. package/build/presets/implementations/gatsby.d.ts.map +0 -1
  65. package/build/presets/implementations/gatsby.js +0 -13
  66. package/build/presets/implementations/next.d.ts +0 -11
  67. package/build/presets/implementations/next.d.ts.map +0 -1
  68. package/build/presets/implementations/next.js +0 -13
  69. package/build/presets/implementations/sveltekit.d.ts +0 -11
  70. package/build/presets/implementations/sveltekit.d.ts.map +0 -1
  71. package/build/presets/implementations/sveltekit.js +0 -13
  72. package/build/presets/implementations/vite.d.ts +0 -11
  73. package/build/presets/implementations/vite.d.ts.map +0 -1
  74. package/build/presets/implementations/vite.js +0 -13
  75. package/build/presets/index.d.ts +0 -3
  76. package/build/presets/index.d.ts.map +0 -1
  77. package/build/presets/index.js +0 -16
  78. package/build/presets/preset-base.d.ts +0 -18
  79. package/build/presets/preset-base.d.ts.map +0 -1
  80. package/build/presets/preset-base.js +0 -1
  81. package/build/server/object-store/include-bytes-store-entry.d.ts +0 -19
  82. package/build/server/object-store/include-bytes-store-entry.d.ts.map +0 -1
  83. package/build/server/object-store/include-bytes-store-entry.js +0 -87
  84. package/build/util/data.d.ts +0 -7
  85. package/build/util/data.d.ts.map +0 -1
  86. package/build/util/data.js +0 -58
  87. package/build/util/fastly-api.d.ts +0 -10
  88. package/build/util/fastly-api.d.ts.map +0 -1
  89. package/build/util/fastly-api.js +0 -47
  90. package/build/util/files.d.ts +0 -10
  91. package/build/util/files.d.ts.map +0 -1
  92. package/build/util/files.js +0 -32
  93. package/build/util/hash.d.ts +0 -2
  94. package/build/util/hash.d.ts.map +0 -1
  95. package/build/util/hash.js +0 -8
  96. package/build/util/id.d.ts +0 -3
  97. package/build/util/id.d.ts.map +0 -1
  98. package/build/util/id.js +0 -17
  99. package/build/util/object-store.d.ts +0 -12
  100. package/build/util/object-store.d.ts.map +0 -1
  101. package/build/util/object-store.js +0 -80
  102. /package/build/{cli/clean-object-store.js → server/assets/content-assets-runtime.js} +0 -0
@@ -1,524 +0,0 @@
1
- // This program builds static resources out of the files in the
2
- // public folder to be served.
3
- // e.g., with create-react-app, this would be the ./build directory.
4
- // Outputs:
5
- // statics-metadata.js
6
- // deploymentId: string - deployment ID
7
- // contentAssetMetadataMap: Map<string, ContentAssetMetadata> - mapping of asset keys to their metadata
8
- // - key: filename relative to public dir (e.g., /foo/index.html)
9
- // - value:
10
- // - size (to be implemented soon): number - File size in bytes
11
- // - contentType: string - MIME type
12
- // - timestamp (to be implemented soon): last modified time as unix time
13
- // - etag (to be implemented soon): string - Etag
14
- // - text: boolean - whether this is a text file
15
- // statics.js
16
- // imports statics-metadata.js and adds utilities to load the files
17
- // contentAssetMap: Map<string, ContentAsset>
18
- // - key: filename relative to public dir (e.g., /foo/index.html)
19
- // - value:
20
- // - getMetadata() - gets the metadata entry
21
- // - getBody() - gets a Body object that represents the asset
22
- // moduleAssetMap: Map<string, ModuleAsset>
23
- // - key: filename relative to public dir (e.g., /foo/index.html)
24
- // - value:
25
- // - getMetadata() - gets the metadata entry
26
- // - async getModule() - Returns a promise that imports the module and returns a reference.
27
- // This simply returns the statically imported module if it is statically imported.
28
- // - getStaticModule() - Advanced. Returns the statically imported module, or null.
29
- // This also reexports values like the "spa" value in the static-publish.rc.js
30
- // file so that the C@E handler knows what file to serve up if
31
- // the resource doesn't map to a file.
32
- import * as fs from "fs";
33
- import * as path from "path";
34
- import * as url from "url";
35
- import { loadConfigFile } from "./load-config.js";
36
- import { applyDefaults } from "./util/data.js";
37
- import { calculateFileHash } from "./util/hash.js";
38
- import { getFiles } from "./util/files.js";
39
- import { createStringId } from "./util/id.js";
40
- import { loadApiKey } from "./util/fastly-api.js";
41
- import { objectStoreEntryExists, objectStoreSubmitFile } from "./util/object-store.js";
42
- import { mergeContentTypes, testFileContentType } from "../util/content-types.js";
43
- import { algs } from "./compression/index.js";
44
- function generateOrLoadPublishId() {
45
- let created = false;
46
- const filename = './.publish-id';
47
- let contents;
48
- try {
49
- contents = fs.readFileSync(filename, 'utf-8');
50
- }
51
- catch {
52
- contents = null;
53
- }
54
- let publishId = null;
55
- if (contents != null) {
56
- publishId = contents
57
- .split('\n')
58
- .find(line => line.length > 0 && !line.startsWith('#')) ?? null;
59
- }
60
- if (publishId == null) {
61
- publishId = createStringId();
62
- created = true;
63
- const fileContents = `# Generated by @fastly/compute-js-static-publish.\n${publishId}\n`;
64
- fs.writeFileSync(filename, fileContents, 'utf-8');
65
- }
66
- return { publishId, created };
67
- }
68
- async function uploadFilesToObjectStore(fastlyApiContext, objectStoreName, objectStoreItems) {
69
- for (const { objectStoreKey, staticFilePath, text } of objectStoreItems) {
70
- if (await objectStoreEntryExists(fastlyApiContext, objectStoreName, objectStoreKey)) {
71
- // Already exists in Object Store
72
- console.log(`✔️ Asset already exists in Object Store with key "${objectStoreKey}".`);
73
- }
74
- else {
75
- // Upload to Object Store
76
- const fileData = fs.readFileSync(staticFilePath);
77
- await objectStoreSubmitFile(fastlyApiContext, objectStoreName, objectStoreKey, fileData);
78
- console.log(`✔️ Submitted ${text ? 'text' : 'binary'} asset "${staticFilePath}" to Object Store at key "${objectStoreKey}".`);
79
- }
80
- }
81
- }
82
- function writeObjectStoreEntriesToFastlyToml(objectStoreName, objectStoreItems) {
83
- let fastlyToml = fs.readFileSync('./fastly.toml', 'utf-8');
84
- let before = '';
85
- let after = '';
86
- const tableMarker = `[[local_server.object_store.${objectStoreName}]]`;
87
- const startPos = fastlyToml.indexOf(tableMarker);
88
- if (startPos === -1) {
89
- // Object store decl not in fastly.toml yet
90
- if (fastlyToml.indexOf(objectStoreName) !== -1) {
91
- // don't do this!
92
- console.error("Don't do this!");
93
- throw "No";
94
- }
95
- let newLines;
96
- if (fastlyToml.endsWith('\n\n')) {
97
- newLines = '';
98
- }
99
- else if (fastlyToml.endsWith('\n')) {
100
- newLines = '\n';
101
- }
102
- else {
103
- newLines = '\n\n';
104
- }
105
- before = fastlyToml + newLines;
106
- after = '';
107
- }
108
- else {
109
- const lastObjStoreTablePos = fastlyToml.lastIndexOf(tableMarker);
110
- const nextTablePos = fastlyToml.indexOf('[', lastObjStoreTablePos + tableMarker.length);
111
- before = fastlyToml.slice(0, startPos);
112
- if (nextTablePos === -1) {
113
- after = '';
114
- }
115
- else {
116
- after = fastlyToml.slice(nextTablePos);
117
- }
118
- }
119
- let tablesToml = '';
120
- for (const { objectStoreKey, staticFilePath } of objectStoreItems) {
121
- // Probably, JSON.stringify is wrong, but it should do its job
122
- tablesToml += tableMarker + '\n';
123
- tablesToml += 'key = ' + JSON.stringify(objectStoreKey) + '\n';
124
- tablesToml += 'path = ' + JSON.stringify(path.relative('./', staticFilePath)) + '\n';
125
- tablesToml += '\n';
126
- }
127
- fastlyToml = before + tablesToml + after;
128
- fs.writeFileSync('./fastly.toml', fastlyToml, 'utf-8');
129
- }
130
- export async function buildStaticLoader(commandLineValues) {
131
- const { 'suppress-framework-warnings': suppressFrameworkWarnings } = commandLineValues;
132
- const displayFrameworkWarnings = !suppressFrameworkWarnings;
133
- const { publishId, created } = generateOrLoadPublishId();
134
- if (created) {
135
- console.log("✅ Created publish ID");
136
- }
137
- console.log(`Publish ID: ${publishId}`);
138
- console.log("🚀 Building loader...");
139
- const errors = [];
140
- const config = await loadConfigFile(errors);
141
- if (config == null) {
142
- console.error("❌ Can't load static-publish.rc.js");
143
- console.error("Run this from a compute-js-static-publish compute-js directory.");
144
- for (const error of errors) {
145
- console.error(error);
146
- }
147
- process.exitCode = 1;
148
- return;
149
- }
150
- const outputDir = path.resolve();
151
- const publicDirRoot = path.resolve(config.rootDir);
152
- console.log(`✔️ Public directory '${publicDirRoot}'.`);
153
- const objectStoreName = config.objectStore;
154
- let fastlyApiContext = null;
155
- if (objectStoreName != null) {
156
- // TODO: load api key from command line
157
- const apiKeyResult = loadApiKey();
158
- if (apiKeyResult == null) {
159
- console.error("❌ Fastly API Token not provided.");
160
- console.error("Specify one on the command line, or use the FASTLY_API_TOKEN environment variable.");
161
- process.exitCode = 1;
162
- return;
163
- }
164
- fastlyApiContext = { apiToken: apiKeyResult.apiToken };
165
- console.log(`✔️ Using Object Store mode, with object store: ${objectStoreName}`);
166
- console.log(`✔️ Fastly API Token: ${fastlyApiContext.apiToken.slice(0, 4)}${'*'.repeat(fastlyApiContext.apiToken.length - 4)} from '${apiKeyResult.source}'`);
167
- }
168
- else {
169
- if (displayFrameworkWarnings) {
170
- console.log(`✔️ Not using Object Store mode.`);
171
- }
172
- }
173
- const excludeDirs = config.excludeDirs;
174
- if (excludeDirs.length > 0) {
175
- console.log(`✔️ Using exclude directories: ${excludeDirs.join(', ')}`);
176
- }
177
- else {
178
- if (displayFrameworkWarnings) {
179
- console.log(`✔️ No exclude directories defined.`);
180
- }
181
- }
182
- const excludeDotFiles = config.excludeDotFiles;
183
- if (excludeDotFiles) {
184
- console.log(`✔️ Files/Directories starting with . are excluded.`);
185
- }
186
- const includeWellKnown = config.includeWellKnown;
187
- if (includeWellKnown) {
188
- console.log(`✔️ (.well-known is exempt from exclusion.)`);
189
- }
190
- const __dirname = url.fileURLToPath(new URL('.', import.meta.url));
191
- // Load content types
192
- const finalContentTypes = mergeContentTypes(config.contentTypes);
193
- // getFiles() applies excludeDirs, excludeDotFiles, and includeWellKnown.
194
- let files = getFiles(publicDirRoot, config);
195
- // If public dir is not inside the c@e dir, then
196
- // exclude files that come from C@E app dir
197
- if (!publicDirRoot.startsWith(outputDir)) {
198
- files = files.filter(file => !file.startsWith(outputDir));
199
- }
200
- // And then we apply assetInclusionTest.
201
- const assetInfos = files.map(file => {
202
- const assetKey = file.slice(publicDirRoot.length);
203
- let contentTypeTestResult = testFileContentType(finalContentTypes, assetKey);
204
- if (contentTypeTestResult == null) {
205
- contentTypeTestResult = {
206
- text: false,
207
- contentType: 'application/octet-stream',
208
- };
209
- if (displayFrameworkWarnings) {
210
- console.log('⚠️ Notice: Unknown file type ' + assetKey + '. Treating as binary file.');
211
- }
212
- }
213
- let contentAssetInclusionResultValue = config.contentAssetInclusionTest?.(assetKey, contentTypeTestResult.contentType);
214
- if (typeof contentAssetInclusionResultValue === 'boolean') {
215
- contentAssetInclusionResultValue = {
216
- includeContent: contentAssetInclusionResultValue,
217
- };
218
- }
219
- else if (contentAssetInclusionResultValue === 'inline') {
220
- contentAssetInclusionResultValue = {
221
- includeContent: true,
222
- inline: true,
223
- };
224
- }
225
- const contentAssetInclusionResult = applyDefaults(contentAssetInclusionResultValue ?? null, {
226
- includeContent: true,
227
- inline: false,
228
- });
229
- let moduleAssetInclusionResultValue = config.moduleAssetInclusionTest?.(assetKey, contentTypeTestResult.contentType);
230
- if (typeof moduleAssetInclusionResultValue === 'boolean') {
231
- moduleAssetInclusionResultValue = {
232
- includeModule: moduleAssetInclusionResultValue,
233
- };
234
- }
235
- else if (moduleAssetInclusionResultValue === 'static-import') {
236
- moduleAssetInclusionResultValue = {
237
- includeModule: true,
238
- useStaticImport: true,
239
- };
240
- }
241
- const moduleAssetInclusionResult = applyDefaults(moduleAssetInclusionResultValue ?? null, {
242
- includeModule: false,
243
- useStaticImport: false,
244
- });
245
- const stats = fs.statSync(file);
246
- const lastModifiedTime = Math.floor((stats.mtime).getTime() / 1000);
247
- const hash = calculateFileHash(file);
248
- return {
249
- file,
250
- assetKey,
251
- lastModifiedTime,
252
- hash,
253
- ...contentAssetInclusionResult,
254
- ...moduleAssetInclusionResult,
255
- ...contentTypeTestResult,
256
- };
257
- });
258
- console.log("🚀 Preparing content assets ...");
259
- // Create "static content" dir that will be used to hold a copy of static files.
260
- // NOTE: this is needed because includeBytes doesn't seem to be able to traverse up to parent dir of the Compute project.
261
- const staticContentDir = './src/static-content';
262
- fs.rmSync(staticContentDir, { recursive: true, force: true });
263
- fs.mkdirSync(staticContentDir, { recursive: true });
264
- // Build content assets metadata
265
- const contentAssetMetadataMap = {};
266
- // Object store items to upload
267
- const objectStoreItems = [];
268
- let contentItems = 0;
269
- const counts = {
270
- inline: 0,
271
- objectStore: 0,
272
- excluded: 0,
273
- };
274
- for (const assetInfo of assetInfos) {
275
- if (!assetInfo.includeContent) {
276
- // Non-content asset
277
- counts.excluded++;
278
- continue;
279
- }
280
- contentItems++;
281
- console.log(`✔️ [${contentItems}] ${assetInfo.assetKey}: ${JSON.stringify(assetInfo.contentType)}`);
282
- const { file, assetKey, contentType, text, hash, lastModifiedTime, } = assetInfo;
283
- const entryBase = {
284
- assetKey,
285
- contentType,
286
- lastModifiedTime,
287
- hash,
288
- text,
289
- fileInfo: {
290
- hash,
291
- },
292
- };
293
- let metadata;
294
- const isInline = objectStoreName == null || assetInfo.inline;
295
- const staticContentFilePath = `${staticContentDir}/file${contentItems}.${assetInfo.text ? 'txt' : 'bin'}`;
296
- async function prepareCompressedVersions(contentCompressions, func) {
297
- for (const alg of contentCompression) {
298
- const compressTo = algs[alg];
299
- if (compressTo != null) {
300
- // Even for items that are not inlined, compressed copies of the file are
301
- // always created in the static content directory.
302
- const staticFilePath = `${staticContentFilePath}_${alg}`;
303
- if (await compressTo(file, staticFilePath, text)) {
304
- console.log(`✔️ Compressed ${text ? 'text' : 'binary'} asset "${file}" to "${staticFilePath}" [${alg}].`);
305
- const hash = calculateFileHash(staticFilePath);
306
- func(alg, staticFilePath, hash);
307
- }
308
- }
309
- }
310
- }
311
- const contentCompression = config.contentCompression;
312
- if (isInline) {
313
- // We will inline this file using includeBytes(), so we copy it to the static-content directory.
314
- const staticFilePath = staticContentFilePath;
315
- fs.cpSync(file, staticFilePath);
316
- console.log(`✔️ Copied ${text ? 'text' : 'binary'} asset "${file}" to "${staticFilePath}".`);
317
- const compressedFileInfos = {};
318
- await prepareCompressedVersions(contentCompression, (alg, staticFilePath, hash) => {
319
- compressedFileInfos[alg] = { staticFilePath, hash };
320
- });
321
- metadata = {
322
- ...entryBase,
323
- isInline,
324
- fileInfo: {
325
- ...entryBase.fileInfo,
326
- staticFilePath,
327
- },
328
- compressedFileInfos,
329
- };
330
- counts.inline++;
331
- }
332
- else {
333
- // For object store mode, we don't need to make a copy of the original file
334
- const staticFilePath = file;
335
- // Use the hash as part of the object store key name. This avoids having to
336
- // re-upload a file if it already exists.
337
- const objectStoreKey = `${publishId}:${assetKey}_${hash}`;
338
- objectStoreItems.push({
339
- objectStoreKey,
340
- staticFilePath,
341
- text,
342
- });
343
- const compressedFileInfos = {};
344
- await prepareCompressedVersions(contentCompression, (alg, staticFilePath, hash) => {
345
- const objectStoreKey = `${publishId}:${assetKey}_${alg}_${hash}`;
346
- compressedFileInfos[alg] = { staticFilePath, objectStoreKey, hash };
347
- objectStoreItems.push({
348
- objectStoreKey,
349
- staticFilePath,
350
- text,
351
- });
352
- });
353
- metadata = {
354
- ...entryBase,
355
- isInline,
356
- fileInfo: {
357
- ...entryBase.fileInfo,
358
- staticFilePath,
359
- objectStoreKey,
360
- },
361
- compressedFileInfos,
362
- };
363
- counts.objectStore++;
364
- }
365
- contentAssetMetadataMap[assetKey] = metadata;
366
- }
367
- if (objectStoreName != null) {
368
- await uploadFilesToObjectStore(fastlyApiContext, objectStoreName, objectStoreItems);
369
- writeObjectStoreEntriesToFastlyToml(objectStoreName, objectStoreItems);
370
- }
371
- console.log("✅ Prepared " + (counts.inline + counts.objectStore) + " content asset(s):");
372
- if (counts.inline > 0) {
373
- console.log(" " + counts.inline + " inline");
374
- }
375
- if (counts.objectStore > 0) {
376
- console.log(" " + counts.objectStore + " object store");
377
- }
378
- // Build statics-metadata.js
379
- let metadataFileContents = `/*
380
- * Generated by @fastly/compute-js-static-publish.
381
- */
382
-
383
- `;
384
- metadataFileContents += `\nexport const objectStoreName = ${JSON.stringify(objectStoreName)};\n`;
385
- metadataFileContents += `\nexport const contentAssetMetadataMap = {\n`;
386
- for (const [key, value] of Object.entries(contentAssetMetadataMap)) {
387
- metadataFileContents += ` ${JSON.stringify(key)}: ${JSON.stringify(value)},\n`;
388
- }
389
- metadataFileContents += '};\n';
390
- fs.writeFileSync('./src/statics-metadata.js', metadataFileContents);
391
- console.log(`✅ Wrote static file metadata for ${contentItems} file(s).`);
392
- // Copy Types file for static file loader
393
- try {
394
- const typesFile = path.resolve(__dirname, '../../resources/statics-metadata.d.ts');
395
- fs.copyFileSync(typesFile, './src/statics-metadata.d.ts');
396
- console.log("✅ Wrote content assets metadata types file statics-metadata.d.ts.");
397
- }
398
- catch {
399
- console.log("⚠️ Notice: could not write content assets metadata types file statics-metadata.d.ts.");
400
- }
401
- // Build statics.js
402
- let fileContents = `/*
403
- * Generated by @fastly/compute-js-static-publish.
404
- */
405
-
406
- `;
407
- fileContents += 'import { ContentAssets, ModuleAssets, PublisherServer } from "@fastly/compute-js-static-publish";\n\n';
408
- fileContents += 'import { objectStoreName, contentAssetMetadataMap } from "./statics-metadata";\n';
409
- // Add import statements for assets that are modules and that need to be statically imported.
410
- const staticImportModuleNumbers = {};
411
- let staticImportModuleNumber = 0;
412
- for (const assetInfo of assetInfos) {
413
- if (assetInfo.includeModule && assetInfo.useStaticImport) {
414
- staticImportModuleNumber++;
415
- staticImportModuleNumbers[assetInfo.assetKey] = staticImportModuleNumber;
416
- // static-content lives in the src dir, so the import must be declared as
417
- // relative to that file.
418
- const relativeFilePath = path.relative('./src', assetInfo.file);
419
- fileContents += `import * as fileModule${staticImportModuleNumber} from "${relativeFilePath}";\n`;
420
- }
421
- }
422
- fileContents += `\nexport const moduleAssetsMap = {\n`;
423
- for (const assetInfo of assetInfos) {
424
- if (!assetInfo.includeModule) {
425
- continue;
426
- }
427
- let module;
428
- let loadModuleFunction;
429
- if (assetInfo.useStaticImport) {
430
- const moduleNumber = staticImportModuleNumbers[assetInfo.assetKey];
431
- if (moduleNumber == null) {
432
- throw new Error(`Unexpected! module asset number for "${assetInfo.assetKey}" was not found!`);
433
- }
434
- loadModuleFunction = `() => Promise.resolve(fileModule${moduleNumber})`;
435
- module = `fileModule${moduleNumber}`;
436
- }
437
- else {
438
- // static-content lives in the src dir, so the import must be declared as
439
- // relative to that file.
440
- const relativeFilePath = path.relative('./src', assetInfo.file);
441
- loadModuleFunction = `() => import("${relativeFilePath}")`;
442
- module = 'null';
443
- }
444
- fileContents += ` ${JSON.stringify(assetInfo.assetKey)}: { isStaticImport: ${JSON.stringify(assetInfo.useStaticImport)}, module: ${module}, loadModule: ${loadModuleFunction} },\n`;
445
- }
446
- fileContents += '};\n';
447
- const server = applyDefaults(config.server, {
448
- publicDirPrefix: '',
449
- staticItems: [],
450
- compression: ['br', 'gzip'],
451
- spaFile: null,
452
- notFoundPageFile: null,
453
- autoExt: [],
454
- autoIndex: [],
455
- });
456
- let publicDirPrefix = server.publicDirPrefix;
457
- console.log(`✔️ Server public dir prefix '${publicDirPrefix}'.`);
458
- let staticItems = server.staticItems;
459
- let compression = server.compression;
460
- let spaFile = server.spaFile;
461
- if (spaFile != null) {
462
- console.log(`✔️ Application SPA file '${spaFile}'.`);
463
- const spaAsset = assetInfos.find(assetInfo => assetInfo.assetKey === spaFile);
464
- if (spaAsset == null || spaAsset.contentType !== 'text/html') {
465
- if (displayFrameworkWarnings) {
466
- console.log(`⚠️ Notice: '${spaFile}' does not exist or is not of type 'text/html'. Ignoring.`);
467
- }
468
- spaFile = null;
469
- }
470
- }
471
- else {
472
- if (displayFrameworkWarnings) {
473
- console.log(`✔️ Application is not a SPA.`);
474
- }
475
- }
476
- let notFoundPageFile = server.notFoundPageFile;
477
- if (notFoundPageFile != null) {
478
- console.log(`✔️ Application 'not found (404)' file '${notFoundPageFile}'.`);
479
- const notFoundPageAsset = assetInfos.find(assetInfo => assetInfo.assetKey === notFoundPageFile);
480
- if (notFoundPageAsset == null || notFoundPageAsset.contentType !== 'text/html') {
481
- if (displayFrameworkWarnings) {
482
- console.log(`⚠️ Notice: '${notFoundPageFile}' does not exist or is not of type 'text/html'. Ignoring.`);
483
- }
484
- notFoundPageFile = null;
485
- }
486
- }
487
- else {
488
- if (displayFrameworkWarnings) {
489
- console.log(`✔️ Application specifies no 'not found (404)' page.`);
490
- }
491
- }
492
- let autoIndex = server.autoIndex;
493
- let autoExt = server.autoExt;
494
- const serverConfig = {
495
- publicDirPrefix,
496
- staticItems,
497
- compression,
498
- spaFile,
499
- notFoundPageFile,
500
- autoExt,
501
- autoIndex,
502
- };
503
- fileContents += `\nexport const serverConfig = ${JSON.stringify(serverConfig, null, 2)};\n`;
504
- fileContents += '\nexport const contentAssets = new ContentAssets(objectStoreName, contentAssetMetadataMap);';
505
- fileContents += '\nexport const moduleAssets = new ModuleAssets(moduleAssetsMap);\n';
506
- fileContents += '\nlet server = null;';
507
- fileContents += '\nexport function getServer() {' +
508
- '\n if (server == null) {' +
509
- '\n server = new PublisherServer(serverConfig, contentAssets);' +
510
- '\n }' +
511
- '\n return server;' +
512
- '\n}\n';
513
- fs.writeFileSync('./src/statics.js', fileContents);
514
- console.log("✅ Wrote static file loader for " + files.length + " file(s).");
515
- // Copy Types file for static file loader
516
- try {
517
- const staticsTypeFile = path.resolve(__dirname, '../../resources/statics.d.ts');
518
- fs.copyFileSync(staticsTypeFile, './src/statics.d.ts');
519
- console.log("✅ Wrote static file loader types file statics.d.ts.");
520
- }
521
- catch {
522
- console.log("⚠️ Notice: could not write static file loader types file statics.d.ts.");
523
- }
524
- }
@@ -1,2 +0,0 @@
1
- export {};
2
- //# sourceMappingURL=clean-object-store.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"clean-object-store.d.ts","sourceRoot":"","sources":["../../src/cli/clean-object-store.ts"],"names":[],"mappings":""}
@@ -1,3 +0,0 @@
1
- #!/usr/bin/env node
2
- export {};
3
- //# sourceMappingURL=cli.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"cli.d.ts","sourceRoot":"","sources":["../../src/cli/cli.ts"],"names":[],"mappings":""}
package/build/cli/cli.js DELETED
@@ -1,77 +0,0 @@
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: 'suppress-framework-warnings', type: Boolean },
16
- { name: 'output', alias: 'o', type: String, defaultValue: './compute-js', },
17
- { name: 'public-dir', type: String, },
18
- { name: 'static-dir', type: String, },
19
- // List of files to automatically use as index, for example, index.html,index.htm
20
- // If a request comes in but the route does not exist, we check the route
21
- // plus a slash plus the items in this array.
22
- {
23
- name: 'auto-index',
24
- type: (val) => {
25
- if (val == null) {
26
- return null;
27
- }
28
- const values = val
29
- .split(',')
30
- .map(x => x.trim())
31
- .filter(x => x !== '');
32
- return values.length > 0 ? values : null;
33
- },
34
- },
35
- // List of extensions to apply to a path name, for example, if
36
- // http://example.com/about is requested, we can respond with http://example.com/about.html
37
- {
38
- name: 'auto-ext',
39
- type: (val) => {
40
- if (val == null) {
41
- return null;
42
- }
43
- const values = val
44
- .split(',')
45
- .map(x => x.trim())
46
- .map(x => {
47
- while (x.startsWith('.')) {
48
- x = x.slice(1);
49
- }
50
- return '.' + x;
51
- })
52
- .filter(x => x !== '');
53
- return values.length > 0 ? values : null;
54
- },
55
- },
56
- { name: 'spa', type: String, },
57
- { name: 'not-found-page', type: String, },
58
- { name: 'name', type: String, },
59
- { name: 'author', type: String, },
60
- { name: 'description', type: String, },
61
- // Fastly Service ID to be added to the fastly.toml that is generated.
62
- { name: 'service-id', type: String },
63
- ];
64
- const commandLineValues = commandLineArgs(optionDefinitions);
65
- console.log("Fastly Compute@Edge JavaScript Static Publisher");
66
- let mode = 'init-app';
67
- if (commandLineValues['build-static']) {
68
- mode = 'build-static';
69
- }
70
- switch (mode) {
71
- case 'build-static':
72
- await buildStaticLoader(commandLineValues);
73
- break;
74
- case 'init-app':
75
- initApp(commandLineValues);
76
- break;
77
- }
@@ -1,3 +0,0 @@
1
- import { CommandLineOptions } from "command-line-args";
2
- export declare function initApp(commandLineValues: CommandLineOptions): void;
3
- //# sourceMappingURL=init-app.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"init-app.d.ts","sourceRoot":"","sources":["../../src/cli/init-app.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,MAAM,mBAAmB,CAAC;AAiDvD,wBAAgB,OAAO,CAAC,iBAAiB,EAAE,kBAAkB,QAgS5D"}