mdorigin 0.7.3 → 0.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -80,6 +80,18 @@ export interface CreateCloudflareWorkerOptions {
80
80
  /** Maximum isolate-memoized search results. Defaults to 100. */
81
81
  searchCacheLimit?: number;
82
82
  }
83
+ /**
84
+ * Browser cache policy for external binary assets, regardless of whether
85
+ * they are R2-backed or staged in the static assets bundle. Public paths
86
+ * stay stable while the underlying object can change on a redeploy, so
87
+ * responses must stay revalidatable (no immutable): browsers reuse images
88
+ * for a day, then revalidate in the background while stale content keeps
89
+ * rendering. Without this header browsers fall back to Cloudflare's default
90
+ * max-age=0 must-revalidate and pay one conditional round trip per image on
91
+ * every visit. The build step mirrors this value into the generated assets
92
+ * `_headers` file, so keep the two in sync.
93
+ */
94
+ export declare const EXTERNAL_BINARY_BROWSER_CACHE_CONTROL = "public, max-age=86400, stale-while-revalidate=604800";
83
95
  export declare function createCloudflareWorker(manifest: CloudflareManifest, options?: CreateCloudflareWorkerOptions): ExportedHandlerLike;
84
96
  /**
85
97
  * Memoizes deterministic search results per isolate. The search index is
@@ -1,4 +1,5 @@
1
1
  import { MemoryContentStore } from '../core/content-store.js';
2
+ import { createExternalAssetUrlResolver } from '../core/asset-urls.js';
2
3
  import { handleSiteRequest } from '../core/request-handler.js';
3
4
  import { resolveRequest } from '../core/router.js';
4
5
  import { createSearchApiFromBundle, createSearchApiFromExternalBundle, } from '../search.js';
@@ -6,6 +7,24 @@ const BROWSER_CACHE_CONTROL = 'public, max-age=120, stale-while-revalidate=60480
6
7
  const CDN_CACHE_CONTROL = 'max-age=86400';
7
8
  const L2_CACHE_CONTROL = 'public, max-age=86400';
8
9
  const L2_CACHE_KEY_ORIGIN = 'https://cache.mdorigin.internal';
10
+ /**
11
+ * Browser cache policy for external binary assets, regardless of whether
12
+ * they are R2-backed or staged in the static assets bundle. Public paths
13
+ * stay stable while the underlying object can change on a redeploy, so
14
+ * responses must stay revalidatable (no immutable): browsers reuse images
15
+ * for a day, then revalidate in the background while stale content keeps
16
+ * rendering. Without this header browsers fall back to Cloudflare's default
17
+ * max-age=0 must-revalidate and pay one conditional round trip per image on
18
+ * every visit. The build step mirrors this value into the generated assets
19
+ * `_headers` file, so keep the two in sync.
20
+ */
21
+ export const EXTERNAL_BINARY_BROWSER_CACHE_CONTROL = 'public, max-age=86400, stale-while-revalidate=604800';
22
+ /**
23
+ * Edge cache policy for R2-backed binary assets. Mirrors the HTML CDN policy
24
+ * so edge hits are deterministic while a redeploy can serve stale bytes for
25
+ * at most one day.
26
+ */
27
+ const EXTERNAL_BINARY_CDN_CACHE_CONTROL = 'max-age=86400';
9
28
  const CACHE_DEBUG_HEADER = 'x-mdorigin-cache';
10
29
  const RESPONSE_CACHE_LIMIT_DEFAULT = 100;
11
30
  const SEARCH_CACHE_LIMIT_DEFAULT = 100;
@@ -49,6 +68,12 @@ export function createCloudflareWorker(manifest, options = {}) {
49
68
  : undefined;
50
69
  const externalSearchApis = new WeakMap();
51
70
  let defaultExternalSearchApi;
71
+ /**
72
+ * External asset origin rewriting. Only R2-backed binary entries are
73
+ * rewritten: `assets`-staged binaries live in the Workers static assets,
74
+ * not in the R2 bucket, so an R2 custom domain would not serve them.
75
+ */
76
+ const resolveAssetUrl = createWorkerAssetUrlResolver(manifest);
52
77
  return {
53
78
  async fetch(request, env, ctx) {
54
79
  const url = new URL(request.url);
@@ -129,6 +154,7 @@ export function createCloudflareWorker(manifest, options = {}) {
129
154
  requestUrl: request.url,
130
155
  searchApi: inlineSearchApi ?? externalSearchApi,
131
156
  plugins: options.plugins,
157
+ resolveAssetUrl,
132
158
  });
133
159
  const headers = new Headers(siteResponse.headers);
134
160
  const cacheHeaders = collectResponseCacheHeaders(siteResponse, request, url, etag);
@@ -448,7 +474,8 @@ async function tryServeExternalBinary(manifest, request, env, resolved) {
448
474
  }
449
475
  const assetUrl = new URL(request.url);
450
476
  assetUrl.pathname = `/${manifestEntry.storageKey}`;
451
- return assetsBinding.fetch(new Request(assetUrl.toString(), request));
477
+ const assetResponse = await assetsBinding.fetch(new Request(assetUrl.toString(), request));
478
+ return withExternalBinaryBrowserCacheControl(assetResponse);
452
479
  }
453
480
  const bucket = env?.[manifest.runtime?.r2Binding ?? 'MDORIGIN_R2'];
454
481
  if (!bucket) {
@@ -465,7 +492,11 @@ async function tryServeExternalBinary(manifest, request, env, resolved) {
465
492
  }
466
493
  const headers = new Headers({
467
494
  'content-type': manifestEntry.mediaType,
495
+ 'cache-control': EXTERNAL_BINARY_BROWSER_CACHE_CONTROL,
496
+ 'cdn-cache-control': EXTERNAL_BINARY_CDN_CACHE_CONTROL,
468
497
  });
498
+ // Keep the R2 etag so browsers and the edge can revalidate cheaply once
499
+ // the freshness window expires.
469
500
  if (object.httpEtag) {
470
501
  headers.set('etag', object.httpEtag);
471
502
  }
@@ -498,9 +529,48 @@ async function tryServeExternalBinary(manifest, request, env, resolved) {
498
529
  headers,
499
530
  });
500
531
  }
532
+ /**
533
+ * Applies the external-binary browser cache policy to a Workers Assets
534
+ * binding response. Requests that match a static asset are normally served
535
+ * by the assets layer without invoking the Worker, so the build step also
536
+ * emits an assets `_headers` rule with this policy; this override keeps
537
+ * Worker-served fallbacks (for example sites running `run_worker_first:
538
+ * true`) consistent with that rule. Only the browser directive is
539
+ * overridden: the assets layer owns its edge cache (`cf-cache-status`) and
540
+ * already resolved this response, so no CDN directive is added here. Error
541
+ * responses pass through untouched.
542
+ */
543
+ function withExternalBinaryBrowserCacheControl(response) {
544
+ if (response.status !== 200 && response.status !== 304) {
545
+ return response;
546
+ }
547
+ const headers = new Headers(response.headers);
548
+ headers.set('cache-control', EXTERNAL_BINARY_BROWSER_CACHE_CONTROL);
549
+ return new Response(response.body, {
550
+ status: response.status,
551
+ headers,
552
+ });
553
+ }
501
554
  function isExternalBinaryEntry(entry) {
502
555
  return entry.kind === 'binary' && 'storageKind' in entry;
503
556
  }
557
+ /**
558
+ * Builds the asset-origin rewriter for a manifest, or undefined when the site
559
+ * does not configure `assets.baseUrl` or has no R2-backed binary assets.
560
+ */
561
+ function createWorkerAssetUrlResolver(manifest) {
562
+ const baseUrl = manifest.siteConfig?.assets?.baseUrl;
563
+ if (baseUrl === undefined) {
564
+ return undefined;
565
+ }
566
+ const externalAssetPaths = new Set(manifest.entries
567
+ .filter((entry) => isExternalBinaryEntry(entry) && entry.storageKind === 'r2')
568
+ .map((entry) => entry.path));
569
+ if (externalAssetPaths.size === 0) {
570
+ return undefined;
571
+ }
572
+ return createExternalAssetUrlResolver(baseUrl, externalAssetPaths);
573
+ }
504
574
  class CloudflareManifestContentStore {
505
575
  storeIndex;
506
576
  request;
@@ -3,7 +3,7 @@ import { createHash } from 'node:crypto';
3
3
  import { createReadStream } from 'node:fs';
4
4
  import { copyFile, mkdir, readFile, readdir, realpath, rm, stat, writeFile, } from 'node:fs/promises';
5
5
  import path from 'node:path';
6
- import { createCloudflareWorker } from './adapters/cloudflare.js';
6
+ import { createCloudflareWorker, EXTERNAL_BINARY_BROWSER_CACHE_CONTROL, } from './adapters/cloudflare.js';
7
7
  import { getMediaTypeForPath, isIgnoredContentName, isLikelyTextPath, normalizeContentPath, } from './core/content-store.js';
8
8
  export { createCloudflareWorker };
9
9
  const DEFAULT_ASSETS_MAX_BYTES = 25 * 1024 * 1024;
@@ -273,6 +273,7 @@ async function writeExternalStaging(rootDir, searchDir, outDir, manifest, option
273
273
  const stagedObjects = new Map();
274
274
  let hasAssets = false;
275
275
  let hasR2 = false;
276
+ let hasAssetsBinaries = false;
276
277
  if (options.binaryMode === 'external') {
277
278
  for (const entry of manifest.entries) {
278
279
  if (entry.kind !== 'binary' || !('storageKind' in entry)) {
@@ -284,6 +285,7 @@ async function writeExternalStaging(rootDir, searchDir, outDir, manifest, option
284
285
  await mkdir(path.dirname(targetFile), { recursive: true });
285
286
  await copyFile(sourceFile, targetFile);
286
287
  hasAssets = true;
288
+ hasAssetsBinaries = true;
287
289
  stagedObjects.set(`assets:${entry.storageKey}`, {
288
290
  kind: 'binary',
289
291
  path: entry.path,
@@ -350,6 +352,17 @@ async function writeExternalStaging(rootDir, searchDir, outDir, manifest, option
350
352
  }
351
353
  }
352
354
  }
355
+ if (hasAssetsBinaries) {
356
+ // Binaries staged in the static assets bundle are served by the assets
357
+ // layer without invoking the Worker when `run_worker_first` is false
358
+ // (the generated wrangler config), so the browser cache policy has to
359
+ // ride along in the assets `_headers` file. A single `/*` rule stays
360
+ // well within Cloudflare's 100-rule limit and the assets directory only
361
+ // holds mdorigin-staged binaries plus internal search bundle files. The
362
+ // Worker adapter applies the same policy to binding-served fallbacks, so
363
+ // keep both in sync.
364
+ await writeFile(path.join(assetsDir, '_headers'), `/*\n\tCache-Control: ${EXTERNAL_BINARY_BROWSER_CACHE_CONTROL}\n`, 'utf8');
365
+ }
353
366
  return {
354
367
  version: 2,
355
368
  workerEntry: 'worker.mjs',
@@ -0,0 +1,34 @@
1
+ /**
2
+ * External asset origin support.
3
+ *
4
+ * Sites deployed with external binary mode can mirror their R2 bucket on a
5
+ * custom origin (R2 custom domain or CDN). When `assets.baseUrl` is
6
+ * configured, rendered asset references are rewritten to that origin while
7
+ * keeping the same public path structure, so the Worker route keeps working
8
+ * as a fallback for crawlers and old links.
9
+ */
10
+ /**
11
+ * Resolves a rendered asset href to an external absolute URL.
12
+ *
13
+ * @param href Asset reference as written in content: relative (`./a.png`),
14
+ * root-relative (`/a.png`), or already absolute (returned unchanged by
15
+ * concrete implementations).
16
+ * @param pageRequestPath URL path of the page being rendered, used to resolve
17
+ * relative references the same way a browser would.
18
+ * @returns The absolute external URL, or undefined when the reference should
19
+ * not be rewritten.
20
+ */
21
+ export type AssetUrlResolver = (href: string, pageRequestPath: string) => string | undefined;
22
+ /**
23
+ * Builds a resolver that rewrites hrefs resolving to one of the known
24
+ * external binary asset paths. Asset paths use content-path form (decoded,
25
+ * no leading slash) so they match manifest entries directly.
26
+ */
27
+ export declare function createExternalAssetUrlResolver(baseUrl: string, assetPaths: ReadonlySet<string>): AssetUrlResolver;
28
+ /** Applies a resolver to an optional href, leaving non-matching values unchanged. */
29
+ export declare function applyAssetUrlResolver(href: string | undefined, pageRequestPath: string, resolver: AssetUrlResolver | undefined): string | undefined;
30
+ /**
31
+ * Normalizes an asset base URL: must be an absolute http(s) URL; trailing
32
+ * slashes are removed so `${baseUrl}${path}` concatenation stays correct.
33
+ */
34
+ export declare function normalizeAssetBaseUrl(value: string): string;
@@ -0,0 +1,90 @@
1
+ /**
2
+ * External asset origin support.
3
+ *
4
+ * Sites deployed with external binary mode can mirror their R2 bucket on a
5
+ * custom origin (R2 custom domain or CDN). When `assets.baseUrl` is
6
+ * configured, rendered asset references are rewritten to that origin while
7
+ * keeping the same public path structure, so the Worker route keeps working
8
+ * as a fallback for crawlers and old links.
9
+ */
10
+ const RESOLUTION_BASE_ORIGIN = 'https://asset.mdorigin.invalid';
11
+ /**
12
+ * Builds a resolver that rewrites hrefs resolving to one of the known
13
+ * external binary asset paths. Asset paths use content-path form (decoded,
14
+ * no leading slash) so they match manifest entries directly.
15
+ */
16
+ export function createExternalAssetUrlResolver(baseUrl, assetPaths) {
17
+ const normalizedBaseUrl = normalizeAssetBaseUrl(baseUrl);
18
+ return (href, pageRequestPath) => {
19
+ if (href === '' || assetPaths.size === 0) {
20
+ return undefined;
21
+ }
22
+ // Already absolute or protocol-relative references stay untouched.
23
+ if (href.startsWith('//') || /^[a-zA-Z][a-zA-Z\d+.-]*:/.test(href)) {
24
+ return undefined;
25
+ }
26
+ const directory = pageRequestPath.includes('/')
27
+ ? pageRequestPath.slice(0, pageRequestPath.lastIndexOf('/') + 1)
28
+ : '/';
29
+ let resolved;
30
+ try {
31
+ resolved = new URL(href, `${RESOLUTION_BASE_ORIGIN}${directory}`);
32
+ }
33
+ catch {
34
+ return undefined;
35
+ }
36
+ if (resolved.origin !== RESOLUTION_BASE_ORIGIN) {
37
+ return undefined;
38
+ }
39
+ const assetPath = toContentPathForm(resolved.pathname);
40
+ if (assetPath === null || !assetPaths.has(assetPath)) {
41
+ return undefined;
42
+ }
43
+ // Emit the URL-encoded path: percent-encoded hrefs stay encoded and
44
+ // raw unicode hrefs become correctly encoded absolute URLs. Query and
45
+ // fragment (cache-busting, anchors) are preserved as written.
46
+ return `${normalizedBaseUrl}${resolved.pathname}${resolved.search}${resolved.hash}`;
47
+ };
48
+ }
49
+ /** Applies a resolver to an optional href, leaving non-matching values unchanged. */
50
+ export function applyAssetUrlResolver(href, pageRequestPath, resolver) {
51
+ if (href === undefined || resolver === undefined) {
52
+ return href;
53
+ }
54
+ return resolver(href, pageRequestPath) ?? href;
55
+ }
56
+ /**
57
+ * Normalizes an asset base URL: must be an absolute http(s) URL; trailing
58
+ * slashes are removed so `${baseUrl}${path}` concatenation stays correct.
59
+ */
60
+ export function normalizeAssetBaseUrl(value) {
61
+ let parsed;
62
+ try {
63
+ parsed = new URL(value);
64
+ }
65
+ catch {
66
+ throw new Error(`Invalid asset base URL: ${value} is not an absolute URL`);
67
+ }
68
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
69
+ throw new Error(`Invalid asset base URL: ${value} must use http or https`);
70
+ }
71
+ return parsed.toString().replace(/\/+$/, '');
72
+ }
73
+ /**
74
+ * Converts a percent-encoded URL pathname to content-path form (decoded, no
75
+ * leading slash), matching how the router resolves request paths to manifest
76
+ * entries. Returns null when the pathname cannot be decoded.
77
+ */
78
+ function toContentPathForm(pathname) {
79
+ try {
80
+ const decoded = decodeURIComponent(pathname);
81
+ const withoutLeadingSlash = decoded.replace(/^\/+/, '');
82
+ if (withoutLeadingSlash === '') {
83
+ return null;
84
+ }
85
+ return withoutLeadingSlash;
86
+ }
87
+ catch {
88
+ return null;
89
+ }
90
+ }
@@ -1,5 +1,6 @@
1
1
  import matter from 'gray-matter';
2
2
  import type { ContentEntry } from './content-store.js';
3
+ import type { AssetUrlResolver } from './asset-urls.js';
3
4
  import { type PageRobots } from './seo.js';
4
5
  export interface ParsedDocumentMeta {
5
6
  title?: string;
@@ -52,7 +53,19 @@ export interface MarkdownHeading {
52
53
  }
53
54
  export declare function getDocumentTitle(meta: ParsedDocumentMeta, body: string, fallback: string): string;
54
55
  export declare function getDocumentSummary(meta: ParsedDocumentMeta, body: string): string | undefined;
55
- export declare function parseMarkdownDocument(sourcePath: string, markdown: string): Promise<ParsedDocument>;
56
+ export interface ParseMarkdownDocumentOptions {
57
+ /**
58
+ * URL path of the page being rendered. Relative media sources resolve
59
+ * against this path the same way a browser would resolve them.
60
+ */
61
+ requestPath?: string;
62
+ /**
63
+ * Optional rewriter mapping binary asset references to an external asset
64
+ * origin (see `assets.baseUrl`). Only matching references change.
65
+ */
66
+ resolveAssetUrl?: AssetUrlResolver;
67
+ }
68
+ export declare function parseMarkdownDocument(sourcePath: string, markdown: string, options?: ParseMarkdownDocumentOptions): Promise<ParsedDocument>;
56
69
  export declare function parseDocumentMeta(sourcePath: string, markdown: string): ParsedDocumentLite;
57
70
  /** Read original scalar values without applying page metadata normalization. */
58
71
  export declare function parseMarkdownFrontmatter(markdown: string): matter.GrayMatterFile<string>;
@@ -15,9 +15,9 @@ export function getDocumentSummary(meta, body) {
15
15
  return (firstNonEmptyString(meta.summary, meta.description) ??
16
16
  extractFirstParagraph(body));
17
17
  }
18
- export async function parseMarkdownDocument(sourcePath, markdown) {
18
+ export async function parseMarkdownDocument(sourcePath, markdown, options = {}) {
19
19
  const { body, meta } = parseDocumentMeta(sourcePath, markdown);
20
- const html = rewriteMarkdownLinksInHtml(await renderMarkdown(body));
20
+ const html = enhanceHtmlMediaSources(rewriteMarkdownLinksInHtml(await renderMarkdown(body)), options);
21
21
  return {
22
22
  sourcePath,
23
23
  body,
@@ -121,6 +121,47 @@ function assignHeadingIds(root, headings) {
121
121
  export function rewriteMarkdownLinksInHtml(html) {
122
122
  return html.replaceAll(/(<a\b[^>]*?\shref=")([^"]+)(")/g, (_match, prefix, href, suffix) => `${prefix}${rewriteMarkdownHref(href)}${suffix}`);
123
123
  }
124
+ const MEDIA_SOURCE_TAG_PATTERN = /(<(?:img|source|video|audio)\b[^>]*?\ssrc=")([^"]+)(")/g;
125
+ const IMG_TAG_PATTERN = /<img\b[^>]*>/g;
126
+ /**
127
+ * Applies asset-origin and lazy-loading enhancements to media elements in
128
+ * rendered HTML:
129
+ *
130
+ * - When an asset resolver is configured, `src` attributes on media elements
131
+ * that resolve to a known external binary asset are rewritten to the
132
+ * external origin.
133
+ * - Rendered `<img>` tags get `loading="lazy"` and `decoding="async"` so
134
+ * off-screen images stay out of the critical path. Attributes the author
135
+ * already set are preserved.
136
+ */
137
+ function enhanceHtmlMediaSources(html, options) {
138
+ const { requestPath, resolveAssetUrl } = options;
139
+ let result = html;
140
+ if (resolveAssetUrl !== undefined && requestPath !== undefined) {
141
+ result = result.replaceAll(MEDIA_SOURCE_TAG_PATTERN, (match, prefix, src, suffix) => {
142
+ const rewritten = resolveAssetUrl(src, requestPath);
143
+ return rewritten === undefined ? match : `${prefix}${rewritten}${suffix}`;
144
+ });
145
+ }
146
+ return result.replaceAll(IMG_TAG_PATTERN, addLazyLoadingAttributes);
147
+ }
148
+ function addLazyLoadingAttributes(tag) {
149
+ let enhanced = tag;
150
+ if (!/\bloading\s*=/.test(enhanced)) {
151
+ enhanced = insertAttributeBeforeTagEnd(enhanced, ' loading="lazy"');
152
+ }
153
+ if (!/\bdecoding\s*=/.test(enhanced)) {
154
+ enhanced = insertAttributeBeforeTagEnd(enhanced, ' decoding="async"');
155
+ }
156
+ return enhanced;
157
+ }
158
+ function insertAttributeBeforeTagEnd(tag, attribute) {
159
+ const endMatch = tag.match(/\s*\/?>$/);
160
+ if (endMatch === null) {
161
+ return tag;
162
+ }
163
+ return tag.slice(0, tag.length - endMatch[0].length) + attribute + endMatch[0];
164
+ }
124
165
  export function stripManagedIndexBlock(markdown) {
125
166
  return markdown.replace(/\n?<!-- INDEX:START -->[\s\S]*?<!-- INDEX:END -->\n?/g, '\n').trimEnd();
126
167
  }
@@ -1,4 +1,5 @@
1
1
  import type { ContentStore } from './content-store.js';
2
+ import { type AssetUrlResolver } from './asset-urls.js';
2
3
  import type { MdoPlugin } from './extensions.js';
3
4
  import type { ResolvedSiteConfig } from './site-config.js';
4
5
  import type { SearchApi } from '../search.js';
@@ -13,6 +14,13 @@ export interface HandleSiteRequestOptions {
13
14
  requestUrl?: string;
14
15
  searchApi?: SearchApi;
15
16
  plugins?: MdoPlugin[];
17
+ /**
18
+ * Optional external asset origin rewriter for rendered binary asset
19
+ * references (markdown media sources, cover / social images). Supplied by
20
+ * deployments that know which paths live on the external origin, e.g. the
21
+ * Cloudflare worker from its manifest.
22
+ */
23
+ resolveAssetUrl?: AssetUrlResolver;
16
24
  }
17
25
  export interface SiteResponse {
18
26
  status: number;
@@ -1,4 +1,5 @@
1
1
  import path from 'node:path';
2
+ import { applyAssetUrlResolver } from './asset-urls.js';
2
3
  import { isIgnoredContentName } from './content-store.js';
3
4
  import { inferDirectoryContentType, resolveContentType, } from './content-type.js';
4
5
  import { getDirectoryIndexCandidates, isCanonicalContentSource } from './directory-index.js';
@@ -174,7 +175,10 @@ async function handleSiteRequestWithoutLocaleDetection(store, pathname, options)
174
175
  return renderListingPostsFragment(listingEntries, listingFragmentRequest);
175
176
  }
176
177
  const documentBody = listingEntries.length > 0 ? stripManagedIndexBlock(renderedBody) : renderedBody;
177
- const renderedParsed = await parseMarkdownDocument(resolved.sourcePath, documentBody);
178
+ const renderedParsed = await parseMarkdownDocument(resolved.sourcePath, documentBody, {
179
+ requestPath: resolved.requestPath,
180
+ resolveAssetUrl: options.resolveAssetUrl,
181
+ });
178
182
  return renderStructuredPage({
179
183
  requestPath: resolved.requestPath,
180
184
  sourcePath: resolved.sourcePath,
@@ -184,6 +188,7 @@ async function handleSiteRequestWithoutLocaleDetection(store, pathname, options)
184
188
  topNav: navigation.items,
185
189
  listingEntries,
186
190
  searchEnabled,
191
+ resolveAssetUrl: options.resolveAssetUrl,
187
192
  plugins,
188
193
  store,
189
194
  requestLocale,
@@ -297,8 +302,8 @@ function buildPageRenderModel(options) {
297
302
  siteDescription: options.siteDescription ?? options.siteConfig.siteDescription,
298
303
  siteUrl: options.siteConfig.siteUrl,
299
304
  favicon: options.siteConfig.favicon,
300
- socialImage: resolvePageSocialImage(options.parsed.meta.socialImage, options.resolvedRequestPath) ??
301
- options.siteConfig.socialImage,
305
+ socialImage: applyAssetUrlResolver(resolvePageSocialImage(options.parsed.meta.socialImage, options.resolvedRequestPath) ??
306
+ options.siteConfig.socialImage, options.resolvedRequestPath, options.resolveAssetUrl),
302
307
  logo: options.siteConfig.logo,
303
308
  title: getDocumentTitle(options.parsed),
304
309
  meta: options.parsed.meta,
@@ -343,6 +348,7 @@ async function renderStructuredPage(options) {
343
348
  siteDescription: getEffectiveSiteDescription(options.siteConfig, localeConfig),
344
349
  footerNav: getEffectiveFooterNav(options.siteConfig, localeConfig),
345
350
  topNav: options.topNav,
351
+ resolveAssetUrl: options.resolveAssetUrl,
346
352
  listingEntries: options.listingEntries,
347
353
  searchEnabled: options.searchEnabled,
348
354
  });
@@ -1155,7 +1161,10 @@ async function tryRenderAlternateDirectoryIndex(store, requestPath, options) {
1155
1161
  return renderListingPostsFragment(listingEntries, listingFragmentRequest);
1156
1162
  }
1157
1163
  const documentBody = listingEntries.length > 0 ? stripManagedIndexBlock(renderedBody) : renderedBody;
1158
- const renderedParsed = await parseMarkdownDocument(candidatePath, documentBody);
1164
+ const renderedParsed = await parseMarkdownDocument(candidatePath, documentBody, {
1165
+ requestPath,
1166
+ resolveAssetUrl: options.resolveAssetUrl,
1167
+ });
1159
1168
  return renderStructuredPage({
1160
1169
  requestPath,
1161
1170
  sourcePath: candidatePath,
@@ -1165,6 +1174,7 @@ async function tryRenderAlternateDirectoryIndex(store, requestPath, options) {
1165
1174
  topNav: navigation.items,
1166
1175
  listingEntries,
1167
1176
  searchEnabled: options.searchApi !== undefined,
1177
+ resolveAssetUrl: options.resolveAssetUrl,
1168
1178
  plugins,
1169
1179
  store,
1170
1180
  requestLocale,
@@ -63,6 +63,19 @@ export interface SiteSearchConfig {
63
63
  scoreAdjustment?: SiteSearchScoreAdjustmentConfig;
64
64
  policy?: SiteSearchPolicyConfig;
65
65
  }
66
+ export interface SiteAssetsConfig {
67
+ /**
68
+ * Absolute http(s) base URL of an external asset origin, e.g. an R2 custom
69
+ * domain or a CDN in front of the same bucket. Requires external binary
70
+ * mode: rendered references to R2-backed binary assets are rewritten to
71
+ * `${baseUrl}<same path>`, while the Worker route keeps serving the same
72
+ * paths as a fallback for crawlers and old links.
73
+ */
74
+ baseUrl?: string;
75
+ }
76
+ export interface ResolvedSiteAssetsConfig {
77
+ baseUrl: string;
78
+ }
66
79
  export interface SiteConfig {
67
80
  siteTitle?: string;
68
81
  siteDescription?: string;
@@ -103,6 +116,7 @@ export interface SiteConfig {
103
116
  listingInitialPostCount?: number;
104
117
  listingLoadMoreStep?: number;
105
118
  search?: SiteSearchConfig;
119
+ assets?: SiteAssetsConfig;
106
120
  }
107
121
  export interface UserSiteConfig extends SiteConfig {
108
122
  plugins?: MdoPlugin[];
@@ -133,6 +147,7 @@ export interface ResolvedSiteConfig {
133
147
  listingInitialPostCount: number;
134
148
  listingLoadMoreStep: number;
135
149
  search?: SiteSearchConfig;
150
+ assets?: ResolvedSiteAssetsConfig;
136
151
  stylesheetContent?: string;
137
152
  siteTitleConfigured: boolean;
138
153
  siteDescriptionConfigured: boolean;
@@ -5,6 +5,7 @@ import { tsImport } from 'tsx/esm/api';
5
5
  import { getDirectoryIndexCandidates } from './directory-index.js';
6
6
  import { parseEntryDocumentMeta } from './markdown.js';
7
7
  import { normalizeSiteRobots } from './seo.js';
8
+ import { normalizeAssetBaseUrl } from './asset-urls.js';
8
9
  import { DEFAULT_SITE_LOCALE, validateSiteMessages, } from '../i18n/messages.js';
9
10
  export async function loadSiteConfig(options = {}) {
10
11
  return (await loadUserSiteConfig(options)).siteConfig;
@@ -62,6 +63,7 @@ export async function loadUserSiteConfig(options = {}) {
62
63
  listingInitialPostCount: normalizePositiveInteger(parsedConfig.listingInitialPostCount ?? legacyConfig.catalogInitialPostCount, 10),
63
64
  listingLoadMoreStep: normalizePositiveInteger(parsedConfig.listingLoadMoreStep ?? legacyConfig.catalogLoadMoreStep, 10),
64
65
  search: normalizeSearchConfig(parsedConfig.search, configFilePath),
66
+ assets: resolveAssetsConfig(parsedConfig.assets, configFilePath),
65
67
  stylesheetContent,
66
68
  siteTitleConfigured: typeof parsedConfig.siteTitle === 'string' && parsedConfig.siteTitle !== '',
67
69
  siteDescriptionConfigured: typeof parsedConfig.siteDescription === 'string' &&
@@ -122,6 +124,26 @@ function resolveLocaleDetectionConfig(value, configFilePath) {
122
124
  redirect: 'root',
123
125
  };
124
126
  }
127
+ function resolveAssetsConfig(value, configFilePath) {
128
+ if (value === undefined) {
129
+ return undefined;
130
+ }
131
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) {
132
+ throw new Error(`Invalid "assets" in ${configFilePath}: expected an object`);
133
+ }
134
+ if (value.baseUrl === undefined) {
135
+ return undefined;
136
+ }
137
+ if (typeof value.baseUrl !== 'string' || value.baseUrl === '') {
138
+ throw new Error(`Invalid "assets.baseUrl" in ${configFilePath}: expected a non-empty string`);
139
+ }
140
+ try {
141
+ return { baseUrl: normalizeAssetBaseUrl(value.baseUrl) };
142
+ }
143
+ catch (error) {
144
+ throw new Error(`Invalid "assets.baseUrl" in ${configFilePath}: ${error instanceof Error ? error.message : String(error)}`);
145
+ }
146
+ }
125
147
  function resolveMessageOverrides(value, configFilePath) {
126
148
  if (value === undefined) {
127
149
  return {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mdorigin",
3
- "version": "0.7.3",
3
+ "version": "0.8.1",
4
4
  "type": "module",
5
5
  "description": "Markdown-first publishing for humans and agents.",
6
6
  "repository": {