mdorigin 0.5.2 → 0.5.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/adapters/cloudflare.d.ts +31 -2
- package/dist/adapters/cloudflare.js +287 -17
- package/dist/adapters/node.js +3 -0
- package/dist/cloudflare.js +10 -1
- package/dist/core/extensions.d.ts +2 -0
- package/dist/core/markdown.d.ts +23 -6
- package/dist/core/markdown.js +27 -2
- package/dist/core/request-handler.d.ts +3 -0
- package/dist/core/request-handler.js +157 -17
- package/dist/core/site-config.d.ts +14 -0
- package/dist/core/site-config.js +25 -2
- package/dist/html/template.js +1 -1
- package/package.json +1 -1
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { MdoPlugin } from '../core/extensions.js';
|
|
2
2
|
import type { ResolvedSiteConfig } from '../core/site-config.js';
|
|
3
|
-
import { type ExternalSearchBundleEntry, type SearchBundleEntry } from '../search.js';
|
|
3
|
+
import { type ExternalSearchBundleEntry, type SearchApi, type SearchBundleEntry } from '../search.js';
|
|
4
4
|
export interface TextCloudflareManifestEntry {
|
|
5
5
|
path: string;
|
|
6
6
|
kind: 'text';
|
|
@@ -32,6 +32,13 @@ export interface CloudflareManifest {
|
|
|
32
32
|
searchEntries?: SearchBundleEntry[];
|
|
33
33
|
externalSearchEntries?: ExternalSearchBundleEntry[];
|
|
34
34
|
runtime?: CloudflareBundleRuntimeConfig;
|
|
35
|
+
/**
|
|
36
|
+
* Build-time deploy version. Bundle content is immutable within one deploy,
|
|
37
|
+
* so this value doubles as a strong ETag and lets If-None-Match matches skip
|
|
38
|
+
* rendering entirely. A new deploy produces a new version and invalidates
|
|
39
|
+
* every cached response.
|
|
40
|
+
*/
|
|
41
|
+
deployVersion?: string;
|
|
35
42
|
}
|
|
36
43
|
export interface CloudflareAssetsBindingLike {
|
|
37
44
|
fetch(request: Request): Promise<Response>;
|
|
@@ -52,9 +59,31 @@ export interface CloudflareWorkerEnv {
|
|
|
52
59
|
[binding: string]: unknown;
|
|
53
60
|
}
|
|
54
61
|
export interface ExportedHandlerLike {
|
|
55
|
-
fetch(request: Request, env?: CloudflareWorkerEnv, ctx?:
|
|
62
|
+
fetch(request: Request, env?: CloudflareWorkerEnv, ctx?: CloudflareWorkerExecutionContextLike): Promise<Response>;
|
|
63
|
+
}
|
|
64
|
+
export interface CloudflareWorkerExecutionContextLike {
|
|
65
|
+
waitUntil(promise: Promise<unknown>): void;
|
|
66
|
+
}
|
|
67
|
+
export interface CloudflareCacheLike {
|
|
68
|
+
match(request: Request): Promise<Response | undefined>;
|
|
69
|
+
put(request: Request, response: Response): Promise<void>;
|
|
56
70
|
}
|
|
57
71
|
export interface CreateCloudflareWorkerOptions {
|
|
58
72
|
plugins?: MdoPlugin[];
|
|
73
|
+
/**
|
|
74
|
+
* Per-colo L2 cache. Defaults to the runtime `caches.default` when the
|
|
75
|
+
* runtime exposes one. Pass `null` to disable L2 caching.
|
|
76
|
+
*/
|
|
77
|
+
cache?: CloudflareCacheLike | null;
|
|
78
|
+
/** Maximum isolate-memoized rendered responses. Defaults to 100. */
|
|
79
|
+
responseCacheLimit?: number;
|
|
80
|
+
/** Maximum isolate-memoized search results. Defaults to 100. */
|
|
81
|
+
searchCacheLimit?: number;
|
|
59
82
|
}
|
|
60
83
|
export declare function createCloudflareWorker(manifest: CloudflareManifest, options?: CreateCloudflareWorkerOptions): ExportedHandlerLike;
|
|
84
|
+
/**
|
|
85
|
+
* Memoizes deterministic search results per isolate. The search index is
|
|
86
|
+
* static within one deploy, so identical (query, options) calls return the
|
|
87
|
+
* same hits and repeated queries skip retrieval entirely.
|
|
88
|
+
*/
|
|
89
|
+
export declare function withSearchResultCache(api: SearchApi, limit: number): SearchApi;
|
|
@@ -2,6 +2,21 @@ import { MemoryContentStore } from '../core/content-store.js';
|
|
|
2
2
|
import { handleSiteRequest } from '../core/request-handler.js';
|
|
3
3
|
import { resolveRequest } from '../core/router.js';
|
|
4
4
|
import { createSearchApiFromBundle, createSearchApiFromExternalBundle, } from '../search.js';
|
|
5
|
+
const BROWSER_CACHE_CONTROL = 'public, max-age=120, stale-while-revalidate=604800';
|
|
6
|
+
const CDN_CACHE_CONTROL = 'max-age=86400';
|
|
7
|
+
const L2_CACHE_CONTROL = 'public, max-age=86400';
|
|
8
|
+
const L2_CACHE_KEY_ORIGIN = 'https://cache.mdorigin.internal';
|
|
9
|
+
const CACHE_DEBUG_HEADER = 'x-mdorigin-cache';
|
|
10
|
+
const RESPONSE_CACHE_LIMIT_DEFAULT = 100;
|
|
11
|
+
const SEARCH_CACHE_LIMIT_DEFAULT = 100;
|
|
12
|
+
const CACHEABLE_CONTENT_TYPE_PREFIXES = [
|
|
13
|
+
'text/html',
|
|
14
|
+
'text/markdown',
|
|
15
|
+
'application/xml',
|
|
16
|
+
'text/xml',
|
|
17
|
+
'application/rss+xml',
|
|
18
|
+
'application/atom+xml',
|
|
19
|
+
];
|
|
5
20
|
export function createCloudflareWorker(manifest, options = {}) {
|
|
6
21
|
const storeIndex = new MemoryContentStore(manifest.entries.map((entry) => {
|
|
7
22
|
if (entry.kind === 'text') {
|
|
@@ -26,22 +41,63 @@ export function createCloudflareWorker(manifest, options = {}) {
|
|
|
26
41
|
bytes: decodeBase64(entry.base64 ?? ''),
|
|
27
42
|
};
|
|
28
43
|
}));
|
|
44
|
+
const responseCache = new LruCache(options.responseCacheLimit ?? RESPONSE_CACHE_LIMIT_DEFAULT);
|
|
45
|
+
const searchCacheLimit = options.searchCacheLimit ?? SEARCH_CACHE_LIMIT_DEFAULT;
|
|
46
|
+
const cache = options.cache === undefined ? resolveDefaultCache() : options.cache ?? undefined;
|
|
29
47
|
const inlineSearchApi = manifest.searchEntries && manifest.searchEntries.length > 0
|
|
30
|
-
? createSearchApiFromBundle(manifest.searchEntries, manifest.siteConfig?.search)
|
|
48
|
+
? withSearchResultCache(createSearchApiFromBundle(manifest.searchEntries, manifest.siteConfig?.search), searchCacheLimit)
|
|
31
49
|
: undefined;
|
|
32
50
|
const externalSearchApis = new WeakMap();
|
|
33
51
|
let defaultExternalSearchApi;
|
|
34
52
|
return {
|
|
35
|
-
async fetch(request, env) {
|
|
53
|
+
async fetch(request, env, ctx) {
|
|
36
54
|
const url = new URL(request.url);
|
|
37
|
-
const externalSearchApi = getExternalSearchApi(manifest, env, externalSearchApis, defaultExternalSearchApi);
|
|
55
|
+
const externalSearchApi = getExternalSearchApi(manifest, env, externalSearchApis, defaultExternalSearchApi, searchCacheLimit);
|
|
38
56
|
if (env === undefined && externalSearchApi !== undefined) {
|
|
39
57
|
defaultExternalSearchApi = externalSearchApi;
|
|
40
58
|
}
|
|
41
|
-
const
|
|
59
|
+
const resolvedRequest = resolveRequest(url.pathname);
|
|
60
|
+
const directBinaryResponse = await tryServeExternalBinary(manifest, request, env, resolvedRequest);
|
|
42
61
|
if (directBinaryResponse !== null) {
|
|
43
62
|
return directBinaryResponse;
|
|
44
63
|
}
|
|
64
|
+
const etag = manifest.deployVersion === undefined
|
|
65
|
+
? undefined
|
|
66
|
+
: `"${manifest.deployVersion}"`;
|
|
67
|
+
if (etag !== undefined &&
|
|
68
|
+
isCacheableRequest(request, url) &&
|
|
69
|
+
!isLocaleDetectionRequest(manifest, url) &&
|
|
70
|
+
requestMatchesEtag(request.headers.get('if-none-match'), etag)) {
|
|
71
|
+
return new Response(null, {
|
|
72
|
+
status: 304,
|
|
73
|
+
headers: {
|
|
74
|
+
etag,
|
|
75
|
+
'cache-control': BROWSER_CACHE_CONTROL,
|
|
76
|
+
},
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
const cacheDebugEnabled = isCacheDebugEnabled(env);
|
|
80
|
+
const responseCacheKey = manifest.deployVersion !== undefined &&
|
|
81
|
+
isCacheableRequest(request, url) &&
|
|
82
|
+
!isLocaleDetectionRequest(manifest, url)
|
|
83
|
+
? buildResponseCacheKey(manifest.deployVersion, resolvedRequest, request.headers.get('accept'), url.pathname)
|
|
84
|
+
: undefined;
|
|
85
|
+
if (responseCacheKey !== undefined) {
|
|
86
|
+
const memoized = responseCache.get(responseCacheKey);
|
|
87
|
+
if (memoized !== undefined) {
|
|
88
|
+
return toWorkerResponse(memoized, cacheDebugEnabled ? 'l1' : undefined);
|
|
89
|
+
}
|
|
90
|
+
if (cache !== undefined) {
|
|
91
|
+
const cached = await cache.match(toL2CacheRequest(responseCacheKey));
|
|
92
|
+
if (cached !== undefined) {
|
|
93
|
+
const entry = await cachedResponseFromL2(cached);
|
|
94
|
+
if (entry !== null) {
|
|
95
|
+
responseCache.set(responseCacheKey, entry);
|
|
96
|
+
return toWorkerResponse(entry, cacheDebugEnabled ? 'l2' : undefined);
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
}
|
|
45
101
|
const store = new CloudflareManifestContentStore(manifest, storeIndex, request, env);
|
|
46
102
|
const siteResponse = await handleSiteRequest(store, url.pathname, {
|
|
47
103
|
draftMode: 'exclude',
|
|
@@ -66,37 +122,252 @@ export function createCloudflareWorker(manifest, options = {}) {
|
|
|
66
122
|
siteDescriptionConfigured: false,
|
|
67
123
|
},
|
|
68
124
|
acceptHeader: request.headers.get('accept') ?? undefined,
|
|
125
|
+
acceptLanguageHeader: request.headers.get('accept-language') ?? undefined,
|
|
126
|
+
cookieHeader: request.headers.get('cookie') ?? undefined,
|
|
127
|
+
userAgentHeader: request.headers.get('user-agent') ?? undefined,
|
|
69
128
|
searchParams: url.searchParams,
|
|
70
129
|
requestUrl: request.url,
|
|
71
130
|
searchApi: inlineSearchApi ?? externalSearchApi,
|
|
72
131
|
plugins: options.plugins,
|
|
73
132
|
});
|
|
74
133
|
const headers = new Headers(siteResponse.headers);
|
|
75
|
-
const
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
134
|
+
const cacheHeaders = collectResponseCacheHeaders(siteResponse, request, url, etag);
|
|
135
|
+
if (cacheHeaders !== undefined) {
|
|
136
|
+
for (const [name, value] of Object.entries(cacheHeaders)) {
|
|
137
|
+
headers.set(name, value);
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
const rendered = {
|
|
81
141
|
status: siteResponse.status,
|
|
82
|
-
headers,
|
|
83
|
-
|
|
142
|
+
headers: Object.fromEntries(headers.entries()),
|
|
143
|
+
body: siteResponse.body ?? '',
|
|
144
|
+
};
|
|
145
|
+
if (responseCacheKey !== undefined &&
|
|
146
|
+
siteResponse.status === 200 &&
|
|
147
|
+
isCacheableContentType(siteResponse.headers['content-type'])) {
|
|
148
|
+
responseCache.set(responseCacheKey, rendered);
|
|
149
|
+
if (cache !== undefined) {
|
|
150
|
+
const putPromise = cache.put(toL2CacheRequest(responseCacheKey), toL2CacheResponse(rendered));
|
|
151
|
+
if (ctx?.waitUntil !== undefined) {
|
|
152
|
+
ctx.waitUntil(putPromise);
|
|
153
|
+
}
|
|
154
|
+
else {
|
|
155
|
+
await putPromise;
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
return toWorkerResponse(rendered, cacheDebugEnabled && responseCacheKey !== undefined ? 'miss' : undefined);
|
|
160
|
+
},
|
|
161
|
+
};
|
|
162
|
+
}
|
|
163
|
+
function isCacheableRequest(request, url) {
|
|
164
|
+
if (request.method !== 'GET' && request.method !== 'HEAD') {
|
|
165
|
+
return false;
|
|
166
|
+
}
|
|
167
|
+
if (url.search !== '') {
|
|
168
|
+
return false;
|
|
169
|
+
}
|
|
170
|
+
return url.pathname !== '/api' && !url.pathname.startsWith('/api/');
|
|
171
|
+
}
|
|
172
|
+
function isLocaleDetectionRequest(manifest, url) {
|
|
173
|
+
return (url.pathname === '/' &&
|
|
174
|
+
manifest.siteConfig?.localeDetection?.enabled === true);
|
|
175
|
+
}
|
|
176
|
+
function isCacheableContentType(contentType) {
|
|
177
|
+
if (contentType === undefined) {
|
|
178
|
+
return false;
|
|
179
|
+
}
|
|
180
|
+
const mediaType = contentType.split(';', 1)[0]?.trim().toLowerCase();
|
|
181
|
+
if (mediaType === undefined || mediaType === '') {
|
|
182
|
+
return false;
|
|
183
|
+
}
|
|
184
|
+
return CACHEABLE_CONTENT_TYPE_PREFIXES.some((prefix) => mediaType === prefix || mediaType.startsWith(`${prefix}/`));
|
|
185
|
+
}
|
|
186
|
+
function requestMatchesEtag(ifNoneMatch, etag) {
|
|
187
|
+
if (ifNoneMatch === null || ifNoneMatch.trim() === '') {
|
|
188
|
+
return false;
|
|
189
|
+
}
|
|
190
|
+
if (ifNoneMatch.trim() === '*') {
|
|
191
|
+
return true;
|
|
192
|
+
}
|
|
193
|
+
return ifNoneMatch.split(',').some((candidate) => {
|
|
194
|
+
const trimmed = candidate.trim();
|
|
195
|
+
const value = trimmed.startsWith('W/') ? trimmed.slice(2) : trimmed;
|
|
196
|
+
return value === etag;
|
|
197
|
+
});
|
|
198
|
+
}
|
|
199
|
+
function collectResponseCacheHeaders(siteResponse, request, url, etag) {
|
|
200
|
+
if (etag === undefined ||
|
|
201
|
+
siteResponse.status !== 200 ||
|
|
202
|
+
!isCacheableRequest(request, url) ||
|
|
203
|
+
!isCacheableContentType(siteResponse.headers['content-type'])) {
|
|
204
|
+
return undefined;
|
|
205
|
+
}
|
|
206
|
+
const cacheHeaders = {
|
|
207
|
+
etag,
|
|
208
|
+
'cache-control': BROWSER_CACHE_CONTROL,
|
|
209
|
+
};
|
|
210
|
+
const varyValues = siteResponse.headers['vary']
|
|
211
|
+
?.split(',')
|
|
212
|
+
.map((value) => value.trim().toLowerCase()) ?? [];
|
|
213
|
+
// The Cloudflare edge cache does not vary on Accept, so extensionless
|
|
214
|
+
// content-negotiated routes must stay out of the CDN cache. They still get
|
|
215
|
+
// ETag/304 handling and browser revalidation.
|
|
216
|
+
if (!varyValues.includes('accept')) {
|
|
217
|
+
cacheHeaders['cdn-cache-control'] = CDN_CACHE_CONTROL;
|
|
218
|
+
}
|
|
219
|
+
return cacheHeaders;
|
|
220
|
+
}
|
|
221
|
+
class LruCache {
|
|
222
|
+
limit;
|
|
223
|
+
entries = new Map();
|
|
224
|
+
constructor(limit) {
|
|
225
|
+
this.limit = limit;
|
|
226
|
+
}
|
|
227
|
+
get(key) {
|
|
228
|
+
const cached = this.entries.get(key);
|
|
229
|
+
if (cached === undefined) {
|
|
230
|
+
return undefined;
|
|
231
|
+
}
|
|
232
|
+
this.entries.delete(key);
|
|
233
|
+
this.entries.set(key, cached);
|
|
234
|
+
return cached;
|
|
235
|
+
}
|
|
236
|
+
set(key, value) {
|
|
237
|
+
if (this.limit <= 0) {
|
|
238
|
+
return;
|
|
239
|
+
}
|
|
240
|
+
this.entries.delete(key);
|
|
241
|
+
this.entries.set(key, value);
|
|
242
|
+
while (this.entries.size > this.limit) {
|
|
243
|
+
const oldest = this.entries.keys().next().value;
|
|
244
|
+
if (oldest === undefined) {
|
|
245
|
+
break;
|
|
246
|
+
}
|
|
247
|
+
this.entries.delete(oldest);
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
/**
|
|
252
|
+
* Memoizes deterministic search results per isolate. The search index is
|
|
253
|
+
* static within one deploy, so identical (query, options) calls return the
|
|
254
|
+
* same hits and repeated queries skip retrieval entirely.
|
|
255
|
+
*/
|
|
256
|
+
export function withSearchResultCache(api, limit) {
|
|
257
|
+
if (limit <= 0) {
|
|
258
|
+
return api;
|
|
259
|
+
}
|
|
260
|
+
const cache = new LruCache(limit);
|
|
261
|
+
return {
|
|
262
|
+
async search(query, options) {
|
|
263
|
+
const key = JSON.stringify([query, options ?? null]);
|
|
264
|
+
const cached = cache.get(key);
|
|
265
|
+
if (cached !== undefined) {
|
|
266
|
+
return cached;
|
|
267
|
+
}
|
|
268
|
+
const hits = await api.search(query, options);
|
|
269
|
+
cache.set(key, hits);
|
|
270
|
+
return hits;
|
|
84
271
|
},
|
|
85
272
|
};
|
|
86
273
|
}
|
|
87
|
-
function
|
|
274
|
+
function resolveDefaultCache() {
|
|
275
|
+
const cachesRef = globalThis
|
|
276
|
+
.caches;
|
|
277
|
+
const defaultCache = cachesRef?.default;
|
|
278
|
+
if (defaultCache === undefined ||
|
|
279
|
+
typeof defaultCache.match !== 'function' ||
|
|
280
|
+
typeof defaultCache.put !== 'function') {
|
|
281
|
+
return undefined;
|
|
282
|
+
}
|
|
283
|
+
return defaultCache;
|
|
284
|
+
}
|
|
285
|
+
function isCacheDebugEnabled(env) {
|
|
286
|
+
const value = env?.MDORIGIN_CACHE_DEBUG;
|
|
287
|
+
return value === '1' || value === 'true';
|
|
288
|
+
}
|
|
289
|
+
function buildResponseCacheKey(deployVersion, resolved, acceptHeader, pathname) {
|
|
290
|
+
const variant = resolveCacheVariant(resolved, acceptHeader);
|
|
291
|
+
return `${deployVersion}/${variant}${pathname}`;
|
|
292
|
+
}
|
|
293
|
+
function resolveCacheVariant(resolved, acceptHeader) {
|
|
294
|
+
if (resolved.kind === 'markdown') {
|
|
295
|
+
return 'md';
|
|
296
|
+
}
|
|
297
|
+
if (resolved.kind === 'html' &&
|
|
298
|
+
!resolved.requestPath.endsWith('.html') &&
|
|
299
|
+
acceptsMarkdown(acceptHeader)) {
|
|
300
|
+
return 'md';
|
|
301
|
+
}
|
|
302
|
+
return 'html';
|
|
303
|
+
}
|
|
304
|
+
function acceptsMarkdown(acceptHeader) {
|
|
305
|
+
if (!acceptHeader) {
|
|
306
|
+
return false;
|
|
307
|
+
}
|
|
308
|
+
return acceptHeader
|
|
309
|
+
.split(',')
|
|
310
|
+
.map((part) => part.split(';', 1)[0]?.trim().toLowerCase())
|
|
311
|
+
.includes('text/markdown');
|
|
312
|
+
}
|
|
313
|
+
function toL2CacheRequest(cacheKey) {
|
|
314
|
+
return new Request(`${L2_CACHE_KEY_ORIGIN}/${cacheKey}`);
|
|
315
|
+
}
|
|
316
|
+
function toL2CacheResponse(entry) {
|
|
317
|
+
const headers = new Headers(entry.headers);
|
|
318
|
+
headers.set('cache-control', L2_CACHE_CONTROL);
|
|
319
|
+
return new Response(toResponseBody(entry), {
|
|
320
|
+
status: entry.status,
|
|
321
|
+
headers,
|
|
322
|
+
});
|
|
323
|
+
}
|
|
324
|
+
async function cachedResponseFromL2(cached) {
|
|
325
|
+
if (cached.status !== 200) {
|
|
326
|
+
return null;
|
|
327
|
+
}
|
|
328
|
+
const headers = new Headers(cached.headers);
|
|
329
|
+
headers.set('cache-control', BROWSER_CACHE_CONTROL);
|
|
330
|
+
const headerEntries = {};
|
|
331
|
+
headers.forEach((value, name) => {
|
|
332
|
+
headerEntries[name] = value;
|
|
333
|
+
});
|
|
334
|
+
return {
|
|
335
|
+
status: cached.status,
|
|
336
|
+
headers: headerEntries,
|
|
337
|
+
body: new Uint8Array(await cached.arrayBuffer()),
|
|
338
|
+
};
|
|
339
|
+
}
|
|
340
|
+
function toWorkerResponse(entry, cacheStatus) {
|
|
341
|
+
const headers = new Headers(entry.headers);
|
|
342
|
+
if (cacheStatus !== undefined) {
|
|
343
|
+
headers.set(CACHE_DEBUG_HEADER, cacheStatus);
|
|
344
|
+
}
|
|
345
|
+
return new Response(toResponseBody(entry), {
|
|
346
|
+
status: entry.status,
|
|
347
|
+
headers,
|
|
348
|
+
});
|
|
349
|
+
}
|
|
350
|
+
function toResponseBody(entry) {
|
|
351
|
+
if (entry.body instanceof Uint8Array) {
|
|
352
|
+
return new Blob([Uint8Array.from(entry.body)], {
|
|
353
|
+
type: entry.headers['content-type'],
|
|
354
|
+
});
|
|
355
|
+
}
|
|
356
|
+
return entry.body;
|
|
357
|
+
}
|
|
358
|
+
function getExternalSearchApi(manifest, env, cache, defaultApi, searchCacheLimit) {
|
|
88
359
|
if (!manifest.externalSearchEntries || manifest.externalSearchEntries.length === 0) {
|
|
89
360
|
return undefined;
|
|
90
361
|
}
|
|
91
362
|
if (!env) {
|
|
92
363
|
return (defaultApi ??
|
|
93
|
-
createSearchApiFromExternalBundle(manifest.externalSearchEntries, async (entry) => loadExternalSearchEntryResponse(entry, undefined, manifest.runtime?.r2Binding), manifest.siteConfig?.search));
|
|
364
|
+
withSearchResultCache(createSearchApiFromExternalBundle(manifest.externalSearchEntries, async (entry) => loadExternalSearchEntryResponse(entry, undefined, manifest.runtime?.r2Binding), manifest.siteConfig?.search), searchCacheLimit));
|
|
94
365
|
}
|
|
95
366
|
const cached = cache.get(env);
|
|
96
367
|
if (cached) {
|
|
97
368
|
return cached;
|
|
98
369
|
}
|
|
99
|
-
const searchApi = createSearchApiFromExternalBundle(manifest.externalSearchEntries, async (entry) => loadExternalSearchEntryResponse(entry, env, manifest.runtime?.r2Binding), manifest.siteConfig?.search);
|
|
370
|
+
const searchApi = withSearchResultCache(createSearchApiFromExternalBundle(manifest.externalSearchEntries, async (entry) => loadExternalSearchEntryResponse(entry, env, manifest.runtime?.r2Binding), manifest.siteConfig?.search), searchCacheLimit);
|
|
100
371
|
cache.set(env, searchApi);
|
|
101
372
|
return searchApi;
|
|
102
373
|
}
|
|
@@ -162,8 +433,7 @@ async function loadExternalSearchEntryResponse(entry, env, r2Binding) {
|
|
|
162
433
|
headers,
|
|
163
434
|
});
|
|
164
435
|
}
|
|
165
|
-
async function tryServeExternalBinary(manifest, request, env) {
|
|
166
|
-
const resolved = resolveRequest(new URL(request.url).pathname);
|
|
436
|
+
async function tryServeExternalBinary(manifest, request, env, resolved) {
|
|
167
437
|
if (resolved.kind !== 'asset' || !resolved.sourcePath) {
|
|
168
438
|
return null;
|
|
169
439
|
}
|
package/dist/adapters/node.js
CHANGED
|
@@ -123,6 +123,9 @@ export function createNodeRequestListener(options) {
|
|
|
123
123
|
draftMode: options.draftMode,
|
|
124
124
|
siteConfig: options.siteConfig,
|
|
125
125
|
acceptHeader: request.headers.accept,
|
|
126
|
+
acceptLanguageHeader: request.headers['accept-language'],
|
|
127
|
+
cookieHeader: request.headers.cookie,
|
|
128
|
+
userAgentHeader: request.headers['user-agent'],
|
|
126
129
|
searchParams: url.searchParams,
|
|
127
130
|
requestUrl: url.toString(),
|
|
128
131
|
searchApi: options.searchApi,
|
package/dist/cloudflare.js
CHANGED
|
@@ -82,6 +82,13 @@ export async function writeCloudflareBundle(options) {
|
|
|
82
82
|
assetsMaxBytes,
|
|
83
83
|
r2Binding,
|
|
84
84
|
});
|
|
85
|
+
// Deploy version = hash of the manifest payload (all entries, config, and
|
|
86
|
+
// search bundle references). Workers use it as a strong ETag so content
|
|
87
|
+
// edits produce a new version and invalidate every cached response.
|
|
88
|
+
manifest.deployVersion = createHash('sha256')
|
|
89
|
+
.update(JSON.stringify(manifest))
|
|
90
|
+
.digest('hex')
|
|
91
|
+
.slice(0, 16);
|
|
85
92
|
const packageImport = options.packageImport ?? 'mdorigin/cloudflare-runtime';
|
|
86
93
|
const workerFile = path.join(outDir, 'worker.mjs');
|
|
87
94
|
const bundleFile = path.join(outDir, BUNDLE_FILE_NAME);
|
|
@@ -163,7 +170,9 @@ export async function initCloudflareProject(options) {
|
|
|
163
170
|
' "assets": {',
|
|
164
171
|
` "directory": ${JSON.stringify(toPosixPath(path.relative(projectDir, path.join(path.dirname(options.workerEntry), bundleMetadata.assetsDir))))},`,
|
|
165
172
|
` "binding": ${JSON.stringify(DEFAULT_ASSETS_BINDING)},`,
|
|
166
|
-
' "run_worker_first":
|
|
173
|
+
' "run_worker_first": false,',
|
|
174
|
+
' "html_handling": "none",',
|
|
175
|
+
' "not_found_handling": "none"',
|
|
167
176
|
' }',
|
|
168
177
|
].join('\n')
|
|
169
178
|
: '',
|
|
@@ -13,6 +13,8 @@ export interface PageLanguage {
|
|
|
13
13
|
label: string;
|
|
14
14
|
/** Root-relative href for this language: the translated page when available, otherwise the language home. */
|
|
15
15
|
href: string;
|
|
16
|
+
/** Preference-recording href used by the built-in language switcher. */
|
|
17
|
+
preferenceHref?: string;
|
|
16
18
|
current: boolean;
|
|
17
19
|
/** Whether a page-level translation exists for this language. */
|
|
18
20
|
translated: boolean;
|
package/dist/core/markdown.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { ContentEntry } from './content-store.js';
|
|
1
2
|
export interface ParsedDocumentMeta {
|
|
2
3
|
title?: string;
|
|
3
4
|
name?: string;
|
|
@@ -10,21 +11,37 @@ export interface ParsedDocumentMeta {
|
|
|
10
11
|
aliases?: string[];
|
|
11
12
|
[key: string]: unknown;
|
|
12
13
|
}
|
|
13
|
-
export interface ParsedDocument {
|
|
14
|
-
sourcePath: string;
|
|
15
|
-
body: string;
|
|
16
|
-
html: string;
|
|
17
|
-
meta: ParsedDocumentMeta;
|
|
18
|
-
}
|
|
19
14
|
export interface ManagedIndexEntry {
|
|
20
15
|
kind: 'directory' | 'article';
|
|
21
16
|
title: string;
|
|
22
17
|
href: string;
|
|
23
18
|
detail?: string;
|
|
24
19
|
}
|
|
20
|
+
/**
|
|
21
|
+
* Parsed document without rendered HTML. Extracting frontmatter metadata is
|
|
22
|
+
* orders of magnitude cheaper than rendering markdown to HTML, so metadata
|
|
23
|
+
* consumers (listings, sitemaps, feeds, alias scans) use this shape.
|
|
24
|
+
*/
|
|
25
|
+
export interface ParsedDocumentLite {
|
|
26
|
+
sourcePath: string;
|
|
27
|
+
body: string;
|
|
28
|
+
meta: ParsedDocumentMeta;
|
|
29
|
+
}
|
|
30
|
+
export interface ParsedDocument extends ParsedDocumentLite {
|
|
31
|
+
html: string;
|
|
32
|
+
}
|
|
25
33
|
export declare function getDocumentTitle(meta: ParsedDocumentMeta, body: string, fallback: string): string;
|
|
26
34
|
export declare function getDocumentSummary(meta: ParsedDocumentMeta, body: string): string | undefined;
|
|
27
35
|
export declare function parseMarkdownDocument(sourcePath: string, markdown: string): Promise<ParsedDocument>;
|
|
36
|
+
export declare function parseDocumentMeta(sourcePath: string, markdown: string): ParsedDocumentLite;
|
|
37
|
+
/**
|
|
38
|
+
* Parse a store entry's frontmatter metadata, memoized by entry identity.
|
|
39
|
+
* Immutable in-memory stores return the same entry object per path, so
|
|
40
|
+
* repeated metadata reads (alias scans, listings, feeds) parse each document
|
|
41
|
+
* at most once per isolate. File-system stores return fresh entry objects,
|
|
42
|
+
* which naturally bypasses the cache after content edits.
|
|
43
|
+
*/
|
|
44
|
+
export declare function parseEntryDocumentMeta(entry: ContentEntry): ParsedDocumentLite;
|
|
28
45
|
export declare function renderMarkdown(markdown: string): Promise<string>;
|
|
29
46
|
export declare function rewriteMarkdownLinksInHtml(html: string): string;
|
|
30
47
|
export declare function stripManagedIndexBlock(markdown: string): string;
|
package/dist/core/markdown.js
CHANGED
|
@@ -14,15 +14,40 @@ export function getDocumentSummary(meta, body) {
|
|
|
14
14
|
extractFirstParagraph(body));
|
|
15
15
|
}
|
|
16
16
|
export async function parseMarkdownDocument(sourcePath, markdown) {
|
|
17
|
+
const { body, meta } = parseDocumentMeta(sourcePath, markdown);
|
|
18
|
+
const html = rewriteMarkdownLinksInHtml(await renderMarkdown(body));
|
|
19
|
+
return {
|
|
20
|
+
sourcePath,
|
|
21
|
+
body,
|
|
22
|
+
html,
|
|
23
|
+
meta,
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
export function parseDocumentMeta(sourcePath, markdown) {
|
|
17
27
|
const parsed = matter(markdown);
|
|
18
|
-
const html = rewriteMarkdownLinksInHtml(await renderMarkdown(parsed.content));
|
|
19
28
|
return {
|
|
20
29
|
sourcePath,
|
|
21
30
|
body: parsed.content,
|
|
22
|
-
html,
|
|
23
31
|
meta: normalizeMeta(parsed.data),
|
|
24
32
|
};
|
|
25
33
|
}
|
|
34
|
+
const entryDocumentMetaCache = new WeakMap();
|
|
35
|
+
/**
|
|
36
|
+
* Parse a store entry's frontmatter metadata, memoized by entry identity.
|
|
37
|
+
* Immutable in-memory stores return the same entry object per path, so
|
|
38
|
+
* repeated metadata reads (alias scans, listings, feeds) parse each document
|
|
39
|
+
* at most once per isolate. File-system stores return fresh entry objects,
|
|
40
|
+
* which naturally bypasses the cache after content edits.
|
|
41
|
+
*/
|
|
42
|
+
export function parseEntryDocumentMeta(entry) {
|
|
43
|
+
const cached = entryDocumentMetaCache.get(entry);
|
|
44
|
+
if (cached !== undefined) {
|
|
45
|
+
return cached;
|
|
46
|
+
}
|
|
47
|
+
const parsed = parseDocumentMeta(entry.path, entry.text ?? '');
|
|
48
|
+
entryDocumentMetaCache.set(entry, parsed);
|
|
49
|
+
return parsed;
|
|
50
|
+
}
|
|
26
51
|
export async function renderMarkdown(markdown) {
|
|
27
52
|
const output = await remark()
|
|
28
53
|
.use(remarkGfm)
|
|
@@ -6,6 +6,9 @@ export interface HandleSiteRequestOptions {
|
|
|
6
6
|
draftMode: 'include' | 'exclude';
|
|
7
7
|
siteConfig: ResolvedSiteConfig;
|
|
8
8
|
acceptHeader?: string;
|
|
9
|
+
acceptLanguageHeader?: string;
|
|
10
|
+
cookieHeader?: string;
|
|
11
|
+
userAgentHeader?: string;
|
|
9
12
|
searchParams?: URLSearchParams;
|
|
10
13
|
requestUrl?: string;
|
|
11
14
|
searchApi?: SearchApi;
|
|
@@ -2,7 +2,7 @@ import path from 'node:path';
|
|
|
2
2
|
import { isIgnoredContentName } from './content-store.js';
|
|
3
3
|
import { inferDirectoryContentType, resolveContentType, } from './content-type.js';
|
|
4
4
|
import { getDirectoryIndexCandidates } from './directory-index.js';
|
|
5
|
-
import { extractManagedIndexEntries, getDocumentSummary, getDocumentTitle as getParsedDocumentTitle, parseMarkdownDocument, stripManagedIndexBlock, stripManagedIndexLinks, stripMachineOnlyMarkdownComments, } from './markdown.js';
|
|
5
|
+
import { extractManagedIndexEntries, getDocumentSummary, getDocumentTitle as getParsedDocumentTitle, parseEntryDocumentMeta, parseMarkdownDocument, stripManagedIndexBlock, stripManagedIndexLinks, stripMachineOnlyMarkdownComments, } from './markdown.js';
|
|
6
6
|
import { ensureTrailingSlash, trimLeadingSlash } from './site-url.js';
|
|
7
7
|
import { applyIndexTransforms, renderFooterOverride, renderHeaderOverride, renderPageWithPlugins, transformHtmlWithPlugins, } from './extensions.js';
|
|
8
8
|
import { handleApiRoute } from './api.js';
|
|
@@ -10,6 +10,38 @@ import { matchRequestLocale, normalizeRequestPath, resolveRequest } from './rout
|
|
|
10
10
|
import { escapeHtml, renderListingArticleItems, renderDocument, } from '../html/template.js';
|
|
11
11
|
import { formatSiteMessage, resolveSiteMessages, } from '../i18n/messages.js';
|
|
12
12
|
export async function handleSiteRequest(store, pathname, options) {
|
|
13
|
+
if (options.siteConfig.localeDetection?.enabled) {
|
|
14
|
+
const explicitPreference = getExplicitLocalePreference(options);
|
|
15
|
+
if (explicitPreference !== null) {
|
|
16
|
+
return localePreferenceRedirect(pathname, options, explicitPreference);
|
|
17
|
+
}
|
|
18
|
+
if (pathname === '/' && !isCrawler(options.userAgentHeader)) {
|
|
19
|
+
const preferredLocale = resolvePreferredLocale(options);
|
|
20
|
+
if (preferredLocale !== null && preferredLocale.pathPrefix !== '') {
|
|
21
|
+
return {
|
|
22
|
+
status: 302,
|
|
23
|
+
headers: {
|
|
24
|
+
location: `${preferredLocale.pathPrefix}/`,
|
|
25
|
+
'set-cookie': serializeLocalePreference(preferredLocale.code),
|
|
26
|
+
'cache-control': 'private, no-store',
|
|
27
|
+
vary: 'accept-language, cookie',
|
|
28
|
+
},
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
const response = await handleSiteRequestWithoutLocaleDetection(store, pathname, options);
|
|
32
|
+
return {
|
|
33
|
+
...response,
|
|
34
|
+
headers: {
|
|
35
|
+
...response.headers,
|
|
36
|
+
'cache-control': 'private, no-store',
|
|
37
|
+
vary: mergeVary(response.headers.vary, 'accept-language', 'cookie'),
|
|
38
|
+
},
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
return handleSiteRequestWithoutLocaleDetection(store, pathname, options);
|
|
43
|
+
}
|
|
44
|
+
async function handleSiteRequestWithoutLocaleDetection(store, pathname, options) {
|
|
13
45
|
const plugins = options.plugins ?? [];
|
|
14
46
|
const searchEnabled = options.searchApi !== undefined;
|
|
15
47
|
const requestLocale = matchRequestLocale(pathname, options.siteConfig.locales);
|
|
@@ -82,7 +114,7 @@ export async function handleSiteRequest(store, pathname, options) {
|
|
|
82
114
|
return renderNotFoundForResolvedRequest(store, resolved, options, negotiatedMarkdown, requestLocale);
|
|
83
115
|
}
|
|
84
116
|
if (resolved.kind === 'markdown' || negotiatedMarkdown) {
|
|
85
|
-
const parsed =
|
|
117
|
+
const parsed = parseEntryDocumentMeta(entry);
|
|
86
118
|
if (parsed.meta.draft === true && options.draftMode === 'exclude') {
|
|
87
119
|
return renderNotFoundForResolvedRequest(store, resolved, options, negotiatedMarkdown, requestLocale);
|
|
88
120
|
}
|
|
@@ -94,7 +126,7 @@ export async function handleSiteRequest(store, pathname, options) {
|
|
|
94
126
|
body: entry.text,
|
|
95
127
|
};
|
|
96
128
|
}
|
|
97
|
-
const parsed =
|
|
129
|
+
const parsed = parseEntryDocumentMeta(entry);
|
|
98
130
|
if (parsed.meta.draft === true && options.draftMode === 'exclude') {
|
|
99
131
|
return renderNotFoundForResolvedRequest(store, resolved, options, negotiatedMarkdown, requestLocale);
|
|
100
132
|
}
|
|
@@ -114,9 +146,7 @@ export async function handleSiteRequest(store, pathname, options) {
|
|
|
114
146
|
return renderListingPostsFragment(listingEntries, listingFragmentRequest);
|
|
115
147
|
}
|
|
116
148
|
const documentBody = listingEntries.length > 0 ? stripManagedIndexBlock(renderedBody) : renderedBody;
|
|
117
|
-
const renderedParsed =
|
|
118
|
-
? parsed
|
|
119
|
-
: await parseMarkdownDocument(resolved.sourcePath, documentBody);
|
|
149
|
+
const renderedParsed = await parseMarkdownDocument(resolved.sourcePath, documentBody);
|
|
120
150
|
return renderStructuredPage({
|
|
121
151
|
requestPath: resolved.requestPath,
|
|
122
152
|
sourcePath: resolved.sourcePath,
|
|
@@ -438,12 +468,120 @@ async function buildLanguageOptions(store, target, currentLocale, siteConfig, dr
|
|
|
438
468
|
href: translated === null
|
|
439
469
|
? getLocaleHomePath(locale)
|
|
440
470
|
: getCanonicalHtmlPathForContentPath(translated),
|
|
471
|
+
preferenceHref: siteConfig.localeDetection?.enabled
|
|
472
|
+
? appendLocalePreference(translated === null
|
|
473
|
+
? getLocaleHomePath(locale)
|
|
474
|
+
: getCanonicalHtmlPathForContentPath(translated), locale.code)
|
|
475
|
+
: undefined,
|
|
441
476
|
current: locale === currentLocale,
|
|
442
477
|
translated: translated !== null,
|
|
443
478
|
});
|
|
444
479
|
}
|
|
445
480
|
return languages;
|
|
446
481
|
}
|
|
482
|
+
const LOCALE_PREFERENCE_COOKIE = 'mdorigin_locale';
|
|
483
|
+
function getExplicitLocalePreference(options) {
|
|
484
|
+
const requested = options.searchParams?.get('lang');
|
|
485
|
+
if (requested === null || requested === undefined) {
|
|
486
|
+
return null;
|
|
487
|
+
}
|
|
488
|
+
return findConfiguredLocale(requested, options.siteConfig.locales);
|
|
489
|
+
}
|
|
490
|
+
function localePreferenceRedirect(pathname, options, locale) {
|
|
491
|
+
const searchParams = new URLSearchParams(options.searchParams);
|
|
492
|
+
searchParams.delete('lang');
|
|
493
|
+
const search = searchParams.toString();
|
|
494
|
+
return {
|
|
495
|
+
status: 302,
|
|
496
|
+
headers: {
|
|
497
|
+
location: `${pathname}${search === '' ? '' : `?${search}`}`,
|
|
498
|
+
'set-cookie': serializeLocalePreference(locale.code),
|
|
499
|
+
'cache-control': 'private, no-store',
|
|
500
|
+
},
|
|
501
|
+
};
|
|
502
|
+
}
|
|
503
|
+
function resolvePreferredLocale(options) {
|
|
504
|
+
const cookiePreference = readCookie(options.cookieHeader, LOCALE_PREFERENCE_COOKIE);
|
|
505
|
+
const cookieLocale = findConfiguredLocale(cookiePreference, options.siteConfig.locales);
|
|
506
|
+
if (cookieLocale !== null) {
|
|
507
|
+
return cookieLocale;
|
|
508
|
+
}
|
|
509
|
+
for (const language of parseAcceptLanguage(options.acceptLanguageHeader)) {
|
|
510
|
+
const exact = findConfiguredLocale(language, options.siteConfig.locales);
|
|
511
|
+
if (exact !== null) {
|
|
512
|
+
return exact;
|
|
513
|
+
}
|
|
514
|
+
const base = language.split('-')[0];
|
|
515
|
+
const baseMatch = options.siteConfig.locales?.find((locale) => locale.code.toLowerCase() === base ||
|
|
516
|
+
locale.code.toLowerCase().startsWith(`${base}-`));
|
|
517
|
+
if (baseMatch !== undefined) {
|
|
518
|
+
return baseMatch;
|
|
519
|
+
}
|
|
520
|
+
}
|
|
521
|
+
return null;
|
|
522
|
+
}
|
|
523
|
+
function findConfiguredLocale(code, locales) {
|
|
524
|
+
if (code === null || locales === undefined) {
|
|
525
|
+
return null;
|
|
526
|
+
}
|
|
527
|
+
const normalized = code.trim().toLowerCase();
|
|
528
|
+
return locales.find((locale) => locale.code.toLowerCase() === normalized) ?? null;
|
|
529
|
+
}
|
|
530
|
+
function parseAcceptLanguage(value) {
|
|
531
|
+
if (value === undefined) {
|
|
532
|
+
return [];
|
|
533
|
+
}
|
|
534
|
+
return value
|
|
535
|
+
.split(',')
|
|
536
|
+
.map((part, index) => {
|
|
537
|
+
const [language, ...parameters] = part.trim().split(';');
|
|
538
|
+
const qualityParameter = parameters.find((parameter) => parameter.trim().toLowerCase().startsWith('q='));
|
|
539
|
+
const quality = qualityParameter === undefined
|
|
540
|
+
? 1
|
|
541
|
+
: Number.parseFloat(qualityParameter.trim().slice(2));
|
|
542
|
+
return { language: language.toLowerCase(), quality, index };
|
|
543
|
+
})
|
|
544
|
+
.filter(({ language, quality }) => language !== '' && language !== '*' && Number.isFinite(quality) && quality > 0)
|
|
545
|
+
.sort((left, right) => right.quality - left.quality || left.index - right.index)
|
|
546
|
+
.map(({ language }) => language);
|
|
547
|
+
}
|
|
548
|
+
function readCookie(header, name) {
|
|
549
|
+
if (header === undefined) {
|
|
550
|
+
return null;
|
|
551
|
+
}
|
|
552
|
+
for (const item of header.split(';')) {
|
|
553
|
+
const separator = item.indexOf('=');
|
|
554
|
+
if (separator === -1 || item.slice(0, separator).trim() !== name) {
|
|
555
|
+
continue;
|
|
556
|
+
}
|
|
557
|
+
try {
|
|
558
|
+
return decodeURIComponent(item.slice(separator + 1).trim());
|
|
559
|
+
}
|
|
560
|
+
catch {
|
|
561
|
+
return null;
|
|
562
|
+
}
|
|
563
|
+
}
|
|
564
|
+
return null;
|
|
565
|
+
}
|
|
566
|
+
function serializeLocalePreference(code) {
|
|
567
|
+
return `${LOCALE_PREFERENCE_COOKIE}=${encodeURIComponent(code)}; Path=/; Max-Age=31536000; SameSite=Lax; HttpOnly`;
|
|
568
|
+
}
|
|
569
|
+
function appendLocalePreference(href, code) {
|
|
570
|
+
return `${href}${href.includes('?') ? '&' : '?'}lang=${encodeURIComponent(code)}`;
|
|
571
|
+
}
|
|
572
|
+
function isCrawler(userAgent) {
|
|
573
|
+
return userAgent !== undefined && /bot|crawler|spider|slurp|bingpreview/i.test(userAgent);
|
|
574
|
+
}
|
|
575
|
+
function mergeVary(current, ...values) {
|
|
576
|
+
const entries = new Map();
|
|
577
|
+
for (const value of [...(current?.split(',') ?? []), ...values]) {
|
|
578
|
+
const trimmed = value.trim();
|
|
579
|
+
if (trimmed !== '') {
|
|
580
|
+
entries.set(trimmed.toLowerCase(), trimmed);
|
|
581
|
+
}
|
|
582
|
+
}
|
|
583
|
+
return [...entries.values()].join(', ');
|
|
584
|
+
}
|
|
447
585
|
async function localeHasContent(store, target, currentLocale, locale, draftMode) {
|
|
448
586
|
if (locale === currentLocale) {
|
|
449
587
|
return target.sourcePath
|
|
@@ -488,7 +626,7 @@ async function hasPublishedContent(store, contentPath, draftMode) {
|
|
|
488
626
|
return false;
|
|
489
627
|
}
|
|
490
628
|
if (draftMode === 'exclude') {
|
|
491
|
-
const parsed =
|
|
629
|
+
const parsed = parseEntryDocumentMeta(entry);
|
|
492
630
|
if (parsed.meta.draft === true) {
|
|
493
631
|
return false;
|
|
494
632
|
}
|
|
@@ -658,7 +796,7 @@ async function collectSitemapEntries(store, directoryPath, options) {
|
|
|
658
796
|
if (document === null || document.kind !== 'text' || document.text === undefined) {
|
|
659
797
|
continue;
|
|
660
798
|
}
|
|
661
|
-
const parsed =
|
|
799
|
+
const parsed = parseEntryDocumentMeta(document);
|
|
662
800
|
if (parsed.meta.draft === true && options.draftMode === 'exclude') {
|
|
663
801
|
continue;
|
|
664
802
|
}
|
|
@@ -706,7 +844,7 @@ async function collectRssFeedItems(store, directoryPath, options, excludedDirect
|
|
|
706
844
|
if (document === null || document.kind !== 'text' || document.text === undefined) {
|
|
707
845
|
continue;
|
|
708
846
|
}
|
|
709
|
-
const parsed =
|
|
847
|
+
const parsed = parseEntryDocumentMeta(document);
|
|
710
848
|
if (parsed.meta.draft === true && options.draftMode === 'exclude') {
|
|
711
849
|
continue;
|
|
712
850
|
}
|
|
@@ -842,7 +980,7 @@ async function tryRenderAlternateDirectoryIndex(store, requestPath, options) {
|
|
|
842
980
|
if (entry === null || entry.kind !== 'text' || entry.text === undefined) {
|
|
843
981
|
continue;
|
|
844
982
|
}
|
|
845
|
-
const parsed =
|
|
983
|
+
const parsed = parseEntryDocumentMeta(entry);
|
|
846
984
|
if (parsed.meta.draft === true && options.draftMode === 'exclude') {
|
|
847
985
|
return notFound();
|
|
848
986
|
}
|
|
@@ -864,9 +1002,7 @@ async function tryRenderAlternateDirectoryIndex(store, requestPath, options) {
|
|
|
864
1002
|
return renderListingPostsFragment(listingEntries, listingFragmentRequest);
|
|
865
1003
|
}
|
|
866
1004
|
const documentBody = listingEntries.length > 0 ? stripManagedIndexBlock(renderedBody) : renderedBody;
|
|
867
|
-
const renderedParsed =
|
|
868
|
-
? parsed
|
|
869
|
-
: await parseMarkdownDocument(candidatePath, documentBody);
|
|
1005
|
+
const renderedParsed = await parseMarkdownDocument(candidatePath, documentBody);
|
|
870
1006
|
return renderStructuredPage({
|
|
871
1007
|
requestPath,
|
|
872
1008
|
sourcePath: candidatePath,
|
|
@@ -880,6 +1016,10 @@ async function tryRenderAlternateDirectoryIndex(store, requestPath, options) {
|
|
|
880
1016
|
store,
|
|
881
1017
|
requestLocale,
|
|
882
1018
|
draftMode: options.draftMode,
|
|
1019
|
+
// This branch only renders extensionless directory routes, which serve
|
|
1020
|
+
// a raw markdown variant through Accept negotiation; the HTML variant
|
|
1021
|
+
// must therefore declare Vary: Accept like every other negotiated route.
|
|
1022
|
+
varyOnAccept: true,
|
|
883
1023
|
});
|
|
884
1024
|
}
|
|
885
1025
|
return null;
|
|
@@ -900,7 +1040,7 @@ async function tryServeAlternateDirectoryMarkdown(store, resolved, options, nego
|
|
|
900
1040
|
if (entry === null || entry.kind !== 'text' || entry.text === undefined) {
|
|
901
1041
|
continue;
|
|
902
1042
|
}
|
|
903
|
-
const parsed =
|
|
1043
|
+
const parsed = parseEntryDocumentMeta(entry);
|
|
904
1044
|
if (parsed.meta.draft === true && options.draftMode === 'exclude') {
|
|
905
1045
|
return notFound();
|
|
906
1046
|
}
|
|
@@ -931,7 +1071,7 @@ async function tryRedirectAlternateDirectoryMarkdown(store, resolved, options) {
|
|
|
931
1071
|
if (entry === null || entry.kind !== 'text' || entry.text === undefined) {
|
|
932
1072
|
continue;
|
|
933
1073
|
}
|
|
934
|
-
const parsed =
|
|
1074
|
+
const parsed = parseEntryDocumentMeta(entry);
|
|
935
1075
|
if (parsed.meta.draft === true && options.draftMode === 'exclude') {
|
|
936
1076
|
return null;
|
|
937
1077
|
}
|
|
@@ -1011,7 +1151,7 @@ async function findAliasRedirectLocation(store, directoryPath, requestPath, opti
|
|
|
1011
1151
|
if (document === null || document.kind !== 'text' || document.text === undefined) {
|
|
1012
1152
|
continue;
|
|
1013
1153
|
}
|
|
1014
|
-
const parsed =
|
|
1154
|
+
const parsed = parseEntryDocumentMeta(document);
|
|
1015
1155
|
if (parsed.meta.draft === true && options.draftMode === 'exclude') {
|
|
1016
1156
|
continue;
|
|
1017
1157
|
}
|
|
@@ -1137,7 +1277,7 @@ async function resolveDirectoryNav(store, entry) {
|
|
|
1137
1277
|
if (contentEntry === null || contentEntry.kind !== 'text' || contentEntry.text === undefined) {
|
|
1138
1278
|
continue;
|
|
1139
1279
|
}
|
|
1140
|
-
const parsed =
|
|
1280
|
+
const parsed = parseEntryDocumentMeta(contentEntry);
|
|
1141
1281
|
const shape = await inspectDirectoryShape(store, entry.path);
|
|
1142
1282
|
return {
|
|
1143
1283
|
title: getParsedDocumentTitle(parsed.meta, parsed.body, entry.name),
|
|
@@ -75,6 +75,11 @@ export interface SiteConfig {
|
|
|
75
75
|
* path prefix. Omit for single-language sites.
|
|
76
76
|
*/
|
|
77
77
|
locales?: LocaleConfigInput[];
|
|
78
|
+
/**
|
|
79
|
+
* Optional server-side locale detection. When enabled, only the site root
|
|
80
|
+
* redirects according to the saved locale preference or Accept-Language.
|
|
81
|
+
*/
|
|
82
|
+
localeDetection?: SiteLocaleDetectionConfig;
|
|
78
83
|
siteUrl?: string;
|
|
79
84
|
favicon?: string;
|
|
80
85
|
socialImage?: string;
|
|
@@ -102,6 +107,7 @@ export interface ResolvedSiteConfig {
|
|
|
102
107
|
locale: string;
|
|
103
108
|
messages: Partial<SiteMessages>;
|
|
104
109
|
locales?: ResolvedLocaleConfig[];
|
|
110
|
+
localeDetection?: ResolvedSiteLocaleDetectionConfig;
|
|
105
111
|
siteUrl?: string;
|
|
106
112
|
favicon?: string;
|
|
107
113
|
socialImage?: string;
|
|
@@ -122,6 +128,14 @@ export interface ResolvedSiteConfig {
|
|
|
122
128
|
siteTitleConfigured: boolean;
|
|
123
129
|
siteDescriptionConfigured: boolean;
|
|
124
130
|
}
|
|
131
|
+
export interface SiteLocaleDetectionConfig {
|
|
132
|
+
enabled?: boolean;
|
|
133
|
+
redirect?: 'root';
|
|
134
|
+
}
|
|
135
|
+
export interface ResolvedSiteLocaleDetectionConfig {
|
|
136
|
+
enabled: true;
|
|
137
|
+
redirect: 'root';
|
|
138
|
+
}
|
|
125
139
|
export interface LoadSiteConfigOptions {
|
|
126
140
|
cwd?: string;
|
|
127
141
|
rootDir?: string;
|
package/dist/core/site-config.js
CHANGED
|
@@ -3,7 +3,7 @@ import path from 'node:path';
|
|
|
3
3
|
import { pathToFileURL } from 'node:url';
|
|
4
4
|
import { tsImport } from 'tsx/esm/api';
|
|
5
5
|
import { getDirectoryIndexCandidates } from './directory-index.js';
|
|
6
|
-
import {
|
|
6
|
+
import { parseEntryDocumentMeta } from './markdown.js';
|
|
7
7
|
import { DEFAULT_SITE_LOCALE, validateSiteMessages, } from '../i18n/messages.js';
|
|
8
8
|
export async function loadSiteConfig(options = {}) {
|
|
9
9
|
return (await loadUserSiteConfig(options)).siteConfig;
|
|
@@ -18,6 +18,7 @@ export async function loadUserSiteConfig(options = {}) {
|
|
|
18
18
|
const legacyConfig = parsedConfig;
|
|
19
19
|
const messageOverrides = resolveMessageOverrides(parsedConfig.messages, configFilePath);
|
|
20
20
|
const locales = resolveLocalesConfig(parsedConfig, configFilePath);
|
|
21
|
+
const localeDetection = resolveLocaleDetectionConfig(parsedConfig.localeDetection, configFilePath);
|
|
21
22
|
const stylesheetPath = parsedConfig.stylesheet
|
|
22
23
|
? path.resolve(path.dirname(configFilePath), parsedConfig.stylesheet)
|
|
23
24
|
: null;
|
|
@@ -36,6 +37,7 @@ export async function loadUserSiteConfig(options = {}) {
|
|
|
36
37
|
normalizeSiteLocale(parsedConfig.locale),
|
|
37
38
|
messages: messageOverrides,
|
|
38
39
|
locales,
|
|
40
|
+
localeDetection,
|
|
39
41
|
siteUrl: normalizeSiteUrl(parsedConfig.siteUrl),
|
|
40
42
|
favicon: normalizeSiteHref(parsedConfig.favicon),
|
|
41
43
|
socialImage: normalizeSiteHref(parsedConfig.socialImage),
|
|
@@ -78,7 +80,7 @@ export async function applySiteConfigFrontmatterDefaults(store, siteConfig) {
|
|
|
78
80
|
if (entry === null || entry.kind !== 'text' || entry.text === undefined) {
|
|
79
81
|
continue;
|
|
80
82
|
}
|
|
81
|
-
const parsed =
|
|
83
|
+
const parsed = parseEntryDocumentMeta(entry);
|
|
82
84
|
return {
|
|
83
85
|
...siteConfig,
|
|
84
86
|
siteTitle: siteConfig.siteTitleConfigured
|
|
@@ -95,6 +97,27 @@ export async function applySiteConfigFrontmatterDefaults(store, siteConfig) {
|
|
|
95
97
|
}
|
|
96
98
|
return siteConfig;
|
|
97
99
|
}
|
|
100
|
+
function resolveLocaleDetectionConfig(value, configFilePath) {
|
|
101
|
+
if (value === undefined) {
|
|
102
|
+
return undefined;
|
|
103
|
+
}
|
|
104
|
+
if (typeof value !== 'object' || value === null || Array.isArray(value)) {
|
|
105
|
+
throw new Error(`Invalid "localeDetection" in ${configFilePath}: expected an object`);
|
|
106
|
+
}
|
|
107
|
+
if (value.enabled === false) {
|
|
108
|
+
return undefined;
|
|
109
|
+
}
|
|
110
|
+
if (value.enabled !== true) {
|
|
111
|
+
throw new Error(`Invalid "localeDetection.enabled" in ${configFilePath}: expected true or false`);
|
|
112
|
+
}
|
|
113
|
+
if (value.redirect !== undefined && value.redirect !== 'root') {
|
|
114
|
+
throw new Error(`Invalid "localeDetection.redirect" in ${configFilePath}: expected "root"`);
|
|
115
|
+
}
|
|
116
|
+
return {
|
|
117
|
+
enabled: true,
|
|
118
|
+
redirect: 'root',
|
|
119
|
+
};
|
|
120
|
+
}
|
|
98
121
|
function resolveMessageOverrides(value, configFilePath) {
|
|
99
122
|
if (value === undefined) {
|
|
100
123
|
return {};
|
package/dist/html/template.js
CHANGED
|
@@ -68,7 +68,7 @@ export function renderDocument(options) {
|
|
|
68
68
|
'<details class="site-languages__details" data-site-languages>',
|
|
69
69
|
`<summary class="site-languages__toggle"><span class="site-languages__label">${escapeHtml(currentLanguage.label)}</span><svg class="site-languages__chevron" viewBox="0 0 16 16" width="11" height="11" aria-hidden="true" focusable="false"><path d="M4 6.5 8 10.5 12 6.5" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"></path></svg></summary>`,
|
|
70
70
|
`<ul class="site-languages__panel">${options.languages
|
|
71
|
-
.map((language) => `<li><a href="${escapeHtml(language.href)}" hreflang="${escapeHtml(language.code)}"${language.current ? ' aria-current="page"' : ''}>${escapeHtml(language.label)}</a></li>`)
|
|
71
|
+
.map((language) => `<li><a href="${escapeHtml(language.preferenceHref ?? language.href)}" hreflang="${escapeHtml(language.code)}"${language.current ? ' aria-current="page"' : ''}>${escapeHtml(language.label)}</a></li>`)
|
|
72
72
|
.join('')}</ul>`,
|
|
73
73
|
'</details>',
|
|
74
74
|
'</nav>',
|