mdorigin 0.5.3 → 0.5.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.
- package/dist/adapters/cloudflare.js +11 -1
- package/dist/adapters/node.js +3 -0
- package/dist/core/extensions.d.ts +2 -0
- package/dist/core/request-handler.d.ts +3 -0
- package/dist/core/request-handler.js +140 -0
- package/dist/core/site-config.d.ts +14 -0
- package/dist/core/site-config.js +23 -0
- package/dist/html/template.js +29 -11
- package/package.json +1 -1
|
@@ -66,6 +66,7 @@ export function createCloudflareWorker(manifest, options = {}) {
|
|
|
66
66
|
: `"${manifest.deployVersion}"`;
|
|
67
67
|
if (etag !== undefined &&
|
|
68
68
|
isCacheableRequest(request, url) &&
|
|
69
|
+
!isLocaleDetectionRequest(manifest, url) &&
|
|
69
70
|
requestMatchesEtag(request.headers.get('if-none-match'), etag)) {
|
|
70
71
|
return new Response(null, {
|
|
71
72
|
status: 304,
|
|
@@ -76,7 +77,9 @@ export function createCloudflareWorker(manifest, options = {}) {
|
|
|
76
77
|
});
|
|
77
78
|
}
|
|
78
79
|
const cacheDebugEnabled = isCacheDebugEnabled(env);
|
|
79
|
-
const responseCacheKey = manifest.deployVersion !== undefined &&
|
|
80
|
+
const responseCacheKey = manifest.deployVersion !== undefined &&
|
|
81
|
+
isCacheableRequest(request, url) &&
|
|
82
|
+
!isLocaleDetectionRequest(manifest, url)
|
|
80
83
|
? buildResponseCacheKey(manifest.deployVersion, resolvedRequest, request.headers.get('accept'), url.pathname)
|
|
81
84
|
: undefined;
|
|
82
85
|
if (responseCacheKey !== undefined) {
|
|
@@ -119,6 +122,9 @@ export function createCloudflareWorker(manifest, options = {}) {
|
|
|
119
122
|
siteDescriptionConfigured: false,
|
|
120
123
|
},
|
|
121
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,
|
|
122
128
|
searchParams: url.searchParams,
|
|
123
129
|
requestUrl: request.url,
|
|
124
130
|
searchApi: inlineSearchApi ?? externalSearchApi,
|
|
@@ -163,6 +169,10 @@ function isCacheableRequest(request, url) {
|
|
|
163
169
|
}
|
|
164
170
|
return url.pathname !== '/api' && !url.pathname.startsWith('/api/');
|
|
165
171
|
}
|
|
172
|
+
function isLocaleDetectionRequest(manifest, url) {
|
|
173
|
+
return (url.pathname === '/' &&
|
|
174
|
+
manifest.siteConfig?.localeDetection?.enabled === true);
|
|
175
|
+
}
|
|
166
176
|
function isCacheableContentType(contentType) {
|
|
167
177
|
if (contentType === undefined) {
|
|
168
178
|
return false;
|
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,
|
|
@@ -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;
|
|
@@ -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;
|
|
@@ -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);
|
|
@@ -436,12 +468,120 @@ async function buildLanguageOptions(store, target, currentLocale, siteConfig, dr
|
|
|
436
468
|
href: translated === null
|
|
437
469
|
? getLocaleHomePath(locale)
|
|
438
470
|
: getCanonicalHtmlPathForContentPath(translated),
|
|
471
|
+
preferenceHref: siteConfig.localeDetection?.enabled
|
|
472
|
+
? appendLocalePreference(translated === null
|
|
473
|
+
? getLocaleHomePath(locale)
|
|
474
|
+
: getCanonicalHtmlPathForContentPath(translated), locale.code)
|
|
475
|
+
: undefined,
|
|
439
476
|
current: locale === currentLocale,
|
|
440
477
|
translated: translated !== null,
|
|
441
478
|
});
|
|
442
479
|
}
|
|
443
480
|
return languages;
|
|
444
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
|
+
}
|
|
445
585
|
async function localeHasContent(store, target, currentLocale, locale, draftMode) {
|
|
446
586
|
if (locale === currentLocale) {
|
|
447
587
|
return target.sourcePath
|
|
@@ -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
|
@@ -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),
|
|
@@ -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
|
@@ -8,23 +8,41 @@ export function renderDocument(options) {
|
|
|
8
8
|
const siteDescription = options.siteDescription
|
|
9
9
|
? escapeHtml(options.siteDescription)
|
|
10
10
|
: undefined;
|
|
11
|
+
const socialDescription = options.summary ?? options.siteDescription;
|
|
11
12
|
const summaryMeta = options.summary
|
|
12
13
|
? `<meta name="description" content="${escapeHtml(options.summary)}">`
|
|
13
14
|
: '';
|
|
14
|
-
const
|
|
15
|
-
?
|
|
15
|
+
const canonicalUrl = options.siteUrl && options.canonicalPath
|
|
16
|
+
? `${options.siteUrl}${options.canonicalPath}`
|
|
17
|
+
: undefined;
|
|
18
|
+
const canonicalMeta = canonicalUrl
|
|
19
|
+
? `<link rel="canonical" href="${escapeHtml(canonicalUrl)}">`
|
|
16
20
|
: '';
|
|
17
21
|
const faviconMeta = options.favicon
|
|
18
22
|
? `<link rel="icon" href="${escapeHtml(options.favicon)}">`
|
|
19
23
|
: '';
|
|
20
24
|
const absoluteSocialImageUrl = getAbsoluteSiteAssetUrl(options.siteUrl, options.socialImage);
|
|
21
|
-
const
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
25
|
+
const socialMeta = [
|
|
26
|
+
`<meta property="og:title" content="${title}">`,
|
|
27
|
+
socialDescription
|
|
28
|
+
? `<meta property="og:description" content="${escapeHtml(socialDescription)}">`
|
|
29
|
+
: '',
|
|
30
|
+
canonicalUrl
|
|
31
|
+
? `<meta property="og:url" content="${escapeHtml(canonicalUrl)}">`
|
|
32
|
+
: '',
|
|
33
|
+
'<meta property="og:type" content="website">',
|
|
34
|
+
`<meta name="twitter:title" content="${title}">`,
|
|
35
|
+
socialDescription
|
|
36
|
+
? `<meta name="twitter:description" content="${escapeHtml(socialDescription)}">`
|
|
37
|
+
: '',
|
|
38
|
+
absoluteSocialImageUrl
|
|
39
|
+
? [
|
|
40
|
+
`<meta property="og:image" content="${escapeHtml(absoluteSocialImageUrl)}">`,
|
|
41
|
+
'<meta name="twitter:card" content="summary_large_image">',
|
|
42
|
+
`<meta name="twitter:image" content="${escapeHtml(absoluteSocialImageUrl)}">`,
|
|
43
|
+
].join('')
|
|
44
|
+
: '',
|
|
45
|
+
].join('');
|
|
28
46
|
const alternateMarkdownMeta = options.alternateMarkdownPath
|
|
29
47
|
? `<link rel="alternate" type="text/markdown" href="${escapeHtml(options.alternateMarkdownPath)}">`
|
|
30
48
|
: '';
|
|
@@ -68,7 +86,7 @@ export function renderDocument(options) {
|
|
|
68
86
|
'<details class="site-languages__details" data-site-languages>',
|
|
69
87
|
`<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
88
|
`<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>`)
|
|
89
|
+
.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
90
|
.join('')}</ul>`,
|
|
73
91
|
'</details>',
|
|
74
92
|
'</nav>',
|
|
@@ -133,7 +151,7 @@ export function renderDocument(options) {
|
|
|
133
151
|
summaryMeta,
|
|
134
152
|
canonicalMeta,
|
|
135
153
|
faviconMeta,
|
|
136
|
-
|
|
154
|
+
socialMeta,
|
|
137
155
|
alternateMarkdownMeta,
|
|
138
156
|
rssMeta,
|
|
139
157
|
hreflangMeta,
|