@conloca/cloud-astro 0.2.3 → 0.2.5

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 (159) hide show
  1. package/README.md +155 -37
  2. package/dist/.build-inputs.json +32 -23
  3. package/dist/src/constants.d.ts +12 -3
  4. package/dist/src/constants.d.ts.map +1 -1
  5. package/dist/src/constants.js +12 -3
  6. package/dist/src/constants.js.map +1 -1
  7. package/dist/src/d3-build.d.ts +70 -0
  8. package/dist/src/d3-build.d.ts.map +1 -0
  9. package/dist/src/d3-build.js +272 -0
  10. package/dist/src/d3-build.js.map +1 -0
  11. package/dist/src/descriptors.d.ts.map +1 -1
  12. package/dist/src/descriptors.js +4 -2
  13. package/dist/src/descriptors.js.map +1 -1
  14. package/dist/src/doctor/checks-live.d.ts +2 -2
  15. package/dist/src/doctor/checks-live.d.ts.map +1 -1
  16. package/dist/src/doctor/checks-live.js +10 -4
  17. package/dist/src/doctor/checks-live.js.map +1 -1
  18. package/dist/src/doctor/checks-offline.d.ts +1 -5
  19. package/dist/src/doctor/checks-offline.d.ts.map +1 -1
  20. package/dist/src/doctor/checks-offline.js +15 -27
  21. package/dist/src/doctor/checks-offline.js.map +1 -1
  22. package/dist/src/doctor/checks-preview-limits.d.ts +11 -0
  23. package/dist/src/doctor/checks-preview-limits.d.ts.map +1 -0
  24. package/dist/src/doctor/checks-preview-limits.js +133 -0
  25. package/dist/src/doctor/checks-preview-limits.js.map +1 -0
  26. package/dist/src/doctor/checks-preview-live.d.ts +14 -0
  27. package/dist/src/doctor/checks-preview-live.d.ts.map +1 -0
  28. package/dist/src/doctor/checks-preview-live.js +72 -0
  29. package/dist/src/doctor/checks-preview-live.js.map +1 -0
  30. package/dist/src/doctor/checks-preview.d.ts +7 -0
  31. package/dist/src/doctor/checks-preview.d.ts.map +1 -0
  32. package/dist/src/doctor/checks-preview.js +287 -0
  33. package/dist/src/doctor/checks-preview.js.map +1 -0
  34. package/dist/src/doctor/config-scan.d.ts +6 -0
  35. package/dist/src/doctor/config-scan.d.ts.map +1 -1
  36. package/dist/src/doctor/config-scan.js +17 -0
  37. package/dist/src/doctor/config-scan.js.map +1 -1
  38. package/dist/src/doctor/run.d.ts.map +1 -1
  39. package/dist/src/doctor/run.js +4 -0
  40. package/dist/src/doctor/run.js.map +1 -1
  41. package/dist/src/doctor/types.d.ts +11 -1
  42. package/dist/src/doctor/types.d.ts.map +1 -1
  43. package/dist/src/doctor/types.js +11 -1
  44. package/dist/src/doctor/types.js.map +1 -1
  45. package/dist/src/editor-page/bundle.d.ts +2 -0
  46. package/dist/src/editor-page/bundle.d.ts.map +1 -1
  47. package/dist/src/editor-page/bundle.js +3 -0
  48. package/dist/src/editor-page/bundle.js.map +1 -1
  49. package/dist/src/editor-page/data-schemas.d.ts +16 -0
  50. package/dist/src/editor-page/data-schemas.d.ts.map +1 -0
  51. package/dist/src/editor-page/data-schemas.js +39 -0
  52. package/dist/src/editor-page/data-schemas.js.map +1 -0
  53. package/dist/src/editor-page/emit.d.ts +37 -1
  54. package/dist/src/editor-page/emit.d.ts.map +1 -1
  55. package/dist/src/editor-page/emit.js +75 -4
  56. package/dist/src/editor-page/emit.js.map +1 -1
  57. package/dist/src/index.d.ts +1 -0
  58. package/dist/src/index.d.ts.map +1 -1
  59. package/dist/src/index.js +2 -0
  60. package/dist/src/index.js.map +1 -1
  61. package/dist/src/integration.d.ts.map +1 -1
  62. package/dist/src/integration.js +165 -41
  63. package/dist/src/integration.js.map +1 -1
  64. package/dist/src/preview/_dispatch.d.ts +12 -0
  65. package/dist/src/preview/_dispatch.d.ts.map +1 -1
  66. package/dist/src/preview/_dispatch.js +31 -0
  67. package/dist/src/preview/_dispatch.js.map +1 -1
  68. package/dist/src/preview/_resolve-opts.d.ts +3 -0
  69. package/dist/src/preview/_resolve-opts.d.ts.map +1 -1
  70. package/dist/src/preview/_resolve-opts.js +3 -1
  71. package/dist/src/preview/_resolve-opts.js.map +1 -1
  72. package/dist/src/preview/banner.d.ts +12 -9
  73. package/dist/src/preview/banner.d.ts.map +1 -1
  74. package/dist/src/preview/banner.js +46 -41
  75. package/dist/src/preview/banner.js.map +1 -1
  76. package/dist/src/preview/cloudflare-adapter.d.ts +35 -0
  77. package/dist/src/preview/cloudflare-adapter.d.ts.map +1 -0
  78. package/dist/src/preview/cloudflare-adapter.js +92 -0
  79. package/dist/src/preview/cloudflare-adapter.js.map +1 -0
  80. package/dist/src/preview/cookie.d.ts +9 -13
  81. package/dist/src/preview/cookie.d.ts.map +1 -1
  82. package/dist/src/preview/cookie.js +15 -25
  83. package/dist/src/preview/cookie.js.map +1 -1
  84. package/dist/src/preview/dispatcher.d.ts +73 -0
  85. package/dist/src/preview/dispatcher.d.ts.map +1 -0
  86. package/dist/src/preview/dispatcher.js +329 -0
  87. package/dist/src/preview/dispatcher.js.map +1 -0
  88. package/dist/src/preview/entry-code.d.ts +33 -0
  89. package/dist/src/preview/entry-code.d.ts.map +1 -0
  90. package/dist/src/preview/entry-code.js +33 -0
  91. package/dist/src/preview/entry-code.js.map +1 -0
  92. package/dist/src/preview/headers.d.ts +24 -4
  93. package/dist/src/preview/headers.d.ts.map +1 -1
  94. package/dist/src/preview/headers.js +35 -7
  95. package/dist/src/preview/headers.js.map +1 -1
  96. package/dist/src/preview/landing.d.ts +21 -0
  97. package/dist/src/preview/landing.d.ts.map +1 -1
  98. package/dist/src/preview/landing.js +103 -35
  99. package/dist/src/preview/landing.js.map +1 -1
  100. package/dist/src/preview/middleware.d.ts +29 -7
  101. package/dist/src/preview/middleware.d.ts.map +1 -1
  102. package/dist/src/preview/middleware.js +238 -84
  103. package/dist/src/preview/middleware.js.map +1 -1
  104. package/dist/src/preview/preview-path.d.ts +29 -0
  105. package/dist/src/preview/preview-path.d.ts.map +1 -1
  106. package/dist/src/preview/preview-path.js +41 -0
  107. package/dist/src/preview/preview-path.js.map +1 -1
  108. package/dist/src/preview/redeem-url.d.ts +7 -0
  109. package/dist/src/preview/redeem-url.d.ts.map +1 -0
  110. package/dist/src/preview/redeem-url.js +14 -0
  111. package/dist/src/preview/redeem-url.js.map +1 -0
  112. package/dist/src/preview/site-middleware.d.ts.map +1 -1
  113. package/dist/src/preview/site-middleware.js +39 -12
  114. package/dist/src/preview/site-middleware.js.map +1 -1
  115. package/dist/src/preview-build.d.ts +19 -8
  116. package/dist/src/preview-build.d.ts.map +1 -1
  117. package/dist/src/preview-build.js +47 -21
  118. package/dist/src/preview-build.js.map +1 -1
  119. package/dist/src/skill.d.ts +11 -0
  120. package/dist/src/skill.d.ts.map +1 -1
  121. package/dist/src/skill.js +32 -9
  122. package/dist/src/skill.js.map +1 -1
  123. package/dist/src/types.d.ts +15 -12
  124. package/dist/src/types.d.ts.map +1 -1
  125. package/package.json +33 -7
  126. package/src/constants.ts +14 -3
  127. package/src/d3-build.ts +315 -0
  128. package/src/descriptors.ts +4 -2
  129. package/src/doctor/checks-live.ts +10 -4
  130. package/src/doctor/checks-offline.ts +16 -25
  131. package/src/doctor/checks-preview-limits.ts +137 -0
  132. package/src/doctor/checks-preview-live.ts +77 -0
  133. package/src/doctor/checks-preview.ts +302 -0
  134. package/src/doctor/config-scan.ts +14 -0
  135. package/src/doctor/run.ts +4 -0
  136. package/src/doctor/types.ts +11 -1
  137. package/src/editor-page/bundle.ts +5 -0
  138. package/src/editor-page/data-schemas.ts +47 -0
  139. package/src/editor-page/emit.ts +124 -8
  140. package/src/index.ts +2 -0
  141. package/src/integration.ts +176 -40
  142. package/src/preview/_dispatch.ts +36 -1
  143. package/src/preview/_resolve-opts.ts +6 -1
  144. package/src/preview/banner.ts +61 -41
  145. package/src/preview/cloudflare-adapter.ts +103 -0
  146. package/src/preview/cookie.ts +14 -23
  147. package/src/preview/dispatcher.ts +407 -0
  148. package/src/preview/entry-code.ts +51 -0
  149. package/src/preview/headers.ts +35 -7
  150. package/src/preview/landing.ts +115 -37
  151. package/src/preview/middleware.ts +264 -88
  152. package/src/preview/preview-path.ts +57 -0
  153. package/src/preview/redeem-url.ts +14 -0
  154. package/src/preview/site-middleware.ts +47 -12
  155. package/src/preview-build.ts +67 -24
  156. package/src/preview-handler.astro +2 -1
  157. package/src/skill/SKILL.md +14 -2
  158. package/src/skill.ts +36 -8
  159. package/src/types.ts +15 -12
@@ -0,0 +1,315 @@
1
+ /**
2
+ * The site's build finishing a D3 preview: the preview server was built next to the static site (a child build),
3
+ * and this writes what Cloudflare Workers needs to serve both: the preview build's `_astro` files merged into the
4
+ * site's, the route list `wrangler.jsonc` must run the dispatcher on, and the dispatcher module and its config.
5
+ */
6
+
7
+ import { existsSync } from 'node:fs';
8
+ import { copyFile, mkdir, readdir, readFile, rm, writeFile } from 'node:fs/promises';
9
+ import { dirname, join, relative, resolve, sep } from 'node:path';
10
+ import { isRecord } from '@conloca/content-api/component-vocabulary';
11
+ import { readSitesConfig } from '@conloca/content-api/node';
12
+ import { PACKAGE_NAME } from './constants.js';
13
+ import { parseWranglerConfig, wranglerConfigPath } from './preview/cloudflare-adapter.js';
14
+ import type { DispatcherConfig, DispatcherExit } from './preview/dispatcher.js';
15
+ import { previewOwnEntries, previewRoutePrefix } from './preview/preview-path.js';
16
+
17
+ /** What the preview build tells the site's build: its pages, its on-demand routes and the exit values it baked. */
18
+ export interface PreviewRoutes {
19
+ /** Request paths without a trailing slash, under the base. */
20
+ prerendered: string[];
21
+ /** `run_worker_first` globs under the base. */
22
+ onDemand: string[];
23
+ /** What the dispatcher's exit route answers with. */
24
+ exit: DispatcherExit;
25
+ }
26
+
27
+ const ROUTES_FILE = 'routes.json';
28
+ /** The binding `conloca connect` writes and the dispatcher reads (`DispatcherEnv`). */
29
+ const LIMIT_BINDING = 'conlocaPreviewLimit';
30
+
31
+ /**
32
+ * The routes the live site must hand to its dispatcher: everything the preview build renders on demand, except the
33
+ * CMS pages (prerendered in production), the preview route itself, redirects (the static site writes them as pages)
34
+ * and Astro's internals other than islands, actions and the image endpoint draft pages use.
35
+ */
36
+ export function onDemandPatterns(
37
+ routes: readonly { pattern: string; isPrerendered: boolean; origin: string; entrypoint: string; type: string }[],
38
+ ): string[] {
39
+ return routes
40
+ .filter((route) => !route.isPrerendered && route.type !== 'redirect')
41
+ .filter((route) => !route.entrypoint.endsWith('/internal/page-handler.astro'))
42
+ .filter((route) => !/preview-handler(\.astro)?$/u.test(route.entrypoint))
43
+ .filter((route) => route.origin !== 'internal' || /^\/_(server-islands|actions|image)(\/|$)/u.test(route.pattern))
44
+ .map((route) => route.pattern);
45
+ }
46
+
47
+ /** An Astro route pattern as a `run_worker_first` glob under the base: from the first dynamic segment on, `*`. */
48
+ export function workerFirstPattern(pattern: string, base: string): string {
49
+ const segments = pattern.split('/');
50
+ const dynamic = segments.findIndex((segment) => segment.includes('['));
51
+ const path = dynamic === -1 ? pattern : `${segments.slice(0, dynamic).join('/')}/*`;
52
+ return `${base.replace(/\/+$/u, '')}${path}`;
53
+ }
54
+
55
+ export async function writePreviewRoutes(previewOut: string, routes: PreviewRoutes): Promise<void> {
56
+ await mkdir(previewOut, { recursive: true });
57
+ await writeFile(join(previewOut, ROUTES_FILE), `${JSON.stringify(routes, null, 2)}\n`);
58
+ }
59
+
60
+ function isStrings(value: unknown): value is string[] {
61
+ return Array.isArray(value) && value.every((item) => typeof item === 'string');
62
+ }
63
+
64
+ function isExit(value: unknown): value is DispatcherExit {
65
+ return (
66
+ isRecord(value) &&
67
+ typeof value.repo === 'string' &&
68
+ typeof value.siteId === 'string' &&
69
+ typeof value.branch === 'string' &&
70
+ typeof value.audience === 'string' &&
71
+ (value.issuer === undefined || typeof value.issuer === 'string')
72
+ );
73
+ }
74
+
75
+ /** The preview build's report, or undefined when it wrote none (it failed, or is from an older release). */
76
+ export async function readPreviewRoutes(previewOut: string): Promise<PreviewRoutes | undefined> {
77
+ let value: unknown;
78
+ try {
79
+ value = JSON.parse(await readFile(join(previewOut, ROUTES_FILE), 'utf8'));
80
+ } catch {
81
+ return undefined;
82
+ }
83
+ return isRecord(value) && isStrings(value.prerendered) && isStrings(value.onDemand) && isExit(value.exit)
84
+ ? { prerendered: value.prerendered, onDemand: value.onDemand, exit: value.exit }
85
+ : undefined;
86
+ }
87
+
88
+ /**
89
+ * Copies the preview build's built files into the site's, so the drafts' scripts and styles load from the one asset
90
+ * set the site serves. Content-hashed names mean the same name holds the same bytes; a name that holds other bytes
91
+ * copies nothing and answers false.
92
+ */
93
+ export async function mergeAssets(from: string, to: string): Promise<boolean> {
94
+ if (!existsSync(from)) return true;
95
+ const files = (await readdir(from, { recursive: true, withFileTypes: true }))
96
+ .filter((entry) => entry.isFile())
97
+ .map((entry) => relative(from, join(entry.parentPath, entry.name)));
98
+ const clashes = await Promise.all(
99
+ files.map(
100
+ async (file) =>
101
+ existsSync(join(to, file)) && !(await readFile(join(to, file))).equals(await readFile(join(from, file))),
102
+ ),
103
+ );
104
+ if (clashes.includes(true)) return false;
105
+ await Promise.all(
106
+ files.map(async (file) => {
107
+ if (existsSync(join(to, file))) return;
108
+ await mkdir(dirname(join(to, file)), { recursive: true });
109
+ await copyFile(join(from, file), join(to, file));
110
+ }),
111
+ );
112
+ return true;
113
+ }
114
+
115
+ /** The config's blocks a deploy can use, labelled: the top level, and each env block (the build selects one). */
116
+ function blocksOf(config: unknown): { label: string; block: unknown; inherited: unknown }[] {
117
+ if (!isRecord(config)) return [];
118
+ const env = isRecord(config.env) ? config.env : {};
119
+ return [
120
+ { label: '', block: config, inherited: undefined },
121
+ ...Object.entries(env).map(([name, block]) => ({ label: ` (env.${name})`, block, inherited: config })),
122
+ ];
123
+ }
124
+
125
+ /** `run_worker_first` of a block's own `assets`, else what it inherits; `true` covers every path. */
126
+ function workerFirstOf(block: unknown, inherited: unknown): readonly unknown[] | true | undefined {
127
+ const own = isRecord(block) && isRecord(block.assets) ? block.assets : undefined;
128
+ const assets = own ?? (isRecord(inherited) && isRecord(inherited.assets) ? inherited.assets : undefined);
129
+ if (assets === undefined) return undefined;
130
+ if (assets.run_worker_first === true) return true;
131
+ return Array.isArray(assets.run_worker_first) ? assets.run_worker_first : [];
132
+ }
133
+
134
+ function hasLimit(block: unknown): boolean {
135
+ if (!isRecord(block) || !Array.isArray(block.ratelimits)) return false;
136
+ return block.ratelimits.some(
137
+ (entry) =>
138
+ isRecord(entry) &&
139
+ entry.name === LIMIT_BINDING &&
140
+ typeof entry.namespace_id === 'string' &&
141
+ /^[1-9]\d*$/u.test(entry.namespace_id),
142
+ );
143
+ }
144
+
145
+ /**
146
+ * What `wrangler.jsonc` lacks for D3, as fix messages: `run_worker_first` entries per block that has its own
147
+ * `assets` (an env block's replaces the top level's), and, when the plan needs it, the rate limit in every block
148
+ * (bindings are not inherited).
149
+ */
150
+ export function deployProblems(config: unknown, expected: readonly string[], needsLimit: boolean): string[] {
151
+ const problems: string[] = [];
152
+ for (const { label, block, inherited } of blocksOf(config)) {
153
+ const ownAssets = isRecord(block) && isRecord(block.assets);
154
+ if (label === '' || ownAssets) {
155
+ const listed = workerFirstOf(block, inherited);
156
+ const missing = listed === true ? [] : expected.filter((entry) => !(listed ?? []).includes(entry));
157
+ if (missing.length > 0) problems.push(`wrangler.jsonc run_worker_first lacks ${missing.join(', ')}${label}`);
158
+ }
159
+ if (needsLimit && !hasLimit(block)) problems.push(`wrangler.jsonc lacks the ${LIMIT_BINDING} rate limit${label}`);
160
+ }
161
+ return problems;
162
+ }
163
+
164
+ /** The site's recorded Cloudflare plan (`package.json` `conloca.cfPlan`, written by `conloca connect`), or undefined. */
165
+ export async function recordedCfPlan(root: string): Promise<'free' | 'paid' | undefined> {
166
+ let value: unknown;
167
+ try {
168
+ value = JSON.parse(await readFile(join(root, 'package.json'), 'utf8'));
169
+ } catch {
170
+ return undefined;
171
+ }
172
+ const plan = isRecord(value) && isRecord(value.conloca) ? value.conloca.cfPlan : undefined;
173
+ return plan === 'free' || plan === 'paid' ? plan : undefined;
174
+ }
175
+
176
+ /**
177
+ * What the preview server serves for the live site beyond the preview route, per the config: `run_worker_first`
178
+ * entries past the prefix pair and the image endpoint (only drafts use it), and `not_found_handling: "none"` (it
179
+ * answers every miss). A failed preview build must not ship over any of these.
180
+ */
181
+ export function servedBeyondPrefix(config: unknown, base: string): string[] {
182
+ const own = new Set(previewOwnEntries(base));
183
+ const served = new Set<string>();
184
+ for (const { block, inherited } of blocksOf(config)) {
185
+ const listed = workerFirstOf(block, inherited);
186
+ if (listed === true) served.add('run_worker_first: true');
187
+ for (const entry of listed === true || listed === undefined ? [] : listed) {
188
+ if (typeof entry === 'string' && !entry.startsWith('!') && !own.has(entry)) served.add(entry);
189
+ }
190
+ const assets = isRecord(block) && isRecord(block.assets) ? block.assets : undefined;
191
+ if (assets?.not_found_handling === 'none') served.add('not_found_handling "none"');
192
+ }
193
+ return [...served];
194
+ }
195
+
196
+ /** The module `wrangler.jsonc` `main` names. Its preview server import is lazy, so a slow one never delays start-up. */
197
+ export function dispatcherModule(serverEntry: string | null): string {
198
+ const load = serverEntry === null ? 'null' : `() => import(${JSON.stringify(serverEntry)})`;
199
+ return [
200
+ '// Written by @conloca/cloud-astro on every build.',
201
+ "import { createDispatcher } from '@conloca/cloud-astro/dispatcher';",
202
+ "import config from './dispatcher.json';",
203
+ '',
204
+ `export default createDispatcher(config, ${load});`,
205
+ '',
206
+ ].join('\n');
207
+ }
208
+
209
+ /** Every host sites.json declares: links to them are links to this site. */
210
+ async function declaredDomains(): Promise<string[]> {
211
+ const contentRoot = process.env.CONLOCA_CONTENT_ROOT;
212
+ if (!contentRoot) return [];
213
+ const { sites } = await readSitesConfig(contentRoot);
214
+ return [...new Set(Object.values(sites).flatMap((site) => Object.values(site.domains ?? {})))];
215
+ }
216
+
217
+ /** A plain `wrangler deploy` follows `.wrangler/deploy/config.json`; one the preview build left would ship it as the site. */
218
+ async function dropDeployRedirect(root: string, previewOut: string, logger: { info(message: string): void }) {
219
+ const redirect = join(root, '.wrangler', 'deploy', 'config.json');
220
+ if (!existsSync(redirect)) return;
221
+ let target: string | undefined;
222
+ try {
223
+ const value: unknown = JSON.parse(await readFile(redirect, 'utf8'));
224
+ target =
225
+ isRecord(value) && typeof value.configPath === 'string'
226
+ ? resolve(dirname(redirect), value.configPath)
227
+ : undefined;
228
+ } catch {
229
+ target = undefined;
230
+ }
231
+ if (target === undefined || !target.startsWith(`${resolve(previewOut)}${sep}`)) return;
232
+ await rm(redirect);
233
+ logger.info('removed .wrangler/deploy/config.json: it pointed a plain `wrangler deploy` at the preview server');
234
+ }
235
+
236
+ export interface FinishD3Input {
237
+ root: string;
238
+ dist: string;
239
+ previewOut: string;
240
+ base: string;
241
+ endpoint: string;
242
+ /** Whether the preview build succeeded. */
243
+ built: boolean;
244
+ logger: { info(message: string): void; warn(message: string): void };
245
+ }
246
+
247
+ const FIX = 'run `conloca connect --update --yes`';
248
+
249
+ /** D3: everything after the preview build; it fails the site's build only where shipping would break it. */
250
+ export async function finishD3Build(input: FinishD3Input): Promise<void> {
251
+ const { root, dist, previewOut, base, logger } = input;
252
+ const prefix = previewRoutePrefix(base);
253
+ const routes = input.built ? await readPreviewRoutes(previewOut) : undefined;
254
+ let serving = routes !== undefined;
255
+ if (input.built && routes === undefined)
256
+ logger.warn('the preview build wrote no routes.json, so no preview is served');
257
+ if (serving && !(await mergeAssets(join(previewOut, 'client', '_astro'), join(dist, '_astro')))) {
258
+ serving = false;
259
+ logger.warn(`the preview build's _astro files clash with the site's, so ${prefix}/ answers "preview unavailable"`);
260
+ }
261
+ await dropDeployRedirect(root, previewOut, logger);
262
+
263
+ const outDir = join(root, '.conloca', 'dispatcher');
264
+ await mkdir(outDir, { recursive: true });
265
+ const expected = [prefix, `${prefix}/*`, ...(serving && routes !== undefined ? routes.onDemand : [])];
266
+ await writeFile(join(outDir, 'run_worker_first.json'), `${JSON.stringify(expected, null, 2)}\n`);
267
+
268
+ const configPath = wranglerConfigPath(root);
269
+ const config = configPath === undefined ? undefined : parseWranglerConfig(await readFile(configPath, 'utf8'));
270
+ // Production safety first: with no preview server, every route it serves for the live site would 404.
271
+ if (!serving) {
272
+ const served = servedBeyondPrefix(config, base);
273
+ if (served.length > 0) {
274
+ throw new Error(
275
+ `${PACKAGE_NAME}: the preview build failed and it serves this site's on-demand routes (${served.join(', ')}); fixing it is required to deploy`,
276
+ );
277
+ }
278
+ }
279
+ const problems =
280
+ configPath === undefined
281
+ ? [
282
+ existsSync(join(root, 'wrangler.toml'))
283
+ ? "wrangler.toml can't carry the preview settings: convert it to wrangler.jsonc, then"
284
+ : 'no wrangler.jsonc:',
285
+ ]
286
+ : // A Free site carries no binding (a blocked request still counts against its quota); one with no recorded plan needs it.
287
+ deployProblems(config, expected, (await recordedCfPlan(root)) !== 'free').map((problem) => `${problem}:`);
288
+ for (const problem of problems) {
289
+ const message = `${PACKAGE_NAME}: ${problem} ${FIX}`;
290
+ // `conloca connect` builds to learn the routes it then writes; any other build must not ship a route that 404s.
291
+ if (process.env.CONLOCA_CONNECT === '1') logger.warn(message);
292
+ else throw new Error(message);
293
+ }
294
+ for (const glob of routes?.onDemand ?? []) {
295
+ if (glob === `${base.replace(/\/+$/u, '')}/*`) {
296
+ logger.warn(
297
+ `${PACKAGE_NAME}: the on-demand route ${glob} covers every path, so every visitor starts a Worker; give it a fixed first segment`,
298
+ );
299
+ }
300
+ }
301
+
302
+ const dispatcher: DispatcherConfig = {
303
+ base,
304
+ endpoint: input.endpoint,
305
+ prerendered: serving && routes !== undefined ? routes.prerendered : [],
306
+ domains: await declaredDomains(),
307
+ exit: serving && routes !== undefined ? routes.exit : null,
308
+ };
309
+ await writeFile(join(outDir, 'dispatcher.json'), `${JSON.stringify(dispatcher, null, 2)}\n`);
310
+ const entry = relative(outDir, join(previewOut, 'server', 'entry.mjs'))
311
+ .split(sep)
312
+ .join('/');
313
+ await writeFile(join(outDir, 'index.mjs'), dispatcherModule(serving ? entry : null));
314
+ logger.info(`preview dispatcher written to .conloca/dispatcher/${serving ? '' : ' (preview unavailable)'}`);
315
+ }
@@ -68,12 +68,13 @@ export async function resolveEditorDescriptors(
68
68
  }
69
69
 
70
70
  const templateCount = Object.keys(channel.templates ?? {}).length;
71
- const { dataBindings } = channel;
71
+ const { dataBindings, assetRefBase } = channel;
72
72
  if (
73
73
  channel.schemasPath === undefined &&
74
74
  discovered.length === 0 &&
75
75
  templateCount === 0 &&
76
- dataBindings === undefined
76
+ dataBindings === undefined &&
77
+ assetRefBase === undefined
77
78
  ) {
78
79
  return undefined;
79
80
  }
@@ -88,5 +89,6 @@ export async function resolveEditorDescriptors(
88
89
  ...(discovered.length === 0 ? {} : { discoveredMdxComponents: discovered }),
89
90
  ...(templateCount === 0 ? {} : { templates: channel.templates }),
90
91
  ...(dataBindings === undefined ? {} : { dataBindings }),
92
+ ...(assetRefBase === undefined ? {} : { assetRefBase }),
91
93
  };
92
94
  }
@@ -11,6 +11,7 @@ import {
11
11
  import { messageOf } from '../message-of.js';
12
12
  import { resolveBuildSiteId } from '../site-id.js';
13
13
  import { INTEGRATION_NOT_CALLED, suppliedEndpoint } from './checks-offline.js';
14
+ import { runPreviewLiveChecks } from './checks-preview-live.js';
14
15
  import { type ConfigScan, optionLiteral } from './config-scan.js';
15
16
  import {
16
17
  type CheckId,
@@ -21,7 +22,7 @@ import {
21
22
  skipped,
22
23
  } from './types.js';
23
24
 
24
- const LIVE_CHECK_IDS: readonly CheckId[] = ['CC11', 'CC12', 'CC13'];
25
+ const LIVE_CHECK_IDS: readonly CheckId[] = ['CC11', 'CC12', 'CC13', 'CC24'];
25
26
 
26
27
  /** Every doctor request is bounded: a hanging host must never hang `conloca doctor` (the CLI seam has no timer of its own). */
27
28
  const REQUEST_TIMEOUT_MS = 10_000;
@@ -295,8 +296,8 @@ async function checkProtocol(
295
296
  }
296
297
 
297
298
  /**
298
- * CC11–CC13. Networks only under --live, sends no credential, and contacts only the site's own domain and the editor UI's
299
- * public protocols.json — so it runs anywhere, forks and Dependabot included.
299
+ * CC11–CC13 and CC24. Networks only under --live and sends no credential: it contacts only the site's own domain, the
300
+ * editor UI's public protocols.json and the site's previewUrl, so it runs anywhere, forks and Dependabot included.
300
301
  */
301
302
  export async function runLiveChecks(input: LiveInput): Promise<CheckOutcome[]> {
302
303
  const { context, deps, scan, address } = input;
@@ -308,5 +309,10 @@ export async function runLiveChecks(input: LiveInput): Promise<CheckOutcome[]> {
308
309
  checkEditorPage(input, address),
309
310
  checkFrameHeaders(address, origin, deps.fetch),
310
311
  ]);
311
- return [page.outcome, frame, await checkProtocol(page.info, origin, deps.fetch)];
312
+ return [
313
+ page.outcome,
314
+ frame,
315
+ await checkProtocol(page.info, origin, deps.fetch),
316
+ ...(await runPreviewLiveChecks({ context, deps, scan, info: page.info })),
317
+ ];
312
318
  }
@@ -1,5 +1,5 @@
1
1
  import type { RepositoryEnvironment } from '../repository.js';
2
- import { type ConfigScan, hasOption, optionLiteral, previewBuildSetting } from './config-scan.js';
2
+ import { type ConfigScan, hasOption, optionLiteral, previewServeSetting } from './config-scan.js';
3
3
  import { type CheckOutcome, outcomeOf, skipped } from './types.js';
4
4
 
5
5
  /** Doctor-only override for an endpoint the config computes (e.g. from an env var). */
@@ -53,35 +53,26 @@ export function checkWiring(scan: ConfigScan, repoUri: string | undefined): Chec
53
53
  return outcome;
54
54
  }
55
55
 
56
- /**
57
- * CC8 — only a previewBuild given as an object starts the preview build, which needs an SSR adapter: the project's own
58
- * or previewBuild.adapter. A static project with neither fails astro build at config time. Only what the config text
59
- * shows is judged.
60
- */
56
+ const SERVE_DETAIL = {
57
+ d2: "the site's own server deploy renders drafts (D2)",
58
+ d3: 'the preview server runs next to the static site on Cloudflare Workers (D3)',
59
+ d4: "a separate preview deploy (D4): its address goes in sites.json's previewUrl",
60
+ unknown: 'not verified — doctor cannot read previewBuild, output or the adapter from the config text',
61
+ } as const;
62
+
63
+ /** CC8 — how the preview build serves drafts, read from the config text. */
61
64
  export function checkPreviewBuildAdapter(scan: ConfigScan): CheckOutcome {
62
65
  if (scan.kind !== 'read') {
63
66
  return skipped('CC8', scan.kind === 'none' ? 'no astro.config found' : 'astro config could not be read');
64
67
  }
65
68
  if (scan.config.conlocaCloud === 'absent') return skipped('CC8', INTEGRATION_NOT_CALLED);
66
69
  const outcome = outcomeOf('CC8');
67
- const previewBuild = previewBuildSetting(scan);
68
- const { output, adapter } = scan.config.site;
69
- if (previewBuild === 'off') {
70
- outcome.detail = hasOption(scan, 'previewBuild')
71
- ? 'previewBuild: false — no preview build runs'
72
- : 'previewBuild is not set — no preview build runs';
73
- } else if (previewBuild === 'adapter' || adapter) {
74
- outcome.detail = 'the preview build has an SSR adapter';
75
- } else if (previewBuild === 'unknown' || output !== 'static') {
76
- outcome.detail = 'not verified — doctor cannot read previewBuild, output or the adapter from the config text';
77
- } else {
78
- outcome.problems.push({
79
- check: 'CC8',
80
- level: 'error',
81
- message:
82
- 'previewBuild is set, but the project is static and has no SSR adapter, so astro build fails at config time — add one (previewBuild: { adapter }) or remove previewBuild from conlocaCloud(...)',
83
- path: scan.config.path,
84
- });
85
- }
70
+ const mode = previewServeSetting(scan);
71
+ outcome.detail =
72
+ mode === 'off'
73
+ ? hasOption(scan, 'previewBuild')
74
+ ? 'previewBuild: false — no preview build runs'
75
+ : 'previewBuild is not set — no preview build runs'
76
+ : SERVE_DETAIL[mode];
86
77
  return outcome;
87
78
  }
@@ -0,0 +1,137 @@
1
+ import { join } from 'node:path';
2
+ import { isRecord } from '@conloca/content-api/component-vocabulary';
3
+ import { parseWranglerConfig } from '../preview/cloudflare-adapter.js';
4
+ import { previewOwnEntries, previewRoutePrefix } from '../preview/preview-path.js';
5
+ import { type ConfigScan, previewServeSetting } from './config-scan.js';
6
+ import { type CheckOutcome, type DoctorDeps, outcomeOf, skipped } from './types.js';
7
+
8
+ type LimitDeps = Pick<DoctorDeps, 'exists' | 'readFile'>;
9
+ const UPDATE = '— run `conloca connect --update --yes`';
10
+ /** The binding connect writes: 60 requests per 10 s per visitor, not configurable. */
11
+ const BINDING = 'conlocaPreviewLimit';
12
+ const LIMIT = 60;
13
+ const PERIOD = 10;
14
+
15
+ /** A JSON file's object, or undefined; the return type is `isRecord`'s narrowing, never written out. */
16
+ function jsonRecord(deps: LimitDeps, path: string) {
17
+ try {
18
+ const value: unknown = JSON.parse(deps.readFile(path));
19
+ return isRecord(value) ? value : undefined;
20
+ } catch {
21
+ return undefined;
22
+ }
23
+ }
24
+
25
+ /** A JSON file's array of strings, or undefined. */
26
+ function jsonStrings(deps: LimitDeps, path: string): string[] | undefined {
27
+ try {
28
+ const value: unknown = JSON.parse(deps.readFile(path));
29
+ return Array.isArray(value) && value.every((item) => typeof item === 'string') ? value : undefined;
30
+ } catch {
31
+ return undefined;
32
+ }
33
+ }
34
+
35
+ /** What is wrong with one config block's preview binding, or null when it is the one connect writes. */
36
+ function bindingProblem(block: unknown, where: string): string | null {
37
+ const list: unknown[] = isRecord(block) && Array.isArray(block.ratelimits) ? block.ratelimits : [];
38
+ const binding = list.find((entry) => isRecord(entry) && entry.name === BINDING);
39
+ if (!isRecord(binding)) {
40
+ return `${where} has no ${BINDING} rate-limit binding, so nothing limits preview requests ${UPDATE}`;
41
+ }
42
+ if (typeof binding.namespace_id !== 'string' || !/^[1-9]\d*$/u.test(binding.namespace_id)) {
43
+ return `${where}'s ${BINDING} namespace_id must be a positive integer, as a string ${UPDATE}`;
44
+ }
45
+ const simple = isRecord(binding.simple) ? binding.simple : {};
46
+ if (simple.limit !== LIMIT || simple.period !== PERIOD) {
47
+ return `${where} limits previews to ${String(simple.limit)} requests per ${String(simple.period)} s; previews use ${LIMIT} per ${PERIOD} s ${UPDATE}`;
48
+ }
49
+ return null;
50
+ }
51
+
52
+ /**
53
+ * CC22–CC23: the dispatcher's rate-limit binding and the Cloudflare plan connect recorded, read from the project's
54
+ * files. Never networks and reads no token: Conloca's own setup is all doctor checks; a dashboard rule is the site's
55
+ * choice.
56
+ */
57
+ export function runPreviewLimitChecks(scan: ConfigScan, projectDir: string, deps: LimitDeps): CheckOutcome[] {
58
+ if (previewServeSetting(scan) !== 'd3') {
59
+ const reason = 'only a static site previewing next to itself (D3) shares a Worker with previews';
60
+ return [skipped('CC22', reason), skipped('CC23', reason)];
61
+ }
62
+ const base = scan.kind === 'read' ? (scan.config.site.base ?? '/') : '/';
63
+ const prefix = previewRoutePrefix(base);
64
+
65
+ // The recorded plan decides CC22 (the binding is for the Paid plan only) and is CC23 itself.
66
+ const manifest = jsonRecord(deps, join(projectDir, 'package.json'));
67
+ const conloca = isRecord(manifest?.conloca) ? manifest.conloca : {};
68
+ const recorded = conloca.cfPlan;
69
+
70
+ // CC22
71
+ const path = ['wrangler.jsonc', 'wrangler.json'].map((name) => join(projectDir, name)).find((p) => deps.exists(p));
72
+ let text: string | undefined;
73
+ try {
74
+ text = path === undefined ? undefined : deps.readFile(path);
75
+ } catch {
76
+ text = undefined;
77
+ }
78
+ const config = text === undefined ? undefined : parseWranglerConfig(text);
79
+ let limited: CheckOutcome;
80
+ if (config === undefined) limited = skipped('CC22', 'no wrangler.jsonc (see CC15)');
81
+ else {
82
+ limited = outcomeOf('CC22');
83
+ // Wrangler does not inherit bindings into env blocks: each one needs its own.
84
+ const envs = Object.entries(isRecord(config.env) ? config.env : {});
85
+ const blocks: [string, unknown][] = [
86
+ ['wrangler.jsonc', config],
87
+ ...envs.map(([name, block]): [string, unknown] => [`wrangler.jsonc env.${name}`, block]),
88
+ ];
89
+ if (recorded === 'free') {
90
+ // On Free a blocked request still counts against the daily quota, so connect writes no binding; one left over
91
+ // from a Paid answer does no harm.
92
+ const present = blocks.some(
93
+ ([, block]) =>
94
+ isRecord(block) &&
95
+ Array.isArray(block.ratelimits) &&
96
+ block.ratelimits.some((entry) => isRecord(entry) && entry.name === BINDING),
97
+ );
98
+ limited.detail = present
99
+ ? `a ${BINDING} binding is there; the Free plan needs none, and \`conloca connect --update --yes\` removes it`
100
+ : 'no rate limit on the Cloudflare Workers Free plan, as expected';
101
+ } else {
102
+ // Paid, or no plan recorded yet (CC23 reports that): the binding is required, as the build requires it.
103
+ for (const [where, block] of blocks) {
104
+ const problem = bindingProblem(block, where);
105
+ if (problem !== null) limited.problems.push({ check: 'CC22', level: 'error', message: problem, path });
106
+ }
107
+ if (limited.problems.length === 0) limited.detail = `${LIMIT} preview requests per ${PERIOD} s per visitor`;
108
+ }
109
+ }
110
+
111
+ // CC23
112
+ const plan = outcomeOf('CC23');
113
+ if (recorded === 'paid') plan.detail = 'the Cloudflare Workers Paid plan, recorded in package.json';
114
+ else if (recorded !== 'free') {
115
+ plan.problems.push({
116
+ check: 'CC23',
117
+ level: 'error',
118
+ message:
119
+ 'package.json records no Cloudflare plan (conloca.cfPlan) — run `conloca connect`, or `conloca connect --yes --cf-plan paid` (or `free`)',
120
+ });
121
+ } else {
122
+ const reported = jsonStrings(deps, join(projectDir, '.conloca', 'dispatcher', 'run_worker_first.json')) ?? [];
123
+ const own = previewOwnEntries(base);
124
+ const onDemand = reported.filter((entry) => !own.includes(entry) && !entry.startsWith(`${prefix}/`));
125
+ // The site's on-demand routes stay next to the preview (a separate deploy would leave them without a Worker): a
126
+ // warning, as connect gives, never an error.
127
+ plan.problems.push({
128
+ check: 'CC23',
129
+ level: 'warn',
130
+ message:
131
+ onDemand.length > 0
132
+ ? `On the Free plan, previews and your on-demand routes (${onDemand.join(', ')}) share one daily request quota; a flood of preview requests can stop those routes until 00:00 UTC. Cloudflare Workers Paid removes the daily limit.`
133
+ : "On the Cloudflare Workers Free plan, a preview page over 10 ms of CPU fails, and a flood of preview requests can use up the day's requests and pause preview, never the published pages, until the quota resets: the Paid plan avoids both",
134
+ });
135
+ }
136
+ return [limited, plan];
137
+ }
@@ -0,0 +1,77 @@
1
+ import { join } from 'node:path';
2
+ import { isRecord } from '@conloca/content-api/component-vocabulary';
3
+ import type { EditorPageInfo } from '@conloca/content-api/editor-host';
4
+ import { type ConfigScan, previewServeSetting } from './config-scan.js';
5
+ import { type CheckOutcome, type CloudDoctorContext, type DoctorDeps, outcomeOf, skipped } from './types.js';
6
+
7
+ interface Input {
8
+ context: CloudDoctorContext;
9
+ deps: DoctorDeps;
10
+ scan: ConfigScan;
11
+ /** The deployed site's conloca.json, when CC11 read it. */
12
+ info: EditorPageInfo | undefined;
13
+ }
14
+
15
+ /** sites.json's previewUrl for the default site's default locale, when it names one. */
16
+ function declaredPreviewUrl(contentRoot: string, deps: DoctorDeps): string | undefined {
17
+ let sites: unknown;
18
+ try {
19
+ sites = JSON.parse(deps.readFile(join(contentRoot, 'sites.json')));
20
+ } catch {
21
+ return undefined;
22
+ }
23
+ const all = isRecord(sites) && isRecord(sites.sites) ? sites.sites : {};
24
+ const names = Object.keys(all);
25
+ const site = all.default ?? (names.length === 1 ? all[names[0] ?? ''] : undefined);
26
+ if (!isRecord(site) || !isRecord(site.previewUrl) || typeof site.defaultLocale !== 'string') return undefined;
27
+ const value = site.previewUrl[site.defaultLocale];
28
+ return typeof value === 'string' ? value : undefined;
29
+ }
30
+
31
+ /** CC24, under --live only: the separate preview deploy answers its own conloca.json as D4, on the site's release. */
32
+ export async function runPreviewLiveChecks(input: Input): Promise<CheckOutcome[]> {
33
+ const { context, deps, scan } = input;
34
+ if (previewServeSetting(scan) !== 'd4') return [skipped('CC24', 'no separate preview deploy (D4)')];
35
+ const base = scan.kind === 'read' ? (scan.config.site.base ?? '/') : '/';
36
+ const release = outcomeOf('CC24');
37
+ const previewUrl = declaredPreviewUrl(context.contentRoot, deps);
38
+ if (previewUrl === undefined) {
39
+ release.problems.push({
40
+ check: 'CC24',
41
+ level: 'error',
42
+ message:
43
+ "sites.json names no previewUrl for the default locale: add the separate preview deploy's https:// address",
44
+ });
45
+ return [release];
46
+ }
47
+ // A base written without its trailing slash (`/docs`) still needs one before `_conloca`.
48
+ const url = `${previewUrl.replace(/\/+$/u, '')}${base.replace(/\/?$/u, '/')}_conloca/editor/conloca.json`;
49
+ let served: unknown;
50
+ try {
51
+ const answer = await deps.fetch(url, {
52
+ redirect: 'manual',
53
+ credentials: 'omit',
54
+ signal: AbortSignal.timeout(10_000),
55
+ });
56
+ served = answer.ok ? await answer.json() : undefined;
57
+ } catch {
58
+ served = undefined;
59
+ }
60
+ const preview = isRecord(served) && isRecord(served.preview) ? served.preview : undefined;
61
+ if (preview?.mode !== 'd4') {
62
+ release.problems.push({
63
+ check: 'CC24',
64
+ level: 'error',
65
+ message: `${url} does not serve as a separate preview deploy: build it with CONLOCA_PREVIEW_BUILD=1 and deploy it`,
66
+ });
67
+ } else if (isRecord(served) && input.info !== undefined && served.builtWith !== input.info.builtWith) {
68
+ release.problems.push({
69
+ check: 'CC24',
70
+ level: 'warn',
71
+ message: `the preview deploy runs ${String(served.builtWith)} and the site ${input.info.builtWith}: deploy both from the same commit`,
72
+ });
73
+ } else {
74
+ release.detail = 'the preview deploy answers as D4';
75
+ }
76
+ return [release];
77
+ }