@conloca/cloud-astro 0.2.2 → 0.2.4

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 (241) hide show
  1. package/README.md +378 -207
  2. package/dist/.build-inputs.json +69 -0
  3. package/dist/src/component-manifest.d.ts +5 -3
  4. package/dist/src/component-manifest.d.ts.map +1 -1
  5. package/dist/src/component-manifest.js +7 -7
  6. package/dist/src/component-manifest.js.map +1 -1
  7. package/dist/src/constants.d.ts +14 -13
  8. package/dist/src/constants.d.ts.map +1 -1
  9. package/dist/src/constants.js +14 -13
  10. package/dist/src/constants.js.map +1 -1
  11. package/dist/src/d3-build.d.ts +70 -0
  12. package/dist/src/d3-build.d.ts.map +1 -0
  13. package/dist/src/d3-build.js +272 -0
  14. package/dist/src/d3-build.js.map +1 -0
  15. package/dist/src/descriptors.d.ts +2 -2
  16. package/dist/src/descriptors.d.ts.map +1 -1
  17. package/dist/src/descriptors.js +4 -2
  18. package/dist/src/descriptors.js.map +1 -1
  19. package/dist/src/doctor/checks-address.d.ts +18 -0
  20. package/dist/src/doctor/checks-address.d.ts.map +1 -0
  21. package/dist/src/doctor/checks-address.js +163 -0
  22. package/dist/src/doctor/checks-address.js.map +1 -0
  23. package/dist/src/doctor/checks-live.d.ts +8 -5
  24. package/dist/src/doctor/checks-live.d.ts.map +1 -1
  25. package/dist/src/doctor/checks-live.js +226 -188
  26. package/dist/src/doctor/checks-live.js.map +1 -1
  27. package/dist/src/doctor/checks-offline.d.ts +6 -25
  28. package/dist/src/doctor/checks-offline.d.ts.map +1 -1
  29. package/dist/src/doctor/checks-offline.js +30 -259
  30. package/dist/src/doctor/checks-offline.js.map +1 -1
  31. package/dist/src/doctor/checks-preview-limits.d.ts +11 -0
  32. package/dist/src/doctor/checks-preview-limits.d.ts.map +1 -0
  33. package/dist/src/doctor/checks-preview-limits.js +133 -0
  34. package/dist/src/doctor/checks-preview-limits.js.map +1 -0
  35. package/dist/src/doctor/checks-preview-live.d.ts +14 -0
  36. package/dist/src/doctor/checks-preview-live.d.ts.map +1 -0
  37. package/dist/src/doctor/checks-preview-live.js +72 -0
  38. package/dist/src/doctor/checks-preview-live.js.map +1 -0
  39. package/dist/src/doctor/checks-preview.d.ts +7 -0
  40. package/dist/src/doctor/checks-preview.d.ts.map +1 -0
  41. package/dist/src/doctor/checks-preview.js +287 -0
  42. package/dist/src/doctor/checks-preview.js.map +1 -0
  43. package/dist/src/doctor/config-scan.d.ts +12 -3
  44. package/dist/src/doctor/config-scan.d.ts.map +1 -1
  45. package/dist/src/doctor/config-scan.js +38 -11
  46. package/dist/src/doctor/config-scan.js.map +1 -1
  47. package/dist/src/doctor/run.d.ts.map +1 -1
  48. package/dist/src/doctor/run.js +16 -10
  49. package/dist/src/doctor/run.js.map +1 -1
  50. package/dist/src/doctor/types.d.ts +17 -7
  51. package/dist/src/doctor/types.d.ts.map +1 -1
  52. package/dist/src/doctor/types.js +17 -7
  53. package/dist/src/doctor/types.js.map +1 -1
  54. package/dist/src/editor-page/bundle.d.ts +90 -0
  55. package/dist/src/editor-page/bundle.d.ts.map +1 -0
  56. package/dist/src/editor-page/bundle.js +373 -0
  57. package/dist/src/editor-page/bundle.js.map +1 -0
  58. package/dist/src/editor-page/data-schemas.d.ts +16 -0
  59. package/dist/src/editor-page/data-schemas.d.ts.map +1 -0
  60. package/dist/src/editor-page/data-schemas.js +39 -0
  61. package/dist/src/editor-page/data-schemas.js.map +1 -0
  62. package/dist/src/editor-page/emit.d.ts +69 -0
  63. package/dist/src/editor-page/emit.d.ts.map +1 -0
  64. package/dist/src/editor-page/emit.js +254 -0
  65. package/dist/src/editor-page/emit.js.map +1 -0
  66. package/dist/src/editor-page/framing.d.ts +23 -0
  67. package/dist/src/editor-page/framing.d.ts.map +1 -0
  68. package/dist/src/editor-page/framing.js +39 -0
  69. package/dist/src/editor-page/framing.js.map +1 -0
  70. package/dist/src/editor-page/page.d.ts +9 -0
  71. package/dist/src/editor-page/page.d.ts.map +1 -0
  72. package/dist/src/editor-page/page.js +31 -0
  73. package/dist/src/editor-page/page.js.map +1 -0
  74. package/dist/src/editor-page/site-base.d.ts +4 -0
  75. package/dist/src/editor-page/site-base.d.ts.map +1 -0
  76. package/dist/src/editor-page/site-base.js +13 -0
  77. package/dist/src/editor-page/site-base.js.map +1 -0
  78. package/dist/src/git.d.ts +11 -8
  79. package/dist/src/git.d.ts.map +1 -1
  80. package/dist/src/git.js +25 -8
  81. package/dist/src/git.js.map +1 -1
  82. package/dist/src/index.d.ts +4 -1
  83. package/dist/src/index.d.ts.map +1 -1
  84. package/dist/src/index.js +11 -6
  85. package/dist/src/index.js.map +1 -1
  86. package/dist/src/integration.d.ts +1 -1
  87. package/dist/src/integration.d.ts.map +1 -1
  88. package/dist/src/integration.js +377 -416
  89. package/dist/src/integration.js.map +1 -1
  90. package/dist/src/node.d.ts +3 -1
  91. package/dist/src/node.d.ts.map +1 -1
  92. package/dist/src/node.js +7 -2
  93. package/dist/src/node.js.map +1 -1
  94. package/dist/src/preview/_dispatch.d.ts +12 -0
  95. package/dist/src/preview/_dispatch.d.ts.map +1 -1
  96. package/dist/src/preview/_dispatch.js +31 -0
  97. package/dist/src/preview/_dispatch.js.map +1 -1
  98. package/dist/src/preview/_resolve-opts.d.ts +19 -10
  99. package/dist/src/preview/_resolve-opts.d.ts.map +1 -1
  100. package/dist/src/preview/_resolve-opts.js +24 -11
  101. package/dist/src/preview/_resolve-opts.js.map +1 -1
  102. package/dist/src/preview/banner.d.ts +12 -9
  103. package/dist/src/preview/banner.d.ts.map +1 -1
  104. package/dist/src/preview/banner.js +46 -43
  105. package/dist/src/preview/banner.js.map +1 -1
  106. package/dist/src/preview/cloudflare-adapter.d.ts +35 -0
  107. package/dist/src/preview/cloudflare-adapter.d.ts.map +1 -0
  108. package/dist/src/preview/cloudflare-adapter.js +92 -0
  109. package/dist/src/preview/cloudflare-adapter.js.map +1 -0
  110. package/dist/src/preview/cookie.d.ts +13 -14
  111. package/dist/src/preview/cookie.d.ts.map +1 -1
  112. package/dist/src/preview/cookie.js +19 -26
  113. package/dist/src/preview/cookie.js.map +1 -1
  114. package/dist/src/preview/dispatcher.d.ts +73 -0
  115. package/dist/src/preview/dispatcher.d.ts.map +1 -0
  116. package/dist/src/preview/dispatcher.js +329 -0
  117. package/dist/src/preview/dispatcher.js.map +1 -0
  118. package/dist/src/preview/entry-code.d.ts +33 -0
  119. package/dist/src/preview/entry-code.d.ts.map +1 -0
  120. package/dist/src/preview/entry-code.js +33 -0
  121. package/dist/src/preview/entry-code.js.map +1 -0
  122. package/dist/src/preview/headers.d.ts +24 -4
  123. package/dist/src/preview/headers.d.ts.map +1 -1
  124. package/dist/src/preview/headers.js +35 -7
  125. package/dist/src/preview/headers.js.map +1 -1
  126. package/dist/src/preview/label.d.ts +8 -0
  127. package/dist/src/preview/label.d.ts.map +1 -0
  128. package/dist/src/preview/label.js +14 -0
  129. package/dist/src/preview/label.js.map +1 -0
  130. package/dist/src/preview/landing.d.ts +23 -2
  131. package/dist/src/preview/landing.d.ts.map +1 -1
  132. package/dist/src/preview/landing.js +105 -37
  133. package/dist/src/preview/landing.js.map +1 -1
  134. package/dist/src/preview/middleware.d.ts +49 -22
  135. package/dist/src/preview/middleware.d.ts.map +1 -1
  136. package/dist/src/preview/middleware.js +259 -100
  137. package/dist/src/preview/middleware.js.map +1 -1
  138. package/dist/src/preview/preview-path.d.ts +47 -5
  139. package/dist/src/preview/preview-path.d.ts.map +1 -1
  140. package/dist/src/preview/preview-path.js +65 -8
  141. package/dist/src/preview/preview-path.js.map +1 -1
  142. package/dist/src/preview/redeem-url.d.ts +7 -0
  143. package/dist/src/preview/redeem-url.d.ts.map +1 -0
  144. package/dist/src/preview/redeem-url.js +14 -0
  145. package/dist/src/preview/redeem-url.js.map +1 -0
  146. package/dist/src/preview/site-middleware.d.ts +5 -5
  147. package/dist/src/preview/site-middleware.d.ts.map +1 -1
  148. package/dist/src/preview/site-middleware.js +53 -26
  149. package/dist/src/preview/site-middleware.js.map +1 -1
  150. package/dist/src/preview-build.d.ts +29 -15
  151. package/dist/src/preview-build.d.ts.map +1 -1
  152. package/dist/src/preview-build.js +66 -25
  153. package/dist/src/preview-build.js.map +1 -1
  154. package/dist/src/preview.d.ts +1 -1
  155. package/dist/src/preview.d.ts.map +1 -1
  156. package/dist/src/preview.js +1 -1
  157. package/dist/src/preview.js.map +1 -1
  158. package/dist/src/repository.d.ts +1 -1
  159. package/dist/src/repository.js +1 -1
  160. package/dist/src/resolve-options.d.ts +17 -0
  161. package/dist/src/resolve-options.d.ts.map +1 -0
  162. package/dist/src/resolve-options.js +21 -0
  163. package/dist/src/resolve-options.js.map +1 -0
  164. package/dist/src/site-id.d.ts +0 -2
  165. package/dist/src/site-id.d.ts.map +1 -1
  166. package/dist/src/site-id.js +2 -3
  167. package/dist/src/site-id.js.map +1 -1
  168. package/dist/src/skill.d.ts +11 -0
  169. package/dist/src/skill.d.ts.map +1 -1
  170. package/dist/src/skill.js +32 -9
  171. package/dist/src/skill.js.map +1 -1
  172. package/dist/src/types.d.ts +33 -78
  173. package/dist/src/types.d.ts.map +1 -1
  174. package/package.json +63 -13
  175. package/src/component-manifest.ts +11 -8
  176. package/src/constants.ts +15 -13
  177. package/src/d3-build.ts +315 -0
  178. package/src/descriptors.ts +6 -4
  179. package/src/doctor/checks-address.ts +190 -0
  180. package/src/doctor/checks-live.ts +262 -268
  181. package/src/doctor/checks-offline.ts +32 -279
  182. package/src/doctor/checks-preview-limits.ts +137 -0
  183. package/src/doctor/checks-preview-live.ts +77 -0
  184. package/src/doctor/checks-preview.ts +302 -0
  185. package/src/doctor/config-scan.ts +35 -9
  186. package/src/doctor/run.ts +18 -16
  187. package/src/doctor/types.ts +17 -7
  188. package/src/editor-page/bundle.ts +487 -0
  189. package/src/editor-page/data-schemas.ts +47 -0
  190. package/src/editor-page/emit.ts +362 -0
  191. package/src/editor-page/framing.ts +62 -0
  192. package/src/editor-page/page.ts +37 -0
  193. package/src/editor-page/site-base.ts +11 -0
  194. package/src/git.ts +29 -10
  195. package/src/index.ts +22 -6
  196. package/src/integration.ts +399 -469
  197. package/src/node.ts +18 -2
  198. package/src/preview/_dispatch.ts +36 -1
  199. package/src/preview/_resolve-opts.ts +35 -12
  200. package/src/preview/banner.ts +61 -43
  201. package/src/preview/cloudflare-adapter.ts +103 -0
  202. package/src/preview/cookie.ts +18 -24
  203. package/src/preview/dispatcher.ts +407 -0
  204. package/src/preview/entry-code.ts +51 -0
  205. package/src/preview/headers.ts +35 -7
  206. package/src/preview/label.ts +12 -0
  207. package/src/preview/landing.ts +117 -39
  208. package/src/preview/middleware.ts +302 -115
  209. package/src/preview/preview-path.ts +83 -8
  210. package/src/preview/redeem-url.ts +14 -0
  211. package/src/preview/site-middleware.ts +60 -30
  212. package/src/preview-build.ts +85 -26
  213. package/src/preview-handler.astro +12 -9
  214. package/src/preview.ts +0 -1
  215. package/src/repository.ts +1 -1
  216. package/src/resolve-options.ts +37 -0
  217. package/src/site-id.ts +2 -4
  218. package/src/skill/SKILL.md +63 -55
  219. package/src/skill.ts +36 -8
  220. package/src/types.ts +33 -79
  221. package/src/virtual-modules.d.ts +4 -1
  222. package/dist/src/build-commit.d.ts +0 -19
  223. package/dist/src/build-commit.d.ts.map +0 -1
  224. package/dist/src/build-commit.js +0 -6
  225. package/dist/src/build-commit.js.map +0 -1
  226. package/dist/src/bundle.d.ts +0 -181
  227. package/dist/src/bundle.d.ts.map +0 -1
  228. package/dist/src/bundle.js +0 -413
  229. package/dist/src/bundle.js.map +0 -1
  230. package/dist/src/discovery.d.ts +0 -58
  231. package/dist/src/discovery.d.ts.map +0 -1
  232. package/dist/src/discovery.js +0 -133
  233. package/dist/src/discovery.js.map +0 -1
  234. package/dist/src/register.d.ts +0 -98
  235. package/dist/src/register.d.ts.map +0 -1
  236. package/dist/src/register.js +0 -103
  237. package/dist/src/register.js.map +0 -1
  238. package/src/build-commit.ts +0 -22
  239. package/src/bundle.ts +0 -570
  240. package/src/discovery.ts +0 -183
  241. package/src/register.ts +0 -180
@@ -1,17 +1,16 @@
1
- import { existsSync } from 'node:fs';
2
1
  import { createRequire } from 'node:module';
3
2
  import { fileURLToPath } from 'node:url';
4
3
  import { readEditorDescriptors } from '@conloca/astro-cms/node';
5
- import { registrationCommits } from './build-commit.js';
6
- import { bundleEditorAssets, emitRouteCssArtifact, mirrorEditorAssets } from './bundle.js';
7
- import { emitComponentManifest } from './component-manifest.js';
8
- import { BUILD_TOKEN_ENV_VAR, PACKAGE_NAME, PREVIEW_BUILD_ENV_FLAG, PREVIEW_SECRET_ENV_FLAG } from './constants.js';
9
- import { resolveEditorDescriptors } from './descriptors.js';
10
- import { discoverStyleContext } from './discovery.js';
4
+ import { DEFAULT_EDITOR_ENDPOINT, editorUiOrigin } from '@conloca/content-api/editor-host';
5
+ import { PACKAGE_NAME, PREVIEW_BUILD_ENV_FLAG } from './constants.js';
6
+ import { finishD3Build, onDemandPatterns, workerFirstPattern, writePreviewRoutes } from './d3-build.js';
7
+ import { emitEditorPage, emitPreviewServerInfo, mirrorEditorPage } from './editor-page/emit.js';
11
8
  import { gitOutput, resolveBuildRef, resolveRepositoryUri } from './git.js';
12
- import { packageVersion } from './package-version.js';
13
- import { spawnPreviewBuild } from './preview-build.js';
14
- import { postRegistration } from './register.js';
9
+ import { messageOf } from './message-of.js';
10
+ import { cloudflareAdapter, resolveCloudflareAdapter } from './preview/cloudflare-adapter.js';
11
+ import { normalizeTrailingSlash, PREVIEW_ROUTE_SEGMENT } from './preview/preview-path.js';
12
+ import { prerenderedKey, previewBuildMode, previewChildMode, previewChildPrerendered, spawnPreviewBuild, } from './preview-build.js';
13
+ import { resolveInheritedOptions } from './resolve-options.js';
15
14
  import { resolveBuildSiteId } from './site-id.js';
16
15
  import { scaffoldSkill } from './skill.js';
17
16
  // Re-export the constants that moved out of this module when the preview
@@ -20,214 +19,260 @@ import { scaffoldSkill } from './skill.js';
20
19
  export { PACKAGE_NAME, PREVIEW_BUILD_ENV_FLAG };
21
20
  /**
22
21
  * Returns the site's Astro integration that hooks into `astro:build:done`
23
- * to bundle editor assets, register the build at `endpoint`, and
24
- * (optionally) trigger a recursive preview build.
22
+ * to write the editor page and, when the site opts in, trigger a recursive
23
+ * preview build.
25
24
  *
26
25
  * The build:done pipeline:
27
26
  *
28
- * 1. esbuild the site's puck config into one browser ESM bundle under
29
- * `dist/_conloca/` with react/react-dom/jsx-runtime/puck externalized
30
- * (the editor supplies them at runtime), plus a `_headers` CORS
31
- * rule so the editor's origin can load it cross-origin. For a conlocaCMS
32
- * build it also writes the component manifest there (what each
33
- * component accepts, read from source) and registers its URL + hash
34
- * with the bundle.
35
- * 2. POST the registration (repo, git sha, branch, bundle URL + hash) to the
36
- * endpoint, authenticated by the build token. An ATTEMPTED
37
- * registration that is rejected FAILS THE BUILD — the error carries the
38
- * endpoint's exact status and body. Only a never-attempted registration (no
39
- * build token, repo identity, git sha/branch, or public base URL) skips,
40
- * ending the build with one summary block — or failing it when
41
- * `requireRegistration` is set.
42
- * 3. Spawn the recursive preview build with the preview secret
43
- * returned by registration (or the env override).
27
+ * 0. Write the editor page to `dist/_conloca/editor/`: `index.html`, the
28
+ * site's compiled puck config and styles, the MDX sandbox frame and
29
+ * `conloca.json`. Every build does this; the page carries no credential.
30
+ * 1. Only when `previewBuild` is given as an object: D2 spawns the recursive preview build and mirrors the editor
31
+ * page into its client folder; D3 spawns it next to the static site and writes the dispatcher (`d3-build.ts`),
32
+ * failing the build when a failed preview build would leave the site's own on-demand routes unserved; D4 builds
33
+ * it in a separate deploy, not here. The preview build mounts `/_conloca/preview/` and bakes in the repository,
34
+ * site and branch it serves (every pass must match them), Astro's base and the commit it was built from.
44
35
  */
45
36
  const VIRTUAL_PREVIEW_OPTS = 'virtual:conloca-preview-opts';
46
37
  const RESOLVED_PREVIEW_OPTS = `\0${VIRTUAL_PREVIEW_OPTS}`;
47
- export function conlocaCloud(options) {
38
+ /** Where the preview build writes its server and client, outside dist/ (see config:setup). */
39
+ function previewOutDir(previewBuild, root) {
40
+ return new URL(`${(previewBuild || undefined)?.outDir ?? '.conloca/preview-server'}/`, root);
41
+ }
42
+ export function conlocaCloud(options = {}) {
48
43
  validateOptions(options);
49
44
  const repoUri = resolveRepositoryUri(options.repoUri, process.env);
50
45
  // Populated during the preview build's config:setup and read by the virtual
51
46
  // module below. Server-only — never reaches a browser bundle.
52
47
  let previewOptsModule;
48
+ // The exit values the preview build baked (its config:setup), reported to the site's build for the dispatcher.
49
+ let childExit;
50
+ // The Astro command, recorded in config:setup: only `astro build` starts
51
+ // the preview build, so only it checks the preview adapter at config:done.
52
+ let astroCommand;
53
53
  // The project root, captured in config:setup: astro:build:done only hands
54
54
  // over the build's own outDir, but the siteStyles resolve against the root,
55
- // and locating the CHILD build's client dir (for the editor-asset mirror)
55
+ // and locating the CHILD build's client dir (for the editor page mirror)
56
56
  // needs the root the child resolves against.
57
57
  let projectRoot;
58
- // Adapter name, finalized only at config:done. Discovery boots the built
59
- // server entry for `output: 'server'` sites, and only the node adapter's
60
- // entry is a plain bootable process (see discovery.ts).
58
+ // Adapter name, finalized only at config:done: the preview build reads it
59
+ // when previewBuild names no adapter of its own.
61
60
  let adapterName;
62
- // The site's Vite config, finalized at config:done: the siteStyles compile
63
- // through it, as they do in conlocaCMS's dev editor.
61
+ // The site's Vite config, finalized at config:done: the editor page and the
62
+ // siteStyles compile through it, as they do in conlocaCMS's dev editor. It
63
+ // holds the site's and integrations' plugins only; Astro adds its own core
64
+ // plugins to a separate config when it builds, so none reach the editor page.
64
65
  let viteConfig;
66
+ // Astro's base, as written: the editor page's URLs sit below it.
67
+ let astroBase = '/';
68
+ // Where the site's pages live and how Astro builds them: conloca.json lists the prerendered ones.
69
+ let srcDir;
70
+ let serverOutput = false;
71
+ let i18n;
72
+ // The editor options, settled at config:done: conlocaCMS publishes its
73
+ // channel from its own config:setup, which may run after ours.
74
+ let inherited;
75
+ // Whether the parent build starts the preview build, read with the adapter
76
+ // the child will use: previewBuild.adapter, else the project's own.
77
+ const previewMode = () => previewBuildMode(options.previewBuild, (options.previewBuild || undefined)?.adapter?.name ?? adapterName);
78
+ // Whether the project has no adapter of its own, read in config:setup before the preview build switches to
79
+ // server output: such a site can use no server islands, so its dispatcher never runs on their route.
80
+ let projectStatic = false;
81
+ // The routes the preview build renders on demand (astro:routes:resolved), as Astro patterns.
82
+ let onDemand = [];
83
+ // The site's build: the routes it prerendered (astro:routes:resolved), handed to a D3 child.
84
+ let sitePrerendered = [];
85
+ // A D3 child: the routes its site's build prerendered, which it keeps prerendered (config:setup).
86
+ let keepPrerendered = new Set();
87
+ // The preview build's mode (config:setup): a D4 child of a static site has no site build to ask.
88
+ let childServeMode = 'd4';
65
89
  return {
66
90
  name: PACKAGE_NAME,
67
91
  hooks: {
68
- 'astro:config:setup': ({ logger, injectRoute, updateConfig, config, addMiddleware }) => {
92
+ 'astro:config:setup': async ({ logger, injectRoute, updateConfig, config, addMiddleware, command }) => {
69
93
  // Optional-chained: unit tests drive this hook with a bare { logger }.
70
94
  projectRoot = config?.root;
95
+ astroCommand = command;
96
+ projectStatic = config?.adapter === undefined;
71
97
  // The agent skill: write-if-not-exists, fail-soft, and
72
98
  // never from the recursive preview child (it would race the parent).
73
99
  if (process.env[PREVIEW_BUILD_ENV_FLAG] !== '1' && config?.root) {
74
100
  scaffoldSkill(fileURLToPath(config.root), logger);
75
101
  }
76
- logger.info(`integration registered (endpoint=${options.endpoint}, previewMode=${options.previewDomain ? 'preview-domain' : 'same-domain-runtime'})`);
102
+ logger.info(`integration registered (endpoint=${options.endpoint ?? DEFAULT_EDITOR_ENDPOINT})`);
77
103
  // Only the recursive preview build (which sets PREVIEW_BUILD_ENV_FLAG)
78
- // mounts the secret-scoped SSR catch-all that renders previews. A
79
- // site's normal build must never expose it; the per-branch secret in
80
- // the path is the load guard (JWT validation in the handler is the real
81
- // auth boundary). Without a secret there is nothing to scope, so skip.
104
+ // mounts the SSR catch-all that renders previews; a site's normal
105
+ // build never exposes it. The route is fixed and public: the signed
106
+ // pass, checked against what this build bakes in, is the lock.
82
107
  if (process.env[PREVIEW_BUILD_ENV_FLAG] === '1') {
83
- const secret = process.env[PREVIEW_SECRET_ENV_FLAG];
84
- if (secret) {
85
- if (!repoUri) {
86
- throw new Error(`${PACKAGE_NAME}: could not determine repository identity for the preview build ` +
87
- '(build in a Git checkout or set repoUri as an advanced override)');
88
- }
89
- injectRoute({
90
- pattern: `/conloca_preview_${secret}/[...path]`,
91
- entrypoint: '@conloca/cloud-astro/preview-handler',
92
- prerender: false,
93
- });
94
- // The prefixed route above is the ENTRY DOOR — the only URL the
95
- // endpoint can link to before a cookie exists. This interceptor is the
96
- // serving surface: once the init hop sets the `Path=/` cookie, the
97
- // browser sends the credential on every same-origin request, so
98
- // internal links keep rendering drafts instead of silently falling
99
- // back to published content after one page view. Fail-open — an
100
- // uncredentialed visitor gets the ordinary page.
101
- addMiddleware({ entrypoint: '@conloca/cloud-astro/site-middleware', order: 'pre' });
102
- // Bake the middleware's configuration into the artifact. Every
103
- // value is already known here — the secret arrived with
104
- // registration, endpoint/audience are integration options — so a
105
- // correctly built preview deployment needs NO env vars set on it.
106
- // That also closes a chicken-and-egg loop: the secret is generated
107
- // DURING this build, but the deployment that would carry it as an
108
- // env var only happens afterwards. `saasIssuer` stays unbaked
109
- // unless configured: it is a property of the endpoint, not of the site.
110
- // The commit this preview build's checkout holds: a PR build may
111
- // check out a merge commit rather than the PR commit it registers.
112
- // Page-status compares the branch's latest commit with it, so the
113
- // endpoint diffs against the content actually serving, not a newer
114
- // registration whose deploy never landed. A checkout commit the
115
- // endpoint does not have makes it render from the branch instead.
116
- const buildCommit = registrationCommits({
117
- eventCommitSha: process.env.CF_PAGES_COMMIT_SHA,
118
- checkoutCommitSha: gitOutput(['rev-parse', 'HEAD']),
119
- }).buildId;
120
- previewOptsModule = {
121
- secret,
122
- saasEndpoint: options.endpoint,
123
- // The token's `aud` is the repo URI as registered — the same
124
- // string this integration posts at registration time.
125
- saasAudience: repoUri,
126
- ...(options.saasIssuer ? { saasIssuer: options.saasIssuer } : {}),
127
- ...(buildCommit ? { buildCommit } : {}),
128
- };
129
- // Preview-build path: the child build must emit an SSR
130
- // artifact even when the primary build is fully static. Switch to
131
- // server output, apply the preview adapter (the project's own
132
- // adapter stays in force when it already has one), and write to a
133
- // SEPARATE outDir so the child never clobbers the primary dist/.
134
- const previewBuild = options.previewBuild === false ? {} : (options.previewBuild ?? {});
135
- const adapter = previewBuild.adapter ?? config.adapter;
136
- if (!adapter) {
137
- throw new Error(`${PACKAGE_NAME}: the preview build needs an SSR adapter — the project is static and ` +
138
- 'previewBuild.adapter is not set. Pass one (e.g. previewBuild: { adapter: cloudflare() }) ' +
139
- 'or set previewBuild: false to opt out of draft preview.');
140
- }
141
- // Astro allows exactly one deployment integration. Adding
142
- // previewBuild.adapter next to the project's own would make the
143
- // child build die on Astro's adapter-conflict error, which names
144
- // neither this integration nor the option — fail here with the
145
- // actual cause. The child inherits the project adapter, so the
146
- // option is unnecessary on SSR projects.
147
- if (previewBuild.adapter && config.adapter) {
148
- const projectAdapterName = config.adapter.name ?? 'the project adapter';
149
- throw new Error(`${PACKAGE_NAME}: previewBuild.adapter conflicts with the project's own adapter ` +
150
- `(${projectAdapterName}) — Astro allows only one deployment integration per build. ` +
151
- 'Remove previewBuild.adapter; the preview build inherits the project adapter.');
152
- }
153
- // Trailing slash so URL-joining treats it as a directory. Astro
154
- // derives build.client/build.server from outDir BEFORE hooks run,
155
- // so overriding outDir alone still writes into the primary dist/ —
156
- // all three must move together.
157
- // OUTSIDE dist/ on purpose, against the original design: the
158
- // artifact bakes the preview secret, so a wholesale static upload
159
- // of dist/ must never be able to publish it — and Astro clears
160
- // dist/ at the start of a build, which would wipe a sibling
161
- // artifact parked inside it.
162
- const previewOut = new URL(`${previewBuild.outDir ?? '.conloca/preview-server'}/`, config.root);
163
- // The site's extra config goes through its OWN updateConfig
164
- // call: Astro deep-merges successive calls (concatenating
165
- // vite.plugins and integrations), whereas spreading it into the
166
- // object below would shallow-replace whole keys — a user `vite`
167
- // entry silently dropped the required virtual-module plugin.
168
- // Ours comes second so the required scalars (output, outDir,
169
- // build dirs) always win; previewBuild.outDir is the supported
170
- // override for the artifact location.
171
- if (previewBuild.config) {
172
- updateConfig(previewBuild.config);
173
- }
174
- updateConfig({
175
- output: 'server',
176
- outDir: previewOut,
177
- build: { client: new URL('client/', previewOut), server: new URL('server/', previewOut) },
178
- vite: {
179
- // The middleware dynamically imports Cloudflare's runtime
180
- // module (binding transport). The Cloudflare adapter resolves
181
- // the scheme itself; every other adapter's Rollup pass fails
182
- // the child build on it unless externalized. Off Cloudflare
183
- // Workers the runtime import rejects and the middleware falls
184
- // back to the global fetch.
185
- build: { rollupOptions: { external: [/^cloudflare:/] } },
186
- // Starlight renders Steps, Tabs and FileTree with satteri's
187
- // htmlToHast. On Cloudflare Workers satteri resolves to a
188
- // binding that can be neither installed nor run on workerd, so the child
189
- // build fails to resolve it — swap in a stand-in there. The
190
- // target is an absolute path: a bare name would be looked up
191
- // from the Starlight file, which cannot see this package in an
192
- // isolated (non-hoisted) node_modules layout.
193
- ...(adapter.name === '@astrojs/cloudflare'
194
- ? {
195
- resolve: {
196
- alias: [
197
- {
198
- find: /^satteri$/,
199
- replacement: resolveSatteriStandIn(),
200
- },
201
- ],
202
- },
203
- }
204
- : {}),
205
- plugins: [
206
- {
207
- name: 'conloca-preview-opts',
208
- resolveId(id) {
209
- return id === VIRTUAL_PREVIEW_OPTS ? RESOLVED_PREVIEW_OPTS : undefined;
210
- },
211
- load(id) {
212
- if (id !== RESOLVED_PREVIEW_OPTS)
213
- return undefined;
214
- // Read lazily so the values assigned above are captured.
215
- return `export default ${JSON.stringify(previewOptsModule ?? {})};`;
216
- },
217
- },
218
- ],
219
- },
220
- // The adapter must ride in BOTH ways: as `adapter` because the
221
- // build gate checks `config.adapter` before creating the SSR
222
- // bundle, and as an integration because only the adapter's own
223
- // astro:config:done hook calls setAdapter — which is what the
224
- // build pipeline actually renders through. (Astro unshifts
225
- // config.adapter into the integration list BEFORE any hook runs,
226
- // so setting `adapter` alone here is too late for the hooks.)
227
- // A project that is already SSR keeps its own adapter untouched.
228
- ...(previewBuild.adapter ? { adapter: previewBuild.adapter, integrations: [previewBuild.adapter] } : {}),
229
- });
108
+ if (!repoUri) {
109
+ throw new Error(`${PACKAGE_NAME}: could not determine repository identity for the preview build ` +
110
+ '(build in a Git checkout or set repoUri as an advanced override)');
111
+ }
112
+ // The project's own checkout answers git, not the directory the
113
+ // build was started from.
114
+ const projectGit = (args) => gitOutput(args, fileURLToPath(config.root));
115
+ const buildRef = resolveBuildRef(process.env, projectGit);
116
+ if (!buildRef.branch) {
117
+ throw new Error(`${PACKAGE_NAME}: could not determine the branch the preview build serves (set CF_PAGES_BRANCH, ` +
118
+ 'WORKERS_CI_BRANCH, VERCEL_GIT_COMMIT_REF or GITHUB_REF_NAME, or build in a git checkout on a branch)');
119
+ }
120
+ const childMode = previewChildMode(process.env);
121
+ childServeMode = childMode;
122
+ keepPrerendered = previewChildPrerendered(process.env);
123
+ const siteId = resolveBuildSiteId({
124
+ contentRoot: process.env.CONLOCA_CONTENT_ROOT,
125
+ override: options.siteId,
126
+ });
127
+ injectRoute({
128
+ pattern: `${PREVIEW_ROUTE_SEGMENT}/[...path]`,
129
+ entrypoint: '@conloca/cloud-astro/preview-handler',
130
+ prerender: false,
131
+ });
132
+ // The route above is the ENTRY DOOR — the only URL the endpoint can
133
+ // link to before a cookie exists. This interceptor is the serving
134
+ // surface: once the init hop sets the `Path=/` cookie, the browser
135
+ // sends the credential on every same-origin request, so internal
136
+ // links keep rendering drafts instead of silently falling back to
137
+ // published content after one page view. Fail-open — an
138
+ // uncredentialed visitor gets the ordinary page.
139
+ addMiddleware({ entrypoint: '@conloca/cloud-astro/site-middleware', order: 'pre' });
140
+ // The commit this preview build's checkout holds: a PR build may
141
+ // check out a merge commit rather than the commit CI hands over.
142
+ // Page-status compares the branch's latest commit with it, so the
143
+ // endpoint diffs against the content actually serving, not a newer
144
+ // commit whose deploy never landed. A checkout commit the
145
+ // endpoint does not have makes it render from the branch instead.
146
+ const buildCommit = projectGit(['rev-parse', 'HEAD']) ?? buildRef.gitSha;
147
+ // Bake the middleware's configuration into the artifact. Every value
148
+ // is already known here — endpoint and audience are integration
149
+ // options; repository, site, branch, base and commit are what this
150
+ // build was made from, and every pass must match the first three —
151
+ // so a correctly built preview deployment needs NO env vars set on
152
+ // it. `saasIssuer` stays unbaked unless configured: it is a property
153
+ // of the endpoint, not of the site.
154
+ previewOptsModule = {
155
+ saasEndpoint: options.endpoint ?? DEFAULT_EDITOR_ENDPOINT,
156
+ // The token's `aud` is the repo URI this build resolved.
157
+ saasAudience: repoUri,
158
+ ...(options.saasIssuer ? { saasIssuer: options.saasIssuer } : {}),
159
+ ...(buildCommit ? { buildCommit } : {}),
160
+ repo: repoUri,
161
+ siteId,
162
+ branch: buildRef.branch,
163
+ base: config.base ?? '/',
164
+ mode: childMode,
165
+ };
166
+ // The dispatcher's exit route answers with these: the values every pass is checked against, already
167
+ // narrowed by the two throws above.
168
+ childExit = {
169
+ repo: repoUri,
170
+ siteId,
171
+ branch: buildRef.branch,
172
+ audience: repoUri,
173
+ ...(options.saasIssuer ? { issuer: options.saasIssuer } : {}),
174
+ };
175
+ // Preview-build path: the child build must emit an SSR
176
+ // artifact even when the primary build is fully static. Switch to
177
+ // server output, apply the preview adapter (the project's own
178
+ // adapter stays in force when it already has one), and write to a
179
+ // SEPARATE outDir so the child never clobbers the primary dist/.
180
+ const previewBuild = options.previewBuild || {};
181
+ // A site that names no adapter builds its preview server for Cloudflare Workers: next to it (D3) or apart (D4).
182
+ const adapter = previewBuild.adapter ??
183
+ config.adapter ??
184
+ (childMode === 'd2' ? undefined : await cloudflareAdapter(config.root, childMode));
185
+ // Throws for a refused adapter — the parent already checked, this keeps the child honest.
186
+ previewBuildMode(previewBuild, adapter?.name);
187
+ // Astro allows exactly one deployment integration. Adding
188
+ // previewBuild.adapter next to the project's own would make the
189
+ // child build die on Astro's adapter-conflict error, which names
190
+ // neither this integration nor the option — fail here with the
191
+ // actual cause. The child inherits the project adapter, so the
192
+ // option is unnecessary on SSR projects.
193
+ if (previewBuild.adapter && config.adapter) {
194
+ const projectAdapterName = config.adapter.name;
195
+ throw new Error(`${PACKAGE_NAME}: previewBuild.adapter conflicts with the project's own adapter ` +
196
+ `(${projectAdapterName}) — Astro allows only one deployment integration per build. ` +
197
+ 'Remove previewBuild.adapter; the preview build inherits the project adapter.');
198
+ }
199
+ // Trailing slash so URL-joining treats it as a directory. Astro
200
+ // derives build.client/build.server from outDir BEFORE hooks run,
201
+ // so overriding outDir alone still writes into the primary dist/ —
202
+ // all three must move together.
203
+ // OUTSIDE dist/ on purpose, against the original design: a
204
+ // wholesale static upload of dist/ must never publish the preview
205
+ // server — and Astro clears dist/ at the start of a build, which
206
+ // would wipe a sibling artifact parked inside it.
207
+ const previewOut = previewOutDir(previewBuild, config.root);
208
+ // The site's extra config goes through its OWN updateConfig
209
+ // call: Astro deep-merges successive calls (concatenating
210
+ // vite.plugins and integrations), whereas spreading it into the
211
+ // object below would shallow-replace whole keys — a user `vite`
212
+ // entry silently dropped the required virtual-module plugin.
213
+ // Ours comes second so the required scalars (output, outDir,
214
+ // build dirs) always win; previewBuild.outDir is the supported
215
+ // override for the artifact location.
216
+ if (previewBuild.config) {
217
+ updateConfig(previewBuild.config);
230
218
  }
219
+ updateConfig({
220
+ output: 'server',
221
+ outDir: previewOut,
222
+ build: { client: new URL('client/', previewOut), server: new URL('server/', previewOut) },
223
+ vite: {
224
+ // The middleware dynamically imports Cloudflare's runtime
225
+ // module (binding transport). The Cloudflare adapter resolves
226
+ // the scheme itself; every other adapter's Rollup pass fails
227
+ // the child build on it unless externalized. Off Cloudflare
228
+ // Workers the runtime import rejects and the middleware falls
229
+ // back to the global fetch.
230
+ build: { rollupOptions: { external: [/^cloudflare:/] } },
231
+ // Starlight renders Steps, Tabs and FileTree with satteri's
232
+ // htmlToHast. On Cloudflare Workers satteri resolves to a
233
+ // binding that can be neither installed nor run on workerd, so the child
234
+ // build fails to resolve it — swap in a stand-in there. The
235
+ // target is an absolute path: a bare name would be looked up
236
+ // from the Starlight file, which cannot see this package in an
237
+ // isolated (non-hoisted) node_modules layout.
238
+ ...(adapter?.name === '@astrojs/cloudflare'
239
+ ? {
240
+ resolve: {
241
+ alias: [
242
+ {
243
+ find: /^satteri$/,
244
+ replacement: resolveSatteriStandIn(),
245
+ },
246
+ ],
247
+ },
248
+ }
249
+ : {}),
250
+ plugins: [
251
+ {
252
+ name: 'conloca-preview-opts',
253
+ resolveId(id) {
254
+ return id === VIRTUAL_PREVIEW_OPTS ? RESOLVED_PREVIEW_OPTS : undefined;
255
+ },
256
+ load(id) {
257
+ if (id !== RESOLVED_PREVIEW_OPTS)
258
+ return undefined;
259
+ // Read lazily so the values assigned above are captured.
260
+ return `export default ${JSON.stringify(previewOptsModule ?? {})};`;
261
+ },
262
+ },
263
+ ],
264
+ },
265
+ // The adapter must ride in BOTH ways: as `adapter` because the
266
+ // build gate checks `config.adapter` before creating the SSR
267
+ // bundle, and as an integration because only the adapter's own
268
+ // astro:config:done hook calls setAdapter — which is what the
269
+ // build pipeline actually renders through. (Astro unshifts
270
+ // config.adapter into the integration list BEFORE any hook runs,
271
+ // so setting `adapter` alone here is too late for the hooks.)
272
+ // A project that is already SSR keeps its own adapter untouched.
273
+ // A static site's Cloudflare adapter rides in the same way.
274
+ ...(adapter !== undefined && adapter !== config.adapter ? { adapter, integrations: [adapter] } : {}),
275
+ });
231
276
  }
232
277
  },
233
278
  /**
@@ -249,22 +294,37 @@ export function conlocaCloud(options) {
249
294
  * record, runs AFTER the `export const prerender` source parse, and
250
295
  * Astro reads `prerender` back after every integration has run.
251
296
  *
252
- * Gated on the secret as well as the flag, mirroring the config hook: no
253
- * secret means no interceptor was mounted, so stripping the site's
254
- * static output would buy nothing.
297
+ * Gated on the flag, as the config hook is: only the preview build
298
+ * mounts the interceptor these routes must reach.
255
299
  */
256
300
  'astro:route:setup': ({ route, logger }) => {
257
301
  if (process.env[PREVIEW_BUILD_ENV_FLAG] !== '1')
258
302
  return;
259
- if (!process.env[PREVIEW_SECRET_ENV_FLAG])
303
+ const cms = route.component.endsWith('/internal/page-handler.astro');
304
+ const entry = /preview-handler(\.astro)?$/u.test(route.component);
305
+ // `route` (the pattern) and `type` exist at runtime but are absent from the public RouteOptions type.
306
+ const pattern = 'route' in route && typeof route.route === 'string' ? route.route : '';
307
+ // A D3 child keeps prerendered what its static site's build prerendered, endpoints included: on demand, a
308
+ // getStaticPaths route would lose its props, and the dispatcher would have to run on it in production. Its
309
+ // own on-demand routes (and every route of a D2 child) keep their own setting.
310
+ if (!cms && keepPrerendered.has(prerenderedKey(pattern, route.component))) {
311
+ route.prerender = true;
260
312
  return;
261
- // `type` exists at runtime but is absent from the public RouteOptions
262
- // type. Endpoints keep their prerendered data files: they emit no HTML
313
+ }
314
+ // Endpoints keep their prerendered data files: they emit no HTML
263
315
  // to intercept, and one built from getStaticPaths would break on demand.
264
316
  const routeType = route.type;
265
- if (routeType !== undefined && routeType !== 'page')
317
+ // A static site's separate preview deploy (D4) has no site build to ask, but every page of the site was
318
+ // prerendered: they stay so, or a getStaticPaths page would render on demand without its props.
319
+ if (projectStatic &&
320
+ childServeMode === 'd4' &&
321
+ !cms &&
322
+ !entry &&
323
+ (routeType === undefined || routeType === 'page')) {
324
+ route.prerender = true;
266
325
  return;
267
- if (route.prerender === false)
326
+ }
327
+ if (routeType !== undefined && routeType !== 'page')
268
328
  return;
269
329
  // ONLY the CMS page routes go on demand. Forcing every route stripped
270
330
  // the getStaticPaths path-space partitioning: two root catch-alls (the
@@ -274,115 +334,131 @@ export function conlocaCloud(options) {
274
334
  // keep their static output (served by the adapter before the app), and
275
335
  // App.match falls through a prerendered dynamic match to the first
276
336
  // on-demand route — exactly the CMS handler for CMS pathnames.
277
- if (!route.component.endsWith('/internal/page-handler.astro'))
337
+ if (!cms || route.prerender === false)
278
338
  return;
279
339
  route.prerender = false;
280
340
  logger.debug(`preview build: forcing on-demand rendering for ${route.component}`);
281
341
  },
282
- 'astro:config:done': ({ config }) => {
342
+ 'astro:routes:resolved': ({ routes }) => {
343
+ if (process.env[PREVIEW_BUILD_ENV_FLAG] !== '1') {
344
+ sitePrerendered = routes
345
+ .filter((route) => route.isPrerendered)
346
+ .map((route) => prerenderedKey(route.pattern, route.entrypoint));
347
+ return;
348
+ }
349
+ // Astro injects the server-islands route whenever an adapter is set, but refuses islands without one: a static
350
+ // site uses none, so its dispatcher must not run on that route.
351
+ const used = projectStatic ? routes.filter((route) => route.pattern !== '/_server-islands/[name]') : routes;
352
+ onDemand = onDemandPatterns(used);
353
+ },
354
+ 'astro:config:done': ({ config, logger }) => {
283
355
  adapterName = config.adapter?.name;
284
356
  viteConfig = config.vite;
357
+ astroBase = config.base ?? '/';
358
+ srcDir = config.srcDir;
359
+ serverOutput = config.output === 'server';
360
+ i18n = config.i18n;
361
+ inherited = resolveInheritedOptions(options, readEditorDescriptors());
362
+ // A refused or missing preview adapter fails `astro build` here,
363
+ // before the site builds, rather than after it. `astro dev`, `sync`
364
+ // and `preview` never start the preview build, so they are left
365
+ // alone. The child build checks its own.
366
+ if (astroCommand === 'build' && process.env[PREVIEW_BUILD_ENV_FLAG] !== '1') {
367
+ const mode = previewMode();
368
+ // D3 builds its preview server with @astrojs/cloudflare: missing, the build fails here, before the site builds.
369
+ if (mode === 'd3' && projectRoot !== undefined)
370
+ resolveCloudflareAdapter(fileURLToPath(projectRoot));
371
+ if (mode === 'd2' && adapterName === undefined) {
372
+ logger.warn('previewBuild.adapter on a static site serves drafts from the deployed preview server; remove ' +
373
+ 'previewBuild.adapter to serve them next to the static site on Cloudflare Workers instead');
374
+ }
375
+ }
285
376
  },
286
- 'astro:build:done': async ({ dir, logger }) => {
377
+ 'astro:build:done': async ({ dir, logger, pages }) => {
287
378
  if (process.env[PREVIEW_BUILD_ENV_FLAG] === '1') {
288
- // The recursive preview build sets this flag on the child
289
- // Astro process. Re-entering registration there would create an
290
- // infinite build loop, so we short-circuit.
291
- logger.info('skipping registration: recursive preview build detected');
379
+ // The recursive preview build sets this flag on the child Astro process. Writing the editor page there
380
+ // again would race the parent, which writes its own; the child reports only what the parent reads.
381
+ logger.info('skipping the editor page: recursive preview build detected');
382
+ if (previewChildMode(process.env) === 'd4') {
383
+ await emitPreviewServerInfo(fileURLToPath(dir), {
384
+ root: fileURLToPath(projectRoot ?? dir),
385
+ repoUri,
386
+ siteIdOverride: options.siteId,
387
+ logger,
388
+ });
389
+ return;
390
+ }
391
+ if (projectRoot === undefined)
392
+ return;
393
+ // config:setup records the exit values in the child (below), or throws before the build starts.
394
+ const exit = childExit;
395
+ if (exit === undefined)
396
+ throw new Error(`${PACKAGE_NAME}: the preview build recorded no exit values`);
397
+ const root = astroBase.replace(/\/+$/u, '');
398
+ await writePreviewRoutes(fileURLToPath(previewOutDir(options.previewBuild, projectRoot)), {
399
+ prerendered: (pages ?? []).map(({ pathname }) => normalizeTrailingSlash(`${root}/${pathname}`)),
400
+ onDemand: onDemand.map((pattern) => workerFirstPattern(pattern, astroBase)),
401
+ exit,
402
+ });
292
403
  return;
293
404
  }
294
405
  // Astro always runs the config hooks first. No fallback: compiling
295
406
  // against the working directory would build the canvas stylesheet for
296
407
  // the wrong project without a word.
297
- if (projectRoot === undefined || viteConfig === undefined) {
408
+ if (projectRoot === undefined || viteConfig === undefined || inherited === undefined) {
298
409
  throw new Error(`${PACKAGE_NAME}: astro:build:done ran before the config hooks recorded the project root and Vite config`);
299
410
  }
300
- // Editor descriptors (the bundle's third leg): the host's schemas
301
- // module and the auto-discovered MDX registry, both resolved by
302
- // conlocaCMS and read off its channel. The scan runs here because the
303
- // editor at the endpoint has no dev server to serve `/api/registry` from.
304
- const descriptors = await resolveEditorDescriptors(logger);
305
- const bundle = await bundleEditorAssets({
411
+ const mode = previewMode();
412
+ // The editor page: every build writes it.
413
+ await emitEditorPage({
306
414
  dir: fileURLToPath(dir),
307
415
  root: fileURLToPath(projectRoot),
416
+ base: astroBase,
308
417
  vite: viteConfig,
309
- puckConfigPath: options.puckConfigPath,
310
- siteStyles: options.siteStyles,
311
- ...(options.editorBundlePlugins ? { plugins: options.editorBundlePlugins } : {}),
312
- publicBaseUrl: resolveDeploymentUrl(options),
313
- ...(descriptors === undefined ? {} : { descriptors }),
418
+ endpoint: options.endpoint,
419
+ inherited,
420
+ repoUri,
421
+ siteIdOverride: options.siteId,
422
+ previewMode: mode,
423
+ pagesDir: fileURLToPath(new URL('pages/', srcDir ?? new URL('src/', projectRoot))),
424
+ serverOutput,
425
+ i18n,
314
426
  logger,
315
427
  });
316
- // The component vocabulary for agents, read from the config the bundle
317
- // just compiled. Only a build conlocaCMS is part of carries one (its
318
- // descriptor channel is how this add-on knows): without the CMS there
319
- // are no pages for an agent to compose. Gated on the channel itself,
320
- // not on `descriptors` — that is also undefined for a CMS build with
321
- // no schemas module, MDX components or templates, which still has a
322
- // Puck vocabulary. An unreadable channel already warned above.
323
- const componentManifest = readEditorDescriptors(process.env) === undefined
324
- ? undefined
325
- : await emitComponentManifest({
326
- dir: fileURLToPath(dir),
327
- puckConfigPath: options.puckConfigPath,
328
- projectRoot: process.cwd(),
329
- logger,
330
- });
331
- // Build-time style discovery: read the discovery
332
- // route's rendered page, collect its CSS, run the shared wrapper
333
- // heuristic; results ride registration below. Opt-in via the option —
334
- // and fail-soft throughout: a build must never die over preview
335
- // styling.
336
- let discovery;
337
- let routeCssArtifact;
338
- if (options.fragmentPreviewRoute) {
339
- const clientDir = fileURLToPath(dir);
340
- const nodeEntry = fileURLToPath(new URL('../server/entry.mjs', dir));
341
- discovery = await discoverStyleContext({
342
- clientDir,
343
- serverEntry: adapterName === '@astrojs/node' && existsSync(nodeEntry) ? nodeEntry : undefined,
344
- route: options.fragmentPreviewRoute,
345
- logger,
346
- });
347
- if (discovery?.routeCss) {
348
- routeCssArtifact = await emitRouteCssArtifact(clientDir, discovery.routeCss, resolveDeploymentUrl(options), logger);
349
- }
350
- }
351
- const registration = await registerBuild(options, repoUri, bundle, logger, {
352
- hostWrappers: discovery?.hostWrappers,
353
- routeCssArtifact: routeCssArtifact?.stylesheet,
354
- componentManifest,
355
- });
356
- let registeredSecret;
357
- if ('missing' in registration)
358
- reportSkippedRegistration(registration.missing, options, logger);
359
- else
360
- registeredSecret = registration.previewSecret;
361
- if (options.previewBuild === false) {
362
- // The site explicitly opted out of the recursive preview build.
428
+ // Strict opt-in: only a previewBuild given as an object starts the second build. D4 builds it elsewhere.
429
+ const previewBuild = options.previewBuild || undefined;
430
+ if (previewBuild === undefined || mode === 'off' || mode === 'd4')
363
431
  return;
364
- }
365
- // Prefer the secret returned by registration; the env override lets
366
- // CI smoke-test the recursive build path without a reachable endpoint.
367
- const previewSecret = registeredSecret ?? process.env[PREVIEW_SECRET_ENV_FLAG];
368
- if (!previewSecret) {
432
+ const previewOut = previewOutDir(previewBuild, projectRoot);
433
+ if (mode === 'd2') {
434
+ await spawnPreviewBuild(previewBuild, 'd2');
435
+ // The child build cannot write the editor files itself (it
436
+ // short-circuits this hook — see the recursion guard above), but in
437
+ // a deployment that serves the site and the preview from one
438
+ // Cloudflare Worker its client dir is THE asset set serving the site,
439
+ // so the editor files must be there too. Mirror them from this build's dist.
440
+ await mirrorEditorPage(fileURLToPath(dir), fileURLToPath(new URL('client/', previewOut)));
441
+ logger.info('editor page mirrored into the preview client dir');
369
442
  return;
370
443
  }
371
- await spawnPreviewBuild(previewSecret, options.previewBuild ?? {});
372
- // The child build cannot compile the editor bundle itself (it
373
- // short-circuits this hook — see the recursion guard above), but in
374
- // a deployment that serves the site and the preview from one
375
- // Cloudflare Worker its client dir is THE asset set serving the site,
376
- // so the editor at the endpoint loads `/_conloca/*` from it. Mirror
377
- // the bundle + its CORS rule from this build's dist into it.
378
- // previewBuild === false already returned above, so only the options
379
- // object (or undefined) reaches this point.
380
- const previewOut = new URL(`${options.previewBuild?.outDir ?? '.conloca/preview-server'}/`, projectRoot);
381
- await mirrorEditorAssets(fileURLToPath(dir), fileURLToPath(new URL('client/', previewOut)), [
382
- ...bundle.assetCorsPaths,
383
- ...(routeCssArtifact?.assetCorsPaths ?? []),
384
- ]);
385
- logger.info('editor assets mirrored into the preview client dir');
444
+ // D3: a failed preview build is isolated unless its server also serves the live site (finishD3Build decides).
445
+ let built = true;
446
+ try {
447
+ await spawnPreviewBuild({ ...previewBuild, required: true }, 'd3', sitePrerendered);
448
+ }
449
+ catch (error) {
450
+ built = false;
451
+ logger.warn(`the preview build failed: ${messageOf(error)}`);
452
+ }
453
+ await finishD3Build({
454
+ root: fileURLToPath(projectRoot),
455
+ dist: fileURLToPath(dir),
456
+ previewOut: fileURLToPath(previewOut),
457
+ base: astroBase,
458
+ endpoint: options.endpoint ?? DEFAULT_EDITOR_ENDPOINT,
459
+ built,
460
+ logger,
461
+ });
386
462
  },
387
463
  },
388
464
  };
@@ -397,142 +473,24 @@ function resolveSatteriStandIn() {
397
473
  'Cloudflare preview build uses in place of satteri — is the package installed and built?', { cause });
398
474
  }
399
475
  }
400
- /**
401
- * The origin the deployed site answers on. Used for two things that must agree:
402
- * absolutizing the bundle/stylesheet URLs a registration carries, and re-pointing the
403
- * stylesheet's own asset URLs at the site (they would otherwise resolve
404
- * against the editor's origin — see `rewriteStylesheetAssetUrls`).
405
- */
406
- function resolveDeploymentUrl(options) {
407
- if (!options.previewDomain) {
408
- return options.publicBaseUrl ?? process.env.CF_PAGES_URL;
409
- }
410
- const previewUrl = new URL(options.previewDomain.includes('://') ? options.previewDomain : `https://${options.previewDomain}`);
411
- return previewUrl.origin;
412
- }
413
- /**
414
- * ONE end-of-build block for a skipped registration — every prerequisite that
415
- * was missing and what it costs — the last thing the integration prints.
416
- * With `requireRegistration` it fails the build instead.
417
- */
418
- function reportSkippedRegistration(missing, options, logger) {
419
- const summary = [
420
- `editor at ${options.endpoint} NOT updated by this build`,
421
- ...missing.map((prerequisite) => ` missing: ${prerequisite}`),
422
- " consequence: registration was skipped, so the editor keeps serving the previous build of this branch (or the default branch's, or nothing, if neither was ever registered)",
423
- ' check: conloca doctor --live',
424
- ].join('\n');
425
- if (options.requireRegistration) {
426
- throw new Error(`${PACKAGE_NAME}: ${summary}\n requireRegistration is on, so this build fails.`);
427
- }
428
- logger.warn(summary);
429
- }
430
- /**
431
- * Registers the freshly built editor bundle at the endpoint. Soft-skip ONLY
432
- * when registration was never attempted: the pre-request guards (no build
433
- * token, no repo identity, no sha/branch, no base URL) each warn, and every
434
- * missing prerequisite is returned at once, so one build names all that setup
435
- * still lacks and an unregistered deploy still completes — the hook turns
436
- * that into one end-of-build summary (or a failure under
437
- * `requireRegistration`). Once a registration IS attempted, its failure
438
- * FAILS THE BUILD: postRegistration throws on any
439
- * deterministic 4xx and after exhausting the ≥500 retry backoff, and that
440
- * error — carrying the HTTP status and response body — propagates. A green
441
- * deploy whose registration silently went missing is the "deployed but
442
- * editor unregistered" class this project exists to kill.
443
- */
444
- async function registerBuild(options, repoUri, bundle, logger, discovery = {}) {
445
- const missing = [];
446
- const buildToken = options.buildToken ?? process.env[BUILD_TOKEN_ENV_VAR];
447
- if (!buildToken) {
448
- logger.warn(`skipping registration: no build token (set buildToken or ${BUILD_TOKEN_ENV_VAR})`);
449
- missing.push(`build token (set buildToken or ${BUILD_TOKEN_ENV_VAR})`);
450
- }
451
- if (!repoUri) {
452
- logger.warn('skipping registration: could not determine repository identity ' +
453
- '(build in a supported CI environment or Git checkout, or set repoUri)');
454
- missing.push('repository identity (build in a supported CI environment or Git checkout, or set repoUri)');
455
- }
456
- const { branch } = resolveBuildRef();
457
- // CI may hand over the branch's latest commit to register; the checkout is what was built.
458
- const commits = registrationCommits({
459
- eventCommitSha: process.env.CF_PAGES_COMMIT_SHA,
460
- checkoutCommitSha: gitOutput(['rev-parse', 'HEAD']),
461
- });
462
- const gitSha = commits.gitSha;
463
- if (!gitSha || !branch) {
464
- logger.warn('skipping registration: could not resolve the git sha/branch ' +
465
- '(set CF_PAGES_COMMIT_SHA and CF_PAGES_BRANCH, or build inside a git checkout)');
466
- missing.push('git sha/branch (set CF_PAGES_COMMIT_SHA and CF_PAGES_BRANCH, or build inside a git checkout)');
467
- }
468
- const deploymentUrl = resolveDeploymentUrl(options);
469
- const baseUrl = deploymentUrl;
470
- if (!baseUrl) {
471
- logger.warn('skipping registration: no public base URL for the editor bundle (set previewDomain, publicBaseUrl, or CF_PAGES_URL)');
472
- missing.push('public base URL for the editor bundle (set previewDomain, publicBaseUrl, or CF_PAGES_URL)');
473
- }
474
- // Restates the guards above, so the values below are typed as set.
475
- if (!buildToken || !repoUri || !gitSha || !branch || !baseUrl)
476
- return { missing };
477
- // Resolve the deployable-site id (STRICT): a throw here FAILS THE BUILD —
478
- // after the soft skip guards above, so only a build that is actually
479
- // registering can die on it. A silently mis-attached registration points
480
- // the editor at the wrong site, which is the same miss as never having
481
- // registered at all. The channel is CONLOCA_CONTENT_ROOT (published by
482
- // conlocaCMS); options.siteId is the CMS-less-build override.
483
- const siteId = resolveBuildSiteId({
484
- contentRoot: process.env.CONLOCA_CONTENT_ROOT,
485
- override: options.siteId,
486
- });
487
- // NO catch: from here on the registration is ATTEMPTED, and an attempted
488
- // registration's failure fails the build. postRegistration already retried
489
- // transient (≥500 / network) failures with backoff; what escapes is either
490
- // a deterministic 4xx (unknown siteId, bad token — fix and rebuild) or an
491
- // exhausted retry budget, and the error message carries the HTTP status +
492
- // response body verbatim.
493
- logger.info('registering at the endpoint (transient failures retry, with up to ~2.5 minutes of waiting between attempts)');
494
- const { previewSecret } = await postRegistration({
495
- endpoint: options.endpoint,
496
- buildToken,
497
- repoUri,
498
- gitSha,
499
- siteId,
500
- branch,
501
- editorBundleUrl: new URL(bundle.url, baseUrl).toString(),
502
- bundleHash: bundle.hash,
503
- ...(bundle.stylesheet === undefined
504
- ? {}
505
- : {
506
- stylesheetUrl: new URL(bundle.stylesheet.url, baseUrl).toString(),
507
- stylesheetHash: bundle.stylesheet.hash,
508
- }),
509
- ...(discovery.hostWrappers === undefined ? {} : { hostWrappers: discovery.hostWrappers }),
510
- ...(discovery.routeCssArtifact === undefined
511
- ? {}
512
- : {
513
- routeCssUrl: new URL(discovery.routeCssArtifact.url, baseUrl).toString(),
514
- routeCssHash: discovery.routeCssArtifact.hash,
515
- }),
516
- ...(discovery.componentManifest === undefined
517
- ? {}
518
- : {
519
- componentManifestUrl: new URL(discovery.componentManifest.url, baseUrl).toString(),
520
- componentManifestHash: discovery.componentManifest.hash,
521
- }),
522
- deploymentUrl,
523
- buildId: commits.buildId,
524
- clientVersion: packageVersion(),
525
- });
526
- logger.info(`registration complete (gitSha=${gitSha}, branch=${branch}, buildId=${commits.buildId})`);
527
- return { previewSecret };
528
- }
476
+ /** The options the editor page made obsolete; naming one fails the build so the config gets updated. */
477
+ const REMOVED_OPTIONS = [
478
+ 'buildToken',
479
+ 'requireRegistration',
480
+ 'publicBaseUrl',
481
+ 'previewDomain',
482
+ 'editorBundlePlugins',
483
+ 'fragmentPreviewRoute',
484
+ ];
485
+ /** Refuses a removed option, a malformed endpoint, or one that is not an `app.` address, at config load. */
529
486
  function validateOptions(options) {
530
- if (!options.endpoint) {
531
- throw new Error(`${PACKAGE_NAME}: endpoint is required`);
532
- }
533
- if (!options.puckConfigPath) {
534
- throw new Error(`${PACKAGE_NAME}: puckConfigPath is required`);
487
+ for (const name of REMOVED_OPTIONS) {
488
+ if (name in options) {
489
+ throw new Error(`${PACKAGE_NAME}: option "${name}" was removed — run \`npx @conloca/cli connect\` to update this config`);
490
+ }
535
491
  }
492
+ if (options.endpoint === undefined)
493
+ return;
536
494
  try {
537
495
  // Throws on malformed URLs; we don't keep the parsed value.
538
496
  new URL(options.endpoint);
@@ -540,5 +498,8 @@ function validateOptions(options) {
540
498
  catch {
541
499
  throw new Error(`${PACKAGE_NAME}: endpoint must be a valid URL, got ${options.endpoint}`);
542
500
  }
501
+ if (editorUiOrigin(options.endpoint) === null) {
502
+ throw new Error(`${PACKAGE_NAME}: endpoint must be the workspace editor's app. address (for example https://app.conloca.com), got ${options.endpoint}`);
503
+ }
543
504
  }
544
505
  //# sourceMappingURL=integration.js.map