inlaycms 0.4.0 → 0.5.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 (131) hide show
  1. package/README.md +18 -709
  2. package/assets/admin/admin.css +1 -1
  3. package/assets/admin/editor.js +63 -46
  4. package/assets/site/consent.js +1 -0
  5. package/dist/adapters/admin/context.d.ts +1 -1
  6. package/dist/adapters/admin/context.js +1 -0
  7. package/dist/adapters/admin/routes.d.ts +2 -0
  8. package/dist/adapters/admin/routes.js +2 -0
  9. package/dist/adapters/admin/screens/backups.js +2 -2
  10. package/dist/adapters/admin/screens/editor.js +2 -1
  11. package/dist/adapters/admin/screens/integrations.d.ts +4 -0
  12. package/dist/adapters/admin/screens/integrations.js +140 -0
  13. package/dist/adapters/admin/screens/lists.js +2 -1
  14. package/dist/adapters/admin/screens/releases.js +1 -1
  15. package/dist/adapters/admin/views/layout.js +3 -0
  16. package/dist/adapters/cli/bin.js +8 -3
  17. package/dist/adapters/mcp/tools/read.js +17 -2
  18. package/dist/adapters/mcp/tools/write.js +4 -0
  19. package/dist/adapters/site/cache.d.ts +8 -2
  20. package/dist/adapters/site/cache.js +13 -4
  21. package/dist/adapters/site/code-files.d.ts +44 -0
  22. package/dist/adapters/site/code-files.js +212 -0
  23. package/dist/adapters/site/consent.d.ts +9 -0
  24. package/dist/adapters/site/consent.js +26 -0
  25. package/dist/adapters/site/context.d.ts +5 -0
  26. package/dist/adapters/site/context.js +97 -20
  27. package/dist/adapters/site/csp.d.ts +11 -0
  28. package/dist/adapters/site/csp.js +36 -0
  29. package/dist/adapters/site/head.js +1 -14
  30. package/dist/adapters/site/headers.d.ts +5 -2
  31. package/dist/adapters/site/headers.js +13 -6
  32. package/dist/adapters/site/integrations.d.ts +48 -0
  33. package/dist/adapters/site/integrations.js +118 -0
  34. package/dist/adapters/site/media-routes.d.ts +2 -0
  35. package/dist/adapters/site/media-routes.js +2 -1
  36. package/dist/adapters/site/plugin.d.ts +2 -0
  37. package/dist/adapters/site/plugin.js +64 -34
  38. package/dist/adapters/site/render.d.ts +31 -14
  39. package/dist/adapters/site/render.js +26 -5
  40. package/dist/adapters/site/routes.d.ts +3 -0
  41. package/dist/adapters/site/routes.js +7 -3
  42. package/dist/adapters/site/scripts.d.ts +6 -0
  43. package/dist/adapters/site/scripts.js +27 -0
  44. package/dist/core/auth/roles.d.ts +1 -1
  45. package/dist/core/auth/roles.js +1 -0
  46. package/dist/core/boot.d.ts +2 -0
  47. package/dist/core/boot.js +3 -0
  48. package/dist/core/content/shipped-input.js +1 -2
  49. package/dist/core/content/validate.d.ts +7 -0
  50. package/dist/core/content/validate.js +24 -1
  51. package/dist/core/core.d.ts +29 -0
  52. package/dist/core/core.js +10 -2
  53. package/dist/core/db/migrate.js +2 -0
  54. package/dist/core/db/migrations/0008_integrations.d.ts +3 -0
  55. package/dist/core/db/migrations/0008_integrations.js +11 -0
  56. package/dist/core/db/schema.d.ts +11 -0
  57. package/dist/core/export/export.js +4 -0
  58. package/dist/core/export/format.d.ts +11 -0
  59. package/dist/core/export/format.js +4 -0
  60. package/dist/core/export/import.js +2 -1
  61. package/dist/core/export/replace.d.ts +6 -1
  62. package/dist/core/export/replace.js +4 -1
  63. package/dist/core/export/report.d.ts +6 -0
  64. package/dist/core/export/report.js +7 -0
  65. package/dist/core/fields/builtins.d.ts +4 -0
  66. package/dist/core/fields/builtins.js +11 -1
  67. package/dist/core/fields/widgets.js +5 -1
  68. package/dist/core/integrations/integrations.d.ts +32 -0
  69. package/dist/core/integrations/integrations.js +80 -0
  70. package/dist/core/integrations/warnings.d.ts +4 -0
  71. package/dist/core/integrations/warnings.js +29 -0
  72. package/dist/core/media/store.d.ts +2 -0
  73. package/dist/core/media/store.js +17 -1
  74. package/dist/core/media/variants.d.ts +14 -0
  75. package/dist/core/media/variants.js +54 -0
  76. package/dist/core/messages/en.d.ts +73 -0
  77. package/dist/core/messages/en.js +73 -0
  78. package/dist/core/registry/code-image.d.ts +16 -0
  79. package/dist/core/registry/code-image.js +13 -0
  80. package/dist/core/registry/define.d.ts +7 -0
  81. package/dist/core/registry/define.js +2 -0
  82. package/dist/core/registry/designed.d.ts +6 -0
  83. package/dist/core/registry/designed.js +8 -0
  84. package/dist/core/registry/integration.d.ts +48 -0
  85. package/dist/core/registry/integration.js +29 -0
  86. package/dist/core/registry/js.d.ts +9 -0
  87. package/dist/core/registry/js.js +39 -0
  88. package/dist/core/registry/registry.js +46 -0
  89. package/dist/core/registry/render.d.ts +39 -4
  90. package/dist/core/release/bundle.d.ts +3 -1
  91. package/dist/core/release/bundle.js +169 -11
  92. package/dist/core/release/manifest.d.ts +29 -1
  93. package/dist/core/release/manifest.js +26 -1
  94. package/dist/core/release/pack.js +13 -2
  95. package/dist/core/release/pointer.js +14 -3
  96. package/dist/core/release/read.d.ts +2 -0
  97. package/dist/core/release/read.js +1 -0
  98. package/dist/core/report.d.ts +3 -0
  99. package/dist/core/richtext/headings.d.ts +10 -0
  100. package/dist/core/richtext/headings.js +37 -0
  101. package/dist/core/richtext/html.d.ts +10 -1
  102. package/dist/core/richtext/html.js +17 -6
  103. package/dist/core/richtext/markdown-text.d.ts +24 -0
  104. package/dist/core/richtext/markdown-text.js +38 -0
  105. package/dist/core/richtext/markdown.js +44 -3
  106. package/dist/core/richtext/schema.d.ts +12 -3
  107. package/dist/core/richtext/schema.js +34 -0
  108. package/dist/core/site/live.d.ts +6 -0
  109. package/dist/core/site/live.js +25 -0
  110. package/dist/host/app.d.ts +2 -0
  111. package/dist/host/app.js +1 -0
  112. package/dist/host/diff.d.ts +11 -0
  113. package/dist/host/diff.js +40 -0
  114. package/dist/host/drain.d.ts +12 -0
  115. package/dist/host/drain.js +34 -0
  116. package/dist/host/ipc.d.ts +2 -0
  117. package/dist/host/ipc.js +5 -1
  118. package/dist/host/preview-worker.js +2 -2
  119. package/dist/host/primary.js +15 -4
  120. package/dist/host/push.js +1 -1
  121. package/dist/host/serve.js +1 -1
  122. package/dist/host/store.d.ts +1 -2
  123. package/dist/host/store.js +32 -6
  124. package/dist/host/worker.js +6 -0
  125. package/dist/image-modules.d.ts +29 -0
  126. package/dist/image-modules.js +1 -0
  127. package/dist/index.d.ts +7 -1
  128. package/dist/index.js +4 -0
  129. package/dist/site.d.ts +8 -1
  130. package/dist/site.js +5 -0
  131. package/package.json +5 -1
@@ -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
+ }
@@ -5,6 +5,7 @@ import type { QueryApi } from '../../core/registry/route.js';
5
5
  import type { DocumentData, LiveDocument, LiveState } from '../../core/types.js';
6
6
  import { type PublicAssets } from './assets.js';
7
7
  import { type CollectedHead } from './head.js';
8
+ import { type CodeFiles } from './code-files.js';
8
9
  export interface RenderContextOptions {
9
10
  locale: string;
10
11
  state: LiveState;
@@ -12,6 +13,8 @@ export interface RenderContextOptions {
12
13
  baseUrl: string;
13
14
  alternates: RenderContext['alternates'];
14
15
  assets?: PublicAssets;
16
+ /** Where `markdown` finds its image files; the core's shared index by default. */
17
+ codeFiles?: CodeFiles;
15
18
  }
16
19
  export type PreloadingRenderContext = RenderContext & {
17
20
  /** Loads the media and documents `docs` refer to, so `image`, `file`, `link` and `richText` can resolve them. */
@@ -20,6 +23,8 @@ export type PreloadingRenderContext = RenderContext & {
20
23
  preloadData(template: TemplateDef, data: DocumentData): Promise<void>;
21
24
  /** What `head` collected so far. */
22
25
  headTags(): CollectedHead;
26
+ /** The hashes of the inline scripts written through `script` so far. */
27
+ scriptHashes(): string[];
23
28
  };
24
29
  /**
25
30
  * The `ctx` templates and blocks receive. Synchronous helpers resolve only what was preloaded:
@@ -1,37 +1,44 @@
1
1
  import { documentRefs } from '../../core/content/schema.js';
2
2
  import { findRefs } from '../../core/fields/walk.js';
3
3
  import { validateContent } from '../../core/content/validate.js';
4
+ import { InlayError } from '../../core/errors.js';
4
5
  import { isRasterImage } from '../../core/media/detect.js';
5
6
  import { IMAGE_WIDTHS } from '../../core/media/variants.js';
7
+ import { isCodeImage } from '../../core/registry/code-image.js';
6
8
  import { richTextToHtml } from '../../core/richtext/html.js';
7
9
  import { inlineTextToHtml } from '../../core/richtext/inline.js';
10
+ import { markdownImages } from '../../core/richtext/markdown.js';
11
+ import { isMediaTarget, KEY_HREF, NO_DOCUMENT, parseMarkdownText } from '../../core/richtext/markdown-text.js';
12
+ import { richTextRefs } from '../../core/richtext/schema.js';
8
13
  import { encodePath } from '../../core/site/paths.js';
9
14
  import { publicAssets } from './assets.js';
10
15
  import { createHeadCollector } from './head.js';
16
+ import { codeFilesFor } from './code-files.js';
17
+ import { createScriptCollector } from './scripts.js';
11
18
  import { escapeHtml, raw } from '../../jsx/html.js';
12
19
  /** Rich text images get this width as `src` when the original is at least as wide. */
13
20
  const RICH_TEXT_SRC_WIDTH = 1280;
14
21
  const nonEmpty = (s) => typeof s === 'string' && s !== '';
15
22
  const mediaUrl = (id) => `/media/${id}`;
16
23
  const missing = (v) => v === undefined || v === null;
17
- function resolveImage(media, alt) {
18
- const url = mediaUrl(media.id);
19
- const raster = isRasterImage(media.mime);
20
- const variant = (width, format) => `${url}/${width}.${format}`;
24
+ function resolveImage(image, alt) {
25
+ const { url } = image;
26
+ const raster = isRasterImage(image.mime);
27
+ const variant = (width, format) => `${image.variants}/${width}.${format}`;
21
28
  const widths = () => {
22
29
  const all = [...IMAGE_WIDTHS];
23
- if (media.width === null)
30
+ if (image.width === null)
24
31
  return all;
25
- const fitting = all.filter((w) => w <= media.width);
32
+ const fitting = all.filter((w) => w <= image.width);
26
33
  return fitting.length > 0 ? fitting : all.slice(0, 1);
27
34
  };
28
35
  return {
29
- id: media.id,
36
+ id: image.id,
30
37
  url,
31
- alt: nonEmpty(alt) ? alt : nonEmpty(media.defaultAlt) ? media.defaultAlt : '',
32
- width: media.width,
33
- height: media.height,
34
- mime: media.mime,
38
+ alt,
39
+ width: image.width,
40
+ height: image.height,
41
+ mime: image.mime,
35
42
  src(width, format = 'webp') {
36
43
  if (!raster)
37
44
  return url;
@@ -47,6 +54,27 @@ function resolveImage(media, alt) {
47
54
  },
48
55
  };
49
56
  }
57
+ function mediaSource(media) {
58
+ const url = mediaUrl(media.id);
59
+ return { id: media.id, url, variants: url, mime: media.mime, width: media.width, height: media.height };
60
+ }
61
+ /** Alt is the value's, then the media's default, then `''`. */
62
+ const mediaAlt = (media, alt) => nonEmpty(alt) ? alt : nonEmpty(media.defaultAlt) ? media.defaultAlt : '';
63
+ function codeSource(file) {
64
+ return {
65
+ id: file.sha,
66
+ url: `/media/files/${file.sha}${file.ext.toLowerCase()}`,
67
+ variants: `/media/files/${file.sha}`,
68
+ mime: file.mime,
69
+ width: file.width,
70
+ height: file.height,
71
+ };
72
+ }
73
+ /** A rich text image: `src` at `RICH_TEXT_SRC_WIDTH`, or the original's width when narrower. */
74
+ function richTextImage(img) {
75
+ const width = Math.min(img.width ?? RICH_TEXT_SRC_WIDTH, RICH_TEXT_SRC_WIDTH);
76
+ return { src: img.src(width), srcset: img.srcset(), alt: img.alt, width: img.width, height: img.height };
77
+ }
50
78
  function toEntry(doc) {
51
79
  return {
52
80
  id: doc.groupId,
@@ -107,11 +135,13 @@ export function createRenderContext(core, opts) {
107
135
  const { locale, state } = opts;
108
136
  const preview = state === 'preview';
109
137
  const assets = opts.assets ?? publicAssets(null);
138
+ const codeFiles = opts.codeFiles ?? codeFilesFor(core);
110
139
  const media = new Map();
111
140
  const docs = new Map();
112
141
  const collections = new Map();
113
142
  const globals = new Map();
114
143
  const head = createHeadCollector();
144
+ const scripts = createScriptCollector();
115
145
  /**
116
146
  * Whether `doc` can be shown as is. In preview, a draft that isn't complete can't: an entry is
117
147
  * then treated as not live, and a singleton or global falls back to its published version.
@@ -167,9 +197,18 @@ export function createRenderContext(core, opts) {
167
197
  found.push(...findRefs(slot.block.schema, data.slots[key]?.data));
168
198
  await loadRefs(found.map((r) => r.ref));
169
199
  }
170
- function image(v) {
200
+ function image(v, opts) {
201
+ if (isCodeImage(v)) {
202
+ codeFiles.register(v);
203
+ return resolveImage(codeSource(v), opts?.alt ?? '');
204
+ }
205
+ if (typeof v === 'string' || (typeof v === 'object' && v !== null && v.kind === 'codeImage')) {
206
+ throw new InlayError('definition', 'error.imageNotImported');
207
+ }
171
208
  const info = v ? media.get(v.media) : undefined;
172
- return info ? resolveImage(info, v.alt) : null;
209
+ if (!info)
210
+ return null;
211
+ return resolveImage(mediaSource(info), opts?.alt ?? mediaAlt(info, v.alt));
173
212
  }
174
213
  function file(v) {
175
214
  const info = v ? media.get(v.media) : undefined;
@@ -198,15 +237,50 @@ export function createRenderContext(core, opts) {
198
237
  link: (groupId) => documentHref(groupId)?.href ?? null,
199
238
  image: (id, alt) => {
200
239
  const info = media.get(id);
201
- if (!info)
202
- return null;
203
- const img = resolveImage(info, alt);
204
- const width = Math.min(img.width ?? RICH_TEXT_SRC_WIDTH, RICH_TEXT_SRC_WIDTH);
205
- return { src: img.src(width), srcset: img.srcset(), alt: img.alt, width: img.width, height: img.height };
240
+ return info ? richTextImage(resolveImage(mediaSource(info), mediaAlt(info, alt))) : null;
206
241
  },
207
242
  };
208
- function richText(doc) {
209
- return raw(doc ? richTextToHtml(doc, resolver) : '');
243
+ function richText(doc, opts) {
244
+ return raw(doc ? richTextToHtml(doc, resolver, opts) : '');
245
+ }
246
+ async function markdown(text, renderOpts) {
247
+ const keyRefs = [...text.matchAll(KEY_HREF)].map((m) => ({ type: m[1], key: m[2] ?? null }));
248
+ const groups = await core.groupIdsByKey(keyRefs);
249
+ await loadDocs(groups.values());
250
+ text = text.replace(KEY_HREF, (_href, type, key) => {
251
+ return `](inlay:document/${groups.get(`${type}/${key ?? type}`) ?? NO_DOCUMENT}`;
252
+ });
253
+ const found = new Map();
254
+ const unusable = [];
255
+ await Promise.all(markdownImages(text).map(async ({ src, line }) => {
256
+ if (isMediaTarget(src))
257
+ return;
258
+ const file = /^file:/i.test(src) ? await codeFiles.lookup(src) : null;
259
+ if (file)
260
+ found.set(src, file);
261
+ else
262
+ unusable.push({ src, line });
263
+ }));
264
+ const parsed = parseMarkdownText(text, new Map([...found].map(([src, file]) => [src, file.sha])));
265
+ if (!parsed.ok) {
266
+ const first = parsed.problems[0];
267
+ throw new InlayError('definition', 'error.markdownRender', { line: first?.line ?? 1, problem: first?.message ?? '' });
268
+ }
269
+ const refused = unusable.sort((a, b) => a.line - b.line)[0];
270
+ if (refused)
271
+ throw new InlayError('definition', 'error.markdownRenderImage', refused);
272
+ const files = new Map([...found.values()].map((file) => [file.sha, file]));
273
+ await loadRefs(richTextRefs(parsed.doc).filter((ref) => ref.kind !== 'media' || !files.has(ref.id)));
274
+ const markdownResolver = {
275
+ link: resolver.link,
276
+ image: (id, alt) => {
277
+ const file = files.get(id);
278
+ if (!file)
279
+ return resolver.image(id, alt);
280
+ return richTextImage(resolveImage(codeSource(file), alt ?? ''));
281
+ },
282
+ };
283
+ return raw(richTextToHtml(parsed.doc, markdownResolver, renderOpts));
210
284
  }
211
285
  function inline(value) {
212
286
  if (value === null || value === undefined)
@@ -282,11 +356,13 @@ export function createRenderContext(core, opts) {
282
356
  baseUrl: opts.baseUrl,
283
357
  asset: (path) => assets.url(path),
284
358
  head: head.api,
359
+ script: scripts.api,
285
360
  alternates: opts.alternates,
286
361
  image,
287
362
  file,
288
363
  link,
289
364
  richText,
365
+ markdown,
290
366
  inline,
291
367
  entries,
292
368
  query,
@@ -294,6 +370,7 @@ export function createRenderContext(core, opts) {
294
370
  preload,
295
371
  preloadData,
296
372
  headTags: head.collected,
373
+ scriptHashes: scripts.hashes,
297
374
  };
298
375
  }
299
376
  /** Published content at `locale`, the way templates query it, for one request. */
@@ -0,0 +1,11 @@
1
+ import { type CspSources } from '../../core/registry/integration.js';
2
+ /**
3
+ * The Content-Security-Policy of a public response: Inlay's defaults, then in `script-src` the page's inline-script
4
+ * `hashes`, then the sources the site and then each integration declare, each source once. Hashes are left out when
5
+ * `'unsafe-inline'` is declared for `script-src`, since browsers ignore it beside a hash.
6
+ */
7
+ export declare function buildCsp(input: {
8
+ site: CspSources;
9
+ integrations: readonly CspSources[];
10
+ hashes?: readonly string[];
11
+ }): string;
@@ -0,0 +1,36 @@
1
+ import { CSP_DIRECTIVES } from '../../core/registry/integration.js';
2
+ /** Inlay's own sources per directive, in the order the policy lists them; `worker-src` only when something declares it. */
3
+ const BASE = [
4
+ ['default-src', ["'self'"]],
5
+ ['script-src', ["'self'"]],
6
+ ['style-src', ["'self'", "'unsafe-inline'"]],
7
+ ['img-src', ["'self'", 'data:']],
8
+ ['font-src', ["'self'"]],
9
+ ['connect-src', ["'self'"]],
10
+ ['frame-src', ["'self'"]],
11
+ ['media-src', ["'self'"]],
12
+ ['worker-src', ["'self'"]],
13
+ ['object-src', ["'none'"]],
14
+ ['base-uri', ["'self'"]],
15
+ ['form-action', ["'self'"]],
16
+ ['frame-ancestors', ["'self'"]],
17
+ ];
18
+ const UNSAFE_INLINE = "'unsafe-inline'";
19
+ const declarable = (directive) => CSP_DIRECTIVES.includes(directive);
20
+ /**
21
+ * The Content-Security-Policy of a public response: Inlay's defaults, then in `script-src` the page's inline-script
22
+ * `hashes`, then the sources the site and then each integration declare, each source once. Hashes are left out when
23
+ * `'unsafe-inline'` is declared for `script-src`, since browsers ignore it beside a hash.
24
+ */
25
+ export function buildCsp(input) {
26
+ const declared = (directive) => declarable(directive) ? [input.site, ...input.integrations].flatMap((sources) => sources[directive] ?? []) : [];
27
+ const parts = [];
28
+ for (const [directive, base] of BASE) {
29
+ const own = declared(directive);
30
+ if (directive === 'worker-src' && own.length === 0)
31
+ continue;
32
+ const extra = directive === 'script-src' && !own.includes(UNSAFE_INLINE) ? (input.hashes ?? []) : [];
33
+ parts.push([directive, ...new Set([...base, ...extra, ...own])].join(' '));
34
+ }
35
+ return parts.join('; ');
36
+ }
@@ -1,22 +1,9 @@
1
1
  import { InlayError } from '../../core/errors.js';
2
2
  import { isSafeUrl } from '../../core/fields/define.js';
3
+ import { scriptJson } from '../../core/registry/js.js';
3
4
  import { encodePath } from '../../core/site/paths.js';
4
5
  import { escapeHtml, raw } from '../../jsx/html.js';
5
6
  export const NO_HEAD = { meta: [], links: [], jsonLd: [] };
6
- const SCRIPT_UNSAFE = {
7
- '<': '\\u003c',
8
- '>': '\\u003e',
9
- '&': '\\u0026',
10
- '\u2028': '\\u2028',
11
- '\u2029': '\\u2029',
12
- };
13
- /** `value` as JSON that can't end its `<script>` or open an HTML comment in it. */
14
- function scriptJson(value) {
15
- const json = JSON.stringify(value);
16
- if (json === undefined)
17
- throw new InlayError('config', 'config.headJsonLd');
18
- return json.replace(/[<>&\u2028\u2029]/g, (c) => SCRIPT_UNSAFE[c]);
19
- }
20
7
  const LINK_ATTRS = ['rel', 'hreflang', 'type', 'sizes', 'media', 'as', 'crossorigin', 'href'];
21
8
  /** The `ctx.head` of one render, and what it collected. */
22
9
  export function createHeadCollector() {
@@ -1,5 +1,8 @@
1
1
  import type { FastifyInstance } from 'fastify';
2
2
  /** The headers for a site at `baseUrl`: the defaults (HSTS only over https) with the site's own laid over them. */
3
3
  export declare function siteHeaders(baseUrl: string, own: Readonly<Record<string, string | false>>): Record<string, string>;
4
- /** Adds `headers` to every response that doesn't set them itself, so the admin's and a route's own headers win. */
5
- export declare function registerSiteHeaders(app: FastifyInstance, headers: Readonly<Record<string, string>>): void;
4
+ /**
5
+ * Adds `headers` to every response that doesn't set them itself, so the admin's and a route's own headers win. Then,
6
+ * when the response still has no content-security-policy, sets the one `csp` gives, unless that is null.
7
+ */
8
+ export declare function registerSiteHeaders(app: FastifyInstance, headers: Readonly<Record<string, string>>, csp?: () => Promise<string | null>): void;
@@ -1,12 +1,11 @@
1
1
  /**
2
- * What every response gets unless it sets the header itself: no MIME sniffing, no full URLs leaked to other sites,
3
- * and no framing by other sites. A site can't be given a whole CSP without knowing its templates, so the default
4
- * one only says who may frame it.
2
+ * What every response gets unless it sets the header itself: no MIME sniffing and no full URLs leaked to other sites.
3
+ * The Content-Security-Policy is not among them: it depends on the integrations switched on, so it comes from
4
+ * `registerSiteHeaders`'s `csp`.
5
5
  */
6
6
  const DEFAULTS = {
7
7
  'x-content-type-options': 'nosniff',
8
8
  'referrer-policy': 'strict-origin-when-cross-origin',
9
- 'content-security-policy': "frame-ancestors 'self'",
10
9
  };
11
10
  /** One year, without `includeSubDomains`, so other hosts under the same domain are left alone. */
12
11
  const HSTS = 'max-age=31536000';
@@ -19,13 +18,21 @@ export function siteHeaders(baseUrl, own) {
19
18
  headers[name.toLowerCase()] = value;
20
19
  return Object.fromEntries(Object.entries(headers).filter((entry) => entry[1] !== false));
21
20
  }
22
- /** Adds `headers` to every response that doesn't set them itself, so the admin's and a route's own headers win. */
23
- export function registerSiteHeaders(app, headers) {
21
+ /**
22
+ * Adds `headers` to every response that doesn't set them itself, so the admin's and a route's own headers win. Then,
23
+ * when the response still has no content-security-policy, sets the one `csp` gives, unless that is null.
24
+ */
25
+ export function registerSiteHeaders(app, headers, csp) {
24
26
  const entries = Object.entries(headers);
25
27
  app.addHook('onSend', async (_request, reply, payload) => {
26
28
  for (const [name, value] of entries)
27
29
  if (!reply.hasHeader(name))
28
30
  reply.header(name, value);
31
+ if (csp && !reply.hasHeader('content-security-policy')) {
32
+ const policy = await csp();
33
+ if (policy !== null)
34
+ reply.header('content-security-policy', policy);
35
+ }
29
36
  return payload;
30
37
  });
31
38
  }
@@ -0,0 +1,48 @@
1
+ import type { Core } from '../../core/core.js';
2
+ import type { ActiveIntegration } from '../../core/integrations/integrations.js';
3
+ import type { SiteDefinition } from '../../core/registry/define.js';
4
+ import type { IntegrationPage } from '../../core/registry/integration.js';
5
+ import type { ScriptApi } from '../../core/registry/render.js';
6
+ /** The page an integration renders for, without its `script`. */
7
+ export type IntegrationPageInfo = Omit<IntegrationPage, 'script'>;
8
+ /** The active integrations' output for one page, by slot. */
9
+ export interface RenderedIntegrations {
10
+ head: string;
11
+ bodyStart: string;
12
+ bodyEnd: string;
13
+ }
14
+ export interface SiteIntegrations {
15
+ /** The integrations switched on with valid settings, read once per page-cache generation. */
16
+ active(): Promise<ActiveIntegration[]>;
17
+ /** The header value, or null when the site sets or removes content-security-policy itself. */
18
+ policy(hashes?: readonly string[]): Promise<string | null>;
19
+ /** The versioned URL of the consent script a page with a gated integration loads. */
20
+ consentUrl: string;
21
+ /** The active integrations rendered for `page`; a failure to read or render them is logged and left out. */
22
+ render(page: IntegrationPageInfo, script: ScriptApi): Promise<RenderedIntegrations>;
23
+ }
24
+ /**
25
+ * `generation`: changes on every live change (the page cache's), so a change to the settings is seen on the next call.
26
+ * `log`: where render failures go.
27
+ */
28
+ export declare function createSiteIntegrations(opts: {
29
+ core: Core;
30
+ site: SiteDefinition;
31
+ generation: () => number;
32
+ consentUrl: string;
33
+ log: (error: unknown, message: string) => void;
34
+ }): SiteIntegrations;
35
+ /**
36
+ * Each of `active`'s slots rendered for `page`, in order, skipping in preview the ones without `preview: true`. A
37
+ * gated integration's output is wrapped in an inert `<template data-inlay-consent>`, and `head` then ends with the
38
+ * consent script. An integration whose render throws is logged and left out of this page.
39
+ */
40
+ export declare function renderIntegrations(active: readonly ActiveIntegration[], page: IntegrationPageInfo, script: ScriptApi, opts: {
41
+ consentUrl: string;
42
+ log: (name: string, error: unknown) => void;
43
+ }): Promise<RenderedIntegrations>;
44
+ /**
45
+ * `html` with `rendered.head` before its first `</head>`, `bodyStart` right after its `<body>` and `bodyEnd` before
46
+ * its last `</body>`. A slot whose marker is missing is left out.
47
+ */
48
+ export declare function injectIntegrations(html: string, rendered: RenderedIntegrations): string;