@fastly/compute-js-static-publish 8.0.1 → 8.1.0-beta.2

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 (247) hide show
  1. package/DOCUMENTATION.md +792 -35
  2. package/README.md +13 -3
  3. package/README.short.md +13 -3
  4. package/build/cli/cli/commands/manage/clean.d.ts.map +1 -1
  5. package/build/cli/cli/commands/manage/clean.js +14 -8
  6. package/build/cli/cli/commands/manage/collections/delete.d.ts.map +1 -1
  7. package/build/cli/cli/commands/manage/collections/delete.js +32 -15
  8. package/build/cli/cli/commands/manage/collections/index.d.ts.map +1 -1
  9. package/build/cli/cli/commands/manage/collections/index.js +10 -4
  10. package/build/cli/cli/commands/manage/collections/list.d.ts.map +1 -1
  11. package/build/cli/cli/commands/manage/collections/list.js +49 -8
  12. package/build/cli/cli/commands/manage/collections/promote.d.ts.map +1 -1
  13. package/build/cli/cli/commands/manage/collections/promote.js +69 -21
  14. package/build/cli/cli/commands/manage/collections/update-expiration.d.ts.map +1 -1
  15. package/build/cli/cli/commands/manage/collections/update-expiration.js +12 -12
  16. package/build/cli/cli/commands/manage/deploy.d.ts +2 -0
  17. package/build/cli/cli/commands/manage/deploy.d.ts.map +1 -0
  18. package/build/cli/cli/commands/manage/deploy.js +194 -0
  19. package/build/cli/cli/commands/manage/dev.d.ts +2 -0
  20. package/build/cli/cli/commands/manage/dev.d.ts.map +1 -0
  21. package/build/cli/cli/commands/manage/dev.js +78 -0
  22. package/build/cli/cli/commands/manage/eject.d.ts +2 -0
  23. package/build/cli/cli/commands/manage/eject.d.ts.map +1 -0
  24. package/build/cli/cli/commands/manage/eject.js +155 -0
  25. package/build/cli/cli/commands/manage/index.d.ts.map +1 -1
  26. package/build/cli/cli/commands/manage/index.js +42 -5
  27. package/build/cli/cli/commands/manage/publish-content.d.ts.map +1 -1
  28. package/build/cli/cli/commands/manage/publish-content.js +83 -37
  29. package/build/cli/cli/commands/manage/status.d.ts +2 -0
  30. package/build/cli/cli/commands/manage/status.d.ts.map +1 -0
  31. package/build/cli/cli/commands/manage/status.js +162 -0
  32. package/build/cli/cli/commands/manage/template/index.d.ts +2 -0
  33. package/build/cli/cli/commands/manage/template/index.d.ts.map +1 -0
  34. package/build/cli/cli/commands/manage/template/index.js +43 -0
  35. package/build/cli/cli/commands/manage/template/init.d.ts +13 -0
  36. package/build/cli/cli/commands/manage/template/init.d.ts.map +1 -0
  37. package/build/cli/cli/commands/manage/template/init.js +172 -0
  38. package/build/cli/cli/commands/manage/upgrade.d.ts +2 -0
  39. package/build/cli/cli/commands/manage/upgrade.d.ts.map +1 -0
  40. package/build/cli/cli/commands/manage/upgrade.js +59 -0
  41. package/build/cli/cli/commands/run-dev-watch.d.ts +8 -0
  42. package/build/cli/cli/commands/run-dev-watch.d.ts.map +1 -0
  43. package/build/cli/cli/commands/run-dev-watch.js +41 -0
  44. package/build/cli/cli/commands/run-template-hook.d.ts +2 -0
  45. package/build/cli/cli/commands/run-template-hook.d.ts.map +1 -0
  46. package/build/cli/cli/commands/run-template-hook.js +28 -0
  47. package/build/cli/cli/commands/scaffold/app-template.d.ts +17 -0
  48. package/build/cli/cli/commands/scaffold/app-template.d.ts.map +1 -0
  49. package/build/cli/cli/commands/scaffold/app-template.js +54 -0
  50. package/build/cli/cli/commands/scaffold/fastly-toml-sections.d.ts +5 -0
  51. package/build/cli/cli/commands/scaffold/fastly-toml-sections.d.ts.map +1 -0
  52. package/build/cli/cli/commands/scaffold/fastly-toml-sections.js +154 -0
  53. package/build/cli/cli/commands/scaffold/generate-app.d.ts +47 -0
  54. package/build/cli/cli/commands/scaffold/generate-app.d.ts.map +1 -0
  55. package/build/cli/cli/commands/scaffold/generate-app.js +164 -0
  56. package/build/cli/cli/commands/scaffold/index.d.ts +6 -0
  57. package/build/cli/cli/commands/scaffold/index.d.ts.map +1 -1
  58. package/build/cli/cli/commands/scaffold/index.js +208 -290
  59. package/build/cli/cli/commands/scaffold/render.d.ts +7 -0
  60. package/build/cli/cli/commands/scaffold/render.d.ts.map +1 -0
  61. package/build/cli/cli/commands/scaffold/render.js +72 -0
  62. package/build/cli/cli/hono/build.d.ts +43 -0
  63. package/build/cli/cli/hono/build.d.ts.map +1 -0
  64. package/build/cli/cli/hono/build.js +298 -0
  65. package/build/cli/cli/index.js +98 -5
  66. package/build/cli/cli/managed/app.d.ts +21 -0
  67. package/build/cli/cli/managed/app.d.ts.map +1 -0
  68. package/build/cli/cli/managed/app.js +162 -0
  69. package/build/cli/cli/managed/command-helpers.d.ts +6 -0
  70. package/build/cli/cli/managed/command-helpers.d.ts.map +1 -0
  71. package/build/cli/cli/managed/command-helpers.js +81 -0
  72. package/build/cli/cli/managed/eject.d.ts +6 -0
  73. package/build/cli/cli/managed/eject.d.ts.map +1 -0
  74. package/build/cli/cli/managed/eject.js +68 -0
  75. package/build/cli/cli/managed/fastly-service.d.ts +8 -0
  76. package/build/cli/cli/managed/fastly-service.d.ts.map +1 -0
  77. package/build/cli/cli/managed/fastly-service.js +21 -0
  78. package/build/cli/cli/managed/fingerprint.d.ts +13 -0
  79. package/build/cli/cli/managed/fingerprint.d.ts.map +1 -0
  80. package/build/cli/cli/managed/fingerprint.js +60 -0
  81. package/build/cli/cli/managed/lockfile.d.ts +31 -0
  82. package/build/cli/cli/managed/lockfile.d.ts.map +1 -0
  83. package/build/cli/cli/managed/lockfile.js +62 -0
  84. package/build/cli/cli/managed/project-edit.d.ts +3 -0
  85. package/build/cli/cli/managed/project-edit.d.ts.map +1 -0
  86. package/build/cli/cli/managed/project-edit.js +35 -0
  87. package/build/cli/cli/managed/project-file.d.ts +16 -0
  88. package/build/cli/cli/managed/project-file.d.ts.map +1 -0
  89. package/build/cli/cli/managed/project-file.js +119 -0
  90. package/build/cli/cli/managed/template-init.d.ts +12 -0
  91. package/build/cli/cli/managed/template-init.d.ts.map +1 -0
  92. package/build/cli/cli/managed/template-init.js +120 -0
  93. package/build/cli/cli/managed/version-check.d.ts +25 -0
  94. package/build/cli/cli/managed/version-check.d.ts.map +1 -0
  95. package/build/cli/cli/managed/version-check.js +84 -0
  96. package/build/cli/cli/storage/kv-store-local-provider.d.ts +1 -0
  97. package/build/cli/cli/storage/kv-store-local-provider.d.ts.map +1 -1
  98. package/build/cli/cli/storage/kv-store-local-provider.js +6 -3
  99. package/build/cli/cli/storage/kv-store-provider.d.ts +1 -0
  100. package/build/cli/cli/storage/kv-store-provider.d.ts.map +1 -1
  101. package/build/cli/cli/storage/kv-store-provider.js +9 -1
  102. package/build/cli/cli/storage/s3-storage-provider.d.ts +1 -0
  103. package/build/cli/cli/storage/s3-storage-provider.d.ts.map +1 -1
  104. package/build/cli/cli/storage/s3-storage-provider.js +4 -0
  105. package/build/cli/cli/storage/storage-provider.d.ts +3 -0
  106. package/build/cli/cli/storage/storage-provider.d.ts.map +1 -1
  107. package/build/cli/cli/storage/storage-provider.js +32 -0
  108. package/build/cli/cli/util/api-token.d.ts.map +1 -1
  109. package/build/cli/cli/util/collection-name.d.ts +3 -0
  110. package/build/cli/cli/util/collection-name.d.ts.map +1 -0
  111. package/build/cli/cli/util/collection-name.js +24 -0
  112. package/build/cli/cli/util/collection-selection-flags.d.ts +13 -0
  113. package/build/cli/cli/util/collection-selection-flags.d.ts.map +1 -0
  114. package/build/cli/cli/util/collection-selection-flags.js +131 -0
  115. package/build/cli/cli/util/config.d.ts +13 -0
  116. package/build/cli/cli/util/config.d.ts.map +1 -1
  117. package/build/cli/cli/util/config.js +172 -38
  118. package/build/cli/cli/util/data.d.ts.map +1 -1
  119. package/build/cli/cli/util/global-options.d.ts +13 -0
  120. package/build/cli/cli/util/global-options.d.ts.map +1 -0
  121. package/build/cli/cli/util/global-options.js +53 -0
  122. package/build/cli/cli/util/kv-store-items.d.ts +1 -0
  123. package/build/cli/cli/util/kv-store-items.d.ts.map +1 -1
  124. package/build/cli/cli/util/kv-store-items.js +16 -40
  125. package/build/cli/cli/util/kv-store-local-server.d.ts +1 -1
  126. package/build/cli/cli/util/kv-store-local-server.d.ts.map +1 -1
  127. package/build/cli/cli/util/kv-store-local-server.js +4 -2
  128. package/build/cli/cli/util/output.d.ts +31 -0
  129. package/build/cli/cli/util/output.d.ts.map +1 -0
  130. package/build/cli/cli/util/output.js +139 -0
  131. package/build/cli/cli/util/package.d.ts +6 -0
  132. package/build/cli/cli/util/package.d.ts.map +1 -1
  133. package/build/cli/cli/util/package.js +23 -0
  134. package/build/cli/cli/util/progress.d.ts.map +1 -1
  135. package/build/cli/cli/util/purge.d.ts +6 -2
  136. package/build/cli/cli/util/purge.d.ts.map +1 -1
  137. package/build/cli/cli/util/purge.js +7 -2
  138. package/build/cli/cli/util/resources.d.ts +2 -0
  139. package/build/cli/cli/util/resources.d.ts.map +1 -0
  140. package/build/cli/cli/util/resources.js +8 -0
  141. package/build/cli/cli/util/service-id.d.ts +1 -0
  142. package/build/cli/cli/util/service-id.d.ts.map +1 -1
  143. package/build/cli/cli/util/service-id.js +5 -1
  144. package/build/cli/cli/util/variants.d.ts.map +1 -1
  145. package/build/cli/models/assets/index.d.ts +6 -0
  146. package/build/cli/models/assets/index.d.ts.map +1 -1
  147. package/build/cli/models/assets/index.js +24 -0
  148. package/build/cli/models/collections/index.d.ts +3 -0
  149. package/build/cli/models/collections/index.d.ts.map +1 -0
  150. package/build/cli/models/collections/index.js +15 -0
  151. package/build/cli/models/compression/index.d.ts +1 -1
  152. package/build/cli/models/compression/index.d.ts.map +1 -1
  153. package/build/cli/models/config/collection-selection.d.ts +55 -0
  154. package/build/cli/models/config/collection-selection.d.ts.map +1 -0
  155. package/build/cli/models/config/collection-selection.js +238 -0
  156. package/build/cli/models/config/item-patterns.d.ts +4 -0
  157. package/build/cli/models/config/item-patterns.d.ts.map +1 -0
  158. package/build/cli/models/config/item-patterns.js +43 -0
  159. package/build/cli/models/config/publish-content-config.d.ts +6 -1
  160. package/build/cli/models/config/publish-content-config.d.ts.map +1 -1
  161. package/build/cli/models/config/static-publish-project.d.ts +23 -0
  162. package/build/cli/models/config/static-publish-project.d.ts.map +1 -0
  163. package/build/cli/models/config/static-publish-project.js +11 -0
  164. package/build/cli/models/config/static-publish-rc.d.ts +25 -0
  165. package/build/cli/models/config/static-publish-rc.d.ts.map +1 -1
  166. package/build/cli/models/config/static-publish-rc.js +31 -0
  167. package/build/cli/models/config/template-settings.d.ts +10 -0
  168. package/build/cli/models/config/template-settings.d.ts.map +1 -0
  169. package/build/cli/models/config/template-settings.js +72 -0
  170. package/build/cli/models/server/index.d.ts.map +1 -1
  171. package/build/cli/models/server/index.js +6 -2
  172. package/build/server/hono/extensions.d.ts +48 -0
  173. package/build/server/hono/extensions.d.ts.map +1 -0
  174. package/build/server/hono/extensions.js +65 -0
  175. package/build/server/hono/index.d.ts +30 -0
  176. package/build/server/hono/index.d.ts.map +1 -0
  177. package/build/server/hono/index.js +72 -0
  178. package/build/server/hono/path.d.ts +7 -0
  179. package/build/server/hono/path.d.ts.map +1 -0
  180. package/build/server/hono/path.js +32 -0
  181. package/build/server/models/assets/index.d.ts +6 -0
  182. package/build/server/models/assets/index.d.ts.map +1 -1
  183. package/build/server/models/assets/index.js +24 -0
  184. package/build/server/models/collections/index.d.ts +3 -0
  185. package/build/server/models/collections/index.d.ts.map +1 -0
  186. package/build/server/models/collections/index.js +15 -0
  187. package/build/server/models/compression/index.d.ts +1 -1
  188. package/build/server/models/compression/index.d.ts.map +1 -1
  189. package/build/server/models/config/collection-selection.d.ts +55 -0
  190. package/build/server/models/config/collection-selection.d.ts.map +1 -0
  191. package/build/server/models/config/collection-selection.js +238 -0
  192. package/build/server/models/config/item-patterns.d.ts +4 -0
  193. package/build/server/models/config/item-patterns.d.ts.map +1 -0
  194. package/build/server/models/config/item-patterns.js +43 -0
  195. package/build/server/models/config/publish-content-config.d.ts +6 -1
  196. package/build/server/models/config/publish-content-config.d.ts.map +1 -1
  197. package/build/server/models/config/static-publish-project.d.ts +23 -0
  198. package/build/server/models/config/static-publish-project.d.ts.map +1 -0
  199. package/build/server/models/config/static-publish-project.js +11 -0
  200. package/build/server/models/config/static-publish-rc.d.ts +25 -0
  201. package/build/server/models/config/static-publish-rc.d.ts.map +1 -1
  202. package/build/server/models/config/static-publish-rc.js +31 -0
  203. package/build/server/models/server/index.d.ts.map +1 -1
  204. package/build/server/models/server/index.js +6 -2
  205. package/build/server/server/collection-selection/index.d.ts +11 -0
  206. package/build/server/server/collection-selection/index.d.ts.map +1 -0
  207. package/build/server/server/collection-selection/index.js +192 -0
  208. package/build/server/server/collection-selector/from-cookie.d.ts.map +1 -1
  209. package/build/server/server/collection-selector/from-cookie.js +6 -8
  210. package/build/server/server/collection-selector/from-request.d.ts.map +1 -1
  211. package/build/server/server/index.d.ts +4 -1
  212. package/build/server/server/index.d.ts.map +1 -1
  213. package/build/server/server/index.js +3 -1
  214. package/build/server/server/publisher-server/accept-html.d.ts +2 -0
  215. package/build/server/server/publisher-server/accept-html.d.ts.map +1 -0
  216. package/build/server/server/publisher-server/accept-html.js +50 -0
  217. package/build/server/server/publisher-server/index.d.ts +59 -7
  218. package/build/server/server/publisher-server/index.d.ts.map +1 -1
  219. package/build/server/server/publisher-server/index.js +362 -145
  220. package/build/server/server/publisher-server/response-cache.d.ts +3 -0
  221. package/build/server/server/publisher-server/response-cache.d.ts.map +1 -1
  222. package/build/server/server/publisher-server/response-cache.js +24 -1
  223. package/build/server/server/storage/kv-store-provider.d.ts.map +1 -1
  224. package/build/server/server/storage/s3-storage-provider.d.ts.map +1 -1
  225. package/build/server/server/storage/storage-provider.d.ts.map +1 -1
  226. package/build/server/server/util/body-length.d.ts.map +1 -1
  227. package/build/server/server/util/server-timing.d.ts.map +1 -1
  228. package/package.json +21 -3
  229. package/resources/app/fastly.toml.njk +58 -0
  230. package/resources/app/gitignore.njk +9 -0
  231. package/resources/app/publish-content.config.from-project.js.njk +9 -0
  232. package/resources/app/publish-content.config.js.njk +35 -0
  233. package/resources/app/static-publish.project.js.njk +83 -0
  234. package/resources/app/static-publish.rc.js.njk +43 -0
  235. package/resources/template-init/hono/_example.ts +22 -0
  236. package/resources/template-init/hono/tsconfig.json +17 -0
  237. package/resources/templates/hono/package-lock.json +4123 -0
  238. package/resources/templates/hono/package.json +15 -0
  239. package/resources/templates/hono/scripts/template_postinstall.js +10 -0
  240. package/resources/templates/hono/scripts/template_prebuild.js +8 -0
  241. package/resources/templates/hono/scripts/template_watch.js +15 -0
  242. package/resources/templates/hono/src/hono-extensions.generated.d.ts +5 -0
  243. package/resources/templates/hono/src/index.ts +53 -0
  244. package/resources/templates/hono/tsconfig.json +17 -0
  245. package/resources/templates/plain/package-lock.json +4088 -0
  246. package/resources/templates/plain/package.json +10 -0
  247. package/resources/templates/plain/src/index.js +34 -0
@@ -10,14 +10,25 @@ import * as child_process from 'node:child_process';
10
10
  import * as path from 'node:path';
11
11
  import * as fs from 'node:fs';
12
12
  import { parseCommandLine } from '../../util/args.js';
13
- import { dotRelative, rootRelative } from '../../util/files.js';
14
- import { findComputeJsStaticPublisherVersion } from '../../util/package.js';
13
+ import { fail, recordFailure } from '../../util/output.js';
14
+ import { rootRelative } from '../../util/files.js';
15
+ import { cliCommand, findComputeJsStaticPublisherVersion, getOwnVersion } from '../../util/package.js';
16
+ import { runTemplateInit } from '../manage/template/init.js';
17
+ import { templateHasInit } from '../../managed/template-init.js';
15
18
  import { findHostnameForAwsS3RegionAndBucket } from '../../util/s3.js';
19
+ import { APP_TEMPLATE_NAMES, DEFAULT_APP_TEMPLATE_NAME, isAppTemplateName, loadAppTemplate, } from './app-template.js';
20
+ import { COLLECTION_SELECTION_FLAGS_HELP, collectionSelectionFromFlags } from '../../util/collection-selection-flags.js';
21
+ import { generateApp } from './generate-app.js';
22
+ import { renderProjectFile } from '../../managed/project-file.js';
23
+ import { dotRelative } from '../../util/files.js';
24
+ import { checkStaticPublisherWorkingDir } from '../../../models/config/static-publish-rc.js';
25
+ import { MANAGED_APP_DIR, PROJECT_FILE_NAME } from '../../../models/config/static-publish-project.js';
26
+ import { COLLECTION_NAME_RULE, isValidCollectionName } from '../../../models/collections/index.js';
16
27
  function help() {
17
28
  console.log(`\
18
29
 
19
30
  Usage:
20
- npx @fastly/compute-js-static-publish@latest [options]
31
+ ${cliCommand({ latest: true })} [options]
21
32
 
22
33
  Description:
23
34
  Scaffold a new Compute app configured for static publishing.
@@ -42,6 +53,13 @@ Options:
42
53
  --static-publisher-working-dir <dir> Working directory for build artifacts (default: <output>/static-publisher)
43
54
  (default: ./compute-js/static-publisher)
44
55
  --publish-id <id> Advanced. Prefix for KV keys (default: "default")
56
+ --default-collection-name <name> Collection to serve when none is selected (default: "live")
57
+ --template <name> The template of the app's code (default: "plain")
58
+ Valid templates: ${APP_TEMPLATE_NAMES.join(', ')}
59
+
60
+ --managed Write only static-publish.project.js (a managed project) in the
61
+ current directory, and add .static-publish/ and the working
62
+ directory to .gitignore. The CLI generates the app when it needs it.
45
63
 
46
64
  Compute Service Metadata:
47
65
  --name <name> App name (for fastly.toml)
@@ -58,7 +76,12 @@ Server Config:
58
76
  --auto-index <name>,<name...> Index filename (e.g., index.html,index.htm)
59
77
  --auto-ext <ext>,<ext...> Automatic extensions (e.g., .html,.htm)
60
78
 
79
+ Collection Selection (previews):
80
+ ${COLLECTION_SELECTION_FLAGS_HELP}
81
+
61
82
  Other:
83
+ --version Print the version of this package and exit
84
+ --non-interactive Never ask a question (also on when CI is set)
62
85
  --verbose Enable verbose output
63
86
  -h, --help Show help
64
87
  `);
@@ -78,11 +101,13 @@ const defaultOptions = {
78
101
  description: 'Fastly Compute static site',
79
102
  serviceId: undefined,
80
103
  publishId: undefined,
104
+ defaultCollectionName: undefined,
81
105
  storageMode: undefined,
82
106
  kvStoreName: undefined,
83
107
  s3Region: undefined,
84
108
  s3Bucket: undefined,
85
109
  s3Endpoint: undefined,
110
+ template: DEFAULT_APP_TEMPLATE_NAME,
86
111
  };
87
112
  function buildOptions(packageJson, commandLineOptions) {
88
113
  // Applied in this order for proper overriding
@@ -253,6 +278,18 @@ function buildOptions(packageJson, commandLineOptions) {
253
278
  options.description = description;
254
279
  }
255
280
  }
281
+ {
282
+ const defaultCollectionNameValue = commandLineOptions['default-collection-name'];
283
+ if (typeof defaultCollectionNameValue === 'string') {
284
+ options.defaultCollectionName = defaultCollectionNameValue;
285
+ }
286
+ }
287
+ {
288
+ const templateValue = commandLineOptions['template'];
289
+ if (typeof templateValue === 'string') {
290
+ options.template = templateValue;
291
+ }
292
+ }
256
293
  {
257
294
  let serviceId;
258
295
  const serviceIdValue = commandLineOptions['service-id'];
@@ -359,6 +396,11 @@ export async function action(actionArgs) {
359
396
  { name: 'author', type: String, },
360
397
  // Fastly Service ID to be added to the fastly.toml that is generated.
361
398
  { name: 'service-id', type: String },
399
+ // The template of the app's code.
400
+ { name: 'template', type: String, },
401
+ // The collection to serve when no collection is selected.
402
+ // If not provided, the default value of 'live' is used.
403
+ { name: 'default-collection-name', type: String, },
362
404
  // Required. The 'root' directory for the publishing.
363
405
  // All assets are expected to exist under this root. Required.
364
406
  // For backwards compatibility, if this value is not provided,
@@ -399,13 +441,20 @@ export async function action(actionArgs) {
399
441
  // List of extensions to apply to a path name, for example, if
400
442
  // http://example.com/about is requested, we can respond with http://example.com/about.html
401
443
  { name: 'auto-ext', type: String, multiple: true, },
444
+ // Collection selection. See util/collection-selection-flags.ts.
445
+ { name: 'collection-selection', type: String, multiple: true, },
446
+ { name: 'collection-allow', type: String, multiple: true, },
447
+ { name: 'collection-on-missing', type: String, },
448
+ { name: 'collection-noindex', type: String, },
449
+ // Write static-publish.project.js (a managed project) in place of the app.
450
+ { name: 'managed', type: Boolean, },
402
451
  ];
403
452
  const parsed = parseCommandLine(actionArgs, optionDefinitions);
404
453
  if (parsed.needHelp) {
405
454
  if (parsed.error != null) {
406
455
  console.error(String(parsed.error));
407
456
  console.error();
408
- process.exitCode = 1;
457
+ recordFailure('usage', String(parsed.error));
409
458
  }
410
459
  help();
411
460
  return;
@@ -420,25 +469,44 @@ export async function action(actionArgs) {
420
469
  packageJson = null;
421
470
  }
422
471
  const options = buildOptions(packageJson, parsed.commandLineOptions);
423
- const COMPUTE_JS_DIR = options.outputDir;
472
+ if (!isAppTemplateName(options.template)) {
473
+ fail('usage', `Unknown template '${options.template}'.`);
474
+ console.error(` * Valid templates: ${APP_TEMPLATE_NAMES.join(', ')}`);
475
+ return;
476
+ }
477
+ const { collectionSelection, errors: collectionSelectionErrors } = collectionSelectionFromFlags({
478
+ sources: parsed.commandLineOptions['collection-selection'],
479
+ allow: parsed.commandLineOptions['collection-allow'],
480
+ onMissing: parsed.commandLineOptions['collection-on-missing'],
481
+ noindex: parsed.commandLineOptions['collection-noindex'],
482
+ });
483
+ if (collectionSelectionErrors.length > 0) {
484
+ for (const error of collectionSelectionErrors) {
485
+ console.error(`❌ ${error}`);
486
+ }
487
+ recordFailure('usage', collectionSelectionErrors.join(' '));
488
+ return;
489
+ }
490
+ // A managed project: the project dir is the current directory. The CLI
491
+ // generates the app in .static-publish/app when it needs it.
492
+ const managed = parsed.commandLineOptions['managed'] === true;
493
+ const projectDir = path.resolve();
494
+ const COMPUTE_JS_DIR = managed ? MANAGED_APP_DIR : options.outputDir;
424
495
  if (COMPUTE_JS_DIR == null) {
425
- console.error("❌ required parameter --output not provided.");
426
- process.exitCode = 1;
496
+ fail('usage', "required parameter --output not provided.");
427
497
  return;
428
498
  }
429
499
  const computeJsDir = path.resolve(COMPUTE_JS_DIR);
430
500
  // Resolve the root dir, relative to current directory, and make sure it exists.
431
501
  const ROOT_DIR = options.rootDir;
432
502
  if (ROOT_DIR == null) {
433
- console.error("❌ required parameter --root-dir not provided.");
434
- process.exitCode = 1;
503
+ fail('usage', "required parameter --root-dir not provided.");
435
504
  return;
436
505
  }
437
506
  const rootDir = path.resolve(ROOT_DIR);
438
507
  if (!fs.existsSync(rootDir) || !fs.statSync(rootDir).isDirectory()) {
439
- console.error(`❌ Specified root directory '${ROOT_DIR}' does not exist.`);
508
+ fail('usage', `Specified root directory '${ROOT_DIR}' does not exist.`);
440
509
  console.error(` * ${rootRelative(rootDir)} must exist and be a directory.`);
441
- process.exitCode = 1;
442
510
  return;
443
511
  }
444
512
  if (options.publicDir != null) {
@@ -449,16 +517,14 @@ export async function action(actionArgs) {
449
517
  const PUBLIC_DIR = options.publicDir ?? ROOT_DIR;
450
518
  const publicDir = path.resolve(PUBLIC_DIR);
451
519
  if (!fs.existsSync(publicDir) || !fs.statSync(publicDir).isDirectory()) {
452
- console.error(`❌ Specified public directory '${PUBLIC_DIR}' does not exist.`);
520
+ fail('usage', `Specified public directory '${PUBLIC_DIR}' does not exist.`);
453
521
  console.error(` * ${rootRelative(publicDir)} must exist and be a directory.`);
454
- process.exitCode = 1;
455
522
  return;
456
523
  }
457
524
  // Public dir must be inside the root dir.
458
525
  if (!publicDir.startsWith(rootDir)) {
459
- console.error(`❌ Specified public directory '${PUBLIC_DIR}' is not under the asset root directory.`);
526
+ fail('usage', `Specified public directory '${PUBLIC_DIR}' is not under the asset root directory.`);
460
527
  console.error(` * ${rootRelative(publicDir)} must be under ${rootRelative(rootDir)}`);
461
- process.exitCode = 1;
462
528
  return;
463
529
  }
464
530
  // Static dirs must be inside the public dir.
@@ -482,17 +548,25 @@ export async function action(actionArgs) {
482
548
  // Static Publisher Working Root Dir must be under the current dir
483
549
  // This comes in relative to cwd.
484
550
  const STATIC_PUBLISHER_WORKING_DIR = options.staticPublisherWorkingDir ??
485
- path.resolve(computeJsDir, './static-publisher');
551
+ path.resolve(managed ? projectDir : computeJsDir, './static-publisher');
486
552
  const staticPublisherWorkingDir = path.resolve(STATIC_PUBLISHER_WORKING_DIR);
487
- if (!staticPublisherWorkingDir.startsWith(computeJsDir) ||
553
+ if (managed) {
554
+ // In a managed project, the working dir is relative to the project file.
555
+ const workingDirError = checkStaticPublisherWorkingDir(dotRelative(projectDir, staticPublisherWorkingDir).split(path.sep).join('/'));
556
+ if (workingDirError != null || staticPublisherWorkingDir.startsWith(path.resolve(projectDir, '.static-publish') + path.sep)) {
557
+ fail('usage', `Specified static publisher working directory '${rootRelative(staticPublisherWorkingDir)}' is not valid.`);
558
+ console.error(` * It must not be the project directory, a directory above it, or in .static-publish.`);
559
+ return;
560
+ }
561
+ }
562
+ else if (!staticPublisherWorkingDir.startsWith(computeJsDir) ||
488
563
  staticPublisherWorkingDir === computeJsDir ||
489
564
  staticPublisherWorkingDir === path.resolve(computeJsDir, './bin') ||
490
565
  staticPublisherWorkingDir === path.resolve(computeJsDir, './pkg') ||
491
566
  staticPublisherWorkingDir === path.resolve(computeJsDir, './src') ||
492
567
  staticPublisherWorkingDir === path.resolve(computeJsDir, './node_modules')) {
493
- console.error(`❌ Specified static publisher working directory '${rootRelative(staticPublisherWorkingDir)}' must be under ${rootRelative(computeJsDir)}.`);
568
+ fail('usage', `Specified static publisher working directory '${rootRelative(staticPublisherWorkingDir)}' must be under ${rootRelative(computeJsDir)}.`);
494
569
  console.error(` It also must not be bin, pkg, src, or node_modules.`);
495
- process.exitCode = 1;
496
570
  return;
497
571
  }
498
572
  // SPA and Not Found are relative to the asset root dir.
@@ -503,16 +577,14 @@ export async function action(actionArgs) {
503
577
  spaFilename = processPublicDirToken(SPA, publicDir);
504
578
  // At any rate it must exist under the root directory
505
579
  if (!spaFilename.startsWith(rootDir)) {
506
- console.error(`❌ Specified SPA file '${SPA}' is not under the asset root directory.`);
580
+ fail('usage', `Specified SPA file '${SPA}' is not under the asset root directory.`);
507
581
  console.error(` * ${rootRelative(spaFilename)} must be under ${rootRelative(rootDir)}`);
508
582
  console.error(` Give the path from the current directory, for example ${rootRelative(rootDir)}/index.html.`);
509
- process.exitCode = 1;
510
583
  return;
511
584
  }
512
585
  if (!fs.existsSync(spaFilename)) {
513
- console.error(`❌ Specified SPA file '${SPA}' does not exist.`);
586
+ fail('usage', `Specified SPA file '${SPA}' does not exist.`);
514
587
  console.error(` * ${rootRelative(spaFilename)} does not exist.`);
515
- process.exitCode = 1;
516
588
  return;
517
589
  }
518
590
  }
@@ -523,16 +595,14 @@ export async function action(actionArgs) {
523
595
  notFoundPageFilename = processPublicDirToken(NOT_FOUND_PAGE, publicDir);
524
596
  // At any rate it must exist under the root directory
525
597
  if (!notFoundPageFilename.startsWith(rootDir)) {
526
- console.error(`❌ Specified Not Found file '${NOT_FOUND_PAGE}' is not under the asset root directory.`);
598
+ fail('usage', `Specified Not Found file '${NOT_FOUND_PAGE}' is not under the asset root directory.`);
527
599
  console.error(` * ${rootRelative(notFoundPageFilename)} must be under ${rootRelative(rootDir)}`);
528
600
  console.error(` Give the path from the current directory, for example ${rootRelative(rootDir)}/404.html.`);
529
- process.exitCode = 1;
530
601
  return;
531
602
  }
532
603
  if (!fs.existsSync(notFoundPageFilename)) {
533
- console.error(`❌ Specified Not Found file '${NOT_FOUND_PAGE}' does not exist.`);
604
+ fail('usage', `Specified Not Found file '${NOT_FOUND_PAGE}' does not exist.`);
534
605
  console.error(` * ${rootRelative(notFoundPageFilename)} does not exist.`);
535
- process.exitCode = 1;
536
606
  return;
537
607
  }
538
608
  }
@@ -545,14 +615,13 @@ export async function action(actionArgs) {
545
615
  }
546
616
  const autoIndex = options.autoIndex;
547
617
  const autoExt = options.autoExt;
548
- const exists = fs.existsSync(computeJsDir);
618
+ const exists = !managed && fs.existsSync(computeJsDir);
549
619
  if (exists) {
550
- console.error(`❌ '${COMPUTE_JS_DIR}' directory already exists!`);
620
+ fail('usage', `'${COMPUTE_JS_DIR}' directory already exists!`);
551
621
  console.error(` You should not run this command if this directory exists.`);
552
622
  console.error(` If you need to re-scaffold the static publisher Compute App,`);
553
623
  console.error(` delete the following directory and then try again:`);
554
624
  console.error(` ${rootRelative(computeJsDir)}`);
555
- process.exitCode = 1;
556
625
  return;
557
626
  }
558
627
  const author = options.author;
@@ -561,8 +630,7 @@ export async function action(actionArgs) {
561
630
  const fastlyServiceId = options.serviceId;
562
631
  const storageMode = options.storageMode;
563
632
  if (!(storageMode === 'kv-store' || storageMode === 's3')) {
564
- console.error(`❌ parameter --storage-mode must be set to 'kv-store' or 's3'.`);
565
- process.exitCode = 1;
633
+ fail('usage', `parameter --storage-mode must be set to 'kv-store' or 's3'.`);
566
634
  return;
567
635
  }
568
636
  const kvStoreName = options.kvStoreName;
@@ -572,20 +640,17 @@ export async function action(actionArgs) {
572
640
  let s3EndpointGenerated = false;
573
641
  if (storageMode === 'kv-store') {
574
642
  if (kvStoreName == null) {
575
- console.error(`❌ required parameter --kv-store-name not provided.`);
576
- process.exitCode = 1;
643
+ fail('usage', `required parameter --kv-store-name not provided.`);
577
644
  return;
578
645
  }
579
646
  }
580
647
  else if (storageMode === 's3') {
581
648
  if (s3Region == null) {
582
- console.error(`❌ required parameter --s3-region not provided.`);
583
- process.exitCode = 1;
649
+ fail('usage', `required parameter --s3-region not provided.`);
584
650
  return;
585
651
  }
586
652
  if (s3Bucket == null) {
587
- console.error(`❌ required parameter --s3-bucket not provided.`);
588
- process.exitCode = 1;
653
+ fail('usage', `required parameter --s3-bucket not provided.`);
589
654
  return;
590
655
  }
591
656
  let s3Endpoint = options.s3Endpoint;
@@ -599,8 +664,7 @@ export async function action(actionArgs) {
599
664
  console.log('✅ S3 endpoint resolved:', s3Endpoint);
600
665
  }
601
666
  else {
602
- console.error(`❌ Unable to resolve S3 endpoint from region '${s3Region}' and bucket '${s3Bucket}.`);
603
- process.exitCode = 1;
667
+ fail('failed', `Unable to resolve S3 endpoint from region '${s3Region}' and bucket '${s3Bucket}'.`);
604
668
  return;
605
669
  }
606
670
  s3EndpointUrl = new URL(`https://${s3Endpoint}/`);
@@ -615,8 +679,7 @@ export async function action(actionArgs) {
615
679
  s3EndpointUrl = new URL(s3Endpoint);
616
680
  }
617
681
  catch {
618
- console.error(`❌ Unable to parse '${s3Endpoint}' as a valid URL.`);
619
- process.exitCode = 1;
682
+ fail('usage', `Unable to parse '${s3Endpoint}' as a valid URL.`);
620
683
  return;
621
684
  }
622
685
  }
@@ -625,7 +688,12 @@ export async function action(actionArgs) {
625
688
  if (publishId == null) {
626
689
  publishId = 'default';
627
690
  }
628
- const defaultCollectionName = 'live';
691
+ const defaultCollectionName = options.defaultCollectionName ?? 'live';
692
+ if (!isValidCollectionName(defaultCollectionName)) {
693
+ fail('collection-name-invalid', `parameter --default-collection-name is not a valid collection name: '${defaultCollectionName}'.`);
694
+ console.error(` * ${COLLECTION_NAME_RULE}`);
695
+ return;
696
+ }
629
697
  console.log('');
630
698
  console.log('Compute Application Settings');
631
699
  console.log('----------------------------');
@@ -634,6 +702,7 @@ export async function action(actionArgs) {
634
702
  console.log('author :', author);
635
703
  console.log('description :', description);
636
704
  console.log('Service ID :', fastlyServiceId ?? '(None)');
705
+ console.log('Template :', options.template);
637
706
  if (storageMode === 'kv-store') {
638
707
  console.log('Storage Mode : Fastly KV Store');
639
708
  console.log('KV Store Name :', kvStoreName);
@@ -663,257 +732,52 @@ export async function action(actionArgs) {
663
732
  console.log('Auto-Index :', autoIndex.length > 0 ? autoIndex : '(None)');
664
733
  console.log('Auto-Ext :', autoExt.length > 0 ? autoExt : '(None)');
665
734
  console.log('Static Files Dir :', staticDirs.length > 0 ? staticDirs.map(rootRelative) : '(None)');
735
+ console.log('Collection Selection :', collectionSelection != null ? collectionSelection.sources.map(x => x.type).join(', ') : '(None)');
666
736
  console.log('');
667
- console.log("Initializing Compute Application in " + computeJsDir + "...");
668
- fs.mkdirSync(computeJsDir);
669
- fs.mkdirSync(path.resolve(computeJsDir, './src'));
670
- const resourceFiles = {};
671
- // .gitignore
672
- resourceFiles['.gitignore'] = `\
673
- /node_modules
674
- /bin
675
- /pkg
676
- /${path.relative(computeJsDir, staticPublisherWorkingDir)}
677
- `;
678
- // package.json
679
- const computeJsStaticPublisherVersion = findComputeJsStaticPublisherVersion(packageJson);
680
- const packageJsonScripts = {
681
- 'dev:start': 'fastly compute serve',
682
- 'fastly:deploy': 'fastly compute publish',
683
- 'build': 'js-compute-runtime ./src/index.js ./bin/main.wasm',
684
- };
685
- if (storageMode === 'kv-store') {
686
- packageJsonScripts['dev:publish'] = 'npx @fastly/compute-js-static-publish publish-content --local';
687
- packageJsonScripts['fastly:publish'] = 'npx @fastly/compute-js-static-publish publish-content';
688
- }
689
- else if (storageMode === 's3') {
690
- packageJsonScripts['s3:publish'] = 'npx @fastly/compute-js-static-publish publish-content';
691
- }
692
- resourceFiles['package.json'] = JSON.stringify({
737
+ const appConfig = {
738
+ appDir: computeJsDir,
693
739
  name,
694
- version: '0.1.0',
695
- description,
696
740
  author,
697
- type: 'module',
698
- devDependencies: {
699
- "@fastly/cli": "^16.0.0",
700
- '@fastly/compute-js-static-publish': computeJsStaticPublisherVersion,
701
- },
702
- dependencies: {
703
- '@fastly/js-compute': '^4.0.0',
704
- },
705
- engines: {
706
- node: '>=20.11.0',
741
+ description,
742
+ serviceId: fastlyServiceId,
743
+ storage: storageMode === 'kv-store' ?
744
+ { mode: 'kv-store', kvStoreName: kvStoreName } :
745
+ { mode: 's3', region: s3Region, bucket: s3Bucket, endpointUrl: String(s3EndpointUrl), endpointGenerated: s3EndpointGenerated },
746
+ publishId,
747
+ defaultCollectionName,
748
+ staticPublisherWorkingDir,
749
+ rootDir,
750
+ publicDir,
751
+ staticDirs,
752
+ spaFilename,
753
+ notFoundPageFilename,
754
+ autoIndex,
755
+ autoExt,
756
+ staticPublishVersionSpec: findComputeJsStaticPublisherVersion(packageJson),
757
+ template: loadAppTemplate(options.template),
758
+ // The hono template: the extensions folder is in the directory where
759
+ // scaffold runs (next to the app, or next to the project file).
760
+ ...(options.template === 'hono' ? { build: { hono: { extensionsDir: path.resolve('hono-extensions') } } } : {}),
761
+ generatedFrom: {
762
+ template: options.template,
763
+ staticPublishVersion: getOwnVersion(),
764
+ generatedAt: new Date().toISOString().slice(0, 10),
707
765
  },
708
- private: true,
709
- scripts: packageJsonScripts,
710
- }, undefined, 2);
711
- // fastly.toml
712
- let fastlyTomlLocalServer = '';
713
- let fastlyTomlSetup = '';
714
- if (storageMode === 'kv-store') {
715
- const localServerKvStorePath = dotRelative(computeJsDir, path.resolve(staticPublisherWorkingDir, 'kvstore.json'));
716
- fastlyTomlLocalServer = /* language=text */ `\
717
- [local_server]
718
-
719
- [local_server.kv_stores]
720
- ${kvStoreName} = { file = "${localServerKvStorePath}", format = "json" }
721
- `;
722
- fastlyTomlSetup = /* language=text */ `\
723
- [setup]
724
-
725
- [setup.kv_stores]
726
- [setup.kv_stores.${kvStoreName}]
727
- `;
728
- // kvstore.json
729
- resourceFiles[localServerKvStorePath] = '{}';
730
- }
731
- else if (storageMode === 's3') {
732
- fastlyTomlLocalServer = /* language=text */ `\
733
- [local_server]
734
-
735
- [local_server.secret_stores]
736
- [[local_server.secret_stores.S3_CREDENTIALS]]
737
- key = "S3_ACCESS_KEY_ID"
738
- env = "S3_ACCESS_KEY_ID"
739
- [[local_server.secret_stores.S3_CREDENTIALS]]
740
- key = "S3_SECRET_ACCESS_KEY"
741
- env = "S3_SECRET_ACCESS_KEY"
742
-
743
- [local_server.backends]
744
- [local_server.backends.s3_storage]
745
- url = "${String(s3EndpointUrl)}"
746
- override_host = "${s3EndpointUrl.hostname}"
747
- `;
748
- fastlyTomlSetup = /* language=text */ `\
749
- [setup]
750
-
751
- [setup.backends]
752
- [setup.backends.s3_storage]
753
- address = "${s3EndpointUrl.hostname}"
754
- description = "S3 API endpoint"
755
- port = 443
756
- [setup.secret_stores]
757
- [setup.secret_stores.S3_CREDENTIALS]
758
- description = "Credentials for S3 storage"
759
- [setup.secret_stores.S3_CREDENTIALS.entries]
760
- [setup.secret_stores.S3_CREDENTIALS.entries.S3_ACCESS_KEY_ID]
761
- description = "Access Key ID"
762
- [setup.secret_stores.S3_CREDENTIALS.entries.S3_SECRET_ACCESS_KEY]
763
- description = "Secret Access Key"
764
- `;
765
- }
766
- resourceFiles['fastly.toml'] = /* language=text */ `\
767
- # This file describes a Fastly Compute package. To learn more visit:
768
- # https://developer.fastly.com/reference/fastly-toml/
769
-
770
- authors = [ "${author}" ]
771
- description = "${description}"
772
- language = "javascript"
773
- manifest_version = 3
774
- name = "${name}"
775
- ${fastlyServiceId != null ? `service_id = "${fastlyServiceId}"\n` : ''}
776
- [scripts]
777
- build = "npm run build"
778
-
779
- ${fastlyTomlLocalServer}
780
- ${fastlyTomlSetup}
781
- `;
782
- // static-publish.rc.js
783
- let staticPublishStorage = '';
784
- if (storageMode === 'kv-store') {
785
- staticPublishStorage = `\
786
- storageMode: "kv-store",
787
- kvStore: {
788
- kvStoreName: ${JSON.stringify(kvStoreName)},
789
- },\
790
- `;
766
+ collectionSelection,
767
+ };
768
+ if (managed) {
769
+ writeManagedProject(appConfig, projectDir);
770
+ // The app is not installed yet, so template init uses the versions of the
771
+ // template's lockfile.
772
+ if (templateHasInit(options.template)) {
773
+ await runTemplateInit({ templateName: options.template, rc: {}, baseDir: projectDir, appNodeModulesDir: undefined });
774
+ }
775
+ return;
791
776
  }
792
- else if (storageMode === 's3') {
793
- staticPublishStorage = `\
794
- storageMode: "s3",
795
- s3: {
796
- region: ${JSON.stringify(s3Region)},
797
- bucket: ${JSON.stringify(s3Bucket)},\
798
- ` + (!s3EndpointGenerated ? `
799
- endpoint: ${JSON.stringify(String(s3EndpointUrl))},\
800
- ` : '') + `
801
- },\
802
- `;
803
- }
804
- resourceFiles['static-publish.rc.js'] = `\
805
- /*
806
- * Generated by @fastly/compute-js-static-publish.
807
- */
808
-
809
- /** @type {import('@fastly/compute-js-static-publish').StaticPublishRc} */
810
- const rc = {
811
- ${staticPublishStorage}
812
- publishId: ${JSON.stringify(publishId)},
813
- defaultCollectionName: ${JSON.stringify(defaultCollectionName)},
814
- staticPublisherWorkingDir: ${JSON.stringify(dotRelative(computeJsDir, staticPublisherWorkingDir))},
815
- };
816
-
817
- export default rc;
818
- `;
819
- // publish-content.config.js
820
- // publicDirPrefix -- if public dir is deeper than the root dir, then
821
- // public dir is used as a prefix to drill into asset names.
822
- // e.g.,
823
- // root dir : /path/to/root
824
- // public dir : /path/to/root/public
825
- // then publicDirPrefix = /public
826
- // We've already established publicDir.startsWith(rootDir)
827
- let publicDirPrefix = '';
828
- if (rootDir !== publicDir) {
829
- publicDirPrefix = publicDir.slice(rootDir.length);
830
- }
831
- // staticItems - specified as prefixes, relative to publicDir
832
- const staticItems = [];
833
- for (const staticDir of staticDirs) {
834
- // We've already established staticDir.startsWith(publicDir)
835
- let staticItem = staticDir.slice(publicDir.length);
836
- if (!staticItem.endsWith('/')) {
837
- // Ending with a slash denotes that this is a directory.
838
- staticItem = staticItem + '/';
839
- }
840
- staticItems.push(staticItem);
841
- }
842
- // spaFile - asset key of spa file
843
- let spaFile = false;
844
- if (spaFilename != null) {
845
- // We've already established spaFilename.startsWith(rootDir)
846
- // and that it exists
847
- spaFile = spaFilename.slice(rootDir.length);
848
- }
849
- let notFoundPageFile = false;
850
- if (notFoundPageFilename != null) {
851
- // We've already established notFoundPageFilename.startsWith(rootDir)
852
- // and that it exists
853
- notFoundPageFile = notFoundPageFilename.slice(rootDir.length);
854
- }
855
- resourceFiles['publish-content.config.js'] = `\
856
- /*
857
- * Generated by @fastly/compute-js-static-publish.
858
- */
859
-
860
- // Commented items are defaults, feel free to modify and experiment!
861
- // See README for a detailed explanation of the configuration options.
862
-
863
- /** @type {import('@fastly/compute-js-static-publish').PublishContentConfig} */
864
- const config = {
865
- rootDir: ${JSON.stringify(dotRelative(computeJsDir, rootDir))},
866
- // excludeDirs: [ './node_modules' ],
867
- // excludeDotFiles: true,
868
- // includeWellKnown: true,
869
- // assetInclusionTest: (assetKey) => true,
870
- // contentCompression: [ 'br', 'gzip' ],
871
- // brotliQuality: 11,
872
- // contentTypes: [
873
- // { test: /.custom$/, contentType: 'application/x-custom', text: false },
874
- // ],
875
-
876
- // Server settings are saved to storage per collection
877
- server: {${publicDirPrefix !== '' ? `
878
- publicDirPrefix: ${JSON.stringify(publicDirPrefix)},` : ''}
879
- staticItems: ${JSON.stringify(staticItems)},
880
- allowedEncodings: [ 'br', 'gzip' ],
881
- spaFile: ${JSON.stringify(spaFile)},
882
- notFoundPageFile: ${JSON.stringify(notFoundPageFile)},
883
- autoExt: ${JSON.stringify(autoExt)},
884
- autoIndex: ${JSON.stringify(autoIndex)},
885
- },
886
- };
887
-
888
- export default config;
889
- `;
890
- // src/index.js
891
- resourceFiles['./src/index.js'] = /* language=text */ `\
892
- /// <reference types="@fastly/js-compute" />
893
- import { env } from 'fastly:env';
894
- import { PublisherServer } from '@fastly/compute-js-static-publish';
895
- import rc from '../static-publish.rc.js';
896
- const publisherServer = PublisherServer.fromStaticPublishRc(rc);
897
-
898
- // eslint-disable-next-line no-restricted-globals
899
- addEventListener("fetch", (event) => event.respondWith(handleRequest(event)));
900
- async function handleRequest(event) {
901
-
902
- console.log('FASTLY_SERVICE_VERSION', env('FASTLY_SERVICE_VERSION'));
903
-
904
- const request = event.request;
905
-
906
- const response = await publisherServer.serveRequest(request);
907
- if (response != null) {
908
- return response;
909
- }
910
-
911
- // Do custom things here!
912
- // Handle API requests, serve non-static responses, etc.
913
-
914
- return new Response('Not found', { status: 404 });
915
- }
916
- `;
777
+ console.log("Initializing Compute Application in " + computeJsDir + "...");
778
+ fs.mkdirSync(computeJsDir);
779
+ fs.mkdirSync(path.resolve(computeJsDir, './src'));
780
+ const resourceFiles = generateApp(appConfig);
917
781
  // Write out the files
918
782
  for (const [filename, content] of Object.entries(resourceFiles)) {
919
783
  const filePath = path.resolve(computeJsDir, filename);
@@ -925,6 +789,16 @@ async function handleRequest(event) {
925
789
  console.log(`npm --prefix ${COMPUTE_JS_DIR} install`);
926
790
  child_process.spawnSync('npm', ['--prefix', COMPUTE_JS_DIR, 'install'], { stdio: 'inherit' });
927
791
  console.log('');
792
+ // The folder of the template (for the hono template: hono-extensions/, next
793
+ // to the app). It is in the directory where scaffold runs.
794
+ if (templateHasInit(options.template)) {
795
+ await runTemplateInit({
796
+ templateName: options.template,
797
+ rc: {},
798
+ baseDir: path.resolve(),
799
+ appNodeModulesDir: path.resolve(computeJsDir, 'node_modules'),
800
+ });
801
+ }
928
802
  if (storageMode === 'kv-store') {
929
803
  console.log(`
930
804
  To run your Compute application locally:
@@ -987,7 +861,7 @@ To build and deploy to your Compute service:
987
861
  If a Secret Store named 'S3_CREDENTIALS' already exists, the Fastly CLI asks for a
988
862
  different name. If you leave it empty, it uses the existing Secret Store. If you give
989
863
  a different name, the Fastly CLI uses it for the resource link too. Then call
990
- setSecretStoreForS3Credentials() with that name in src/index.js, and deploy again.
864
+ setSecretStoreForS3Credentials() with that name in ${appConfig.template.entry}, and deploy again.
991
865
 
992
866
  After the deploy, fastly.toml has the service ID, so s3:publish also purges the
993
867
  service's cache. For this purge, s3:publish needs FASTLY_API_TOKEN too.
@@ -995,3 +869,47 @@ To build and deploy to your Compute service:
995
869
  `);
996
870
  }
997
871
  }
872
+ // The lines that scaffold --managed adds to the .gitignore of the project dir.
873
+ const GITIGNORE_COMMENT = '# @fastly/compute-js-static-publish';
874
+ export function addGitignoreLines(existing, lines) {
875
+ const present = new Set((existing ?? '').split(/\r?\n/).map(x => x.trim()));
876
+ const added = lines.filter(line => !present.has(line));
877
+ if (added.length === 0) {
878
+ return { content: existing ?? '', added };
879
+ }
880
+ let content = existing ?? '';
881
+ if (content !== '' && !content.endsWith('\n')) {
882
+ content += '\n';
883
+ }
884
+ if (content !== '') {
885
+ content += '\n';
886
+ }
887
+ content += [GITIGNORE_COMMENT, ...added].join('\n') + '\n';
888
+ return { content, added };
889
+ }
890
+ function writeManagedProject(appConfig, projectDir) {
891
+ const projectFilePath = path.resolve(projectDir, PROJECT_FILE_NAME);
892
+ fs.writeFileSync(projectFilePath, renderProjectFile(appConfig, projectDir, getOwnVersion()), 'utf-8');
893
+ console.log(`🚀 Managed project created: ${rootRelative(projectFilePath)}`);
894
+ // Ignore the generated app and the working dir. Never change the customer's lines.
895
+ const gitignorePath = path.resolve(projectDir, '.gitignore');
896
+ const existing = fs.existsSync(gitignorePath) ? fs.readFileSync(gitignorePath, 'utf-8') : null;
897
+ const workingDir = path.relative(projectDir, appConfig.staticPublisherWorkingDir).split(path.sep).join('/');
898
+ const lines = ['/.static-publish/'];
899
+ if (!workingDir.startsWith('..')) {
900
+ lines.push(`/${workingDir}/`);
901
+ }
902
+ const { content, added } = addGitignoreLines(existing, lines);
903
+ if (added.length > 0) {
904
+ fs.writeFileSync(gitignorePath, content, 'utf-8');
905
+ console.log(`✔️ Added to ${existing == null ? 'a new ' : ''}.gitignore: ${added.join(', ')}`);
906
+ }
907
+ console.log(`
908
+ The CLI generates the Compute app from ${PROJECT_FILE_NAME}.
909
+ Commit ${PROJECT_FILE_NAME}. Do not commit .static-publish/.
910
+
911
+ To publish your content from this directory:
912
+
913
+ ${cliCommand()} publish-content --local
914
+ `);
915
+ }