inlaycms 0.5.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/assets/admin/admin.css +1 -1
  2. package/assets/admin/admin.js +1 -1
  3. package/dist/adapters/admin/publish.js +2 -2
  4. package/dist/adapters/admin/screens/editor.js +4 -2
  5. package/dist/adapters/admin/screens/media.d.ts +4 -1
  6. package/dist/adapters/admin/screens/media.js +22 -2
  7. package/dist/adapters/admin/screens/redirects.js +3 -1
  8. package/dist/adapters/admin/screens/releases.js +8 -3
  9. package/dist/adapters/admin/views/data-table.js +1 -1
  10. package/dist/adapters/admin/views/layout.d.ts +1 -1
  11. package/dist/adapters/admin/views/layout.js +12 -2
  12. package/dist/adapters/cli/main.js +21 -3
  13. package/dist/adapters/mcp/agent-refs.d.ts +2 -1
  14. package/dist/adapters/mcp/agent-refs.js +4 -4
  15. package/dist/adapters/mcp/tools/publish.js +1 -1
  16. package/dist/adapters/mcp/tools/read.d.ts +1 -1
  17. package/dist/adapters/mcp/tools/read.js +46 -3
  18. package/dist/adapters/mcp/tools/write.js +77 -6
  19. package/dist/adapters/site/context.d.ts +4 -1
  20. package/dist/adapters/site/context.js +9 -7
  21. package/dist/adapters/site/head.d.ts +2 -0
  22. package/dist/adapters/site/head.js +6 -6
  23. package/dist/adapters/site/plugin.d.ts +2 -0
  24. package/dist/adapters/site/plugin.js +25 -8
  25. package/dist/adapters/site/preview.d.ts +2 -0
  26. package/dist/adapters/site/preview.js +10 -5
  27. package/dist/adapters/site/public.d.ts +9 -1
  28. package/dist/adapters/site/public.js +48 -30
  29. package/dist/adapters/site/render.js +7 -2
  30. package/dist/adapters/site/routes.js +4 -3
  31. package/dist/adapters/site/sitemap.d.ts +2 -1
  32. package/dist/adapters/site/sitemap.js +3 -3
  33. package/dist/core/content/find-text.d.ts +31 -0
  34. package/dist/core/content/find-text.js +124 -0
  35. package/dist/core/content/search.js +1 -14
  36. package/dist/core/content/text-match.d.ts +14 -0
  37. package/dist/core/content/text-match.js +99 -0
  38. package/dist/core/content/text-replace.d.ts +14 -0
  39. package/dist/core/content/text-replace.js +100 -0
  40. package/dist/core/core.d.ts +7 -0
  41. package/dist/core/core.js +2 -0
  42. package/dist/core/messages/en.d.ts +43 -4
  43. package/dist/core/messages/en.js +43 -4
  44. package/dist/core/registry/define.d.ts +5 -0
  45. package/dist/core/registry/define.js +1 -0
  46. package/dist/core/registry/render.d.ts +6 -1
  47. package/dist/core/release/manifest.d.ts +0 -5
  48. package/dist/core/release/manifest.js +0 -24
  49. package/dist/core/release/pack.js +4 -0
  50. package/dist/core/release/public-files.d.ts +14 -0
  51. package/dist/core/release/public-files.js +43 -0
  52. package/dist/core/release/read.d.ts +2 -2
  53. package/dist/core/release/read.js +11 -12
  54. package/dist/core/release/window.d.ts +13 -0
  55. package/dist/core/release/window.js +40 -0
  56. package/dist/core/report.d.ts +1 -1
  57. package/dist/core/richtext/runs.d.ts +12 -0
  58. package/dist/core/richtext/runs.js +31 -0
  59. package/dist/core/site/paths.d.ts +5 -0
  60. package/dist/core/site/paths.js +32 -0
  61. package/dist/core/site/resolve.js +17 -6
  62. package/dist/core/version.d.ts +6 -0
  63. package/dist/core/version.js +6 -0
  64. package/dist/host/activate.js +2 -1
  65. package/dist/host/app.d.ts +6 -0
  66. package/dist/host/app.js +3 -0
  67. package/dist/host/push.d.ts +5 -1
  68. package/dist/host/push.js +17 -5
  69. package/dist/host/worker.js +9 -3
  70. package/dist/site.d.ts +1 -1
  71. package/package.json +1 -1
@@ -1,7 +1,7 @@
1
1
  import { InlayError } from '../../core/errors.js';
2
2
  import { isSafeUrl } from '../../core/fields/define.js';
3
3
  import { scriptJson } from '../../core/registry/js.js';
4
- import { encodePath } from '../../core/site/paths.js';
4
+ import { encodePath, presentHref } from '../../core/site/paths.js';
5
5
  import { escapeHtml, raw } from '../../jsx/html.js';
6
6
  export const NO_HEAD = { meta: [], links: [], jsonLd: [] };
7
7
  const LINK_ATTRS = ['rel', 'hreflang', 'type', 'sizes', 'media', 'as', 'crossorigin', 'href'];
@@ -33,14 +33,14 @@ export function createHeadCollector() {
33
33
  };
34
34
  return { api, collected: () => ({ meta: [...head.meta], links: [...head.links], jsonLd: [...head.jsonLd] }) };
35
35
  }
36
- function absolute(baseUrl, path) {
36
+ function absolute(baseUrl, path, mode) {
37
37
  const [p = '', query] = path.split('?');
38
- return `${baseUrl}${p === '/' ? '/' : encodePath(p)}${query === undefined ? '' : `?${query}`}`;
38
+ return `${baseUrl}${p === '/' ? '/' : presentHref(encodePath(p), mode)}${query === undefined ? '' : `?${query}`}`;
39
39
  }
40
40
  const meta = (attr, key, content) => ({ tag: 'meta', attr, key, content });
41
41
  /** Inlay's own tags for the page, before any Twitter tags. */
42
42
  function inlayTags(input) {
43
- const url = input.canonical === null ? null : absolute(input.baseUrl, input.canonical);
43
+ const url = input.canonical === null ? null : absolute(input.baseUrl, input.canonical, input.trailingSlash);
44
44
  const tags = [{ tag: 'title', text: input.title }];
45
45
  if (input.description)
46
46
  tags.push(meta('name', 'description', input.description));
@@ -48,11 +48,11 @@ function inlayTags(input) {
48
48
  tags.push({ tag: 'link', attrs: { rel: 'canonical', href: url } });
49
49
  if (input.alternates.length >= 2) {
50
50
  for (const a of input.alternates) {
51
- tags.push({ tag: 'link', attrs: { rel: 'alternate', hreflang: a.locale, href: absolute(input.baseUrl, a.path) } });
51
+ tags.push({ tag: 'link', attrs: { rel: 'alternate', hreflang: a.locale, href: absolute(input.baseUrl, a.path, input.trailingSlash) } });
52
52
  }
53
53
  const def = input.alternates.find((a) => a.locale === input.defaultLocale);
54
54
  if (def)
55
- tags.push({ tag: 'link', attrs: { rel: 'alternate', hreflang: 'x-default', href: absolute(input.baseUrl, def.path) } });
55
+ tags.push({ tag: 'link', attrs: { rel: 'alternate', hreflang: 'x-default', href: absolute(input.baseUrl, def.path, input.trailingSlash) } });
56
56
  }
57
57
  tags.push(meta('property', 'og:type', input.ogType));
58
58
  tags.push(meta('property', 'og:title', input.title));
@@ -76,6 +76,8 @@ export interface InlayOptions {
76
76
  trustedKeys?: readonly string[];
77
77
  /** What the admin's Releases screen can ask of `inlaycms serve` (preview, activate, push checks). */
78
78
  adminHost?: AdminHostHooks;
79
+ /** Also serves the files in `publicDir` whose names have a dot at the site root, such as `/privacy-policy.pdf`. */
80
+ rootPublicFiles?: boolean;
79
81
  }
80
82
  /** What a site running under `inlaycms serve` can ask of the server. */
81
83
  export interface HostApi {
@@ -9,7 +9,7 @@ import { DEFAULT_MAX_BYTES, DEFAULT_UPLOAD_TYPES } from '../../core/media/detect
9
9
  import { t } from '../../core/messages/index.js';
10
10
  import { externalTarget } from '../../core/redirects/rule.js';
11
11
  import { buildRegistry } from '../../core/registry/registry.js';
12
- import { encodePath, normalizePath, splitLocale } from '../../core/site/paths.js';
12
+ import { encodePath, normalizePath, presentHref, splitLocale } from '../../core/site/paths.js';
13
13
  import { loadAdminAssets } from '../admin/assets.js';
14
14
  import { registerAdminRoutes } from '../admin/routes.js';
15
15
  import { resolveTheme, themeContrastProblems } from '../admin/theme.js';
@@ -30,7 +30,7 @@ import { startBackupSchedule } from './backup-schedule.js';
30
30
  import { isLockedRequest, registerSiteLockGate, registerUnlockRoute } from './lock.js';
31
31
  import { codeFilesFor, registerCodeFileRoutes } from './code-files.js';
32
32
  import { registerMediaRoutes } from './media-routes.js';
33
- import { registerPublicRoutes } from './public.js';
33
+ import { registerPublicRoutes, rootPublicPath, sendPublicFile } from './public.js';
34
34
  import { previewLink, readPreview, registerPreviewRoutes } from './preview.js';
35
35
  import { catalogPage, renderPageResult } from './render.js';
36
36
  import { registerReleaseRoutes } from './routes.js';
@@ -121,7 +121,8 @@ function createApi(core, cache, service, opts) {
121
121
  }
122
122
  function registerSiteRoutes(app, core, cache, integrations, opts) {
123
123
  const { registry } = core;
124
- const { notFound } = registry.site;
124
+ const { notFound, trailingSlash: mode } = registry.site;
125
+ const always = mode === 'always';
125
126
  const { baseUrl, cdn, assets } = opts;
126
127
  const banner = opts.release === undefined ? {} : { release: opts.release };
127
128
  async function notFoundPage(locale, state) {
@@ -183,6 +184,14 @@ function registerSiteRoutes(app, core, cache, integrations, opts) {
183
184
  }
184
185
  async function handle(request, reply) {
185
186
  const { path, search } = splitUrl(request.url);
187
+ if (opts.rootPublic !== undefined) {
188
+ const rootPath = rootPublicPath(request.raw.url ?? '');
189
+ if (rootPath !== null) {
190
+ const sent = await sendPublicFile(request, reply, { ...opts.rootPublic, autoHead: true }, rootPath);
191
+ if (sent !== null)
192
+ return sent;
193
+ }
194
+ }
186
195
  const state = opts.preview === 'forced' ? 'preview' : stateOf(request);
187
196
  const preview = state === 'preview';
188
197
  if (preview)
@@ -194,7 +203,8 @@ function registerSiteRoutes(app, core, cache, integrations, opts) {
194
203
  return await missing(request, reply, localeOf(path), state);
195
204
  const pageNumber = Number(pageParam ?? 1);
196
205
  const normalized = normalizePath(path);
197
- const canonical = normalized !== null && encodePath(normalized) === path;
206
+ const presented = normalized === null ? null : presentHref(encodePath(normalized), mode);
207
+ const canonical = presented !== null && presented === path;
198
208
  const key = preview || normalized === null || !canonical
199
209
  ? null
200
210
  : pageNumber > 1
@@ -204,16 +214,22 @@ function registerSiteRoutes(app, core, cache, integrations, opts) {
204
214
  if (hit)
205
215
  return send(request, reply, hit, true);
206
216
  const generation = cache?.generation ?? 0;
207
- const match = await core.resolvePath(path, { state });
217
+ if (always && presented !== null && !canonical && registry.getRoutePaths.has(normalized ?? '')) {
218
+ return reply.redirect(`${presented}${search}`, 301);
219
+ }
220
+ const lookup = always && path.length > 1 && path.endsWith('/') ? path.slice(0, -1) : path;
221
+ const match = await core.resolvePath(lookup, { state });
208
222
  if (match.kind === 'redirect') {
209
223
  if (match.external === true && externalTarget(match.location) === match.location) {
210
224
  return reply.redirect(match.location, match.status);
211
225
  }
212
226
  if (match.external !== true && match.location.startsWith('/') && !match.location.startsWith('//')) {
213
- return reply.redirect(`${match.location}${search}`, match.status);
227
+ return reply.redirect(`${presentHref(match.location, mode)}${search}`, match.status);
214
228
  }
215
229
  }
216
230
  if (match.kind === 'page') {
231
+ if (always && !canonical && presented !== null)
232
+ return reply.redirect(`${presented}${search}`, 301);
217
233
  const page = await renderPageResult(core, match.document, { state, page: pageNumber, baseUrl, assets, integrations, ...banner });
218
234
  if (preview)
219
235
  return await sendPreview(reply, 200, page);
@@ -241,7 +257,7 @@ function registerSiteRoutes(app, core, cache, integrations, opts) {
241
257
  // A site that is down has no sitemap to give: an empty one would tell search engines its pages are gone.
242
258
  app.get('/sitemap.xml', async (request, reply) => opts.noSite === 'unavailable'
243
259
  ? unavailable(request, reply)
244
- : cached(request, reply, 'sitemap.xml', async () => response(200, renderSitemap(await core.sitemapEntries(), baseUrl), 'application/xml')));
260
+ : cached(request, reply, 'sitemap.xml', async () => response(200, renderSitemap(await core.sitemapEntries(), baseUrl, core.registry.site.trailingSlash), 'application/xml')));
245
261
  app.get('/robots.txt', async (request, reply) => {
246
262
  reply.type('text/plain; charset=utf-8');
247
263
  if (isLockedRequest(request))
@@ -472,12 +488,13 @@ const plugin = async (app, opts) => {
472
488
  if (opts.publicDir !== undefined)
473
489
  registerPublicRoutes(app, { dir: opts.publicDir, maxAge: opts.publicMaxAge ?? 3600 });
474
490
  registerReleaseRoutes(app, { core, registry, baseUrl, assets: siteAssets, integrations: siteIntegrations, secrets: opts.secrets ?? {}, fetch: opts.fetch ?? ((input, init) => globalThis.fetch(input, init)), log: app.log, preview: opts.preview === 'forced' });
475
- registerPreviewRoutes(app, { secret, baseUrl, now });
491
+ registerPreviewRoutes(app, { secret, baseUrl, now, trailingSlash: registry.site.trailingSlash });
476
492
  registerSiteRoutes(app, core, cache, siteIntegrations, {
477
493
  baseUrl,
478
494
  secret,
479
495
  now,
480
496
  assets: siteAssets,
497
+ ...(opts.publicDir !== undefined && opts.rootPublicFiles && { rootPublic: { dir: opts.publicDir, maxAge: opts.publicMaxAge ?? 3600 } }),
481
498
  ...(opts.cdn && { cdn: opts.cdn }),
482
499
  ...(opts.noSite && { noSite: opts.noSite }),
483
500
  ...(opts.preview && { preview: opts.preview }),
@@ -1,4 +1,5 @@
1
1
  import type { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify';
2
+ import { type TrailingSlash } from '../../core/site/paths.js';
2
3
  import type { LiveState } from '../../core/types.js';
3
4
  export declare const PREVIEW_COOKIE = "inlay_preview";
4
5
  export declare const PREVIEW_PATH = "/_inlay/preview";
@@ -33,4 +34,5 @@ export declare function registerPreviewRoutes(app: FastifyInstance, opts: {
33
34
  secret: string;
34
35
  baseUrl: string;
35
36
  now: () => Date;
37
+ trailingSlash?: TrailingSlash;
36
38
  }): void;
@@ -1,5 +1,5 @@
1
1
  import { createPreviewToken, verifyPreviewToken } from '../../core/preview.js';
2
- import { encodePath, normalizePath } from '../../core/site/paths.js';
2
+ import { encodePath, normalizePath, presentHref } from '../../core/site/paths.js';
3
3
  import { catalogPage, PREVIEW_EXIT_PATH } from './render.js';
4
4
  export const PREVIEW_COOKIE = 'inlay_preview';
5
5
  export const PREVIEW_PATH = '/_inlay/preview';
@@ -37,12 +37,16 @@ export function readPreview(request, secret, now) {
37
37
  export function previewState(request, secret, now) {
38
38
  return readPreview(request, secret, now).state;
39
39
  }
40
- /** `raw` when it's a clean, encoded site-relative path, otherwise `/`. */
41
- function safeTarget(raw) {
40
+ /** `raw` in its presented form when it's a clean, encoded site-relative path, otherwise `/`. */
41
+ function safeTarget(raw, mode) {
42
42
  if (typeof raw !== 'string')
43
43
  return '/';
44
44
  const normalized = normalizePath(raw);
45
- return normalized !== null && encodePath(normalized) === raw ? raw : '/';
45
+ if (normalized === null)
46
+ return '/';
47
+ const encoded = encodePath(normalized);
48
+ const presented = presentHref(encoded, mode);
49
+ return raw === encoded || raw === presented ? presented : '/';
46
50
  }
47
51
  /** Turns preview off for this browser. */
48
52
  export function clearPreviewCookie(reply, baseUrl) {
@@ -59,6 +63,7 @@ function setCookie(reply, value, maxAge, secure) {
59
63
  * release a release link previews); `GET /_inlay/preview/exit` turns it off.
60
64
  */
61
65
  export function registerPreviewRoutes(app, opts) {
66
+ const mode = opts.trailingSlash ?? 'never';
62
67
  const secure = opts.baseUrl.startsWith('https:');
63
68
  app.get(PREVIEW_PATH, async (request, reply) => {
64
69
  const query = request.query;
@@ -73,7 +78,7 @@ export function registerPreviewRoutes(app, opts) {
73
78
  .send(catalogPage('preview.expired.title', 'preview.expired'));
74
79
  }
75
80
  setCookie(reply, token, Math.ceil((valid.expiresAt.getTime() - now.getTime()) / 1000), secure);
76
- return reply.redirect(safeTarget(query.path), 302);
81
+ return reply.redirect(safeTarget(query.path, mode), 302);
77
82
  });
78
83
  app.get(PREVIEW_EXIT_PATH, async (_request, reply) => {
79
84
  setCookie(reply, '', 0, secure);
@@ -1,4 +1,12 @@
1
- import type { FastifyInstance } from 'fastify';
1
+ import type { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify';
2
+ /** The request's path without its query or leading `/`, when its last segment has a `.`; null otherwise. */
3
+ export declare function rootPublicPath(rawUrl: string): string | null;
4
+ /** Sends the file `rawPath` names under `opts.dir`, or returns null, leaving `reply` alone, when nothing servable is there. */
5
+ export declare function sendPublicFile(request: FastifyRequest, reply: FastifyReply, opts: {
6
+ dir: string;
7
+ maxAge: number;
8
+ autoHead?: boolean;
9
+ }, rawPath: string): Promise<FastifyReply | null>;
2
10
  /** Serves the files under `opts.dir` at `/public/*`, GET and HEAD, never anything outside it. */
3
11
  export declare function registerPublicRoutes(app: FastifyInstance, opts: {
4
12
  dir: string;
@@ -26,45 +26,63 @@ const TYPES = {
26
26
  '.pdf': 'application/pdf',
27
27
  '.map': 'application/json; charset=utf-8',
28
28
  };
29
+ /** The request's path without its query or leading `/`, when its last segment has a `.`; null otherwise. */
30
+ export function rootPublicPath(rawUrl) {
31
+ const q = rawUrl.indexOf('?');
32
+ const path = q === -1 ? rawUrl : rawUrl.slice(0, q);
33
+ const last = path.slice(path.lastIndexOf('/') + 1);
34
+ if (!last.includes('.'))
35
+ return null;
36
+ return path.slice(1);
37
+ }
38
+ /** Sends the file `rawPath` names under `opts.dir`, or returns null, leaving `reply` alone, when nothing servable is there. */
39
+ export async function sendPublicFile(request, reply, opts, rawPath) {
40
+ const file = locate(opts.dir, rawPath);
41
+ if (file === null)
42
+ return null;
43
+ let bytes;
44
+ try {
45
+ // A symlink is never followed: not as the file, nor as a folder on the way to it.
46
+ if (!(await lstat(file)).isFile())
47
+ return null;
48
+ if (!(await realpath(file)).startsWith((await realpath(opts.dir)) + sep))
49
+ return null;
50
+ bytes = await readFile(file);
51
+ }
52
+ catch {
53
+ return null;
54
+ }
55
+ const rawUrl = request.raw.url ?? '';
56
+ const q = rawUrl.indexOf('?');
57
+ const hex = createHash('sha256').update(bytes).digest('hex');
58
+ const etag = `"${hex.slice(0, 32)}"`;
59
+ const version = new URLSearchParams(q === -1 ? '' : rawUrl.slice(q + 1)).get('v');
60
+ const cacheControl = version === hex.slice(0, ASSET_VERSION_LENGTH) ? 'public, max-age=31536000, immutable' : `public, max-age=${opts.maxAge}`;
61
+ reply.header('cache-control', cacheControl).header('etag', etag);
62
+ if (etagMatches(request.headers['if-none-match'], etag))
63
+ return reply.code(304).send();
64
+ const ext = extname(file).toLowerCase();
65
+ reply.type(TYPES[ext] ?? 'application/octet-stream').header('x-content-type-options', 'nosniff');
66
+ // An SVG opened on its own could run script on the site's origin.
67
+ if (ext === '.svg')
68
+ reply.header('content-security-policy', "default-src 'none'; style-src 'unsafe-inline'");
69
+ // Under a GET-only route Fastify answers HEAD itself, from the payload's length.
70
+ return request.method === 'HEAD' && opts.autoHead !== true ? reply.header('content-length', bytes.length).send() : reply.send(bytes);
71
+ }
29
72
  /** Serves the files under `opts.dir` at `/public/*`, GET and HEAD, never anything outside it. */
30
73
  export function registerPublicRoutes(app, opts) {
31
74
  app.route({
32
75
  method: ['GET', 'HEAD'],
33
76
  url: '/public/*',
34
77
  handler: async (request, reply) => {
35
- const missing = () => reply.code(404).type('text/html; charset=utf-8').header('cache-control', 'no-store').send(catalogPage('site.notFound.title', 'site.notFound'));
36
78
  const wildcard = request.params['*'] ?? '';
37
- const q = request.raw.url?.indexOf('?') ?? -1;
38
79
  const rawUrl = request.raw.url ?? '';
80
+ const q = rawUrl.indexOf('?');
39
81
  const rawPath = (q === -1 ? rawUrl : rawUrl.slice(0, q)).slice('/public/'.length);
40
- const file = locate(opts.dir, rawPath === '' ? wildcard : rawPath);
41
- if (file === null)
42
- return missing();
43
- let bytes;
44
- try {
45
- // A symlink is never followed: not as the file, nor as a folder on the way to it.
46
- if (!(await lstat(file)).isFile())
47
- return missing();
48
- if (!(await realpath(file)).startsWith((await realpath(opts.dir)) + sep))
49
- return missing();
50
- bytes = await readFile(file);
51
- }
52
- catch {
53
- return missing();
54
- }
55
- const hex = createHash('sha256').update(bytes).digest('hex');
56
- const etag = `"${hex.slice(0, 32)}"`;
57
- const version = new URLSearchParams(q === -1 ? '' : rawUrl.slice(q + 1)).get('v');
58
- const cacheControl = version === hex.slice(0, ASSET_VERSION_LENGTH) ? 'public, max-age=31536000, immutable' : `public, max-age=${opts.maxAge}`;
59
- reply.header('cache-control', cacheControl).header('etag', etag);
60
- if (etagMatches(request.headers['if-none-match'], etag))
61
- return reply.code(304).send();
62
- const ext = extname(file).toLowerCase();
63
- reply.type(TYPES[ext] ?? 'application/octet-stream').header('x-content-type-options', 'nosniff');
64
- // An SVG opened on its own could run script on the site's origin.
65
- if (ext === '.svg')
66
- reply.header('content-security-policy', "default-src 'none'; style-src 'unsafe-inline'");
67
- return request.method === 'HEAD' ? reply.header('content-length', bytes.length).send() : reply.send(bytes);
82
+ const sent = await sendPublicFile(request, reply, opts, rawPath === '' ? wildcard : rawPath);
83
+ if (sent !== null)
84
+ return sent;
85
+ return reply.code(404).type('text/html; charset=utf-8').header('cache-control', 'no-store').send(catalogPage('site.notFound.title', 'site.notFound'));
68
86
  },
69
87
  });
70
88
  }
@@ -2,8 +2,9 @@ import { validateContent } from '../../core/content/validate.js';
2
2
  import { InlayError } from '../../core/errors.js';
3
3
  import { fieldMeta } from '../../core/fields/define.js';
4
4
  import { t } from '../../core/messages/index.js';
5
+ import { presentPath } from '../../core/site/paths.js';
5
6
  import { escapeHtml, raw, renderToString, toHtml } from '../../jsx/html.js';
6
- import { createRenderContext } from './context.js';
7
+ import { createRenderContext, pageUrl } from './context.js';
7
8
  import { buildHead, injectHead } from './head.js';
8
9
  import { injectIntegrations } from './integrations.js';
9
10
  import { isHomePath, mediaShareImage, pageTitle, resolveSeoDefaults } from './seo.js';
@@ -128,6 +129,7 @@ async function renderTemplate(core, doc, opts, internal = {}) {
128
129
  contentLocale: doc.contentLocale,
129
130
  fallback: doc.fallback,
130
131
  path: doc.path ?? '',
132
+ url: pageUrl(doc.path ?? '', core.registry.site.trailingSlash),
131
133
  publishedAt: doc.publishedAt,
132
134
  page: opts.page,
133
135
  };
@@ -148,6 +150,7 @@ async function renderTemplate(core, doc, opts, internal = {}) {
148
150
  alternates: doc.fallback ? [] : alternates.filter((a) => !a.fallback),
149
151
  defaultLocale: core.registry.defaultLocale,
150
152
  baseUrl: opts.baseUrl,
153
+ trailingSlash: core.registry.site.trailingSlash,
151
154
  preview: opts.state === 'preview',
152
155
  collected: ctx.headTags(),
153
156
  });
@@ -156,7 +159,7 @@ async function renderTemplate(core, doc, opts, internal = {}) {
156
159
  const open = HEAD_OPEN.exec(out);
157
160
  if (open) {
158
161
  const at = open.index + open[0].length;
159
- out = `${out.slice(0, at)}<base href="${escapeHtml(doc.path)}">${out.slice(at)}`;
162
+ out = `${out.slice(0, at)}<base href="${escapeHtml(presentPath(doc.path, core.registry.site.trailingSlash))}">${out.slice(at)}`;
160
163
  }
161
164
  }
162
165
  if (!internal.pane) {
@@ -192,6 +195,7 @@ export async function renderTemplateResult(core, template, data, opts) {
192
195
  contentLocale: opts.locale,
193
196
  fallback: false,
194
197
  path: opts.path,
198
+ url: pageUrl(opts.path, core.registry.site.trailingSlash),
195
199
  publishedAt: null,
196
200
  page: 1,
197
201
  };
@@ -208,6 +212,7 @@ export async function renderTemplateResult(core, template, data, opts) {
208
212
  alternates: [],
209
213
  defaultLocale: core.registry.defaultLocale,
210
214
  baseUrl: opts.baseUrl,
215
+ trailingSlash: core.registry.site.trailingSlash,
211
216
  preview: opts.preview === true,
212
217
  collected: ctx.headTags(),
213
218
  });
@@ -1,7 +1,7 @@
1
1
  import { normalizeContent } from '../../core/content/schema.js';
2
2
  import { readData } from '../../core/content/reader.js';
3
3
  import { t } from '../../core/messages/index.js';
4
- import { encodePath } from '../../core/site/paths.js';
4
+ import { encodePath, presentPath } from '../../core/site/paths.js';
5
5
  import { publicAssets } from './assets.js';
6
6
  import { queryApi } from './context.js';
7
7
  import { catalogPage, renderTemplateResult } from './render.js';
@@ -89,9 +89,10 @@ export function registerReleaseRoutes(app, opts) {
89
89
  register(scope, route);
90
90
  });
91
91
  function register(scope, route) {
92
+ const url = route.method === 'GET' ? presentPath(route.path, registry.site.trailingSlash) : route.path;
92
93
  scope.route({
93
94
  method: route.method,
94
- url: route.path,
95
+ url,
95
96
  handler: async (request, reply) => {
96
97
  const query = plainQuery(request.url);
97
98
  const type = request.headers['content-type'] ?? '';
@@ -112,7 +113,7 @@ export function registerReleaseRoutes(app, opts) {
112
113
  async render(template, data = {}, o = {}) {
113
114
  const read = templateRegistry(registry, template);
114
115
  const doc = readData(read, template.name, normalizeContent(read, template.name, data), { fill: true }).data;
115
- const canonical = route.sitemap === true && request.url.split('?')[0] === encodePath(route.path) ? route.path : null;
116
+ const canonical = route.sitemap === true && request.url.split('?')[0] === encodePath(url) ? route.path : null;
116
117
  const rendered = await renderTemplateResult(core, template, doc, { locale, path: route.path, baseUrl, canonical, assets, preview: opts.preview === true, ...(opts.integrations && { integrations: opts.integrations }) });
117
118
  const csp = (await opts.integrations?.policy(rendered.scriptHashes)) ?? null;
118
119
  const headers = { 'content-type': HTML };
@@ -1,3 +1,4 @@
1
+ import { type TrailingSlash } from '../../core/site/paths.js';
1
2
  interface Item {
2
3
  path: string;
3
4
  updatedAt?: string;
@@ -6,5 +7,5 @@ interface Item {
6
7
  path: string;
7
8
  }>;
8
9
  }
9
- export declare function renderSitemap(entries: readonly Item[], baseUrl: string): string;
10
+ export declare function renderSitemap(entries: readonly Item[], baseUrl: string, trailingSlash: TrailingSlash): string;
10
11
  export {};
@@ -1,7 +1,7 @@
1
1
  import { escapeHtml } from '../../jsx/html.js';
2
- import { encodePath } from '../../core/site/paths.js';
3
- export function renderSitemap(entries, baseUrl) {
4
- const url = (path) => escapeHtml(`${baseUrl}${path === '/' ? '/' : encodePath(path)}`);
2
+ import { encodePath, presentHref } from '../../core/site/paths.js';
3
+ export function renderSitemap(entries, baseUrl, trailingSlash) {
4
+ const url = (path) => escapeHtml(`${baseUrl}${path === '/' ? '/' : presentHref(encodePath(path), trailingSlash)}`);
5
5
  const items = entries.map((e) => {
6
6
  const links = e.alternates.map((a) => `<xhtml:link rel="alternate" hreflang="${escapeHtml(a.locale)}" href="${url(a.path)}"/>`);
7
7
  return `<url><loc>${url(e.path)}</loc>${e.updatedAt === undefined ? '' : `<lastmod>${escapeHtml(e.updatedAt.slice(0, 10))}</lastmod>`}${links.join('')}</url>`;
@@ -0,0 +1,31 @@
1
+ import { type PathSegment } from '../fields/walk.js';
2
+ import type { CoreDeps, DocumentSummary } from '../types.js';
3
+ export interface TextOccurrence {
4
+ n: number;
5
+ snippet: string;
6
+ spansFormatting?: true;
7
+ }
8
+ export interface FieldMatch {
9
+ path: PathSegment[];
10
+ text: string;
11
+ count: number;
12
+ occurrences: TextOccurrence[];
13
+ hidden?: true;
14
+ }
15
+ export interface FindTextResult {
16
+ total: number;
17
+ documents: Array<{
18
+ document: DocumentSummary;
19
+ matches: FieldMatch[];
20
+ }>;
21
+ designedInCode: Array<{
22
+ type: string;
23
+ title: string;
24
+ }>;
25
+ }
26
+ export declare function findText(deps: CoreDeps, text: string, opts?: {
27
+ type?: string;
28
+ locale?: string;
29
+ limit?: number;
30
+ offset?: number;
31
+ }): Promise<FindTextResult>;
@@ -0,0 +1,124 @@
1
+ import { fieldValues } from '../fields/walk.js';
2
+ import { isRecord } from '../fields/zod-internals.js';
3
+ import { textRuns } from '../richtext/runs.js';
4
+ import { designedInCode } from '../registry/designed.js';
5
+ import { documentSchema } from './schema.js';
6
+ import { parseData, summaryQuery, toSummary } from './read.js';
7
+ import { findPhrase, snippetAround } from './text-match.js';
8
+ const KINDS = new Set(['text', 'textarea', 'richText', 'inlineText', 'link']);
9
+ const SNIPPET = 100;
10
+ const MAX_OCCURRENCES = 20;
11
+ function hiddenSlot(data, path) {
12
+ if (path[0] !== 'slots' || typeof path[1] !== 'string')
13
+ return false;
14
+ const slot = data.slots[path[1]];
15
+ return isRecord(slot) && slot.enabled === false;
16
+ }
17
+ /**
18
+ * The fields of a document's values in schema order, including those in switched-off slots,
19
+ * whose draft schema carries no field kinds: those are walked with their block's schema instead.
20
+ */
21
+ function foundFields(deps, type, data) {
22
+ const { slots } = deps.registry.getType(type).template;
23
+ const keys = Object.keys(slots);
24
+ const off = new Map();
25
+ for (const [key, slot] of Object.entries(slots)) {
26
+ const value = data.slots[key];
27
+ if (!isRecord(value) || value.enabled !== false)
28
+ continue;
29
+ const found = fieldValues(slot.block.schema, value.data, KINDS);
30
+ off.set(key, found.map((v) => ({ ...v, path: ['slots', key, 'data', ...v.path] })));
31
+ }
32
+ const slotOf = (v) => (v.path[0] === 'slots' && typeof v.path[1] === 'string' ? v.path[1] : undefined);
33
+ const rank = (v) => {
34
+ const key = slotOf(v);
35
+ if (key === undefined)
36
+ return -1;
37
+ const i = keys.indexOf(key);
38
+ return i === -1 ? keys.length : i;
39
+ };
40
+ return fieldValues(documentSchema(deps.registry, type, 'strict'), data, KINDS)
41
+ .filter((v) => {
42
+ const key = slotOf(v);
43
+ return key === undefined || !off.has(key);
44
+ })
45
+ .concat(...off.values())
46
+ .sort((a, b) => rank(a) - rank(b));
47
+ }
48
+ function fieldMatches(fields, data, phrase) {
49
+ const matches = [];
50
+ for (const found of fields) {
51
+ let path = found.path;
52
+ const runs = [];
53
+ if (found.meta.kind === 'link') {
54
+ if (!isRecord(found.value) || typeof found.value.text !== 'string')
55
+ continue;
56
+ path = [...path, 'text'];
57
+ runs.push({ text: found.value.text, pieces: [] });
58
+ }
59
+ else if (found.meta.kind === 'richText' || found.meta.kind === 'inlineText') {
60
+ if (!isRecord(found.value) || !Array.isArray(found.value.content))
61
+ continue;
62
+ runs.push(...textRuns(found.value));
63
+ }
64
+ else if (typeof found.value === 'string') {
65
+ runs.push({ text: found.value, pieces: [] });
66
+ }
67
+ const groups = new Map();
68
+ for (const run of runs) {
69
+ for (const hit of findPhrase(run.text, phrase, 'loose')) {
70
+ let group = groups.get(hit.text);
71
+ if (!group) {
72
+ group = { path, text: hit.text, count: 0, occurrences: [] };
73
+ if (hiddenSlot(data, path))
74
+ group.hidden = true;
75
+ groups.set(hit.text, group);
76
+ }
77
+ group.count += 1;
78
+ if (group.occurrences.length < MAX_OCCURRENCES) {
79
+ const occurrence = { n: group.count, snippet: snippetAround(run.text, hit, SNIPPET) };
80
+ if (run.pieces.length > 0 && !run.pieces.some((p) => hit.start >= p.start && hit.end <= p.end)) {
81
+ occurrence.spansFormatting = true;
82
+ }
83
+ group.occurrences.push(occurrence);
84
+ }
85
+ }
86
+ }
87
+ matches.push(...groups.values());
88
+ }
89
+ return matches;
90
+ }
91
+ export async function findText(deps, text, opts = {}) {
92
+ const { registry } = deps;
93
+ if (opts.type !== undefined)
94
+ registry.getType(opts.type);
95
+ const designed = () => [...registry.site.singletons, ...registry.site.globals]
96
+ .filter((def) => (opts.type === undefined || def.name === opts.type) && designedInCode(def.template))
97
+ .map((def) => ({ type: def.name, title: def.label }));
98
+ if (text.trim() === '')
99
+ return { total: 0, documents: [], designedInCode: [] };
100
+ const limit = Math.min(100, Math.max(1, Math.trunc(opts.limit ?? 20)));
101
+ const offset = Math.max(0, Math.trunc(opts.offset ?? 0));
102
+ let query = summaryQuery(deps).where('documents.deleted_at', 'is', null);
103
+ if (opts.type !== undefined)
104
+ query = query.where('documents.type', '=', opts.type);
105
+ if (opts.locale !== undefined)
106
+ query = query.where('documents.locale', '=', opts.locale);
107
+ const rows = await query.execute();
108
+ const typeOrder = [...registry.site.singletons, ...registry.site.globals, ...registry.site.collections].map((d) => d.name);
109
+ const rank = (type) => {
110
+ const i = typeOrder.indexOf(type);
111
+ return i === -1 ? typeOrder.length : i;
112
+ };
113
+ const found = [];
114
+ for (const row of rows) {
115
+ const data = parseData(deps, row.type, row.head_data);
116
+ const matches = fieldMatches(foundFields(deps, row.type, data), data, text);
117
+ if (matches.length > 0)
118
+ found.push({ document: toSummary(deps, row), matches });
119
+ }
120
+ found.sort((a, b) => rank(a.document.type) - rank(b.document.type) ||
121
+ registry.locales.indexOf(a.document.locale) - registry.locales.indexOf(b.document.locale) ||
122
+ b.document.headRev - a.document.headRev);
123
+ return { total: found.length, documents: found.slice(offset, offset + limit), designedInCode: designed() };
124
+ }
@@ -1,23 +1,10 @@
1
1
  import { fieldValues } from '../fields/walk.js';
2
2
  import { richTextText } from '../richtext/schema.js';
3
3
  import { documentSchema } from './schema.js';
4
+ import { fold } from './text-match.js';
4
5
  import { parseData, summaryQuery, toSummary } from './read.js';
5
6
  const KINDS = new Set(['text', 'textarea', 'richText', 'inlineText']);
6
7
  const SNIPPET = 160;
7
- /** Lower-cased text without accents, with each normalized character's index in the original. */
8
- function fold(text) {
9
- let out = '';
10
- const index = [];
11
- let i = 0;
12
- for (const ch of text) {
13
- for (const c of ch.normalize('NFKD').replace(/\p{M}/gu, '').toLowerCase()) {
14
- out += c;
15
- index.push(i);
16
- }
17
- i += ch.length;
18
- }
19
- return { text: out, index };
20
- }
21
8
  const normalize = (text) => fold(text).text;
22
9
  function snippetOf(body, words) {
23
10
  if (words.length === 0)
@@ -0,0 +1,14 @@
1
+ /** Lower-cased text without accents, with each normalized character's index in the original. */
2
+ export declare function fold(text: string): {
3
+ text: string;
4
+ index: number[];
5
+ };
6
+ export interface PhraseHit {
7
+ start: number;
8
+ end: number;
9
+ text: string;
10
+ }
11
+ /** Non-overlapping whole-word hits of a phrase, left to right, as offsets into `text`. None for a phrase that is blank once loose matching drops accents. */
12
+ export declare function findPhrase(text: string, phrase: string, mode: 'loose' | 'exact'): PhraseHit[];
13
+ /** About `size` characters of `text` centered on a hit, trimmed. */
14
+ export declare function snippetAround(text: string, hit: PhraseHit, size: number): string;