@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
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Strips the `[object process]` masquerade from workerd's nodejs_compat
3
+ * `process` shim.
4
+ *
5
+ * Astro picks its response-body strategy with
6
+ * `Object.prototype.toString.call(process) === '[object process]'`
7
+ * (astro/dist/runtime/server/render/util.js). Under nodejs_compat at some
8
+ * compatibility dates (observed broken at 2026-01-01, fixed by 2026-03-15)
9
+ * workerd tags its emulated process exactly like Node's, so Astro takes the
10
+ * Node branch and returns a bare async-iterable as the body — which the
11
+ * Cloudflare Workers `Response` cannot consume and coerces to the literal string
12
+ * "[object Object]" for every on-demand page.
13
+ *
14
+ * The Node branch is ALWAYS wrong on workerd, so the shim removes the tag —
15
+ * on workerd only (identified by its fixed `navigator.userAgent`), before any
16
+ * render runs. On real Node the tag is native and stays.
17
+ */
18
+ export function untagWorkerdProcess(
19
+ proc: unknown = (globalThis as { process?: unknown }).process,
20
+ userAgent: string | undefined = (globalThis as { navigator?: { userAgent?: string } }).navigator?.userAgent,
21
+ ): boolean {
22
+ if (userAgent !== 'Cloudflare-Workers') return false;
23
+ if (typeof proc !== 'object' || proc === null) return false;
24
+ if (Object.prototype.toString.call(proc) !== '[object process]') return false;
25
+ try {
26
+ delete (proc as Record<PropertyKey, unknown>)[Symbol.toStringTag];
27
+ } catch {
28
+ return false;
29
+ }
30
+ return Object.prototype.toString.call(proc) !== '[object process]';
31
+ }
@@ -0,0 +1,147 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { existsSync } from 'node:fs';
3
+ import { join } from 'node:path';
4
+ import { PACKAGE_NAME, PREVIEW_BUILD_ENV_FLAG, PREVIEW_SECRET_ENV_FLAG } from './constants.js';
5
+ import type { PreviewBuildOptions } from './types.js';
6
+
7
+ export { PREVIEW_SECRET_ENV_FLAG };
8
+
9
+ /**
10
+ * The minimal child-process surface this module relies on. Letting
11
+ * {@link _spawnPreviewBuildWith} accept any function that produces a process
12
+ * with an `on('exit', ...)` listener keeps the test seam narrow — tests can
13
+ * pass a tiny fake without reconstructing the full `ChildProcess` shape, and
14
+ * the implementation stays decoupled from internals it doesn't use.
15
+ */
16
+ export interface PreviewBuildChildProcess {
17
+ on(event: 'exit', listener: (code: number | null) => void): unknown;
18
+ }
19
+
20
+ export type PreviewBuildSpawn = (
21
+ command: string,
22
+ args: readonly string[],
23
+ options: { env: NodeJS.ProcessEnv; stdio: 'inherit' },
24
+ ) => PreviewBuildChildProcess;
25
+
26
+ /**
27
+ * Pure constructor for the child-process environment passed to the recursive
28
+ * preview build. Extracted so tests can verify the contract (env flag + secret
29
+ * + parent-env inheritance) without spinning up a child process — and so the
30
+ * real-process smoke test can call it the same way the integration does.
31
+ *
32
+ * Inherits the parent environment so PATH, credentials, and any host-specific
33
+ * build vars (CF_PAGES_*, GITHUB_*) reach the child.
34
+ */
35
+ export function buildPreviewChildEnv(parentEnv: NodeJS.ProcessEnv, previewSecret: string): NodeJS.ProcessEnv {
36
+ return {
37
+ ...parentEnv,
38
+ [PREVIEW_BUILD_ENV_FLAG]: '1',
39
+ [PREVIEW_SECRET_ENV_FLAG]: previewSecret,
40
+ };
41
+ }
42
+
43
+ /**
44
+ * Locate the `astro` CLI binary in the site's `node_modules/.bin/`. We
45
+ * resolve relative to the current working directory (where `astro build` is
46
+ * being invoked) rather than to this package's install location, because
47
+ * `@conloca/cloud-astro` lists `astro` only as a peerDependency and would
48
+ * therefore not have it in its own node_modules.
49
+ *
50
+ * Bare `bun x astro build` would be the obvious one-liner, but `bunx`/`bun x`
51
+ * auto-fetch a package when it is missing, which a build must never do — so
52
+ * resolve the installed binary and spawn it directly.
53
+ */
54
+ export function resolveAstroBin(cwd: string = process.cwd()): string {
55
+ const candidates = [
56
+ join(cwd, 'node_modules', '.bin', 'astro'),
57
+ join(cwd, '..', 'node_modules', '.bin', 'astro'),
58
+ join(cwd, '..', '..', 'node_modules', '.bin', 'astro'),
59
+ ];
60
+ const found = candidates.find((p) => existsSync(p));
61
+ if (!found) {
62
+ throw new Error(
63
+ `${PACKAGE_NAME}: cannot locate the astro binary. Looked in: ${candidates.join(', ')}. ` +
64
+ 'Is astro installed as a dependency?',
65
+ );
66
+ }
67
+ return found;
68
+ }
69
+
70
+ /**
71
+ * Spawns the recursive preview `astro build` from the primary build's
72
+ * `astro:build:done` hook.
73
+ *
74
+ * The child process inherits the parent environment and additionally receives:
75
+ * - {@link PREVIEW_BUILD_ENV_FLAG} set to `'1'` so the integration's own
76
+ * `astro:build:done` short-circuits inside the child (recursion guard
77
+ * contract).
78
+ * - {@link PREVIEW_SECRET_ENV_FLAG} set to the per-branch secret so the
79
+ * child's `astro:config:setup` can inject the literal secret-scoped
80
+ * preview route (`/conloca_preview_${SECRET}/[...path]`).
81
+ *
82
+ * If this function is itself called from within a recursive build (i.e. the
83
+ * env flag is already set to `'1'`), it returns immediately without spawning,
84
+ * which is the outermost layer of the recursion guard.
85
+ *
86
+ * On a non-zero child exit, behaviour depends on {@link PreviewBuildOptions.required}:
87
+ * - `true` (default) → rejects with an error naming the exit code.
88
+ * - `false` → resolves and logs a warning so onboarding setups can continue
89
+ * when the preview build is not yet wired correctly.
90
+ */
91
+ export async function spawnPreviewBuild(previewSecret: string, opts: PreviewBuildOptions): Promise<void> {
92
+ await _spawnPreviewBuildWith(spawn, previewSecret, opts);
93
+ }
94
+
95
+ /**
96
+ * Internal seam that takes the spawn function as a parameter so tests can
97
+ * substitute a fake. Public callers should use {@link spawnPreviewBuild}.
98
+ *
99
+ * Exported with a leading underscore to signal that this is an internal API
100
+ * and not part of the package's public surface; it is not re-exported from
101
+ * `src/index.ts` or `src/node.ts`.
102
+ */
103
+ export async function _spawnPreviewBuildWith(
104
+ spawnFn: PreviewBuildSpawn,
105
+ previewSecret: string,
106
+ opts: PreviewBuildOptions,
107
+ ): Promise<void> {
108
+ // Recursion guard: bail out before doing any work if we're already inside
109
+ // a recursive preview build. This matches the short-circuit in the
110
+ // integration's `astro:build:done` hook.
111
+ if (process.env[PREVIEW_BUILD_ENV_FLAG] === '1') {
112
+ return;
113
+ }
114
+
115
+ if (!previewSecret) {
116
+ throw new Error(`${PACKAGE_NAME}: preview secret is required to spawn the preview build`);
117
+ }
118
+
119
+ const required = opts.required ?? true;
120
+
121
+ const astroBin = resolveAstroBin();
122
+ const child = spawnFn(astroBin, ['build'], {
123
+ env: buildPreviewChildEnv(process.env, previewSecret),
124
+ stdio: 'inherit',
125
+ });
126
+
127
+ await new Promise<void>((resolve, reject) => {
128
+ child.on('exit', (code: number | null) => {
129
+ if (code === 0) {
130
+ resolve();
131
+ return;
132
+ }
133
+ const reason = code === null ? 'signal' : `exit ${code}`;
134
+ if (required) {
135
+ reject(new Error(`${PACKAGE_NAME}: preview build failed (${reason})`));
136
+ return;
137
+ }
138
+ // Soft-fail path — opt-in via `previewBuild.required = false`. Use
139
+ // console.warn rather than the Astro logger because the spawn helper is
140
+ // pure: the integration's `astro:build:done` may evolve to pass a
141
+ // logger down, but until it does, warn keeps the signal
142
+ // visible without leaking a logger dependency into the spawn module.
143
+ console.warn(`${PACKAGE_NAME}: preview build failed (${reason}); previewBuild.required=false, continuing`);
144
+ resolve();
145
+ });
146
+ });
147
+ }
@@ -0,0 +1,55 @@
1
+ ---
2
+ import bakedPreviewOpts from 'virtual:conloca-preview-opts';
3
+ import { resolveEndpointFetch, resolveFromBaked } from './preview/_resolve-opts.js';
4
+ import { stripPreviewPrefix } from './preview/preview-path.js';
5
+ /**
6
+ * Secret-prefixed entry route injected by the recursive preview build at
7
+ * `/conloca_preview_${SECRET}/[...path]`. The secret in the path is a
8
+ * load guard — JWT validation is the actual auth boundary.
9
+ *
10
+ * This route is the ENTRY DOOR only; the site-wide middleware
11
+ * (`./site-middleware.ts`) is the serving surface. Three verdicts:
12
+ *
13
+ * 1. `response` — the query-token init hop (302 that sets the preview
14
+ * cookie and points at the clean path) or the no-preview landing page.
15
+ * 2. `preview` — a valid cookie on the literal prefixed URL: canonicalize
16
+ * with a 302 to the clean path. Rendering under the prefix is never
17
+ * correct (links/assets assume clean paths), and after the redirect the
18
+ * middleware serves the draft. Normally the middleware canonicalizes
19
+ * before this route runs — this branch is the defense-in-depth for an
20
+ * inert (unconfigured) middleware.
21
+ * 3. `pass-through` — only reachable through the request-runtime wrapper;
22
+ * here it means the preview route was hit without any preview marker,
23
+ * so 404 is the safe answer.
24
+ */
25
+ import { handlePreviewRequest } from './preview.js';
26
+
27
+ // Same baked-then-env resolution the middleware uses, so the entry route and
28
+ // the serving surface can never disagree about the secret. Throws loudly on a
29
+ // missing var: reaching this route means someone explicitly asked to preview.
30
+ const opts = resolveFromBaked(bakedPreviewOpts, (name) => process.env[name]);
31
+ const verdict = await handlePreviewRequest(Astro.request, {
32
+ ...opts,
33
+ fetchFn: await resolveEndpointFetch(),
34
+ });
35
+
36
+ if (verdict.kind === 'response') {
37
+ // Bound instead of returned directly: TypeScript skips the expression of a
38
+ // `return` outside a function body, so every response this file produces
39
+ // names its type to get checked.
40
+ const response: Response = verdict.response;
41
+ return response;
42
+ }
43
+ if (verdict.kind === 'pass-through') {
44
+ const notPreview: Response = new Response('not a preview request', { status: 404 });
45
+ return notPreview;
46
+ }
47
+
48
+ // verdict.kind === 'preview' — canonicalize to the clean site path.
49
+ const cleanPath = stripPreviewPrefix(Astro.originPathname ?? Astro.url.pathname);
50
+ const canonical: Response = new Response(null, {
51
+ status: 302,
52
+ headers: { location: cleanPath, 'cache-control': 'private, no-store' },
53
+ });
54
+ return canonical;
55
+ ---
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Types for the `./preview-handler` export, the `.astro` route the preview build injects. Astro compiles and renders
3
+ * it and nothing imports it, so this declares only the default export every Astro component has.
4
+ */
5
+ declare const PreviewHandler: (props: Record<string, unknown>) => unknown;
6
+ export default PreviewHandler;
package/src/preview.ts ADDED
@@ -0,0 +1,22 @@
1
+ // Public `./preview` subpath for `@conloca/cloud-astro`.
2
+ //
3
+ // Re-exports the preview-middleware + preview-reader surface that the SSR
4
+ // catch-all handler (and any site-supplied request-runtime wrapper)
5
+ // consumes. Keeping the implementation behind a `./preview/*` directory lets
6
+ // the public subpath stay stable while the internals evolve.
7
+
8
+ export { getBannerScriptText, injectPreviewBanner } from './preview/banner.js';
9
+ export {
10
+ embeddedKey,
11
+ PreviewContentAPI,
12
+ type PreviewContentAPIOptions,
13
+ } from './preview/content-api.js';
14
+ export { applyPreviewHeaders } from './preview/headers.js';
15
+ export { renderNoPreviewLanding } from './preview/landing.js';
16
+ export {
17
+ handlePreviewRequest,
18
+ type PreviewContext,
19
+ type PreviewMiddlewareOptions,
20
+ type PreviewVerdict,
21
+ previewParamName,
22
+ } from './preview/middleware.js';
@@ -0,0 +1,180 @@
1
+ import { PACKAGE_NAME } from './constants.js';
2
+
3
+ /**
4
+ * Registration request (`POST {endpoint}/api/v1/registrations`). Auth is the
5
+ * build token (`cbt_<id>.<secret>`) the endpoint issued; the body carries build
6
+ * metadata only.
7
+ */
8
+ export interface RegistrationInput {
9
+ /** Editor endpoint, e.g. 'https://cms.example.com'. */
10
+ endpoint: string;
11
+ /** Build token sent as `Authorization: Bearer <token>`. */
12
+ buildToken: string;
13
+ /** Auto-detected `owner/repo` identity of the build checkout. */
14
+ repoUri: string;
15
+ gitSha: string;
16
+ branch: string;
17
+ /** Deployable-site id (top-level siteId in the content root's
18
+ * sites.json, or the implicit 'default' for a zero-config repo). Resolved at
19
+ * build via resolveBuildSiteId — registration attaches, never defines. */
20
+ siteId: string;
21
+ /** Absolute URL the editor fetches the bundle from. */
22
+ editorBundleUrl: string;
23
+ /** Full sha-256 hex of the bundle bytes; the editor refuses non-matching bytes. */
24
+ bundleHash: string;
25
+ /** Absolute URL of the companion canvas stylesheet; absent when the config graph has no styles. */
26
+ stylesheetUrl?: string;
27
+ /** Full sha-256 hex of the stylesheet bytes; the editor skips non-matching bytes (fail-soft). */
28
+ stylesheetHash?: string;
29
+ /**
30
+ * Discovered content-wrapper shape of the fragmentPreviewRoute — inline
31
+ * because it is well under 1 KB; a URL+hash would add a
32
+ * fetch and a verification for nothing.
33
+ */
34
+ hostWrappers?: { content: { tagName: string; className: string } | null; codeBlock: unknown };
35
+ /** Absolute URL of the discovery route's collected CSS; same artifact pattern as stylesheetUrl. */
36
+ routeCssUrl?: string;
37
+ /** Full sha-256 hex of the route-CSS bytes; the editor skips non-matching bytes (fail-soft). */
38
+ routeCssHash?: string;
39
+ /** Absolute URL of the build's component manifest; same artifact pattern as stylesheetUrl. */
40
+ componentManifestUrl?: string;
41
+ /** Full sha-256 hex of the manifest bytes; a reader refuses non-matching bytes. */
42
+ componentManifestHash?: string;
43
+ deploymentUrl?: string;
44
+ deploymentProvider?: string;
45
+ /**
46
+ * The commit the artifact was actually built from; differs from gitSha only when CI hands over the branch's
47
+ * latest commit.
48
+ */
49
+ buildId?: string;
50
+ /**
51
+ * The `@conloca/cloud-astro` version that produced this build, so the endpoint and the doctor can say which
52
+ * package version built the editor bundle.
53
+ */
54
+ clientVersion?: string;
55
+ }
56
+
57
+ export interface RegistrationResult {
58
+ /** Per-branch preview secret consumed by the recursive preview build. */
59
+ previewSecret: string;
60
+ }
61
+
62
+ /**
63
+ * The minimal fetch surface this module relies on. A narrow seam (matching
64
+ * `PreviewBuildSpawn` in preview-build.ts) lets tests pass a tiny fake
65
+ * without reconstructing the full `fetch` typing.
66
+ */
67
+ export type RegistrationFetch = (
68
+ url: string,
69
+ init: { method: 'POST'; headers: Record<string, string>; body: string },
70
+ ) => Promise<Response>;
71
+
72
+ const INITIAL_RETRY_MS = 1_000;
73
+ const MAX_RETRY_MS = 30_000;
74
+ const RETRY_BUDGET_MS = 180_000;
75
+
76
+ /**
77
+ * Backoff before each retry; length + 1 = total attempts. Starts at 1 s,
78
+ * doubles to a 30 s ceiling and stops before the waits alone exceed the
79
+ * budget: an endpoint that has just been set up can answer 503 for a while,
80
+ * and a budget of about a second gives up long before it settles.
81
+ */
82
+ export function _registrationRetryDelays(): number[] {
83
+ const delays: number[] = [];
84
+ let next = INITIAL_RETRY_MS;
85
+ let total = 0;
86
+ while (total + next <= RETRY_BUDGET_MS) {
87
+ delays.push(next);
88
+ total += next;
89
+ next = Math.min(next * 2, MAX_RETRY_MS);
90
+ }
91
+ return delays;
92
+ }
93
+
94
+ const DEFAULT_RETRY_DELAYS_MS: readonly number[] = _registrationRetryDelays();
95
+
96
+ /**
97
+ * POSTs the registration to the endpoint and returns the per-branch preview
98
+ * secret. Network errors and 5xx responses are retried with exponential
99
+ * backoff (1 s doubling to 30 s, ten attempts within a three-minute wait
100
+ * budget); 4xx responses throw immediately with the response body so
101
+ * the caller can surface the exact rejection reason (e.g. an invalid token).
102
+ */
103
+ export async function postRegistration(input: RegistrationInput): Promise<RegistrationResult> {
104
+ return _postRegistrationWith((url, init) => fetch(url, init), input);
105
+ }
106
+
107
+ /**
108
+ * Internal seam that takes the fetch function (and retry backoff) as
109
+ * parameters so tests can substitute fakes. Public callers should use
110
+ * {@link postRegistration}.
111
+ *
112
+ * Exported with a leading underscore to signal that this is an internal API
113
+ * and not part of the package's public surface.
114
+ */
115
+ export async function _postRegistrationWith(
116
+ fetchFn: RegistrationFetch,
117
+ input: RegistrationInput,
118
+ retryDelaysMs: readonly number[] = DEFAULT_RETRY_DELAYS_MS,
119
+ ): Promise<RegistrationResult> {
120
+ const url = `${input.endpoint}/api/v1/registrations`;
121
+ const init = {
122
+ method: 'POST' as const,
123
+ headers: {
124
+ 'content-type': 'application/json',
125
+ authorization: `Bearer ${input.buildToken}`,
126
+ },
127
+ // JSON.stringify drops undefined optional fields, matching the endpoint's
128
+ // "optional means absent" reading of the body.
129
+ body: JSON.stringify({
130
+ repoUri: input.repoUri,
131
+ gitSha: input.gitSha,
132
+ branch: input.branch,
133
+ siteId: input.siteId,
134
+ editorBundleUrl: input.editorBundleUrl,
135
+ bundleHash: input.bundleHash,
136
+ stylesheetUrl: input.stylesheetUrl,
137
+ stylesheetHash: input.stylesheetHash,
138
+ hostWrappers: input.hostWrappers,
139
+ routeCssUrl: input.routeCssUrl,
140
+ routeCssHash: input.routeCssHash,
141
+ componentManifestUrl: input.componentManifestUrl,
142
+ componentManifestHash: input.componentManifestHash,
143
+ deploymentUrl: input.deploymentUrl,
144
+ deploymentProvider: input.deploymentProvider,
145
+ buildId: input.buildId,
146
+ clientVersion: input.clientVersion,
147
+ }),
148
+ };
149
+
150
+ const attempts = retryDelaysMs.length + 1;
151
+ let lastFailure = '';
152
+ for (let attempt = 0; attempt < attempts; attempt++) {
153
+ if (attempt > 0 && retryDelaysMs[attempt - 1] > 0) {
154
+ await new Promise((resolve) => setTimeout(resolve, retryDelaysMs[attempt - 1]));
155
+ }
156
+ let response: Response;
157
+ try {
158
+ response = await fetchFn(url, init);
159
+ } catch (error) {
160
+ // Network-level failure (endpoint unreachable, DNS, reset) — retry.
161
+ lastFailure = error instanceof Error ? error.message : String(error);
162
+ continue;
163
+ }
164
+ if (response.ok) {
165
+ const payload = (await response.json().catch(() => null)) as { previewSecret?: unknown } | null;
166
+ if (typeof payload?.previewSecret !== 'string' || payload.previewSecret === '') {
167
+ throw new Error(`${PACKAGE_NAME}: registration response is missing previewSecret`);
168
+ }
169
+ return { previewSecret: payload.previewSecret };
170
+ }
171
+ const text = await response.text().catch(() => '');
172
+ if (response.status < 500) {
173
+ // 4xx is deterministic (bad token, repo not covered, malformed body) —
174
+ // retrying cannot help, and the body carries the exact reason.
175
+ throw new Error(`${PACKAGE_NAME}: registration rejected: HTTP ${response.status} ${text}`);
176
+ }
177
+ lastFailure = `HTTP ${response.status} ${text}`;
178
+ }
179
+ throw new Error(`${PACKAGE_NAME}: registration failed after ${attempts} attempts: ${lastFailure}`);
180
+ }
@@ -0,0 +1,54 @@
1
+ /** Minimal environment surface used for zero-config repository detection. */
2
+ export type RepositoryEnvironment = Record<string, string | undefined>;
3
+
4
+ export interface DetectRepositoryUriInput {
5
+ /** Advanced escape hatch for non-standard checkouts. Normal builds omit it. */
6
+ explicit?: string;
7
+ env?: RepositoryEnvironment;
8
+ /** `remote.origin.url`, supplied by the integration after a best-effort git read. */
9
+ remote?: string;
10
+ }
11
+
12
+ const REPO_SEGMENT = /^[A-Za-z0-9_.-]+$/;
13
+
14
+ /**
15
+ * Normalize a provider full_name or common Git remote into `owner/repo`.
16
+ * Deliberately rejects local paths and nested groups: a registration names
17
+ * its repository GitHub-style, as two segments.
18
+ */
19
+ export function normalizeRepositoryUri(input: string | undefined): string | undefined {
20
+ if (input === undefined) return undefined;
21
+ let value = input.trim();
22
+ if (value === '' || value.startsWith('/')) return undefined;
23
+
24
+ const scp = /^[^@/]+@[^:/]+:(.+)$/.exec(value);
25
+ if (scp) {
26
+ value = scp[1];
27
+ } else if (value.includes('://')) {
28
+ try {
29
+ value = new URL(value).pathname;
30
+ } catch {
31
+ return undefined;
32
+ }
33
+ }
34
+
35
+ value = value.replace(/^\/+|\/+$/g, '').replace(/\.git$/, '');
36
+ let parts = value.split('/');
37
+ if (parts.length === 3 && parts[0].includes('.')) parts = parts.slice(1);
38
+ if (parts.length !== 2 || !parts.every((part) => REPO_SEGMENT.test(part))) return undefined;
39
+ return `${parts[0]}/${parts[1]}`;
40
+ }
41
+
42
+ /** Resolve repo identity from configuration-free CI metadata, then Git. */
43
+ export function detectRepositoryUri(input: DetectRepositoryUriInput = {}): string | undefined {
44
+ const env = input.env ?? process.env;
45
+ const vercel =
46
+ env.VERCEL_GIT_REPO_OWNER && env.VERCEL_GIT_REPO_SLUG
47
+ ? `${env.VERCEL_GIT_REPO_OWNER}/${env.VERCEL_GIT_REPO_SLUG}`
48
+ : undefined;
49
+ for (const candidate of [input.explicit, env.GITHUB_REPOSITORY, vercel, env.CI_PROJECT_PATH, input.remote]) {
50
+ const normalized = normalizeRepositoryUri(candidate);
51
+ if (normalized !== undefined) return normalized;
52
+ }
53
+ return undefined;
54
+ }
package/src/site-id.ts ADDED
@@ -0,0 +1,86 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { PACKAGE_NAME } from './constants.js';
4
+
5
+ /** The site-id grammar: lowercase alphanumerics and dashes, 1-64 chars, alphanumeric first. */
6
+ export const SITE_ID_RE = /^[a-z0-9][a-z0-9-]{0,63}$/;
7
+
8
+ /**
9
+ * Resolve the build's deployable-site id. STRICT: malformed input fails the
10
+ * build — a silent mis-attach is the same "deployed, but the editor points at
11
+ * the wrong content" miss, only at a different address. A cleanly-parsed
12
+ * sites.json without a top-level siteId is the zero-config repo: implicit
13
+ * 'default'.
14
+ */
15
+ export function resolveBuildSiteId(opts: {
16
+ /** process.env.CONLOCA_CONTENT_ROOT — the channel conlocaCMS already publishes. */
17
+ contentRoot: string | undefined;
18
+ /** options.siteId — advanced override for CMS-less builds. */
19
+ override: string | undefined;
20
+ /** Seam for tests; defaults to a utf8 readFileSync. */
21
+ readFile?: (path: string) => string;
22
+ }): string {
23
+ const read = opts.readFile ?? ((p: string) => readFileSync(p, 'utf8'));
24
+
25
+ if (opts.contentRoot === undefined || opts.contentRoot === '') {
26
+ // CMS channel absent — the override stands alone (a CMS-less build).
27
+ if (opts.override === undefined) {
28
+ throw new Error(
29
+ `${PACKAGE_NAME}: cannot determine siteId — CONLOCA_CONTENT_ROOT is not set ` +
30
+ '(is conlocaCMS installed?) and no siteId override is configured',
31
+ );
32
+ }
33
+ assertSlug(opts.override, 'siteId override');
34
+ return opts.override;
35
+ }
36
+
37
+ const path = join(opts.contentRoot, 'sites.json');
38
+ let raw: string;
39
+ try {
40
+ raw = read(path);
41
+ } catch {
42
+ throw new Error(`${PACKAGE_NAME}: missing ${path} — the CMS content root must carry its sites.json`);
43
+ }
44
+ let parsed: unknown;
45
+ try {
46
+ parsed = JSON.parse(raw);
47
+ } catch {
48
+ throw new Error(`${PACKAGE_NAME}: could not parse ${path} as JSON`);
49
+ }
50
+ const record = parsed as Record<string, unknown> | null;
51
+ if (
52
+ record === null ||
53
+ typeof record !== 'object' ||
54
+ record.sites === null ||
55
+ typeof record.sites !== 'object' ||
56
+ Array.isArray(record.sites)
57
+ ) {
58
+ throw new Error(`${PACKAGE_NAME}: ${path} has no "sites" object — refusing to register a broken content model`);
59
+ }
60
+
61
+ let resolved: string;
62
+ if ('siteId' in record) {
63
+ if (typeof record.siteId !== 'string' || !SITE_ID_RE.test(record.siteId)) {
64
+ throw new Error(`${PACKAGE_NAME}: invalid top-level siteId in ${path} (want ${SITE_ID_RE})`);
65
+ }
66
+ resolved = record.siteId;
67
+ } else {
68
+ resolved = 'default'; // zero-config repo — soft path, never a build failure
69
+ }
70
+
71
+ // The env channel is authoritative: an override that DIFFERS from either the
72
+ // explicit id or the implicit default fails the build, never picks silently.
73
+ if (opts.override !== undefined && opts.override !== resolved) {
74
+ throw new Error(
75
+ `${PACKAGE_NAME}: siteId override "${opts.override}" contradicts ${path} (resolved "${resolved}") — ` +
76
+ 'remove the override or fix sites.json',
77
+ );
78
+ }
79
+ return resolved;
80
+ }
81
+
82
+ function assertSlug(value: string, label: string): void {
83
+ if (!SITE_ID_RE.test(value)) {
84
+ throw new Error(`${PACKAGE_NAME}: ${label} "${value}" is not a valid site slug (${SITE_ID_RE})`);
85
+ }
86
+ }
@@ -0,0 +1,55 @@
1
+ /**
2
+ * Astro middleware entrypoint for the recursive preview build.
3
+ *
4
+ * `addMiddleware({ entrypoint: '@conloca/cloud-astro/site-middleware' })` in
5
+ * the integration resolves to this module, so it must export `onRequest` —
6
+ * Astro's middleware contract. The verdict/render logic lives in
7
+ * `./preview/site-middleware.ts`, which is env-free and unit-testable; this
8
+ * file binds it to the runtime env resolution and to the site's own build
9
+ * graph: `astro:content` and the routing-config virtual module only resolve
10
+ * here, so the collection-backed baseline is constructed here and injected as
11
+ * a seam.
12
+ *
13
+ * Mounted ONLY inside the preview build (see `integration.ts`), never in the
14
+ * site's production build.
15
+ */
16
+
17
+ import { getCollection } from 'astro:content';
18
+ import baked from 'virtual:conloca-preview-opts';
19
+ import routingConfig from 'virtual:conloca-routing-config';
20
+ import { createCollectionBackedContentAPI } from '@conloca/astro-cms';
21
+ import type { ContentAPI } from '@conloca/content-api';
22
+ import { resolveEndpointFetch, resolveFromBaked } from './preview/_resolve-opts.js';
23
+ import {
24
+ createPreviewSiteMiddleware,
25
+ type PreviewMiddlewareContext,
26
+ type PreviewMiddlewareNext,
27
+ } from './preview/site-middleware.js';
28
+ import { untagWorkerdProcess } from './preview/workerd-shim.js';
29
+
30
+ // At Cloudflare Worker start-up, before any render: workerd's nodejs_compat
31
+ // process can masquerade as Node's, sending Astro down a streaming branch whose
32
+ // body the Cloudflare Workers Response cannot consume — every on-demand page then renders as the
33
+ // literal string "[object Object]". See the shim's doc for the full chain.
34
+ untagWorkerdProcess();
35
+
36
+ // One baseline per process: the built collections are immutable at runtime,
37
+ // and constructing the collection-backed reader walks every collection.
38
+ let baselinePromise: Promise<ContentAPI> | undefined;
39
+ function baselineApi(): Promise<ContentAPI> {
40
+ baselinePromise ??= createCollectionBackedContentAPI({
41
+ getCollection: (name) => getCollection(name),
42
+ routing: routingConfig,
43
+ });
44
+ return baselinePromise;
45
+ }
46
+
47
+ export async function onRequest(context: PreviewMiddlewareContext, next: PreviewMiddlewareNext): Promise<Response> {
48
+ const handler = createPreviewSiteMiddleware(() => resolveFromBaked(baked, (name) => process.env[name]), {
49
+ baselineApi,
50
+ site: routingConfig.siteName,
51
+ locale: routingConfig.locale,
52
+ fetchFn: await resolveEndpointFetch(),
53
+ });
54
+ return handler(context, next);
55
+ }