@conloca/cloud-astro 0.2.4 → 0.2.6
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.
- package/README.md +69 -22
- package/dist/.build-inputs.json +36 -23
- package/dist/src/constants.d.ts +4 -4
- package/dist/src/constants.js +4 -4
- package/dist/src/d3-build.d.ts +6 -2
- package/dist/src/d3-build.d.ts.map +1 -1
- package/dist/src/d3-build.js +15 -11
- package/dist/src/d3-build.js.map +1 -1
- package/dist/src/d8-adapters.d.ts +10 -0
- package/dist/src/d8-adapters.d.ts.map +1 -0
- package/dist/src/d8-adapters.js +19 -0
- package/dist/src/d8-adapters.js.map +1 -0
- package/dist/src/d8-build.d.ts +99 -0
- package/dist/src/d8-build.d.ts.map +1 -0
- package/dist/src/d8-build.js +265 -0
- package/dist/src/d8-build.js.map +1 -0
- package/dist/src/d8-guards.d.ts +29 -0
- package/dist/src/d8-guards.d.ts.map +1 -0
- package/dist/src/d8-guards.js +145 -0
- package/dist/src/d8-guards.js.map +1 -0
- package/dist/src/d8-middleware.d.ts +7 -0
- package/dist/src/d8-middleware.d.ts.map +1 -0
- package/dist/src/d8-middleware.js +15 -0
- package/dist/src/d8-middleware.js.map +1 -0
- package/dist/src/d8-render.d.ts +9 -0
- package/dist/src/d8-render.d.ts.map +1 -0
- package/dist/src/d8-render.js +52 -0
- package/dist/src/d8-render.js.map +1 -0
- package/dist/src/doctor/checks-d8.d.ts +7 -0
- package/dist/src/doctor/checks-d8.d.ts.map +1 -0
- package/dist/src/doctor/checks-d8.js +240 -0
- package/dist/src/doctor/checks-d8.js.map +1 -0
- package/dist/src/doctor/checks-live.d.ts.map +1 -1
- package/dist/src/doctor/checks-live.js +3 -5
- package/dist/src/doctor/checks-live.js.map +1 -1
- package/dist/src/doctor/checks-offline.d.ts +2 -0
- package/dist/src/doctor/checks-offline.d.ts.map +1 -1
- package/dist/src/doctor/checks-offline.js +17 -8
- package/dist/src/doctor/checks-offline.js.map +1 -1
- package/dist/src/doctor/checks-preview-live.d.ts +7 -2
- package/dist/src/doctor/checks-preview-live.d.ts.map +1 -1
- package/dist/src/doctor/checks-preview-live.js +107 -7
- package/dist/src/doctor/checks-preview-live.js.map +1 -1
- package/dist/src/doctor/checks-preview.d.ts.map +1 -1
- package/dist/src/doctor/checks-preview.js +9 -4
- package/dist/src/doctor/checks-preview.js.map +1 -1
- package/dist/src/doctor/config-scan.d.ts +24 -6
- package/dist/src/doctor/config-scan.d.ts.map +1 -1
- package/dist/src/doctor/config-scan.js +89 -18
- package/dist/src/doctor/config-scan.js.map +1 -1
- package/dist/src/doctor/run.d.ts.map +1 -1
- package/dist/src/doctor/run.js +2 -0
- package/dist/src/doctor/run.js.map +1 -1
- package/dist/src/doctor/types.d.ts +7 -0
- package/dist/src/doctor/types.d.ts.map +1 -1
- package/dist/src/doctor/types.js +7 -0
- package/dist/src/doctor/types.js.map +1 -1
- package/dist/src/editor-page/emit.d.ts +4 -3
- package/dist/src/editor-page/emit.d.ts.map +1 -1
- package/dist/src/editor-page/emit.js +9 -9
- package/dist/src/editor-page/emit.js.map +1 -1
- package/dist/src/integration.d.ts.map +1 -1
- package/dist/src/integration.js +228 -124
- package/dist/src/integration.js.map +1 -1
- package/dist/src/node.d.ts +2 -0
- package/dist/src/node.d.ts.map +1 -1
- package/dist/src/node.js +4 -0
- package/dist/src/node.js.map +1 -1
- package/dist/src/preview/_resolve-opts.d.ts +26 -1
- package/dist/src/preview/_resolve-opts.d.ts.map +1 -1
- package/dist/src/preview/_resolve-opts.js.map +1 -1
- package/dist/src/preview/content-api.d.ts +15 -0
- package/dist/src/preview/content-api.d.ts.map +1 -1
- package/dist/src/preview/content-api.js +57 -6
- package/dist/src/preview/content-api.js.map +1 -1
- package/dist/src/preview/d8-middleware.d.ts +25 -0
- package/dist/src/preview/d8-middleware.d.ts.map +1 -0
- package/dist/src/preview/d8-middleware.js +94 -0
- package/dist/src/preview/d8-middleware.js.map +1 -0
- package/dist/src/preview/dispatcher.d.ts +3 -16
- package/dist/src/preview/dispatcher.d.ts.map +1 -1
- package/dist/src/preview/dispatcher.js +46 -134
- package/dist/src/preview/dispatcher.js.map +1 -1
- package/dist/src/preview/headers.d.ts +3 -0
- package/dist/src/preview/headers.d.ts.map +1 -1
- package/dist/src/preview/headers.js +10 -1
- package/dist/src/preview/headers.js.map +1 -1
- package/dist/src/preview/links.d.ts +23 -0
- package/dist/src/preview/links.d.ts.map +1 -0
- package/dist/src/preview/links.js +168 -0
- package/dist/src/preview/links.js.map +1 -0
- package/dist/src/preview/middleware.d.ts +9 -3
- package/dist/src/preview/middleware.d.ts.map +1 -1
- package/dist/src/preview/middleware.js +36 -16
- package/dist/src/preview/middleware.js.map +1 -1
- package/dist/src/preview/prefix-router.d.ts +67 -0
- package/dist/src/preview/prefix-router.d.ts.map +1 -0
- package/dist/src/preview/prefix-router.js +153 -0
- package/dist/src/preview/prefix-router.js.map +1 -0
- package/dist/src/preview/preview-path.d.ts +8 -3
- package/dist/src/preview/preview-path.d.ts.map +1 -1
- package/dist/src/preview/preview-path.js +16 -4
- package/dist/src/preview/preview-path.js.map +1 -1
- package/dist/src/preview/site-middleware.d.ts +8 -2
- package/dist/src/preview/site-middleware.d.ts.map +1 -1
- package/dist/src/preview/site-middleware.js +90 -31
- package/dist/src/preview/site-middleware.js.map +1 -1
- package/dist/src/preview/site-page-sources.d.ts +21 -0
- package/dist/src/preview/site-page-sources.d.ts.map +1 -0
- package/dist/src/preview/site-page-sources.js +129 -0
- package/dist/src/preview/site-page-sources.js.map +1 -0
- package/dist/src/preview/site-pages.d.ts +18 -0
- package/dist/src/preview/site-pages.d.ts.map +1 -0
- package/dist/src/preview/site-pages.js +7 -0
- package/dist/src/preview/site-pages.js.map +1 -0
- package/dist/src/preview-build.d.ts +17 -16
- package/dist/src/preview-build.d.ts.map +1 -1
- package/dist/src/preview-build.js +37 -40
- package/dist/src/preview-build.js.map +1 -1
- package/dist/src/preview-image-endpoint.d.ts +8 -0
- package/dist/src/preview-image-endpoint.d.ts.map +1 -0
- package/dist/src/preview-image-endpoint.js +34 -0
- package/dist/src/preview-image-endpoint.js.map +1 -0
- package/dist/src/preview-render-seams.d.ts +7 -0
- package/dist/src/preview-render-seams.d.ts.map +1 -0
- package/dist/src/preview-render-seams.js +27 -0
- package/dist/src/preview-render-seams.js.map +1 -0
- package/dist/src/site-middleware.d.ts +2 -4
- package/dist/src/site-middleware.d.ts.map +1 -1
- package/dist/src/site-middleware.js +6 -22
- package/dist/src/site-middleware.js.map +1 -1
- package/dist/src/types.d.ts +15 -16
- package/dist/src/types.d.ts.map +1 -1
- package/package.json +138 -6
- package/src/constants.ts +4 -4
- package/src/d3-build.ts +20 -14
- package/src/d8-adapters.ts +19 -0
- package/src/d8-build.ts +356 -0
- package/src/d8-guards.ts +177 -0
- package/src/d8-middleware.ts +17 -0
- package/src/d8-render.ts +61 -0
- package/src/doctor/checks-d8.ts +256 -0
- package/src/doctor/checks-live.ts +3 -4
- package/src/doctor/checks-offline.ts +21 -8
- package/src/doctor/checks-preview-live.ts +114 -8
- package/src/doctor/checks-preview.ts +9 -4
- package/src/doctor/config-scan.ts +86 -15
- package/src/doctor/run.ts +2 -0
- package/src/doctor/types.ts +8 -0
- package/src/editor-page/emit.ts +23 -14
- package/src/integration.ts +274 -135
- package/src/node.ts +4 -0
- package/src/preview/_resolve-opts.ts +17 -1
- package/src/preview/content-api.ts +60 -5
- package/src/preview/d8-middleware.ts +124 -0
- package/src/preview/dispatcher.ts +55 -150
- package/src/preview/headers.ts +10 -1
- package/src/preview/links.ts +175 -0
- package/src/preview/middleware.ts +41 -19
- package/src/preview/prefix-router.ts +197 -0
- package/src/preview/preview-path.ts +24 -6
- package/src/preview/site-middleware.ts +109 -38
- package/src/preview/site-page-sources.ts +146 -0
- package/src/preview/site-pages.ts +22 -0
- package/src/preview-build.ts +43 -42
- package/src/preview-image-endpoint.ts +35 -0
- package/src/preview-render-seams.ts +31 -0
- package/src/site-middleware.ts +6 -24
- package/src/skill/SKILL.md +19 -1
- package/src/types.ts +15 -16
- package/src/virtual-modules.d.ts +17 -2
|
@@ -17,6 +17,7 @@ import type {
|
|
|
17
17
|
UpdateLocaleInput,
|
|
18
18
|
UpdateResult,
|
|
19
19
|
} from '@conloca/content-api';
|
|
20
|
+
import { DRAFT_MEDIA_REF_BASE, mediaRefPath } from '@conloca/content-api';
|
|
20
21
|
import type { PreviewContext } from './middleware.js';
|
|
21
22
|
|
|
22
23
|
/**
|
|
@@ -58,6 +59,8 @@ export interface PreviewContentAPIOptions {
|
|
|
58
59
|
baselineApi: ContentAPI;
|
|
59
60
|
embeddedPayloads?: ReadonlyMap<string, LocalizedEntry>;
|
|
60
61
|
fetchFn?: typeof fetch;
|
|
62
|
+
/** Where the draft's images are served (`<route>/__media/`); with a baked list, the media folder images deployed. */
|
|
63
|
+
media?: { route: string; refBase?: string; deployed?: ReadonlySet<string> };
|
|
61
64
|
}
|
|
62
65
|
|
|
63
66
|
/**
|
|
@@ -88,6 +91,8 @@ export class PreviewContentAPI implements ContentAPI {
|
|
|
88
91
|
/** The branch's page set, once {@link loadBranchManifests} has run. */
|
|
89
92
|
private branchManifests?: ContentManifest[];
|
|
90
93
|
private readonly localizedReads = new Map<string, Promise<LocalizedEntry | null>>();
|
|
94
|
+
/** Embedded entries rewritten once per render, not on every read. */
|
|
95
|
+
private readonly embeddedRewritten = new Map<string, LocalizedEntry>();
|
|
91
96
|
|
|
92
97
|
constructor(opts: PreviewContentAPIOptions) {
|
|
93
98
|
this.opts = opts;
|
|
@@ -126,8 +131,13 @@ export class PreviewContentAPI implements ContentAPI {
|
|
|
126
131
|
}
|
|
127
132
|
|
|
128
133
|
async getLocalized(id: string, locale: string): Promise<LocalizedEntry | null> {
|
|
129
|
-
const
|
|
130
|
-
|
|
134
|
+
const key = embeddedKey(id, locale);
|
|
135
|
+
const embedded = this.opts.embeddedPayloads?.get(key);
|
|
136
|
+
if (embedded) {
|
|
137
|
+
const rewritten = this.embeddedRewritten.get(key) ?? this.withDraftMedia(embedded);
|
|
138
|
+
this.embeddedRewritten.set(key, rewritten);
|
|
139
|
+
return rewritten;
|
|
140
|
+
}
|
|
131
141
|
|
|
132
142
|
// Request-scoped memoization (the instance lives for one render, so this
|
|
133
143
|
// is not a long-lived cache): the render enumerates the
|
|
@@ -135,7 +145,6 @@ export class PreviewContentAPI implements ContentAPI {
|
|
|
135
145
|
// reads — and every duplicate would be another round trip to the endpoint
|
|
136
146
|
// against the Cloudflare Workers subrequest budget. Failures are evicted so a later read
|
|
137
147
|
// can retry.
|
|
138
|
-
const key = embeddedKey(id, locale);
|
|
139
148
|
const inFlight = this.localizedReads.get(key);
|
|
140
149
|
if (inFlight) return inFlight;
|
|
141
150
|
const read = this.fetchLocalized(id, locale);
|
|
@@ -161,7 +170,15 @@ export class PreviewContentAPI implements ContentAPI {
|
|
|
161
170
|
if (!isLocalizedEntry(data)) {
|
|
162
171
|
throw new Error(`preview fetch ${id}/${locale}: malformed payload`);
|
|
163
172
|
}
|
|
164
|
-
return data;
|
|
173
|
+
return this.withDraftMedia(data);
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/** Only the endpoint's entries: the baseline's images are the build's own. */
|
|
177
|
+
private withDraftMedia(entry: LocalizedEntry): LocalizedEntry {
|
|
178
|
+
if (this.opts.media === undefined) return entry;
|
|
179
|
+
const rewritten: unknown = JSON.parse(rewriteDraftMedia(JSON.stringify(entry), this.opts.media));
|
|
180
|
+
// Only strings change, so the shape holds; the check keeps the type honest.
|
|
181
|
+
return isLocalizedEntry(rewritten) ? rewritten : entry;
|
|
165
182
|
}
|
|
166
183
|
|
|
167
184
|
async getContentAsBuffer(
|
|
@@ -202,7 +219,9 @@ export class PreviewContentAPI implements ContentAPI {
|
|
|
202
219
|
headers: { authorization: `Bearer ${this.opts.ctx.jwt}` },
|
|
203
220
|
});
|
|
204
221
|
if (!response.ok) return;
|
|
205
|
-
|
|
222
|
+
// Listing cards read the manifests' meta, so their draft images move too.
|
|
223
|
+
const text = await response.text();
|
|
224
|
+
const data: unknown = JSON.parse(this.opts.media === undefined ? text : rewriteDraftMedia(text, this.opts.media));
|
|
206
225
|
if (Array.isArray(data)) this.branchManifests = data as ContentManifest[];
|
|
207
226
|
} catch {
|
|
208
227
|
// Network/parse failure — keep the baseline listing.
|
|
@@ -273,6 +292,42 @@ export function embeddedKey(id: string, locale: string): string {
|
|
|
273
292
|
return `${id} ${locale}`;
|
|
274
293
|
}
|
|
275
294
|
|
|
295
|
+
/**
|
|
296
|
+
* Point a draft's images at the preview media route: every draft address, and every media-folder image link whose file
|
|
297
|
+
* the build did not deploy (committed on the branch only).
|
|
298
|
+
*/
|
|
299
|
+
export function rewriteDraftMedia(json: string, media: NonNullable<PreviewContentAPIOptions['media']>): string {
|
|
300
|
+
const target = `${media.route}/__media/`;
|
|
301
|
+
// A link starts the value, follows a delimiter or a JSON escape (`\n`): never inside another URL.
|
|
302
|
+
const start = '(?:(?<=\\\\[nrt])|(?<![\\w./-]))';
|
|
303
|
+
const drafted = json.replace(new RegExp(`${start}${escapeRegExp(DRAFT_MEDIA_REF_BASE)}/`, 'g'), target);
|
|
304
|
+
const { refBase, deployed } = media;
|
|
305
|
+
// Unbaked, or an empty base (the whole site root): only draft links are known to be media.
|
|
306
|
+
if (refBase === undefined || refBase === '' || deployed === undefined) return drafted;
|
|
307
|
+
// Media-folder links start the same way, and run to the next delimiter.
|
|
308
|
+
const links = new RegExp(`${start}${escapeRegExp(refBase)}/[^\\s"'\\\\()<>\\[\\]]+`, 'g');
|
|
309
|
+
return drafted.replace(links, (link) => {
|
|
310
|
+
const path = mediaRefPath(link, refBase);
|
|
311
|
+
if (path === undefined || link.startsWith(target) || deployed.has(path) || deployed.has(decodedPath(path))) {
|
|
312
|
+
return link;
|
|
313
|
+
}
|
|
314
|
+
return `${target}${path}`;
|
|
315
|
+
});
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
/** The file name a link names (`my%20pic.png` → `my pic.png`); a malformed escape is taken as written. */
|
|
319
|
+
function decodedPath(path: string): string {
|
|
320
|
+
try {
|
|
321
|
+
return decodeURIComponent(path);
|
|
322
|
+
} catch {
|
|
323
|
+
return path;
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
function escapeRegExp(text: string): string {
|
|
328
|
+
return text.replace(/[.*+?^${}()|[\]\\/]/g, '\\$&');
|
|
329
|
+
}
|
|
330
|
+
|
|
276
331
|
/**
|
|
277
332
|
* Lift a localized entry into the `LocaleVersion & { content }` shape that
|
|
278
333
|
* `ContentEntry.locales` expects. The entry is already the right shape — the
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The d8 front: the middleware a d8 site runs on every request. Off the preview route it returns `next()` before
|
|
3
|
+
* anything else runs; under it, the exit, the landing page, entry links and non-navigation requests are answered here,
|
|
4
|
+
* and only a navigation that holds a pass loads the draft render. A render that fails to load or throws answers
|
|
5
|
+
* "Preview couldn't load the draft", never the host's error page.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { type BakedPreviewOpts, resolveEndpointFetch, resolveFromBaked } from './_resolve-opts.js';
|
|
9
|
+
import { applyPreviewHeaders } from './headers.js';
|
|
10
|
+
import { renderNoPreviewLanding } from './landing.js';
|
|
11
|
+
import { isNavigation } from './links.js';
|
|
12
|
+
import { handlePreviewRequest, type PreviewMiddlewareOptions } from './middleware.js';
|
|
13
|
+
import {
|
|
14
|
+
answerExit,
|
|
15
|
+
finishEntry,
|
|
16
|
+
holdsPreviewCredential,
|
|
17
|
+
mediaImageRedirect,
|
|
18
|
+
previewUnavailable,
|
|
19
|
+
routePrefixed,
|
|
20
|
+
serveDraftMedia,
|
|
21
|
+
} from './prefix-router.js';
|
|
22
|
+
import { previewRoutePrefix } from './preview-path.js';
|
|
23
|
+
import type { PreviewMiddlewareContext } from './site-middleware.js';
|
|
24
|
+
|
|
25
|
+
export interface D8Context {
|
|
26
|
+
request: Request;
|
|
27
|
+
url: URL;
|
|
28
|
+
isPrerendered: boolean;
|
|
29
|
+
/** Astro's `locals`: the draft render puts the preview context and the branch reader here. */
|
|
30
|
+
locals: PreviewMiddlewareContext['locals'];
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export interface D8RenderModule {
|
|
34
|
+
render(context: D8Context, next: () => Promise<Response>, slug: string | undefined): Promise<Response>;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export interface D8Deps {
|
|
38
|
+
loadRender: () => Promise<D8RenderModule>;
|
|
39
|
+
env: (name: string) => string | undefined;
|
|
40
|
+
fetchFn?: typeof fetch;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function createD8Middleware(baked: BakedPreviewOpts, deps: D8Deps) {
|
|
44
|
+
const base = baked.base || '/';
|
|
45
|
+
const prefix = previewRoutePrefix(base);
|
|
46
|
+
const root = base.replace(/\/+$/u, '');
|
|
47
|
+
const hosts = new Set(baked.domains ?? []);
|
|
48
|
+
|
|
49
|
+
return async (context: D8Context, next: () => Promise<Response>): Promise<Response> => {
|
|
50
|
+
if (context.isPrerendered) return next();
|
|
51
|
+
const { request, url } = context;
|
|
52
|
+
const at = routePrefixed(url, base, 'd8');
|
|
53
|
+
// `<prefix>/_image` is Astro's image endpoint: the pass cookie's path never covers it, so there is nothing to check.
|
|
54
|
+
// Its answer still carries the preview headers: Cloudflare's passthrough endpoint sets none of its own.
|
|
55
|
+
if (at.kind === 'outside') return next();
|
|
56
|
+
if (at.kind === 'image') return mediaImageRedirect(url, base, 'd8') ?? applyPreviewHeaders(await next());
|
|
57
|
+
if (at.kind === 'exit') {
|
|
58
|
+
let opts: PreviewMiddlewareOptions | null = null;
|
|
59
|
+
try {
|
|
60
|
+
opts = resolveFromBaked(baked, deps.env);
|
|
61
|
+
} catch {
|
|
62
|
+
// Unbaked: answered without a label, so Conloca reads "no preview server".
|
|
63
|
+
}
|
|
64
|
+
const exit =
|
|
65
|
+
opts === null
|
|
66
|
+
? null
|
|
67
|
+
: { repo: opts.repo, siteId: opts.siteId, branch: opts.branch, audience: opts.saasAudience };
|
|
68
|
+
// A failing label still answers a 302 off the route, never the host's error page.
|
|
69
|
+
return answerExit(url, at.slug, exit, base, opts?.saasEndpoint ?? '', 'd8').catch(() =>
|
|
70
|
+
applyPreviewHeaders(new Response(null, { status: 302, headers: { location: base } })),
|
|
71
|
+
);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
if (at.kind === 'media') {
|
|
75
|
+
try {
|
|
76
|
+
const opts = resolveFromBaked(baked, deps.env);
|
|
77
|
+
const fetchFn = deps.fetchFn ?? (await resolveEndpointFetch()) ?? fetch;
|
|
78
|
+
return await serveDraftMedia(request, at, base, opts.saasEndpoint, fetchFn);
|
|
79
|
+
} catch (error) {
|
|
80
|
+
// An `<img>` gets no retry page: a bodiless 404.
|
|
81
|
+
console.error('@conloca/cloud-astro: the draft media read failed', error);
|
|
82
|
+
return applyPreviewHeaders(new Response(null, { status: 404 }));
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
const { inner, entering } = at;
|
|
87
|
+
const slug = at.kind === 'slugged' ? at.slug : undefined;
|
|
88
|
+
const route = at.kind === 'slugged' ? at.route : prefix;
|
|
89
|
+
const page = at.kind === 'slugged' ? at.page : url;
|
|
90
|
+
try {
|
|
91
|
+
const opts = resolveFromBaked(baked, deps.env);
|
|
92
|
+
const landing = () =>
|
|
93
|
+
applyPreviewHeaders(renderNoPreviewLanding({ pathname: inner, saasEndpoint: opts.saasEndpoint }));
|
|
94
|
+
if (entering) {
|
|
95
|
+
// The entry rules read the page under the bare route; a slugless entry takes its slug from the pass.
|
|
96
|
+
const entry = new Request(new URL(`${prefix}${inner.slice(root.length)}${url.search}`, url.origin).href, {
|
|
97
|
+
headers: request.headers,
|
|
98
|
+
});
|
|
99
|
+
const verdict = await handlePreviewRequest(entry, {
|
|
100
|
+
...opts,
|
|
101
|
+
mode: 'd8',
|
|
102
|
+
...(slug === undefined ? {} : { slug }),
|
|
103
|
+
onMiss: 'landing',
|
|
104
|
+
fetchFn: deps.fetchFn ?? (await resolveEndpointFetch()),
|
|
105
|
+
});
|
|
106
|
+
if (verdict.kind !== 'preview')
|
|
107
|
+
return finishEntry(verdict.kind === 'response' ? verdict.response : landing(), page, route, root, hosts);
|
|
108
|
+
} else if (slug === undefined || !holdsPreviewCredential(request.headers.get('cookie'), 'd8', base, slug)) {
|
|
109
|
+
// Refused before the render loads: a request with no credential never pays for its start-up.
|
|
110
|
+
return landing();
|
|
111
|
+
}
|
|
112
|
+
// Scripts and images never read drafts, whatever the entry decided: they get the published bytes at the clean URL.
|
|
113
|
+
if (!isNavigation(request)) {
|
|
114
|
+
return applyPreviewHeaders(
|
|
115
|
+
new Response(null, { status: 302, headers: { location: `${page.pathname}${page.search}` } }),
|
|
116
|
+
);
|
|
117
|
+
}
|
|
118
|
+
return applyPreviewHeaders(await (await deps.loadRender()).render(context, next, slug));
|
|
119
|
+
} catch (error) {
|
|
120
|
+
console.error('@conloca/cloud-astro: the preview render failed', error);
|
|
121
|
+
return previewUnavailable(`${url.pathname}${url.search}`, `${route}/__exit?to=${encodeURIComponent(inner)}`);
|
|
122
|
+
}
|
|
123
|
+
};
|
|
124
|
+
}
|
|
@@ -8,29 +8,22 @@
|
|
|
8
8
|
* the preview server at their own path with the branch slug in a request header only it sets.
|
|
9
9
|
*/
|
|
10
10
|
|
|
11
|
-
import { branchOfPreviewSlug } from '@conloca/content-api/editor-host';
|
|
12
11
|
import { injectPreviewBanner } from './banner.js';
|
|
13
|
-
import {
|
|
14
|
-
import {
|
|
15
|
-
import {
|
|
12
|
+
import { applyPreviewHeaders } from './headers.js';
|
|
13
|
+
import { renderNoPreviewLanding } from './landing.js';
|
|
14
|
+
import { isNavigation, movedSrcset, previewHref } from './links.js';
|
|
16
15
|
import { handlePreviewRequest, type PreviewContext, type PreviewMiddlewareOptions } from './middleware.js';
|
|
17
16
|
import {
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
siteId: string;
|
|
29
|
-
branch: string;
|
|
30
|
-
audience: string;
|
|
31
|
-
/** The issuer every pass must name, when the integration options name one. */
|
|
32
|
-
issuer?: string;
|
|
33
|
-
}
|
|
17
|
+
answerExit,
|
|
18
|
+
finishEntry,
|
|
19
|
+
holdsPreviewCredential,
|
|
20
|
+
mediaImageRedirect,
|
|
21
|
+
type PreviewExit,
|
|
22
|
+
previewUnavailable,
|
|
23
|
+
routePrefixed,
|
|
24
|
+
serveDraftMedia,
|
|
25
|
+
} from './prefix-router.js';
|
|
26
|
+
import { normalizeTrailingSlash, PREVIEW_CODE_PARAM, PREVIEW_SLUG_HEADER, previewRoutePrefix } from './preview-path.js';
|
|
34
27
|
|
|
35
28
|
/** What the build writes next to the dispatcher (`.conloca/dispatcher/dispatcher.json`). */
|
|
36
29
|
export interface DispatcherConfig {
|
|
@@ -43,7 +36,7 @@ export interface DispatcherConfig {
|
|
|
43
36
|
/** Hosts sites.json declares: links to them are links to this site. */
|
|
44
37
|
domains: string[];
|
|
45
38
|
/** The exit route's values; null when the preview build failed, so the probe reads "no preview server". */
|
|
46
|
-
exit:
|
|
39
|
+
exit: PreviewExit | null;
|
|
47
40
|
}
|
|
48
41
|
|
|
49
42
|
/** A Cloudflare Workers rate-limit binding, as the dispatcher calls it. */
|
|
@@ -117,70 +110,7 @@ interface Attributes {
|
|
|
117
110
|
setAttribute(name: string, value: string): void;
|
|
118
111
|
}
|
|
119
112
|
|
|
120
|
-
|
|
121
|
-
* `value` under the preview route when it names a page of this site, else null (left as it is). It is resolved
|
|
122
|
-
* against `page`, the unprefixed URL the page was rendered for, so `../x` and `?q` keep their meaning. Files, built
|
|
123
|
-
* assets, the image endpoint, `/_conloca/` and other sites stay where they are.
|
|
124
|
-
*/
|
|
125
|
-
export function previewHref(
|
|
126
|
-
value: string,
|
|
127
|
-
page: URL,
|
|
128
|
-
route: string,
|
|
129
|
-
root: string,
|
|
130
|
-
hosts: ReadonlySet<string>,
|
|
131
|
-
): string | null {
|
|
132
|
-
if (value === '' || value.startsWith('#')) return null;
|
|
133
|
-
let target: URL;
|
|
134
|
-
try {
|
|
135
|
-
target = new URL(value, page);
|
|
136
|
-
} catch {
|
|
137
|
-
return null;
|
|
138
|
-
}
|
|
139
|
-
if (target.protocol !== 'http:' && target.protocol !== 'https:') return null;
|
|
140
|
-
const own = target.host === page.host;
|
|
141
|
-
if (!own && !hosts.has(target.hostname)) return null;
|
|
142
|
-
const { pathname } = target;
|
|
143
|
-
if (root !== '' && pathname !== root && !pathname.startsWith(`${root}/`)) return null;
|
|
144
|
-
const rest = pathname.slice(root.length) || '/';
|
|
145
|
-
if (rest.startsWith('/_conloca/') || rest.startsWith('/_astro/') || rest === '/_image') return null;
|
|
146
|
-
const last = rest.slice(rest.lastIndexOf('/') + 1);
|
|
147
|
-
if (last.includes('.') && !last.endsWith('.html')) return null;
|
|
148
|
-
const moved = `${route}${rest}${target.search}${target.hash}`;
|
|
149
|
-
return own ? moved : `${target.origin}${moved}`;
|
|
150
|
-
}
|
|
151
|
-
|
|
152
|
-
/** A navigation, the only request that may receive draft HTML; without Sec-Fetch-*, one that asks for HTML. */
|
|
153
|
-
function isNavigation(request: Request): boolean {
|
|
154
|
-
const mode = request.headers.get('sec-fetch-mode');
|
|
155
|
-
if (mode !== null) return mode === 'navigate';
|
|
156
|
-
return (request.headers.get('accept') ?? '').includes('text/html');
|
|
157
|
-
}
|
|
158
|
-
|
|
159
|
-
/**
|
|
160
|
-
* `srcset` with each candidate URL that `move` answers for replaced, everything else kept byte for byte; null when none
|
|
161
|
-
* moved. A URL runs to the next whitespace, as the HTML parser reads it, so a `data:` URL's commas stay inside it.
|
|
162
|
-
*/
|
|
163
|
-
function movedSrcset(value: string, move: (href: string) => string | null): string | null {
|
|
164
|
-
let out = '';
|
|
165
|
-
let rest = value;
|
|
166
|
-
let moved = false;
|
|
167
|
-
while (rest !== '') {
|
|
168
|
-
const gap = /^[\s,]*/u.exec(rest)?.[0] ?? '';
|
|
169
|
-
const token = /^\S*/u.exec(rest.slice(gap.length))?.[0] ?? '';
|
|
170
|
-
const commas = /,*$/u.exec(token)?.[0] ?? '';
|
|
171
|
-
const href = token.slice(0, token.length - commas.length);
|
|
172
|
-
rest = rest.slice(gap.length + token.length);
|
|
173
|
-
// Descriptors (`1x`, `400w`) run to the next comma, unless the URL already ended at one.
|
|
174
|
-
const descriptor = commas === '' ? (/^[^,]*/u.exec(rest)?.[0] ?? '') : '';
|
|
175
|
-
rest = rest.slice(descriptor.length);
|
|
176
|
-
const target = href === '' ? null : move(href);
|
|
177
|
-
if (target !== null) moved = true;
|
|
178
|
-
out += `${gap}${target ?? href}${commas}${descriptor}`;
|
|
179
|
-
}
|
|
180
|
-
return moved ? out : null;
|
|
181
|
-
}
|
|
182
|
-
|
|
183
|
-
function linkRewriter(page: URL, route: string, root: string, hosts: ReadonlySet<string>): HTMLRewriter {
|
|
113
|
+
export function linkRewriter(page: URL, route: string, root: string, hosts: ReadonlySet<string>): HTMLRewriter {
|
|
184
114
|
// A `<base href>` changes what relative links resolve against for every link after it.
|
|
185
115
|
let resolveAgainst = page;
|
|
186
116
|
const move = (element: Attributes, name: string): boolean => {
|
|
@@ -221,7 +151,7 @@ function linkRewriter(page: URL, route: string, root: string, hosts: ReadonlySet
|
|
|
221
151
|
/** How the dispatcher checks a pass: with the values the preview build baked, and the overrides its server reads. */
|
|
222
152
|
function passOptions(
|
|
223
153
|
config: DispatcherConfig,
|
|
224
|
-
exit:
|
|
154
|
+
exit: PreviewExit,
|
|
225
155
|
env: DispatcherEnv,
|
|
226
156
|
slug: string,
|
|
227
157
|
): PreviewMiddlewareOptions {
|
|
@@ -255,37 +185,6 @@ export function createDispatcher(config: DispatcherConfig, loadServer: (() => Pr
|
|
|
255
185
|
const prerendered = new Set(config.prerendered);
|
|
256
186
|
const hosts = new Set(config.domains);
|
|
257
187
|
|
|
258
|
-
/** The exit route, from the build's own values: the probe never waits for the preview server. */
|
|
259
|
-
async function exit(url: URL, slug: string | undefined): Promise<Response> {
|
|
260
|
-
if (config.exit === null) {
|
|
261
|
-
// No label: Conloca reads "no preview server" and says so, instead of minting a link to a 503 page.
|
|
262
|
-
return new Response(null, { status: 302, headers: { location: config.base, ...PREVIEW_CACHE_HEADERS } });
|
|
263
|
-
}
|
|
264
|
-
const verdict = await handlePreviewRequest(new Request(`${url.origin}${prefix}/__exit${url.search}`), {
|
|
265
|
-
saasEndpoint: config.endpoint,
|
|
266
|
-
saasAudience: config.exit.audience,
|
|
267
|
-
repo: config.exit.repo,
|
|
268
|
-
siteId: config.exit.siteId,
|
|
269
|
-
branch: config.exit.branch,
|
|
270
|
-
base: config.base,
|
|
271
|
-
mode: 'd3',
|
|
272
|
-
...(slug === undefined ? {} : { slug }),
|
|
273
|
-
});
|
|
274
|
-
// The exit branch always answers a response; anything else would be a bug in this call, so fail closed.
|
|
275
|
-
return verdict.kind === 'response'
|
|
276
|
-
? applyPreviewHeaders(verdict.response)
|
|
277
|
-
: applyPreviewHeaders(new Response(null, { status: 302, headers: { location: config.base } }));
|
|
278
|
-
}
|
|
279
|
-
|
|
280
|
-
/** An entry answer (a redirect or Conloca's own page): headers and `Location` only, never its HTML. */
|
|
281
|
-
function finishEntry(answer: Response, page: URL, route: string): Response {
|
|
282
|
-
const out = applyPreviewHeaders(answer);
|
|
283
|
-
const location = out.headers.get('location');
|
|
284
|
-
const moved = location === null ? null : previewHref(location, page, route, root, hosts);
|
|
285
|
-
if (moved !== null) out.headers.set('location', moved);
|
|
286
|
-
return out;
|
|
287
|
-
}
|
|
288
|
-
|
|
289
188
|
/** The draft answer with the route put back on its location and links. */
|
|
290
189
|
async function finish(
|
|
291
190
|
answer: Response,
|
|
@@ -293,7 +192,7 @@ export function createDispatcher(config: DispatcherConfig, loadServer: (() => Pr
|
|
|
293
192
|
route: string,
|
|
294
193
|
published: Pick<PreviewContext, 'branch' | 'grant'> | null,
|
|
295
194
|
): Promise<Response> {
|
|
296
|
-
const out = finishEntry(answer, page, route);
|
|
195
|
+
const out = finishEntry(answer, page, route, root, hosts);
|
|
297
196
|
if (!(out.headers.get('content-type') ?? '').includes('text/html')) return out;
|
|
298
197
|
const rewriter = linkRewriter(page, route, root, hosts);
|
|
299
198
|
if (published === null) return rewriter.transform(out);
|
|
@@ -324,32 +223,46 @@ export function createDispatcher(config: DispatcherConfig, loadServer: (() => Pr
|
|
|
324
223
|
return (await load()).default.fetch(forwarded, env, ctx);
|
|
325
224
|
};
|
|
326
225
|
|
|
327
|
-
|
|
226
|
+
let at = routePrefixed(url, config.base, 'd3');
|
|
227
|
+
if (at.kind === 'outside') {
|
|
328
228
|
// `<base>_image` is listed for draft pages only (the live site's pages are prerendered), so it is the
|
|
329
229
|
// preview's to pay for: it counts against the preview route's limit.
|
|
330
230
|
if (url.pathname === `${root}/_image` && !(await withinLimit(request, env)))
|
|
331
231
|
return renderTooManyPreviewRequests();
|
|
232
|
+
// Under D3 a draft's `<Image>` of branch media points here; only the route can read it.
|
|
233
|
+
if (url.pathname === `${root}/_image`) {
|
|
234
|
+
const media = mediaImageRedirect(url, config.base, 'd3');
|
|
235
|
+
if (media !== null) return media;
|
|
236
|
+
}
|
|
332
237
|
// The site's own on-demand routes (and, with not_found_handling "none", its misses): unprefixed, no draft
|
|
333
238
|
// context, and no catch: production fails loudly here. A failed preview build ships with a null server only
|
|
334
239
|
// when the site lists nothing beyond the prefix (`finishD3Build`), so this fallback is never a live API route.
|
|
335
240
|
return loadServer === null ? env.ASSETS.fetch(request) : forward(loadServer, url, undefined);
|
|
336
241
|
}
|
|
337
|
-
const [first = '', ...rest] = url.pathname.slice(prefix.length + 1).split('/');
|
|
338
242
|
// The probe, and a page's own exit: answered here, never counted, never loading the server.
|
|
339
|
-
if (
|
|
340
|
-
|
|
341
|
-
if (
|
|
243
|
+
if (at.kind === 'exit') return answerExit(url, at.slug, config.exit, config.base, config.endpoint, 'd3');
|
|
244
|
+
// D3's image endpoint is `<base>_image`: under the route `_image` is a stray path, as any other slugless one.
|
|
245
|
+
if (at.kind === 'image')
|
|
246
|
+
at = { kind: 'slugless', inner: `${root}/_image`, entering: url.searchParams.has(PREVIEW_CODE_PARAM) };
|
|
342
247
|
|
|
343
248
|
// Every other request under the route counts, `__status` included, before any other work.
|
|
344
|
-
if (!(await withinLimit(request, env)))
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
249
|
+
if (!(await withinLimit(request, env))) {
|
|
250
|
+
// An `<img>` gets no HTML page.
|
|
251
|
+
return at.kind === 'media'
|
|
252
|
+
? applyPreviewHeaders(new Response(null, { status: 429 }))
|
|
253
|
+
: renderTooManyPreviewRequests();
|
|
254
|
+
}
|
|
255
|
+
if (at.kind === 'media') {
|
|
256
|
+
const binding = env.CONLOCA_SAAS;
|
|
257
|
+
const fetchFn =
|
|
258
|
+
binding === undefined ? fetch : Object.assign(binding.fetch.bind(binding), { preconnect: fetch.preconnect });
|
|
259
|
+
// Never throws: a failing endpoint is logged and answered with a bodiless 404.
|
|
260
|
+
return serveDraftMedia(request, at, config.base, env.CONLOCA_SAAS_ENDPOINT || config.endpoint, fetchFn);
|
|
352
261
|
}
|
|
262
|
+
const { inner, entering } = at;
|
|
263
|
+
const route = at.kind === 'slugged' ? at.route : prefix;
|
|
264
|
+
const { exit: baked } = config;
|
|
265
|
+
if (loadServer === null || baked === null) return previewUnavailable(`${url.pathname}${url.search}`, config.base);
|
|
353
266
|
// Under the route a preview server that throws (a Node-only import, a render error) answers
|
|
354
267
|
// "Preview couldn't load the draft", never Cloudflare's own error page.
|
|
355
268
|
const guarded = async (target: URL, slug: string | undefined): Promise<Response> => {
|
|
@@ -357,34 +270,26 @@ export function createDispatcher(config: DispatcherConfig, loadServer: (() => Pr
|
|
|
357
270
|
return await forward(loadServer, target, slug);
|
|
358
271
|
} catch (error) {
|
|
359
272
|
console.error('@conloca/cloud-astro: the preview server failed', error);
|
|
360
|
-
|
|
361
|
-
retryHref: `${url.pathname}${url.search}`,
|
|
362
|
-
exitHref: `${route}/__exit?to=${encodeURIComponent(inner)}`,
|
|
363
|
-
});
|
|
364
|
-
return applyPreviewHeaders(new Response(page.body, { status: 503, headers: page.headers }));
|
|
273
|
+
return previewUnavailable(`${url.pathname}${url.search}`, `${route}/__exit?to=${encodeURIComponent(inner)}`);
|
|
365
274
|
}
|
|
366
275
|
};
|
|
367
276
|
const landing = () =>
|
|
368
277
|
applyPreviewHeaders(renderNoPreviewLanding({ pathname: inner, saasEndpoint: config.endpoint }));
|
|
369
278
|
|
|
370
|
-
if (
|
|
279
|
+
if (at.kind === 'slugless') {
|
|
371
280
|
// A slugless entry link: the preview server exchanges the code and takes the slug from the pass.
|
|
372
281
|
if (!entering) return landing();
|
|
373
|
-
return finishEntry(await guarded(url, undefined), url, prefix);
|
|
282
|
+
return finishEntry(await guarded(url, undefined), url, prefix, root, hosts);
|
|
374
283
|
}
|
|
375
|
-
const
|
|
376
|
-
const cookie = request.headers.get('cookie');
|
|
377
|
-
const holds =
|
|
378
|
-
parseCookieValues(cookie, scope.pass).length > 0 ||
|
|
379
|
-
(scope.grant !== null && parseCookieValues(cookie, scope.grant).length > 0);
|
|
284
|
+
const { slug, page } = at;
|
|
380
285
|
// Refused before the preview server loads: a request with no credential never pays for its start-up.
|
|
381
|
-
if (!entering && !
|
|
382
|
-
|
|
286
|
+
if (!entering && !holdsPreviewCredential(request.headers.get('cookie'), 'd3', config.base, slug))
|
|
287
|
+
return landing();
|
|
383
288
|
if (entering) {
|
|
384
289
|
// The adapter serves a prerendered page from the static files before any middleware runs, so the code goes
|
|
385
290
|
// to the preview build's entry route (`<prefix>/[...path]`, always on demand), as under D2.
|
|
386
291
|
const entry = new URL(`${prefix}${inner.slice(root.length)}${url.search}`, url.origin);
|
|
387
|
-
return finishEntry(await guarded(entry,
|
|
292
|
+
return finishEntry(await guarded(entry, slug), page, route, root, hosts);
|
|
388
293
|
}
|
|
389
294
|
if (!isNavigation(request)) {
|
|
390
295
|
// Scripts never read drafts: a fetch under the route gets published bytes.
|
|
@@ -395,13 +300,13 @@ export function createDispatcher(config: DispatcherConfig, loadServer: (() => Pr
|
|
|
395
300
|
// other: one that fails gets the landing page (or the share link's renewal), never the banner.
|
|
396
301
|
const verdict = await handlePreviewRequest(
|
|
397
302
|
new Request(page.href, { headers }),
|
|
398
|
-
passOptions(config, baked, env,
|
|
303
|
+
passOptions(config, baked, env, slug),
|
|
399
304
|
);
|
|
400
305
|
if (verdict.kind !== 'preview')
|
|
401
|
-
return finishEntry(verdict.kind === 'response' ? verdict.response : landing(), page,
|
|
402
|
-
return finish(await env.ASSETS.fetch(new Request(page.href, { headers })), page,
|
|
306
|
+
return finishEntry(verdict.kind === 'response' ? verdict.response : landing(), page, route, root, hosts);
|
|
307
|
+
return finish(await env.ASSETS.fetch(new Request(page.href, { headers })), page, route, verdict.ctx);
|
|
403
308
|
}
|
|
404
|
-
return finish(await guarded(page,
|
|
309
|
+
return finish(await guarded(page, slug), page, route, null);
|
|
405
310
|
},
|
|
406
311
|
};
|
|
407
312
|
}
|
package/src/preview/headers.ts
CHANGED
|
@@ -8,6 +8,8 @@
|
|
|
8
8
|
* - `cdn-cache-control: no-store` and `vercel-cdn-cache-control: no-store` —
|
|
9
9
|
* CDNs read these before `cache-control` (RFC 9213), so a site-wide CDN
|
|
10
10
|
* rule that caches pages can't cache a draft.
|
|
11
|
+
* - `netlify-cdn-cache-control: no-store` — Netlify reads its own name
|
|
12
|
+
* first, and `_headers` don't apply to function output.
|
|
11
13
|
* - `referrer-policy: same-origin` — a link out of a draft never tells
|
|
12
14
|
* another site the draft's address.
|
|
13
15
|
* - `vary: Cookie` — the same URL answers differently with and without the
|
|
@@ -17,6 +19,7 @@ export const PREVIEW_CACHE_HEADERS = {
|
|
|
17
19
|
'cache-control': 'private, no-store',
|
|
18
20
|
'cdn-cache-control': 'no-store',
|
|
19
21
|
'vercel-cdn-cache-control': 'no-store',
|
|
22
|
+
'netlify-cdn-cache-control': 'no-store',
|
|
20
23
|
'referrer-policy': 'same-origin',
|
|
21
24
|
vary: 'Cookie',
|
|
22
25
|
} as const;
|
|
@@ -45,7 +48,13 @@ export const PREVIEW_CACHE_HEADERS = {
|
|
|
45
48
|
export function applyPreviewHeaders(response: Response): Response {
|
|
46
49
|
const headers = new Headers(response.headers);
|
|
47
50
|
headers.set('x-robots-tag', 'noindex');
|
|
48
|
-
for (const name of [
|
|
51
|
+
for (const name of [
|
|
52
|
+
'cache-control',
|
|
53
|
+
'cdn-cache-control',
|
|
54
|
+
'vercel-cdn-cache-control',
|
|
55
|
+
'netlify-cdn-cache-control',
|
|
56
|
+
'referrer-policy',
|
|
57
|
+
] as const) {
|
|
49
58
|
headers.set(name, PREVIEW_CACHE_HEADERS[name]);
|
|
50
59
|
}
|
|
51
60
|
// Appended, so the site's own Vary and CSP survive; once, because the dispatcher wraps what the server wrapped.
|