inlaycms 0.4.1 → 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 (128) 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/ipc.d.ts +2 -0
  115. package/dist/host/ipc.js +5 -1
  116. package/dist/host/preview-worker.js +2 -2
  117. package/dist/host/primary.js +15 -4
  118. package/dist/host/push.js +1 -1
  119. package/dist/host/serve.js +1 -1
  120. package/dist/host/store.d.ts +1 -2
  121. package/dist/host/store.js +32 -6
  122. package/dist/image-modules.d.ts +29 -0
  123. package/dist/image-modules.js +1 -0
  124. package/dist/index.d.ts +7 -1
  125. package/dist/index.js +4 -0
  126. package/dist/site.d.ts +8 -1
  127. package/dist/site.js +5 -0
  128. package/package.json +5 -1
@@ -5,6 +5,7 @@ import { z } from 'zod';
5
5
  import { imageTarget } from '../content/shipped-images.js';
6
6
  import { mapRichText, shippedFiles } from '../content/shipped-input.js';
7
7
  import { typeSchemas } from '../export/schema.js';
8
+ import { CONSENT_CATEGORIES } from '../registry/integration.js';
8
9
  import { markdownImages } from '../richtext/markdown.js';
9
10
  import { inlayVersion } from '../version.js';
10
11
  import { replaceImageTargets } from './markdown-file.js';
@@ -17,7 +18,7 @@ export const manifestSchema = z.strictObject({
17
18
  inlay: z.strictObject({ version: z.string(), range: z.string() }),
18
19
  secrets: z.array(z.string()),
19
20
  files: z.record(z.string(), z.string().regex(SHA256)),
20
- content: z.array(z.strictObject({ source: z.string(), path: z.string() })),
21
+ content: z.array(z.strictObject({ source: z.string(), path: z.string(), code: z.literal(true).optional() })),
21
22
  schema: z.record(z.string(), z.record(z.string(), z.unknown())),
22
23
  shipped: z.array(z.strictObject({
23
24
  type: z.string(),
@@ -30,6 +31,15 @@ export const manifestSchema = z.strictObject({
30
31
  redirects: z
31
32
  .array(z.strictObject({ from: z.string(), to: z.string(), status: z.union([z.literal(301), z.literal(302)]) }))
32
33
  .optional(),
34
+ integrations: z
35
+ .array(z.strictObject({
36
+ name: z.string(),
37
+ label: z.string(),
38
+ consent: z.enum(CONSENT_CATEGORIES).optional(),
39
+ csp: z.record(z.string(), z.array(z.string())).optional(),
40
+ }))
41
+ .optional(),
42
+ csp: z.record(z.string(), z.array(z.string())).optional(),
33
43
  locales: z.array(z.string()),
34
44
  types: z.record(z.string(), z.strictObject({ kind: z.enum(['singleton', 'collection', 'global']), slots: z.array(z.string()) })),
35
45
  });
@@ -113,6 +123,14 @@ function withReleaseImages(markdown, siteDir, paths) {
113
123
  return text;
114
124
  return { markdown: text, images: markdownImages(markdown).map(({ src }) => releaseCopy(src) ?? src) };
115
125
  }
126
+ /** `csp` as a manifest keeps it, or `undefined` when it adds no source. */
127
+ function cspOf(csp) {
128
+ const out = {};
129
+ for (const [directive, sources] of Object.entries(csp))
130
+ if (sources && sources.length > 0)
131
+ out[directive] = [...sources];
132
+ return Object.keys(out).length > 0 ? out : undefined;
133
+ }
116
134
  /**
117
135
  * The manifest of the site `registry` describes, without its files: what `packRelease` writes, given the shipped
118
136
  * files it packed as `content`. Without `content`, shipped files are read here to name them the way a release
@@ -157,6 +175,13 @@ export function manifestOfRegistry(registry, opts) {
157
175
  migrations: site.migrations.map((m) => m.name),
158
176
  routes: site.routes.map((r) => ({ method: r.method, path: r.path, ...(r.sitemap === true && { sitemap: true }) })),
159
177
  redirects: registry.redirects.map(({ from, to, status }) => ({ from, to, status })),
178
+ ...(site.integrations.length > 0 && {
179
+ integrations: site.integrations.map(({ name, label, consent, csp }) => {
180
+ const sources = cspOf(csp);
181
+ return { name, label, ...(consent !== undefined && { consent }), ...(sources && { csp: sources }) };
182
+ }),
183
+ }),
184
+ ...(cspOf(site.csp) && { csp: cspOf(site.csp) }),
160
185
  locales: [...registry.locales],
161
186
  types: Object.fromEntries([...registry.types].map(([name, def]) => [name, { kind: def.kind, slots: Object.keys(def.template.slots) }])),
162
187
  };
@@ -3,10 +3,12 @@ import { existsSync } from 'node:fs';
3
3
  import { copyFile, mkdir, mkdtemp, readdir, readFile, rm, writeFile } from 'node:fs/promises';
4
4
  import { tmpdir } from 'node:os';
5
5
  import { dirname, join, posix, relative, sep } from 'node:path';
6
+ import { fileURLToPath, pathToFileURL } from 'node:url';
6
7
  import { promisify } from 'node:util';
7
8
  import * as tar from 'tar';
8
9
  import { loadConfig } from '../../config.js';
9
10
  import { shippedFiles } from '../content/shipped-input.js';
11
+ import { realInsideSync } from '../content/shipped-images.js';
10
12
  import { InlayError } from '../errors.js';
11
13
  import { buildRegistry } from '../registry/registry.js';
12
14
  import { bundleSite } from './bundle.js';
@@ -52,9 +54,18 @@ export async function packRelease(opts) {
52
54
  const registry = buildRegistry(config.site);
53
55
  const tmp = await mkdtemp(join(tmpdir(), 'inlay-pack-'));
54
56
  try {
55
- await bundleSite(file, join(tmp, 'site.js'));
57
+ const bundled = await bundleSite(file, join(tmp, 'site.js'));
56
58
  const content = [];
59
+ const codeImages = new Set(bundled.codeImages);
57
60
  const sources = shippedFiles(registry);
61
+ const known = new Set(sources.map((s) => s.source));
62
+ const siteDir = pathToFileURL(dir).href + '/';
63
+ for (const source of bundled.codeImages) {
64
+ if (known.has(source))
65
+ continue;
66
+ const path = fileURLToPath(source);
67
+ sources.push({ source, path, read: realInsideSync(path, siteDir) ?? path });
68
+ }
58
69
  if (sources.length > 0)
59
70
  await mkdir(join(tmp, 'content'));
60
71
  for (const { source, path, read } of sources) {
@@ -67,7 +78,7 @@ export async function packRelease(opts) {
67
78
  }
68
79
  const target = contentPath(path, bytes);
69
80
  await writeFile(join(tmp, target), bytes);
70
- content.push({ source, path: target });
81
+ content.push({ source, path: target, ...(codeImages.has(source) && { code: true }) });
71
82
  }
72
83
  const publicDir = join(dir, 'public');
73
84
  if (existsSync(publicDir)) {
@@ -1,9 +1,16 @@
1
1
  import { randomUUID } from 'node:crypto';
2
2
  import { readFile, rename, rm, writeFile } from 'node:fs/promises';
3
3
  import { dirname, join } from 'node:path';
4
- import { z } from 'zod';
5
4
  import { InlayError } from '../errors.js';
6
- const pointerSchema = z.strictObject({ id: z.string().min(1), name: z.string(), activatedAt: z.string() });
5
+ function isPointer(value) {
6
+ if (typeof value !== 'object' || value === null || Array.isArray(value))
7
+ return false;
8
+ const keys = Object.keys(value).sort();
9
+ if (keys.length !== 3 || keys[0] !== 'activatedAt' || keys[1] !== 'id' || keys[2] !== 'name')
10
+ return false;
11
+ const { id, name, activatedAt } = value;
12
+ return typeof id === 'string' && id !== '' && typeof name === 'string' && typeof activatedAt === 'string';
13
+ }
7
14
  const POINTER = 'current.json';
8
15
  /** The `releases` folder beside the database file, as in the host's data folder. */
9
16
  export function releasesDirOf(dbPath) {
@@ -26,7 +33,11 @@ export async function readCurrentPointer(releasesDir) {
26
33
  throw e;
27
34
  }
28
35
  try {
29
- return pointerSchema.parse(JSON.parse(text));
36
+ const value = JSON.parse(text);
37
+ if (!isPointer(value))
38
+ throw new Error('not a pointer');
39
+ const { id, name, activatedAt } = value;
40
+ return { id, name, activatedAt };
30
41
  }
31
42
  catch {
32
43
  throw new InlayError('release', 'error.releasePointerInvalid', { file });
@@ -6,6 +6,8 @@ export interface LoadedRelease {
6
6
  dir: string;
7
7
  /** Each shipped file's source as the site names it, to the release's copy. */
8
8
  shippedFiles: Map<string, string>;
9
+ /** As `shippedFiles`, only the images `.md` files the site imports name: what `/media/files/` serves. */
10
+ codeFiles: Map<string, string>;
9
11
  publicDir: string | null;
10
12
  }
11
13
  /**
@@ -249,6 +249,7 @@ export async function loadRelease(dir, opts = {}) {
249
249
  site,
250
250
  dir,
251
251
  shippedFiles: new Map(manifest.content.map((c) => [c.source, join(dir, c.path)])),
252
+ codeFiles: new Map(manifest.content.filter((c) => c.code === true).map((c) => [c.source, join(dir, c.path)])),
252
253
  publicDir: existsSync(join(dir, 'public')) ? join(dir, 'public') : null,
253
254
  };
254
255
  }
@@ -23,6 +23,9 @@ export type CheckWarning = {
23
23
  redirect: {
24
24
  from: string;
25
25
  };
26
+ } | {
27
+ code: 'csp_unsafe_inline' | 'csp_unsafe_eval' | 'csp_script_scheme' | 'csp_overridden';
28
+ message: string;
26
29
  };
27
30
  /** What boot or `inlaycms check` did (or would do) to a database. */
28
31
  export interface CheckReport {
@@ -0,0 +1,10 @@
1
+ import type { RichTextDoc } from './schema.js';
2
+ export interface RichTextHeading {
3
+ level: number;
4
+ text: string;
5
+ id: string;
6
+ }
7
+ /** The doc's headings in document order, with the ids `ctx.richText(doc, { headingIds })` gives them. */
8
+ export declare function richTextHeadings(doc: RichTextDoc | null | undefined, opts?: {
9
+ prefix?: string;
10
+ }): RichTextHeading[];
@@ -0,0 +1,37 @@
1
+ function slug(text) {
2
+ const s = text
3
+ .normalize('NFC')
4
+ .toLowerCase()
5
+ .trim()
6
+ .replace(/\s+/g, '-')
7
+ .replace(/[^\p{L}\p{M}\p{N}-]/gu, '')
8
+ .replace(/-+/g, '-')
9
+ .replace(/^-|-$/g, '');
10
+ return s === '' ? 'section' : s;
11
+ }
12
+ /** The doc's headings in document order, with the ids `ctx.richText(doc, { headingIds })` gives them. */
13
+ export function richTextHeadings(doc, opts = {}) {
14
+ const out = [];
15
+ if (!doc)
16
+ return out;
17
+ const prefix = opts.prefix ?? '';
18
+ const used = new Set();
19
+ const walk = (nodes) => {
20
+ for (const node of nodes ?? []) {
21
+ if (node.type === 'heading') {
22
+ const text = (node.content ?? []).map((n) => (n.type === 'text' ? n.text : '')).join('');
23
+ const base = prefix + slug(text);
24
+ let id = base;
25
+ for (let n = 2; used.has(id); n++)
26
+ id = `${base}-${n}`;
27
+ used.add(id);
28
+ out.push({ level: node.attrs.level, text, id });
29
+ }
30
+ else if (node.type === 'blockquote' || node.type === 'bulletList' || node.type === 'orderedList' || node.type === 'listItem') {
31
+ walk(node.content);
32
+ }
33
+ }
34
+ };
35
+ walk(doc.content);
36
+ return out;
37
+ }
@@ -1,3 +1,4 @@
1
+ import { SafeHtml } from '../../jsx/html.js';
1
2
  import { type RichTextDoc, type RichTextInline } from './schema.js';
2
3
  export interface RichTextImageHtml {
3
4
  src: string;
@@ -11,7 +12,15 @@ export interface RichTextResolver {
11
12
  link(groupId: string): string | null;
12
13
  image(id: string, alt: string | undefined): RichTextImageHtml | null;
13
14
  }
15
+ /** Highlights code: the inside of `<code>` as `SafeHtml`, or `null` to leave it plain. */
16
+ export type CodeHighlighter = (code: string, language: string | undefined) => SafeHtml | null;
17
+ export interface RichTextRenderOptions {
18
+ highlight?: CodeHighlighter;
19
+ headingIds?: boolean | {
20
+ prefix: string;
21
+ };
22
+ }
14
23
  /** Inline content, keeping a mark open across neighbors that share it. */
15
24
  export declare function richTextInlineHtml(nodes: RichTextInline[], resolve: RichTextResolver): string;
16
25
  /** The doc as HTML. Every text and attribute is escaped; only Inlay's own tags are emitted. */
17
- export declare function richTextToHtml(doc: RichTextDoc, resolve: RichTextResolver): string;
26
+ export declare function richTextToHtml(doc: RichTextDoc, resolve: RichTextResolver, opts?: RichTextRenderOptions): string;
@@ -1,4 +1,5 @@
1
- import { escapeHtml } from '../../jsx/html.js';
1
+ import { escapeHtml, SafeHtml } from '../../jsx/html.js';
2
+ import { richTextHeadings } from './headings.js';
2
3
  import { isRichTextHref } from './schema.js';
3
4
  function attr(name, value) {
4
5
  return value === null || value === '' ? '' : ` ${name}="${escapeHtml(String(value))}"`;
@@ -53,15 +54,16 @@ export function richTextInlineHtml(nodes, resolve) {
53
54
  out += open[i].close;
54
55
  return out;
55
56
  }
56
- function block(node, resolve) {
57
- const children = (nodes) => (nodes ?? []).map((n) => block(n, resolve)).join('');
57
+ function block(node, resolve, opts, headings) {
58
+ const children = (nodes) => (nodes ?? []).map((n) => block(n, resolve, opts, headings)).join('');
58
59
  switch (node.type) {
59
60
  case 'paragraph':
60
61
  return `<p>${richTextInlineHtml(node.content ?? [], resolve)}</p>`;
61
62
  case 'heading': {
62
63
  const level = node.attrs.level;
63
64
  const tag = Number.isInteger(level) && level >= 1 && level <= 6 ? `h${level}` : 'p';
64
- return `<${tag}>${richTextInlineHtml(node.content ?? [], resolve)}</${tag}>`;
65
+ const id = headings ? headings.ids[headings.next++] ?? null : null;
66
+ return `<${tag}${attr('id', id)}>${richTextInlineHtml(node.content ?? [], resolve)}</${tag}>`;
65
67
  }
66
68
  case 'bulletList':
67
69
  return `<ul>${children(node.content)}</ul>`;
@@ -81,6 +83,13 @@ function block(node, resolve) {
81
83
  (body.length > 0 ? `<tbody>${body.map((r) => cells(r, 'td')).join('')}</tbody>` : '') +
82
84
  '</table>');
83
85
  }
86
+ case 'codeBlock': {
87
+ const code = node.content?.[0]?.text ?? '';
88
+ const language = node.attrs?.language;
89
+ const out = opts.highlight?.(code, language);
90
+ const inside = out instanceof SafeHtml ? out.value : escapeHtml(out === null || out === undefined ? code : String(out));
91
+ return `<pre><code${attr('class', language ? `language-${language}` : null)}>${inside}</code></pre>`;
92
+ }
84
93
  case 'tableRow':
85
94
  case 'tableHeader':
86
95
  case 'tableCell':
@@ -90,6 +99,8 @@ function block(node, resolve) {
90
99
  }
91
100
  }
92
101
  /** The doc as HTML. Every text and attribute is escaped; only Inlay's own tags are emitted. */
93
- export function richTextToHtml(doc, resolve) {
94
- return doc.content.map((node) => block(node, resolve)).join('');
102
+ export function richTextToHtml(doc, resolve, opts = {}) {
103
+ const ids = opts.headingIds;
104
+ const headings = ids ? { ids: richTextHeadings(doc, { prefix: typeof ids === 'object' ? ids.prefix : '' }).map((h) => h.id), next: 0 } : null;
105
+ return doc.content.map((node) => block(node, resolve, opts, headings)).join('');
95
106
  }
@@ -0,0 +1,24 @@
1
+ import { type RichTextHeading } from './headings.js';
2
+ import { type RichTextProblem } from './markdown.js';
3
+ import { type RichTextDoc, type RichTextOptions } from './schema.js';
4
+ export declare const MARKDOWN_TEXT_OPTIONS: RichTextOptions;
5
+ /** The start of a Markdown link target `](inlay:key/<type>` or `](inlay:key/<type>/<key>`; text elsewhere is left alone. */
6
+ export declare const KEY_HREF: RegExp;
7
+ /** A document that never resolves: a link to it shows as plain text. */
8
+ export declare const NO_DOCUMENT = "00000000-0000-0000-0000-000000000000";
9
+ /** The picture files Markdown in templates may name, by extension, with the type each must hold. No SVG. */
10
+ export declare const MARKDOWN_IMAGE_TYPES: Readonly<Record<string, string>>;
11
+ /** True if `src` names a media library image (`inlay:media/<id>`). */
12
+ export declare function isMediaTarget(src: string): boolean;
13
+ /** Reads a template's Markdown text with every rich text feature and heading levels 1 to 6. */
14
+ export declare function parseMarkdownText(text: string, images?: ReadonlyMap<string, string>): {
15
+ ok: true;
16
+ doc: RichTextDoc;
17
+ } | {
18
+ ok: false;
19
+ problems: RichTextProblem[];
20
+ };
21
+ /** The headings of Markdown text, with the ids `ctx.markdown` gives them, or none when it doesn't read. */
22
+ export declare function markdownHeadings(text: string, opts?: {
23
+ prefix?: string;
24
+ }): RichTextHeading[];
@@ -0,0 +1,38 @@
1
+ import { richTextHeadings } from './headings.js';
2
+ import { markdownImages, markdownToRichText } from './markdown.js';
3
+ import { RICH_TEXT_FEATURES } from './schema.js';
4
+ export const MARKDOWN_TEXT_OPTIONS = { features: RICH_TEXT_FEATURES, headings: [1, 2, 3, 4, 5, 6] };
5
+ /** Stands in for an image whose source isn't known, so parsing never fails on it. */
6
+ const PLACEHOLDER_IMAGE = '0'.repeat(64);
7
+ /** The start of a Markdown link target `](inlay:key/<type>` or `](inlay:key/<type>/<key>`; text elsewhere is left alone. */
8
+ export const KEY_HREF = /\]\(inlay:key\/([\w-]+)(?:\/([\w-]+))?(?=[\s)])/g;
9
+ /** A document that never resolves: a link to it shows as plain text. */
10
+ export const NO_DOCUMENT = '00000000-0000-0000-0000-000000000000';
11
+ const MEDIA_TARGET = /^inlay:media\/[0-9a-f]{64}$/;
12
+ /** The picture files Markdown in templates may name, by extension, with the type each must hold. No SVG. */
13
+ export const MARKDOWN_IMAGE_TYPES = {
14
+ '.png': 'image/png',
15
+ '.jpg': 'image/jpeg',
16
+ '.jpeg': 'image/jpeg',
17
+ '.gif': 'image/gif',
18
+ '.webp': 'image/webp',
19
+ '.avif': 'image/avif',
20
+ };
21
+ /** True if `src` names a media library image (`inlay:media/<id>`). */
22
+ export function isMediaTarget(src) {
23
+ return MEDIA_TARGET.test(src);
24
+ }
25
+ /** Reads a template's Markdown text with every rich text feature and heading levels 1 to 6. */
26
+ export function parseMarkdownText(text, images = new Map()) {
27
+ const mapped = new Map(images);
28
+ for (const { src } of markdownImages(text)) {
29
+ if (!mapped.has(src) && !isMediaTarget(src))
30
+ mapped.set(src, PLACEHOLDER_IMAGE);
31
+ }
32
+ return markdownToRichText(text.replace(KEY_HREF, `](inlay:document/${NO_DOCUMENT}`), MARKDOWN_TEXT_OPTIONS, { images: mapped });
33
+ }
34
+ /** The headings of Markdown text, with the ids `ctx.markdown` gives them, or none when it doesn't read. */
35
+ export function markdownHeadings(text, opts = {}) {
36
+ const parsed = parseMarkdownText(text);
37
+ return parsed.ok ? richTextHeadings(parsed.doc, opts) : [];
38
+ }
@@ -3,7 +3,7 @@ import { Fragment, Mark } from 'prosemirror-model';
3
3
  import { MarkdownParser, MarkdownSerializerState } from 'prosemirror-markdown';
4
4
  import { z } from 'zod';
5
5
  import { t } from '../messages/index.js';
6
- import { DEFAULT_RICH_TEXT, isRichTextHref, parseRichText, richTextSchema, } from './schema.js';
6
+ import { CODE_LANGUAGE, DEFAULT_RICH_TEXT, isRichTextHref, parseRichText, richTextSchema, } from './schema.js';
7
7
  const DOCUMENT_PREFIX = 'inlay:document/';
8
8
  const MEDIA_PREFIX = 'inlay:media/';
9
9
  const HEX64 = /^[0-9a-f]{64}$/;
@@ -637,6 +637,24 @@ const nodes = {
637
637
  renderTextblock(state, node, true);
638
638
  state.closeBlock(node);
639
639
  },
640
+ codeBlock(state, node) {
641
+ // Written line by line as it is: escaping, or the stand-ins `renderTextblock` places, would change the code.
642
+ const code = node.textContent;
643
+ let longest = 0;
644
+ for (const run of code.match(/`+/g) ?? [])
645
+ longest = Math.max(longest, run.length);
646
+ const fence = '`'.repeat(Math.max(3, longest + 1));
647
+ const language = node.attrs.language;
648
+ state.write(fence + (typeof language === 'string' ? language : ''));
649
+ state.ensureNewLine();
650
+ for (const line of code.split('\n')) {
651
+ state.write();
652
+ state.append(line);
653
+ state.append('\n');
654
+ }
655
+ state.write(fence);
656
+ state.closeBlock(node);
657
+ },
640
658
  image(state, node) {
641
659
  const alt = typeof node.attrs.alt === 'string' ? oneLine(node.attrs.alt) : '';
642
660
  state.write('![');
@@ -821,6 +839,7 @@ const parser = new MarkdownParser(richTextSchema, tokenizer, {
821
839
  bullet_list: { block: 'bulletList' },
822
840
  ordered_list: { block: 'orderedList', getAttrs: (tok) => ({ start: Number(tok.attrGet('start') ?? 1) }) },
823
841
  heading: { block: 'heading', getAttrs: (tok) => ({ level: Number(tok.tag.slice(1)) }) },
842
+ fence: { block: 'codeBlock', noCloseToken: true, getAttrs: (tok) => ({ language: tok.info.trim() || null }) },
824
843
  image: {
825
844
  node: 'image',
826
845
  getAttrs: (tok) => ({
@@ -878,8 +897,6 @@ const TOKEN_FEATURE = {
878
897
  table_open: 'table',
879
898
  };
880
899
  const TOKEN_UNSUPPORTED = {
881
- code_block: 'codeBlock',
882
- fence: 'codeBlock',
883
900
  hr: 'rule',
884
901
  };
885
902
  /** Token types the parser turns into rich text without any check. */
@@ -947,6 +964,18 @@ function literalSyntaxProblems(markdown) {
947
964
  }
948
965
  const isSafeHref = (href) => href.startsWith(DOCUMENT_PREFIX) ? UUID.safeParse(href.slice(DOCUMENT_PREFIX.length)).success : isRichTextHref(href);
949
966
  const isLibraryImage = (src) => src.startsWith(MEDIA_PREFIX) && HEX64.test(src.slice(MEDIA_PREFIX.length));
967
+ /**
968
+ * True if a fence token ends with a closing fence. A closed fence spans its content lines plus the opening and
969
+ * closing lines; one left open runs to the end of the document or its container and spans one line fewer.
970
+ * The content's last line lacks its `\n` only at the end of the input.
971
+ */
972
+ function fenceClosed(tok) {
973
+ if (!tok.map)
974
+ return true;
975
+ const content = tok.content;
976
+ const lines = content === '' ? 0 : (content.match(/\n/g) ?? []).length + (content.endsWith('\n') ? 0 : 1);
977
+ return tok.map[1] - tok.map[0] === lines + 2;
978
+ }
950
979
  /** Every problem in the token stream and `env`, in line order, before anything is built. */
951
980
  function findProblems(tokens, opts, env) {
952
981
  const problems = [];
@@ -956,6 +985,18 @@ function findProblems(tokens, opts, env) {
956
985
  };
957
986
  const allowed = (f) => opts.features.includes(f);
958
987
  const check = (tok, line, inHeading, inCell) => {
988
+ if (tok.type === 'code_block')
989
+ return add('unsupported', line, 'richtext.indentedCode', {});
990
+ if (tok.type === 'fence') {
991
+ if (!allowed('codeBlock'))
992
+ return add('not_allowed', line, 'richtext.notAllowed', { feature: feature('codeBlock') });
993
+ const language = tok.info.trim();
994
+ if (language !== '' && !CODE_LANGUAGE.test(language))
995
+ add('unsupported', line, 'richtext.codeLanguage', { language });
996
+ if (!fenceClosed(tok))
997
+ add('unsupported', line, 'richtext.unclosedCode', {});
998
+ return;
999
+ }
959
1000
  const unsupported = TOKEN_UNSUPPORTED[tok.type];
960
1001
  if (unsupported)
961
1002
  return add('unsupported', line, 'richtext.unsupported', { feature: feature(unsupported) });
@@ -1,6 +1,8 @@
1
1
  import { Schema } from 'prosemirror-model';
2
2
  import type { ContentRef } from '../types.js';
3
- export declare const RICH_TEXT_FEATURES: readonly ['heading', 'bold', 'italic', 'code', 'link', 'bulletList', 'orderedList', 'blockquote', 'image', 'hardBreak', 'table'];
3
+ export declare const RICH_TEXT_FEATURES: readonly ['heading', 'bold', 'italic', 'code', 'link', 'bulletList', 'orderedList', 'blockquote', 'codeBlock', 'image', 'hardBreak', 'table'];
4
+ /** A code block's language: one short word, kept as written. */
5
+ export declare const CODE_LANGUAGE: RegExp;
4
6
  export type RichTextFeature = (typeof RICH_TEXT_FEATURES)[number];
5
7
  export interface RichTextOptions {
6
8
  features: readonly RichTextFeature[];
@@ -69,6 +71,13 @@ export type RichTextBlockquote = {
69
71
  type: 'blockquote';
70
72
  content: RichTextBlock[];
71
73
  };
74
+ export type RichTextCodeBlock = {
75
+ type: 'codeBlock';
76
+ attrs?: {
77
+ language: string;
78
+ };
79
+ content?: [RichTextText];
80
+ };
72
81
  export type RichTextTableCell = {
73
82
  type: 'tableHeader' | 'tableCell';
74
83
  content: [RichTextParagraph];
@@ -81,7 +90,7 @@ export type RichTextTable = {
81
90
  type: 'table';
82
91
  content: RichTextTableRow[];
83
92
  };
84
- export type RichTextBlock = RichTextParagraph | RichTextHeading | RichTextBulletList | RichTextOrderedList | RichTextBlockquote | RichTextTable;
93
+ export type RichTextBlock = RichTextParagraph | RichTextHeading | RichTextBulletList | RichTextOrderedList | RichTextBlockquote | RichTextCodeBlock | RichTextTable;
85
94
  export type RichTextNode = RichTextBlock | RichTextListItem | RichTextTableRow | RichTextTableCell | RichTextInline;
86
95
  export type RichTextDoc = {
87
96
  type: 'doc';
@@ -91,7 +100,7 @@ export type RichTextDoc = {
91
100
  * Tiptap's node and mark names. The mark order is the canonical order of marks on a node. Code comes last, inside a
92
101
  * link, and never with bold or italic: Markdown can't put either inside a code span.
93
102
  */
94
- export declare const richTextSchema: Schema<"blockquote" | "bulletList" | "doc" | "hardBreak" | "heading" | "image" | "listItem" | "orderedList" | "paragraph" | "table" | "tableCell" | "tableHeader" | "tableRow" | "text", "bold" | "code" | "italic" | "link">;
103
+ export declare const richTextSchema: Schema<"blockquote" | "bulletList" | "codeBlock" | "doc" | "hardBreak" | "heading" | "image" | "listItem" | "orderedList" | "paragraph" | "table" | "tableCell" | "tableHeader" | "tableRow" | "text", "bold" | "code" | "italic" | "link">;
95
104
  /**
96
105
  * A link address rich text can hold: a safe URL without control characters, which
97
106
  * Markdown can't carry and so wouldn't read back.
@@ -11,10 +11,13 @@ export const RICH_TEXT_FEATURES = [
11
11
  'bulletList',
12
12
  'orderedList',
13
13
  'blockquote',
14
+ 'codeBlock',
14
15
  'image',
15
16
  'hardBreak',
16
17
  'table',
17
18
  ];
19
+ /** A code block's language: one short word, kept as written. */
20
+ export const CODE_LANGUAGE = /^[A-Za-z0-9_+#.-]{1,32}$/;
18
21
  export const DEFAULT_RICH_TEXT = { features: RICH_TEXT_FEATURES, headings: [2, 3, 4] };
19
22
  /**
20
23
  * Tiptap's node and mark names. The mark order is the canonical order of marks on a node. Code comes last, inside a
@@ -29,6 +32,7 @@ export const richTextSchema = new Schema({
29
32
  orderedList: { group: 'block', content: 'listItem+', attrs: { start: { default: 1 } } },
30
33
  listItem: { content: 'paragraph block*' },
31
34
  blockquote: { group: 'block', content: 'block+' },
35
+ codeBlock: { group: 'block', content: 'text*', marks: '', code: true, attrs: { language: { default: null } } },
32
36
  table: { group: 'block', content: 'tableRow+' },
33
37
  tableRow: { content: '(tableHeader | tableCell)+' },
34
38
  tableHeader: { content: 'paragraph' },
@@ -49,6 +53,7 @@ const NODE_FEATURE = {
49
53
  bulletList: 'bulletList',
50
54
  orderedList: 'orderedList',
51
55
  blockquote: 'blockquote',
56
+ codeBlock: 'codeBlock',
52
57
  image: 'image',
53
58
  hardBreak: 'hardBreak',
54
59
  table: 'table',
@@ -110,6 +115,14 @@ function cleanAttrs(type, raw, opts) {
110
115
  reject();
111
116
  return start === 1 ? undefined : { start };
112
117
  }
118
+ if (type === 'codeBlock') {
119
+ const { language } = attrs;
120
+ if (absent(language) || language === '')
121
+ return undefined;
122
+ if (typeof language !== 'string' || !CODE_LANGUAGE.test(language))
123
+ reject();
124
+ return { language };
125
+ }
113
126
  if (type === 'image') {
114
127
  const { media, alt } = attrs;
115
128
  if (typeof media !== 'string' || !HEX64.test(media))
@@ -142,6 +155,25 @@ function cleanNode(raw, opts) {
142
155
  if (marks.length > 0)
143
156
  out.marks = marks;
144
157
  }
158
+ if (type === 'codeBlock') {
159
+ if (!absent(raw.marks))
160
+ reject();
161
+ if (!absent(raw.content) && !Array.isArray(raw.content))
162
+ reject();
163
+ let code = '';
164
+ for (const child of raw.content ?? []) {
165
+ if (!isRecord(child) || child.type !== 'text' || typeof child.text !== 'string')
166
+ reject();
167
+ if (!absent(child.marks) && !(Array.isArray(child.marks) && child.marks.length === 0))
168
+ reject();
169
+ code += child.text;
170
+ }
171
+ code = code.replace(/\r\n?/g, '\n');
172
+ if (code === '')
173
+ return null;
174
+ out.content = [{ type: 'text', text: code }];
175
+ return out;
176
+ }
145
177
  if (type === 'text') {
146
178
  if (typeof raw.text !== 'string')
147
179
  reject();
@@ -309,6 +341,8 @@ function blockTexts(node, out) {
309
341
  continue;
310
342
  if (child.type === 'paragraph' || child.type === 'heading')
311
343
  out.push(inlineText(child));
344
+ else if (child.type === 'codeBlock')
345
+ out.push(inlineText(child));
312
346
  else if (child.type === 'tableRow')
313
347
  out.push(childrenOf(child).map(inlineCell).join('\t'));
314
348
  else
@@ -8,6 +8,7 @@ export type LiveOpts = {
8
8
  /** Visible, non-deleted documents, each with its live revision (`rev_*` are `null` when it has none). */
9
9
  export declare function liveQuery(deps: CoreDeps, state: LiveState): import("kysely").SelectQueryBuilder<{
10
10
  documents: DocumentsTable;
11
+ integrations: import("../db/schema.js").IntegrationsTable;
11
12
  media: import("../db/schema.js").MediaTable;
12
13
  media_deletions: import("../db/schema.js").MediaDeletionsTable;
13
14
  oauthClient: import("../db/schema.js").OAuthClientTable;
@@ -55,3 +56,8 @@ export declare function liveAlternates(deps: CoreDeps, groupId: string, opts?: L
55
56
  path: string;
56
57
  fallback: boolean;
57
58
  }>>;
59
+ /** The group id of each keyed document (or singleton or global, whose key is its type), by `type/key`. */
60
+ export declare function groupIdsByKey(deps: CoreDeps, refs: Array<{
61
+ type: string;
62
+ key: string | null;
63
+ }>): Promise<Map<string, string>>;
@@ -144,3 +144,28 @@ export async function liveAlternates(deps, groupId, opts = {}) {
144
144
  }
145
145
  return out;
146
146
  }
147
+ /** The group id of each keyed document (or singleton or global, whose key is its type), by `type/key`. */
148
+ export async function groupIdsByKey(deps, refs) {
149
+ const out = new Map();
150
+ if (refs.length === 0)
151
+ return out;
152
+ const wanted = new Map(refs.map((r) => [`${r.type}/${r.key ?? r.type}`, { type: r.type, key: r.key ?? r.type }]));
153
+ const rows = await deps.db
154
+ .selectFrom('documents')
155
+ .select(['group_id', 'type', 'key'])
156
+ .where('deleted_at', 'is', null)
157
+ .where((eb) => eb.or([...wanted.values()].map(({ type, key }) => {
158
+ const keyed = eb.and([eb('type', '=', type), eb('key', '=', key)]);
159
+ if (key !== type)
160
+ return keyed;
161
+ const unkeyed = eb.and([eb('type', '=', type), eb('key', 'is', null), eb('kind', 'in', ['singleton', 'global'])]);
162
+ return eb.or([keyed, unkeyed]);
163
+ })))
164
+ .execute();
165
+ for (const row of rows) {
166
+ const id = `${row.type}/${row.key ?? row.type}`;
167
+ if (wanted.has(id))
168
+ out.set(id, row.group_id);
169
+ }
170
+ return out;
171
+ }
@@ -13,6 +13,8 @@ export interface SiteSource {
13
13
  publicDir: string | null;
14
14
  /** Each shipped file's source as the site names it, to the file to read. */
15
15
  shippedFiles?: ReadonlyMap<string, string>;
16
+ /** As `shippedFiles`, only the images `.md` files the site imports name. */
17
+ codeFiles?: ReadonlyMap<string, string>;
16
18
  }
17
19
  /** The source of a site run from its code (`inlaycms dev` and `inlaycms/testing`): its `public/` folder, if it has one. */
18
20
  export declare function sourceFromConfig(loaded: LoadedConfig): SiteSource;
package/dist/host/app.js CHANGED
@@ -98,6 +98,7 @@ export async function createSiteApp(config, source, opts) {
98
98
  ...(opts.fetch && { fetch: opts.fetch }),
99
99
  content: opts.content,
100
100
  ...(source?.shippedFiles && { shippedFiles: source.shippedFiles }),
101
+ ...(source?.codeFiles && { codeFiles: source.codeFiles }),
101
102
  ...(opts.now && { now: opts.now }),
102
103
  ...(opts.host && { host: opts.host }),
103
104
  ...(opts.readOnly && { readOnly: true }),
@@ -66,6 +66,17 @@ export interface StructuralDiff {
66
66
  after: ManifestRedirect;
67
67
  }>;
68
68
  };
69
+ /** Integrations by name; `changed` when the label, consent category or sources differ. Absent from an older host. */
70
+ integrations?: {
71
+ added: string[];
72
+ removed: string[];
73
+ changed: string[];
74
+ };
75
+ /** What the site may newly load and no longer may, as `<directive> <source>`, over the site's sources and every integration's. */
76
+ csp?: {
77
+ added: string[];
78
+ removed: string[];
79
+ };
69
80
  /** Every secret the staged release needs. */
70
81
  secrets: string[];
71
82
  /** Every migration function of the staged release, in order. */