inlaycms 0.4.1 → 0.6.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 (151) hide show
  1. package/README.md +18 -709
  2. package/assets/admin/admin.css +1 -1
  3. package/assets/admin/admin.js +1 -1
  4. package/assets/admin/editor.js +63 -46
  5. package/assets/site/consent.js +1 -0
  6. package/dist/adapters/admin/context.d.ts +1 -1
  7. package/dist/adapters/admin/context.js +1 -0
  8. package/dist/adapters/admin/publish.js +2 -2
  9. package/dist/adapters/admin/routes.d.ts +2 -0
  10. package/dist/adapters/admin/routes.js +2 -0
  11. package/dist/adapters/admin/screens/backups.js +2 -2
  12. package/dist/adapters/admin/screens/editor.js +5 -2
  13. package/dist/adapters/admin/screens/integrations.d.ts +4 -0
  14. package/dist/adapters/admin/screens/integrations.js +140 -0
  15. package/dist/adapters/admin/screens/lists.js +2 -1
  16. package/dist/adapters/admin/screens/releases.js +9 -4
  17. package/dist/adapters/admin/views/data-table.js +1 -1
  18. package/dist/adapters/admin/views/layout.d.ts +1 -1
  19. package/dist/adapters/admin/views/layout.js +15 -2
  20. package/dist/adapters/cli/bin.js +8 -3
  21. package/dist/adapters/cli/main.js +12 -2
  22. package/dist/adapters/mcp/agent-refs.d.ts +2 -1
  23. package/dist/adapters/mcp/agent-refs.js +4 -4
  24. package/dist/adapters/mcp/tools/publish.js +1 -1
  25. package/dist/adapters/mcp/tools/read.js +19 -4
  26. package/dist/adapters/mcp/tools/write.js +5 -1
  27. package/dist/adapters/site/cache.d.ts +8 -2
  28. package/dist/adapters/site/cache.js +13 -4
  29. package/dist/adapters/site/code-files.d.ts +44 -0
  30. package/dist/adapters/site/code-files.js +212 -0
  31. package/dist/adapters/site/consent.d.ts +9 -0
  32. package/dist/adapters/site/consent.js +26 -0
  33. package/dist/adapters/site/context.d.ts +9 -1
  34. package/dist/adapters/site/context.js +106 -27
  35. package/dist/adapters/site/csp.d.ts +11 -0
  36. package/dist/adapters/site/csp.js +36 -0
  37. package/dist/adapters/site/head.d.ts +2 -0
  38. package/dist/adapters/site/head.js +7 -20
  39. package/dist/adapters/site/headers.d.ts +5 -2
  40. package/dist/adapters/site/headers.js +13 -6
  41. package/dist/adapters/site/integrations.d.ts +48 -0
  42. package/dist/adapters/site/integrations.js +118 -0
  43. package/dist/adapters/site/media-routes.d.ts +2 -0
  44. package/dist/adapters/site/media-routes.js +2 -1
  45. package/dist/adapters/site/plugin.d.ts +2 -0
  46. package/dist/adapters/site/plugin.js +78 -40
  47. package/dist/adapters/site/preview.d.ts +2 -0
  48. package/dist/adapters/site/preview.js +10 -5
  49. package/dist/adapters/site/render.d.ts +31 -14
  50. package/dist/adapters/site/render.js +33 -7
  51. package/dist/adapters/site/routes.d.ts +3 -0
  52. package/dist/adapters/site/routes.js +11 -6
  53. package/dist/adapters/site/scripts.d.ts +6 -0
  54. package/dist/adapters/site/scripts.js +27 -0
  55. package/dist/adapters/site/sitemap.d.ts +2 -1
  56. package/dist/adapters/site/sitemap.js +3 -3
  57. package/dist/core/auth/roles.d.ts +1 -1
  58. package/dist/core/auth/roles.js +1 -0
  59. package/dist/core/boot.d.ts +2 -0
  60. package/dist/core/boot.js +3 -0
  61. package/dist/core/content/shipped-input.js +1 -2
  62. package/dist/core/content/validate.d.ts +7 -0
  63. package/dist/core/content/validate.js +24 -1
  64. package/dist/core/core.d.ts +29 -0
  65. package/dist/core/core.js +10 -2
  66. package/dist/core/db/migrate.js +2 -0
  67. package/dist/core/db/migrations/0008_integrations.d.ts +3 -0
  68. package/dist/core/db/migrations/0008_integrations.js +11 -0
  69. package/dist/core/db/schema.d.ts +11 -0
  70. package/dist/core/export/export.js +4 -0
  71. package/dist/core/export/format.d.ts +11 -0
  72. package/dist/core/export/format.js +4 -0
  73. package/dist/core/export/import.js +2 -1
  74. package/dist/core/export/replace.d.ts +6 -1
  75. package/dist/core/export/replace.js +4 -1
  76. package/dist/core/export/report.d.ts +6 -0
  77. package/dist/core/export/report.js +7 -0
  78. package/dist/core/fields/builtins.d.ts +4 -0
  79. package/dist/core/fields/builtins.js +11 -1
  80. package/dist/core/fields/widgets.js +5 -1
  81. package/dist/core/integrations/integrations.d.ts +32 -0
  82. package/dist/core/integrations/integrations.js +80 -0
  83. package/dist/core/integrations/warnings.d.ts +4 -0
  84. package/dist/core/integrations/warnings.js +29 -0
  85. package/dist/core/media/store.d.ts +2 -0
  86. package/dist/core/media/store.js +17 -1
  87. package/dist/core/media/variants.d.ts +14 -0
  88. package/dist/core/media/variants.js +54 -0
  89. package/dist/core/messages/en.d.ts +83 -2
  90. package/dist/core/messages/en.js +83 -2
  91. package/dist/core/registry/code-image.d.ts +16 -0
  92. package/dist/core/registry/code-image.js +13 -0
  93. package/dist/core/registry/define.d.ts +12 -0
  94. package/dist/core/registry/define.js +3 -0
  95. package/dist/core/registry/designed.d.ts +6 -0
  96. package/dist/core/registry/designed.js +8 -0
  97. package/dist/core/registry/integration.d.ts +48 -0
  98. package/dist/core/registry/integration.js +29 -0
  99. package/dist/core/registry/js.d.ts +9 -0
  100. package/dist/core/registry/js.js +39 -0
  101. package/dist/core/registry/registry.js +46 -0
  102. package/dist/core/registry/render.d.ts +45 -5
  103. package/dist/core/release/bundle.d.ts +3 -1
  104. package/dist/core/release/bundle.js +169 -11
  105. package/dist/core/release/manifest.d.ts +29 -6
  106. package/dist/core/release/manifest.js +26 -25
  107. package/dist/core/release/pack.js +13 -2
  108. package/dist/core/release/pointer.js +14 -3
  109. package/dist/core/release/read.d.ts +4 -2
  110. package/dist/core/release/read.js +12 -12
  111. package/dist/core/release/window.d.ts +11 -0
  112. package/dist/core/release/window.js +34 -0
  113. package/dist/core/report.d.ts +3 -0
  114. package/dist/core/richtext/headings.d.ts +10 -0
  115. package/dist/core/richtext/headings.js +37 -0
  116. package/dist/core/richtext/html.d.ts +10 -1
  117. package/dist/core/richtext/html.js +17 -6
  118. package/dist/core/richtext/markdown-text.d.ts +24 -0
  119. package/dist/core/richtext/markdown-text.js +38 -0
  120. package/dist/core/richtext/markdown.js +44 -3
  121. package/dist/core/richtext/schema.d.ts +12 -3
  122. package/dist/core/richtext/schema.js +34 -0
  123. package/dist/core/site/live.d.ts +6 -0
  124. package/dist/core/site/live.js +25 -0
  125. package/dist/core/site/paths.d.ts +5 -0
  126. package/dist/core/site/paths.js +32 -0
  127. package/dist/core/site/resolve.js +17 -6
  128. package/dist/core/version.d.ts +4 -0
  129. package/dist/core/version.js +4 -0
  130. package/dist/host/activate.js +2 -1
  131. package/dist/host/app.d.ts +2 -0
  132. package/dist/host/app.js +1 -0
  133. package/dist/host/diff.d.ts +11 -0
  134. package/dist/host/diff.js +40 -0
  135. package/dist/host/ipc.d.ts +2 -0
  136. package/dist/host/ipc.js +5 -1
  137. package/dist/host/preview-worker.js +2 -2
  138. package/dist/host/primary.js +15 -4
  139. package/dist/host/push.d.ts +5 -1
  140. package/dist/host/push.js +18 -6
  141. package/dist/host/serve.js +1 -1
  142. package/dist/host/store.d.ts +1 -2
  143. package/dist/host/store.js +32 -6
  144. package/dist/host/worker.js +9 -3
  145. package/dist/image-modules.d.ts +29 -0
  146. package/dist/image-modules.js +1 -0
  147. package/dist/index.d.ts +7 -1
  148. package/dist/index.js +4 -0
  149. package/dist/site.d.ts +9 -2
  150. package/dist/site.js +5 -0
  151. package/package.json +5 -1
@@ -4,6 +4,7 @@ import { agentTypeSchema } from '../../../core/agent/schema.js';
4
4
  import { docLabels } from '../../../core/content/schema.js';
5
5
  import { InlayError } from '../../../core/errors.js';
6
6
  import { t } from '../../../core/messages/index.js';
7
+ import { designedInCode } from '../../../core/registry/designed.js';
7
8
  import { singletonPath, withLocale } from '../../../core/site/paths.js';
8
9
  import { previewLink } from '../../site/preview.js';
9
10
  import { loadAgentRefs, pageUrl } from '../agent-refs.js';
@@ -69,13 +70,26 @@ async function describeSite(deps) {
69
70
  for (const locale of locales) {
70
71
  const path = singletonPath(def, locale, defaultLocale);
71
72
  if (path !== null)
72
- urls[locale] = pageUrl(baseUrl, withLocale(registry, locale, path));
73
+ urls[locale] = pageUrl(baseUrl, withLocale(registry, locale, path), registry.site.trailingSlash);
73
74
  }
74
- singletons.push({ type: def.name, label: def.label, help: def.help ?? null, urls, documents: await documents(def.name) });
75
+ singletons.push({
76
+ type: def.name,
77
+ label: def.label,
78
+ help: def.help ?? null,
79
+ ...(designedInCode(def.template) && { designedInCode: true }),
80
+ urls,
81
+ documents: await documents(def.name),
82
+ });
75
83
  }
76
84
  const globals = [];
77
85
  for (const def of site.globals) {
78
- globals.push({ type: def.name, label: def.label, help: def.help ?? null, documents: await documents(def.name) });
86
+ globals.push({
87
+ type: def.name,
88
+ label: def.label,
89
+ help: def.help ?? null,
90
+ ...(designedInCode(def.template) && { designedInCode: true }),
91
+ documents: await documents(def.name),
92
+ });
79
93
  }
80
94
  const collections = [];
81
95
  for (const def of site.collections) {
@@ -113,6 +127,7 @@ async function describeType(deps, type) {
113
127
  label: def.label,
114
128
  help: def.help ?? null,
115
129
  ...(def.kind === 'collection' && { titleField: def.titleField }),
130
+ ...(def.kind !== 'collection' && designedInCode(def.template) && { designedInCode: true, note: t('mcp.designedInCode') }),
116
131
  slots: Object.entries(def.template.slots).map(([key, slot]) => ({
117
132
  key,
118
133
  label: slot.label ?? slot.block.label,
@@ -210,7 +225,7 @@ async function getDocument(deps, args) {
210
225
  revisionId: doc.revision.id,
211
226
  publishedRevisionId: doc.publishedRev,
212
227
  hasUnpublishedChanges: doc.publishedRev !== doc.headRev,
213
- url: pageUrl(baseUrl, await livePath(deps, doc, 'published')),
228
+ url: pageUrl(baseUrl, await livePath(deps, doc, 'published'), deps.core.registry.site.trailingSlash),
214
229
  previewUrl: previewLink(deps, path ?? '/'),
215
230
  content: toAgent(registry, doc.type, doc.data, refs),
216
231
  links: agentLinks(registry, doc.type, doc.data, refs),
@@ -7,6 +7,7 @@ import { contentIssue, mergeIssues, validateContent } from '../../../core/conten
7
7
  import { InlayError } from '../../../core/errors.js';
8
8
  import { defOf, unwrap } from '../../../core/fields/zod-internals.js';
9
9
  import { t } from '../../../core/messages/index.js';
10
+ import { designedInCode } from '../../../core/registry/designed.js';
10
11
  import { previewLink } from '../../site/preview.js';
11
12
  import { pageUrl } from '../agent-refs.js';
12
13
  import { DESTRUCTIVE, documentOf, EDIT, livePath, READ_ONLY } from '../documents.js';
@@ -53,7 +54,7 @@ async function created(deps, doc) {
53
54
  groupId: doc.groupId,
54
55
  revisionId: doc.headRev,
55
56
  title: doc.title,
56
- url: pageUrl(deps.baseUrl, await livePath(deps, doc, 'published')),
57
+ url: pageUrl(deps.baseUrl, await livePath(deps, doc, 'published'), deps.core.registry.site.trailingSlash),
57
58
  previewUrl: previewLink(deps, path ?? '/'),
58
59
  };
59
60
  }
@@ -178,6 +179,9 @@ function toOps(deps, type, changes) {
178
179
  */
179
180
  async function updateDocument(deps, args, ctx) {
180
181
  const doc = await documentOf(deps, args.id);
182
+ const def = deps.core.registry.getType(doc.type);
183
+ if (def.kind !== 'collection' && designedInCode(def.template))
184
+ throw new InlayError('invalid_operation', 'mcp.designedInCode');
181
185
  const { ops, issues } = toOps(deps, doc.type, args.changes);
182
186
  issues.push(...(await groupIdIssues(deps, doc.type, opsAsData(ops))));
183
187
  if (issues.length > 0)
@@ -3,9 +3,14 @@ export type CachedResponse = {
3
3
  body: string;
4
4
  type: string;
5
5
  etag: string;
6
+ /** The page's own content-security-policy, with the hashes of its inline scripts. */
7
+ csp?: string;
6
8
  };
7
- /** A response with a strong ETag over its status and body, so unchanged pages revalidate with a 304. */
8
- export declare function response(status: number, body: string, type: string): CachedResponse;
9
+ /**
10
+ * A response with a strong ETag over its status, body and `csp`, so unchanged pages revalidate with a 304 and a page
11
+ * whose policy changed does not.
12
+ */
13
+ export declare function response(status: number, body: string, type: string, csp?: string): CachedResponse;
9
14
  /** True if `header` (an `If-None-Match` value) names `etag`, comparing weakly. */
10
15
  export declare function etagMatches(header: string | undefined, etag: string): boolean;
11
16
  export interface CdnOptions {
@@ -22,6 +27,7 @@ export declare class PageCache {
22
27
  readonly maxEntries: number;
23
28
  /** `changedElsewhere`: asked on every lookup; true empties the cache first (a write the site's own core didn't make). */
24
29
  constructor(maxEntries: number, changedElsewhere?: () => boolean);
30
+ /** Bumped by every `clear`, including the one a change made elsewhere causes, which reading it notices. */
25
31
  get generation(): number;
26
32
  get size(): number;
27
33
  get(key: string): CachedResponse | undefined;
@@ -1,8 +1,14 @@
1
1
  import { createHash } from 'node:crypto';
2
- /** A response with a strong ETag over its status and body, so unchanged pages revalidate with a 304. */
3
- export function response(status, body, type) {
4
- const hash = createHash('sha256').update(`${status}\n`).update(body).digest('hex').slice(0, 32);
5
- return { status, body, type, etag: `"${hash}"` };
2
+ /**
3
+ * A response with a strong ETag over its status, body and `csp`, so unchanged pages revalidate with a 304 and a page
4
+ * whose policy changed does not.
5
+ */
6
+ export function response(status, body, type, csp) {
7
+ const hash = createHash('sha256').update(`${status}\n`);
8
+ if (csp !== undefined)
9
+ hash.update(`${csp}\n`);
10
+ const etag = `"${hash.update(body).digest('hex').slice(0, 32)}"`;
11
+ return { status, body, type, etag, ...(csp !== undefined && { csp }) };
6
12
  }
7
13
  /** True if `header` (an `If-None-Match` value) names `etag`, comparing weakly. */
8
14
  export function etagMatches(header, etag) {
@@ -33,7 +39,10 @@ export class PageCache {
33
39
  this.maxEntries = maxEntries;
34
40
  this.#changedElsewhere = changedElsewhere;
35
41
  }
42
+ /** Bumped by every `clear`, including the one a change made elsewhere causes, which reading it notices. */
36
43
  get generation() {
44
+ if (this.#changedElsewhere())
45
+ this.clear();
37
46
  return this.#generation;
38
47
  }
39
48
  get size() {
@@ -0,0 +1,44 @@
1
+ import type { FastifyInstance } from 'fastify';
2
+ import type { Core } from '../../core/core.js';
3
+ import type { CodeImage } from '../../core/registry/code-image.js';
4
+ export interface CodeFile {
5
+ sha: string;
6
+ ext: string;
7
+ mime: string;
8
+ path: string;
9
+ url: string;
10
+ /** The displayed size (after EXIF rotation), known once the file has been read or registered from an import. */
11
+ width: number | null;
12
+ height: number | null;
13
+ }
14
+ export interface CodeFiles {
15
+ /**
16
+ * The file an image target in a site's code (a `file:` URL) names, or null when it isn't a usable image: one whose extension
17
+ * is in `MARKDOWN_IMAGE_TYPES` and whose bytes are of that type (so never SVG).
18
+ */
19
+ lookup(src: string): Promise<CodeFile | null>;
20
+ /** A known file by its `<sha><ext>` name. */
21
+ get(name: string): CodeFile | undefined;
22
+ /** A known file by its sha256. */
23
+ bySha(sha: string): CodeFile | undefined;
24
+ /**
25
+ * The file an imported image names. From source, one inside the site folder whose bytes match its sha and type,
26
+ * checked once per source and remembered; from a release, only one the release ships. Null otherwise.
27
+ */
28
+ register(image: CodeImage): CodeFile | null;
29
+ }
30
+ /**
31
+ * The image files site code names (Markdown in templates, or imports). A release lists them up front (`releaseFiles`, source URL to the file
32
+ * in the release); from source they are read from the site folder, hashed, and known from then on.
33
+ */
34
+ export declare function createCodeFiles(opts: {
35
+ siteDir: string | null;
36
+ releaseFiles?: ReadonlyMap<string, string>;
37
+ }): CodeFiles;
38
+ /** The one index of `core`'s images named by site code, so every render path and the image route share it. */
39
+ export declare function codeFilesFor(core: Core): CodeFiles;
40
+ /**
41
+ * Serves the known files at `/media/files/:name`, and their resized variants at `/media/files/:sha/:width.:format`,
42
+ * GET and HEAD, never anything but a file in the index.
43
+ */
44
+ export declare function registerCodeFileRoutes(app: FastifyInstance, files: CodeFiles, core: Core): void;
@@ -0,0 +1,212 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { readFileSync } from 'node:fs';
3
+ import { readFile } from 'node:fs/promises';
4
+ import { basename, extname } from 'node:path';
5
+ import { fileURLToPath } from 'node:url';
6
+ import sharp from 'sharp';
7
+ import { realInside, realInsideSync } from '../../core/content/shipped-images.js';
8
+ import { InlayError } from '../../core/errors.js';
9
+ import { detectType } from '../../core/media/detect.js';
10
+ import { MARKDOWN_IMAGE_TYPES } from '../../core/richtext/markdown-text.js';
11
+ import { etagMatches } from './cache.js';
12
+ import { VARIANT } from './media-routes.js';
13
+ const RELEASE_NAME = /^([0-9a-f]{64})(\.[a-z0-9]+)$/;
14
+ const ROUTE_NAME = /^[0-9a-f]{64}\.[a-z0-9]+$/;
15
+ const SHA = /^[0-9a-f]{64}$/;
16
+ function entry(sha, ext, mime, path, size) {
17
+ return { sha, ext, mime, path, url: `/media/files/${sha}${ext}`, width: size?.width ?? null, height: size?.height ?? null };
18
+ }
19
+ /** The displayed size of an image (EXIF orientations 5 to 8 swap width and height), or nulls when sharp can't read it. */
20
+ async function measure(bytes) {
21
+ try {
22
+ const meta = await sharp(bytes).metadata();
23
+ const turned = meta.orientation !== undefined && meta.orientation >= 5 && meta.orientation <= 8;
24
+ return { width: (turned ? meta.height : meta.width) ?? null, height: (turned ? meta.width : meta.height) ?? null };
25
+ }
26
+ catch {
27
+ return { width: null, height: null };
28
+ }
29
+ }
30
+ /**
31
+ * The image files site code names (Markdown in templates, or imports). A release lists them up front (`releaseFiles`, source URL to the file
32
+ * in the release); from source they are read from the site folder, hashed, and known from then on.
33
+ */
34
+ export function createCodeFiles(opts) {
35
+ const byName = new Map();
36
+ const shas = new Map();
37
+ const bySrc = new Map();
38
+ const registered = new Map();
39
+ const { siteDir, releaseFiles } = opts;
40
+ if (releaseFiles) {
41
+ for (const path of releaseFiles.values()) {
42
+ const m = RELEASE_NAME.exec(basename(path));
43
+ const mime = m?.[2] === undefined ? undefined : MARKDOWN_IMAGE_TYPES[m[2]];
44
+ if (m?.[1] === undefined || m[2] === undefined || mime === undefined)
45
+ continue;
46
+ add(entry(m[1], m[2], mime, path));
47
+ }
48
+ }
49
+ function add(file) {
50
+ const name = `${file.sha}${file.ext}`;
51
+ const known = byName.get(name);
52
+ if (known)
53
+ return known;
54
+ byName.set(name, file);
55
+ if (!shas.has(file.sha))
56
+ shas.set(file.sha, file);
57
+ return file;
58
+ }
59
+ /**
60
+ * The file an imported image names, read once: only one inside the site folder whose bytes hash to `image.sha` and
61
+ * are the type its extension names.
62
+ */
63
+ function fromSource(image) {
64
+ const ext = image.ext.toLowerCase();
65
+ const mime = MARKDOWN_IMAGE_TYPES[ext];
66
+ if (siteDir === null || mime === undefined || image.mime !== mime || !/^file:/i.test(image.source))
67
+ return null;
68
+ try {
69
+ const real = realInsideSync(fileURLToPath(image.source), siteDir);
70
+ if (real === null || extname(real).toLowerCase() !== ext)
71
+ return null;
72
+ const bytes = readFileSync(real);
73
+ if (createHash('sha256').update(bytes).digest('hex') !== image.sha || detectType(bytes, real) !== mime)
74
+ return null;
75
+ return add(entry(image.sha, ext, mime, real, { width: image.width, height: image.height }));
76
+ }
77
+ catch {
78
+ return null;
79
+ }
80
+ }
81
+ async function resolve(src) {
82
+ try {
83
+ if (releaseFiles) {
84
+ const path = releaseFiles.get(src);
85
+ if (path === undefined)
86
+ return null;
87
+ const file = byName.get(basename(path));
88
+ if (!file)
89
+ return null;
90
+ const bytes = await readFile(file.path);
91
+ if (detectType(bytes, file.path) !== file.mime)
92
+ return null;
93
+ if (file.width === null || file.height === null)
94
+ Object.assign(file, await measure(bytes));
95
+ return file;
96
+ }
97
+ if (siteDir === null || !/^file:/i.test(src))
98
+ return null;
99
+ const real = await realInside(fileURLToPath(src), siteDir);
100
+ if (real === null)
101
+ return null;
102
+ const bytes = await readFile(real);
103
+ const ext = extname(real).toLowerCase();
104
+ const mime = detectType(bytes, real);
105
+ if (MARKDOWN_IMAGE_TYPES[ext] === undefined || mime !== MARKDOWN_IMAGE_TYPES[ext])
106
+ return null;
107
+ const file = add(entry(createHash('sha256').update(bytes).digest('hex'), ext, mime, real));
108
+ if (file.width === null || file.height === null)
109
+ Object.assign(file, await measure(bytes));
110
+ return file;
111
+ }
112
+ catch {
113
+ return null;
114
+ }
115
+ }
116
+ return {
117
+ lookup(src) {
118
+ let found = bySrc.get(src);
119
+ if (!found) {
120
+ found = resolve(src);
121
+ bySrc.set(src, found);
122
+ }
123
+ return found;
124
+ },
125
+ get: (name) => byName.get(name),
126
+ bySha: (sha) => shas.get(sha),
127
+ register(image) {
128
+ if (!SHA.test(image.sha))
129
+ return null;
130
+ if (releaseFiles)
131
+ return byName.get(`${image.sha}${image.ext}`) ?? null;
132
+ // By everything the check reads, so a hand-built value naming the same file can't stand in for the real one.
133
+ const key = JSON.stringify([image.source, image.sha, image.ext, image.mime]);
134
+ let found = registered.get(key);
135
+ if (found === undefined) {
136
+ found = fromSource(image);
137
+ registered.set(key, found);
138
+ }
139
+ return found;
140
+ },
141
+ };
142
+ }
143
+ const perCore = new WeakMap();
144
+ /** The one index of `core`'s images named by site code, so every render path and the image route share it. */
145
+ export function codeFilesFor(core) {
146
+ let files = perCore.get(core);
147
+ if (!files) {
148
+ files = createCodeFiles({ siteDir: core.registry.siteDir, ...(core.codeFiles && { releaseFiles: core.codeFiles }) });
149
+ perCore.set(core, files);
150
+ }
151
+ return files;
152
+ }
153
+ function notFound(reply) {
154
+ return reply.code(404).header('cache-control', 'no-store').type('text/plain; charset=utf-8').send('Not found');
155
+ }
156
+ function send(request, reply, bytes, mime, etag) {
157
+ reply.header('cache-control', 'public, max-age=31536000, immutable').header('etag', etag);
158
+ if (etagMatches(request.headers['if-none-match'], etag))
159
+ return reply.code(304).send();
160
+ reply.type(mime).header('x-content-type-options', 'nosniff');
161
+ return request.method === 'HEAD' ? reply.header('content-length', bytes.length).send() : reply.send(bytes);
162
+ }
163
+ async function read(path) {
164
+ try {
165
+ return await readFile(path);
166
+ }
167
+ catch {
168
+ return undefined;
169
+ }
170
+ }
171
+ /**
172
+ * Serves the known files at `/media/files/:name`, and their resized variants at `/media/files/:sha/:width.:format`,
173
+ * GET and HEAD, never anything but a file in the index.
174
+ */
175
+ export function registerCodeFileRoutes(app, files, core) {
176
+ app.route({
177
+ method: ['GET', 'HEAD'],
178
+ url: '/media/files/:name',
179
+ handler: async (request, reply) => {
180
+ const name = request.params.name;
181
+ const file = ROUTE_NAME.test(name) ? files.get(name) : undefined;
182
+ const bytes = file && (await read(file.path));
183
+ if (!file || !bytes)
184
+ return notFound(reply);
185
+ return send(request, reply, bytes, file.mime, `"${file.sha.slice(0, 32)}"`);
186
+ },
187
+ });
188
+ app.route({
189
+ method: ['GET', 'HEAD'],
190
+ url: '/media/files/:sha/:variant',
191
+ handler: async (request, reply) => {
192
+ const { sha, variant } = request.params;
193
+ const file = SHA.test(sha) ? files.bySha(sha) : undefined;
194
+ const m = VARIANT.exec(variant);
195
+ if (!file || !m)
196
+ return notFound(reply);
197
+ let made;
198
+ try {
199
+ made = await core.codeImageVariant(file, { width: Number(m[1]), format: m[2] });
200
+ }
201
+ catch (e) {
202
+ if (e instanceof InlayError && (e.code === 'not_found' || e.messageId === 'error.mediaUnreadable'))
203
+ return notFound(reply);
204
+ throw e;
205
+ }
206
+ const bytes = await read(made.path);
207
+ if (!bytes)
208
+ return notFound(reply);
209
+ return send(request, reply, bytes, made.mime, `"${sha.slice(0, 32)}-${m[1]}.${m[2]}"`);
210
+ },
211
+ });
212
+ }
@@ -0,0 +1,9 @@
1
+ import type { FastifyInstance } from 'fastify';
2
+ export interface ConsentAsset {
3
+ url: string;
4
+ body: string;
5
+ }
6
+ export declare function loadConsentAsset(opts?: {
7
+ dir?: string;
8
+ }): Promise<ConsentAsset>;
9
+ export declare function registerConsentRoute(app: FastifyInstance, asset: ConsentAsset): void;
@@ -0,0 +1,26 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { readFile } from 'node:fs/promises';
3
+ import { join } from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+ import { InlayError } from '../../core/errors.js';
6
+ const PATH = '/_inlay/consent.js';
7
+ export async function loadConsentAsset(opts = {}) {
8
+ const dir = opts.dir ?? fileURLToPath(new URL('../../../assets/site/', import.meta.url));
9
+ let body;
10
+ try {
11
+ body = await readFile(join(dir, 'consent.js'), 'utf8');
12
+ }
13
+ catch {
14
+ throw new InlayError('config', 'config.siteAssetsMissing', { dir });
15
+ }
16
+ const hash = createHash('sha256').update(body).digest('hex').slice(0, 12);
17
+ return { url: `${PATH}?v=${hash}`, body };
18
+ }
19
+ export function registerConsentRoute(app, asset) {
20
+ const version = asset.url.slice(asset.url.indexOf('?v=') + 3);
21
+ app.get(PATH, async (request, reply) => {
22
+ const current = request.query.v === version;
23
+ reply.header('cache-control', current ? 'public, max-age=31536000, immutable' : 'no-cache').header('x-content-type-options', 'nosniff');
24
+ return reply.type('text/javascript; charset=utf-8').send(asset.body);
25
+ });
26
+ }
@@ -2,16 +2,22 @@ import type { Core } from '../../core/core.js';
2
2
  import type { TemplateDef } from '../../core/registry/define.js';
3
3
  import type { RenderContext } from '../../core/registry/render.js';
4
4
  import type { QueryApi } from '../../core/registry/route.js';
5
+ import { type TrailingSlash } from '../../core/site/paths.js';
5
6
  import type { DocumentData, LiveDocument, LiveState } from '../../core/types.js';
6
7
  import { type PublicAssets } from './assets.js';
7
8
  import { type CollectedHead } from './head.js';
9
+ import { type CodeFiles } from './code-files.js';
10
+ /** The encoded URL of the decoded site path `path`, in the form the site presents; `''` for `''`. */
11
+ export declare const pageUrl: (path: string, mode: TrailingSlash) => string;
8
12
  export interface RenderContextOptions {
9
13
  locale: string;
10
14
  state: LiveState;
11
15
  page: number;
12
16
  baseUrl: string;
13
- alternates: RenderContext['alternates'];
17
+ alternates: Array<Omit<RenderContext['alternates'][number], 'url'>>;
14
18
  assets?: PublicAssets;
19
+ /** Where `markdown` finds its image files; the core's shared index by default. */
20
+ codeFiles?: CodeFiles;
15
21
  }
16
22
  export type PreloadingRenderContext = RenderContext & {
17
23
  /** Loads the media and documents `docs` refer to, so `image`, `file`, `link` and `richText` can resolve them. */
@@ -20,6 +26,8 @@ export type PreloadingRenderContext = RenderContext & {
20
26
  preloadData(template: TemplateDef, data: DocumentData): Promise<void>;
21
27
  /** What `head` collected so far. */
22
28
  headTags(): CollectedHead;
29
+ /** The hashes of the inline scripts written through `script` so far. */
30
+ scriptHashes(): string[];
23
31
  };
24
32
  /**
25
33
  * The `ctx` templates and blocks receive. Synchronous helpers resolve only what was preloaded: