@conloca/cloud-astro 0.0.0-bootstrap.0 → 0.2.1

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