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,8 @@
1
+ import { defOf } from '../fields/zod-internals.js';
2
+ /**
3
+ * True when `template` has no fields and no slots: a page designed in code, whose words are all in the template.
4
+ * The admin and MCP say so instead of offering an empty form.
5
+ */
6
+ export function designedInCode(template) {
7
+ return Object.keys(defOf(template.fields).shape ?? {}).length === 0 && Object.keys(template.slots).length === 0;
8
+ }
@@ -0,0 +1,48 @@
1
+ import type { z } from 'zod';
2
+ import type { Renderable } from '../../jsx/html.js';
3
+ import type { ScriptApi } from './render.js';
4
+ export declare const CONSENT_CATEGORIES: readonly ['analytics', 'marketing', 'functional'];
5
+ export type ConsentCategory = (typeof CONSENT_CATEGORIES)[number];
6
+ export declare const CSP_DIRECTIVES: readonly ['script-src', 'style-src', 'img-src', 'font-src', 'connect-src', 'frame-src', 'media-src', 'form-action', 'worker-src'];
7
+ export type CspDirective = (typeof CSP_DIRECTIVES)[number];
8
+ /** Sources a site or integration adds to the Content-Security-Policy, by directive. */
9
+ export type CspSources = Partial<Record<CspDirective, readonly string[]>>;
10
+ export interface IntegrationPage {
11
+ path: string;
12
+ locale: string;
13
+ preview: boolean;
14
+ /** Writes an inline script the page's Content-Security-Policy allows. */
15
+ script: ScriptApi;
16
+ }
17
+ export type IntegrationRender<V> = (values: V, page: IntegrationPage) => Renderable;
18
+ export interface IntegrationDef<T extends z.ZodObject = z.ZodObject> {
19
+ kind: 'integration';
20
+ name: string;
21
+ label: string;
22
+ description?: string;
23
+ /** What the owner fills in; `z.object({})` when the integration has none. */
24
+ fields: T;
25
+ /** When set, the integration's output stays inert until the visitor agrees to this category. */
26
+ consent?: ConsentCategory;
27
+ /** Also render in the admin's preview (default `false`). */
28
+ preview: boolean;
29
+ csp: CspSources;
30
+ head?: IntegrationRender<z.output<T>>;
31
+ bodyStart?: IntegrationRender<z.output<T>>;
32
+ bodyEnd?: IntegrationRender<z.output<T>>;
33
+ }
34
+ export interface IntegrationInput<T extends z.ZodObject> {
35
+ name: string;
36
+ label: string;
37
+ description?: string;
38
+ fields?: T;
39
+ consent?: ConsentCategory;
40
+ preview?: boolean;
41
+ csp?: CspSources;
42
+ head?: IntegrationRender<z.output<T>>;
43
+ bodyStart?: IntegrationRender<z.output<T>>;
44
+ bodyEnd?: IntegrationRender<z.output<T>>;
45
+ }
46
+ export declare function defineIntegration<T extends z.ZodObject = z.ZodObject>(def: IntegrationInput<T>): IntegrationDef<T>;
47
+ /** True for a Content-Security-Policy source Inlay accepts: a keyword, a bare scheme or an origin. */
48
+ export declare function isCspSource(source: string): boolean;
@@ -0,0 +1,29 @@
1
+ import { z as zod } from 'zod';
2
+ export const CONSENT_CATEGORIES = ['analytics', 'marketing', 'functional'];
3
+ export const CSP_DIRECTIVES = [
4
+ 'script-src',
5
+ 'style-src',
6
+ 'img-src',
7
+ 'font-src',
8
+ 'connect-src',
9
+ 'frame-src',
10
+ 'media-src',
11
+ 'form-action',
12
+ 'worker-src',
13
+ ];
14
+ export function defineIntegration(def) {
15
+ return {
16
+ ...def,
17
+ kind: 'integration',
18
+ fields: def.fields ?? zod.object({}),
19
+ preview: def.preview ?? false,
20
+ csp: def.csp ?? {},
21
+ };
22
+ }
23
+ const KEYWORDS = new Set(["'unsafe-inline'", "'unsafe-eval'", "'wasm-unsafe-eval'"]);
24
+ const SCHEME = /^[a-z][a-z0-9+.-]*:$/;
25
+ const ORIGIN = /^(https?|wss?):\/\/(\*\.)?[a-z0-9-]+(\.[a-z0-9-]+)*(:\d+)?$/;
26
+ /** True for a Content-Security-Policy source Inlay accepts: a keyword, a bare scheme or an origin. */
27
+ export function isCspSource(source) {
28
+ return typeof source === 'string' && (KEYWORDS.has(source) || SCHEME.test(source) || ORIGIN.test(source));
29
+ }
@@ -0,0 +1,9 @@
1
+ /** `value` as JSON that can't end its `<script>` or open an HTML comment in it. */
2
+ export declare function scriptJson(value: unknown): string;
3
+ /** Script code written with `js`, safe to put between `<script>` and `</script>`. */
4
+ export declare class JsCode {
5
+ readonly code: string;
6
+ constructor(code: string);
7
+ }
8
+ /** A template tag for script code: each value is written as JSON, so it stays data whatever it contains. */
9
+ export declare function js(strings: TemplateStringsArray, ...values: unknown[]): JsCode;
@@ -0,0 +1,39 @@
1
+ import { InlayError } from '../errors.js';
2
+ const SCRIPT_UNSAFE = {
3
+ '<': '\\u003c',
4
+ '>': '\\u003e',
5
+ '&': '\\u0026',
6
+ '\u2028': '\\u2028',
7
+ '\u2029': '\\u2029',
8
+ };
9
+ /** `value` as JSON that can't end its `<script>` or open an HTML comment in it. */
10
+ export function scriptJson(value) {
11
+ const json = JSON.stringify(value);
12
+ if (json === undefined)
13
+ throw new InlayError('config', 'config.headJsonLd');
14
+ return json.replace(/[<>&\u2028\u2029]/g, (c) => SCRIPT_UNSAFE[c]);
15
+ }
16
+ /** Script code written with `js`, safe to put between `<script>` and `</script>`. */
17
+ export class JsCode {
18
+ code;
19
+ constructor(code) {
20
+ this.code = code;
21
+ }
22
+ }
23
+ /** A template tag for script code: each value is written as JSON, so it stays data whatever it contains. */
24
+ export function js(strings, ...values) {
25
+ let code = strings[0] ?? '';
26
+ values.forEach((value, i) => {
27
+ let json;
28
+ try {
29
+ json = JSON.stringify(value);
30
+ }
31
+ catch {
32
+ json = undefined;
33
+ }
34
+ if (json === undefined)
35
+ throw new InlayError('config', 'config.scriptValue', { position: i + 1 });
36
+ code += scriptJson(value) + (strings[i + 1] ?? '');
37
+ });
38
+ return new JsCode(code);
39
+ }
@@ -3,9 +3,11 @@ import { InlayError } from '../errors.js';
3
3
  import { isTitleTemplate } from '../fields/builtins.js';
4
4
  import { fieldMeta } from '../fields/define.js';
5
5
  import { defOf, unwrap } from '../fields/zod-internals.js';
6
+ import { t } from '../messages/index.js';
6
7
  import { isReserved, normalizePath, routeRegExp, singletonPath, withLocale } from '../site/paths.js';
7
8
  import { paramNames, ruleIndex } from '../redirects/collapse.js';
8
9
  import { cleanPath, defaultLocalePrefix, externalTarget, redirectFrom } from '../redirects/rule.js';
10
+ import { CONSENT_CATEGORIES, CSP_DIRECTIVES, isCspSource } from './integration.js';
9
11
  import { KEY_PATTERN } from './content.js';
10
12
  const LOCALE = /^[a-z]{2,3}(-[A-Za-z0-9]+)*$/;
11
13
  const NAME = /^[a-z][A-Za-z0-9_]*$/;
@@ -148,6 +150,49 @@ function checkSettings(site, types) {
148
150
  migrations.add(name);
149
151
  }
150
152
  }
153
+ const INTEGRATION_NAME = /^[a-z0-9]+(-[a-z0-9]+)*$/;
154
+ const INTEGRATION_FIELD_KINDS = new Set(['text', 'textarea', 'number', 'boolean', 'select']);
155
+ function checkCsp(sources, where) {
156
+ if (sources === null || typeof sources !== 'object')
157
+ return;
158
+ for (const [directive, list] of Object.entries(sources)) {
159
+ if (!CSP_DIRECTIVES.includes(directive)) {
160
+ fail('definition.cspDirective', { where, directive, directives: CSP_DIRECTIVES.join(', ') });
161
+ }
162
+ if (!Array.isArray(list))
163
+ fail('definition.cspSource', { where, directive, source: String(list) });
164
+ for (const source of list) {
165
+ if (typeof source !== 'string' || !isCspSource(source))
166
+ fail('definition.cspSource', { where, directive, source: String(source) });
167
+ }
168
+ }
169
+ }
170
+ function checkIntegrations(site) {
171
+ const names = new Set();
172
+ for (const integration of site.integrations) {
173
+ const name = String(integration.name);
174
+ if (!INTEGRATION_NAME.test(name))
175
+ fail('definition.integrationName', { name });
176
+ if (names.has(name))
177
+ fail('definition.integrationDuplicate', { name });
178
+ names.add(name);
179
+ for (const [key, schema] of Object.entries(integration.fields.shape)) {
180
+ if (key === 'enabled')
181
+ fail('definition.integrationFieldReserved', { name });
182
+ const kind = fieldMeta(schema)?.kind;
183
+ if (!NAME.test(key) || kind === undefined || !INTEGRATION_FIELD_KINDS.has(kind)) {
184
+ fail('definition.integrationField', { name, field: key });
185
+ }
186
+ }
187
+ if (!integration.head && !integration.bodyStart && !integration.bodyEnd)
188
+ fail('definition.integrationRender', { name });
189
+ if (integration.consent !== undefined && !CONSENT_CATEGORIES.includes(integration.consent)) {
190
+ fail('definition.integrationConsent', { name, value: String(integration.consent) });
191
+ }
192
+ checkCsp(integration.csp, t('definition.cspOwnerIntegration', { name }));
193
+ }
194
+ checkCsp(site.csp, t('definition.cspOwnerSite'));
195
+ }
151
196
  /** Paths a route can't take: Inlay's reserved paths and the home page. */
152
197
  const isRouteReserved = (path) => path === '/' || isReserved(path);
153
198
  /** The type whose pages `path` would hide, in any locale, with or without its locale prefix. */
@@ -359,5 +404,6 @@ export function buildRegistry(site) {
359
404
  },
360
405
  };
361
406
  checkRoutes(registry);
407
+ checkIntegrations(site);
362
408
  return registry;
363
409
  }
@@ -1,12 +1,15 @@
1
1
  import type { z } from 'zod';
2
2
  import type { SafeHtml } from '../../jsx/html.js';
3
3
  import type { VariantFormat } from '../media/variants.js';
4
+ import type { RichTextRenderOptions } from '../richtext/html.js';
4
5
  import type { RichTextDoc } from '../richtext/schema.js';
5
6
  import type { FileValue, ImageValue, LinkValue } from '../types.js';
7
+ import type { CodeImage } from './code-image.js';
8
+ import type { JsCode } from './js.js';
6
9
  import type { CollectionDef, GlobalDef, TemplateDef } from './define.js';
7
10
  export interface ResolvedImage {
8
11
  id: string;
9
- /** The original: `/media/<id>`. */
12
+ /** The original: `/media/<id>`, or `/media/files/<sha><ext>` for an imported image. */
10
13
  url: string;
11
14
  alt: string;
12
15
  width: number | null;
@@ -102,6 +105,15 @@ export interface HeadApi {
102
105
  /** Replaces Inlay's link with the same `rel` and `hreflang`. Throws on an unsafe `href`. */
103
106
  link(attrs: HeadLink): void;
104
107
  }
108
+ /** What `ctx.script` takes: inline code, or an external script. */
109
+ export type ScriptInput = string | JsCode | {
110
+ src: string;
111
+ async?: boolean;
112
+ defer?: boolean;
113
+ type?: 'module';
114
+ };
115
+ /** Writes a `<script>` and records its hash for the page's Content-Security-Policy. Throws on unsafe code or `src`. */
116
+ export type ScriptApi = (input: ScriptInput) => SafeHtml;
105
117
  export interface RenderContext {
106
118
  locale: string;
107
119
  defaultLocale: string;
@@ -113,17 +125,40 @@ export interface RenderContext {
113
125
  asset(path: string): string;
114
126
  /** Tags for the page's `<head>`, collected during this render. */
115
127
  head: HeadApi;
128
+ /** A `<script>` for the page, to put in the template's output; inline code is allowed by the page's CSP by its hash. */
129
+ script: ScriptApi;
116
130
  alternates: Array<{
117
131
  locale: string;
118
132
  path: string;
119
133
  fallback: boolean;
120
134
  }>;
121
- /** Alt is the value's, then the media's default, then `''`. `null` when the media is missing. */
122
- image(v: ImageValue | null | undefined): ResolvedImage | null;
135
+ /**
136
+ * An image the site imports (`import hero from './hero.jpg'`), served from the site with its variants. Alt is
137
+ * `opts.alt`, then `''`.
138
+ */
139
+ image(v: CodeImage, opts?: {
140
+ alt?: string;
141
+ }): ResolvedImage;
142
+ /**
143
+ * A media library image. Alt is `opts.alt` when given (even `''`), then the value's, then the media's default, then
144
+ * `''`. `null` when the media is missing.
145
+ */
146
+ image(v: ImageValue | null | undefined, opts?: {
147
+ alt?: string;
148
+ }): ResolvedImage | null;
149
+ /** Either kind of image, when the value may be one or the other or missing. */
150
+ image(v: CodeImage | ImageValue | null | undefined, opts?: {
151
+ alt?: string;
152
+ }): ResolvedImage | null;
123
153
  file(v: FileValue | null | undefined): ResolvedFile | null;
124
154
  /** `null` when the target document isn't live. Text is the value's, then the target's title, then the URL. */
125
155
  link(v: LinkValue | null | undefined): ResolvedLink | null;
126
- richText(doc: RichTextDoc | null | undefined): SafeHtml;
156
+ richText(doc: RichTextDoc | null | undefined, opts?: RichTextRenderOptions): SafeHtml;
157
+ /**
158
+ * Markdown text (an imported `.md` file) as HTML, with every rich text feature and headings 1 to 6. Images next to
159
+ * the file are served from the site (`/media/files/…`). Throws when the text can't be read as rich text.
160
+ */
161
+ markdown(text: string, opts?: RichTextRenderOptions): Promise<SafeHtml>;
127
162
  /** An inline-text value's first paragraph without its `<p>`, for a heading or a tagline. A string is escaped. */
128
163
  inline(value: RichTextDoc | string | null | undefined): SafeHtml;
129
164
  /** Live entries in the given order; ones that aren't live are skipped. */
@@ -14,8 +14,10 @@ export declare function bundleConfig(configFile: string, outFile: string): Promi
14
14
  * any other import left outside the bundle (`inlaycms` itself included) with `error.packImport`, and site code
15
15
  * (not installed packages) that reaches for the server with `error.packForbidden`; other build failures are
16
16
  * `error.packBundle`. These checks catch mistakes: the release's signature is what makes it trusted. Returns the
17
- * imports left in the bundle.
17
+ * imports left in the bundle, and the `file:` URLs of the images site code names: those its `.md` files name, and
18
+ * those it imports.
18
19
  */
19
20
  export declare function bundleSite(configFile: string, outFile: string): Promise<{
20
21
  imports: string[];
22
+ codeImages: string[];
21
23
  }>;
@@ -1,12 +1,17 @@
1
- import { randomBytes } from 'node:crypto';
2
- import { existsSync, realpathSync } from 'node:fs';
1
+ import { createHash, randomBytes } from 'node:crypto';
2
+ import { existsSync, readFileSync, realpathSync } from 'node:fs';
3
3
  import { readFile } from 'node:fs/promises';
4
4
  import { builtinModules } from 'node:module';
5
5
  import { dirname, extname, isAbsolute, join, relative, resolve } from 'node:path';
6
6
  import { fileURLToPath, pathToFileURL } from 'node:url';
7
- import { build, transform } from 'esbuild';
7
+ import { build, transform, } from 'esbuild';
8
+ import sharp from 'sharp';
9
+ import { imageTarget, realInsideSync } from '../content/shipped-images.js';
8
10
  import { InlayError } from '../errors.js';
11
+ import { detectType } from '../media/detect.js';
9
12
  import { t } from '../messages/index.js';
13
+ import { markdownImages } from '../richtext/markdown.js';
14
+ import { isMediaTarget, MARKDOWN_IMAGE_TYPES, parseMarkdownText } from '../richtext/markdown-text.js';
10
15
  import { rewriteImageTargets } from './markdown-file.js';
11
16
  import { INLAY_ENTRIES } from './read.js';
12
17
  import { SITE_DIR_EXPORT, siteDirUrl } from './site-dir.js';
@@ -119,12 +124,65 @@ function shownPath(base, file) {
119
124
  const rel = relative(base, file);
120
125
  return rel === '' || rel.startsWith('..') || isAbsolute(rel) ? file : rel;
121
126
  }
127
+ /** The extensions a `.md` image's file may have, for messages: ".png, .jpg, …". */
128
+ const IMAGE_EXTENSIONS = Object.keys(MARKDOWN_IMAGE_TYPES).join(', ');
129
+ /**
130
+ * The first reason the image target `src` (on `line` of the `.md` file shown as `shown`, its relative targets already
131
+ * rewritten to `file:` URLs) can't be used, or null when it is a media library image or a picture file inside the
132
+ * site's folder (`siteDir`, a `file:` URL ending in `/`) whose extension is in `MARKDOWN_IMAGE_TYPES` and matches
133
+ * what it holds. An SVG file is refused.
134
+ */
135
+ function markdownImageProblem(src, line, shown, siteDir) {
136
+ const refuse = (id, extra = {}) => t(id, { file: shown, line, src, ...extra });
137
+ const target = imageTarget(src, siteDir);
138
+ if (target.kind === 'library')
139
+ return isMediaTarget(src) ? null : refuse('error.markdownImageOther');
140
+ if (target.kind === 'remote')
141
+ return refuse('error.markdownImageRemote');
142
+ if (target.kind === 'rooted')
143
+ return refuse('error.markdownImageRooted');
144
+ if (!/^file:/i.test(src))
145
+ return refuse('error.markdownImageOther');
146
+ let path;
147
+ try {
148
+ path = fileURLToPath(src);
149
+ }
150
+ catch {
151
+ return refuse('error.markdownImageOutside');
152
+ }
153
+ if (!existsSync(path))
154
+ return refuse('error.markdownImageMissing');
155
+ const real = realInsideSync(path, siteDir);
156
+ if (real === null)
157
+ return refuse('error.markdownImageOutside');
158
+ let bytes;
159
+ try {
160
+ bytes = readFileSync(real);
161
+ }
162
+ catch {
163
+ return refuse('error.markdownImageMissing');
164
+ }
165
+ const ext = extname(path).toLowerCase();
166
+ const mime = detectType(bytes, path);
167
+ if (mime === 'image/svg+xml' || ext === '.svg')
168
+ return refuse('error.markdownImageSvg');
169
+ if (!mime.startsWith('image/'))
170
+ return refuse('error.markdownImageNotImage');
171
+ const expected = MARKDOWN_IMAGE_TYPES[ext];
172
+ if (expected === undefined)
173
+ return refuse('error.markdownImageExtension', { extensions: IMAGE_EXTENSIONS });
174
+ if (mime !== expected)
175
+ return refuse('error.markdownImageMismatch', { ext });
176
+ return null;
177
+ }
122
178
  /**
123
179
  * A `.md` file at `file` as a module whose default export is its text, with its images' targets rewritten from
124
180
  * the file's own folder; a reference-style image is refused with `error.markdownImageReference`, and one whose
125
- * place in the file can't be found with `error.markdownImageUnplaced`.
181
+ * place in the file can't be found with `error.markdownImageUnplaced`. Then the first thing `parseMarkdownText`
182
+ * refuses is, and then the first image `markdownImageProblem` refuses. `images` is given the `file:` targets of a
183
+ * file that passes.
126
184
  */
127
- async function loadMarkdown(file, base) {
185
+ async function loadMarkdown(file, base, images) {
128
186
  const result = rewriteImageTargets(await readFile(file, 'utf8'), file);
129
187
  const line = result.references[0];
130
188
  if (line !== undefined)
@@ -133,8 +191,103 @@ async function loadMarkdown(file, base) {
133
191
  if (unplaced !== undefined) {
134
192
  return { errors: [{ text: t('error.markdownImageUnplaced', { file: shownPath(base, file), line: unplaced }) }] };
135
193
  }
194
+ const shown = shownPath(base, file);
195
+ const problem = parseMarkdownText(result.text);
196
+ if (!problem.ok) {
197
+ const first = problem.problems[0];
198
+ if (first)
199
+ return { errors: [{ text: t('error.markdownProblem', { file: shown, problem: first.message }) }] };
200
+ }
201
+ const siteDir = pathToFileURL(base).href + '/';
202
+ const targets = [];
203
+ for (const { src, line } of markdownImages(result.text)) {
204
+ const refused = markdownImageProblem(src, line, shown, siteDir);
205
+ if (refused !== null)
206
+ return { errors: [{ text: refused }] };
207
+ if (/^file:/i.test(src))
208
+ targets.push(src);
209
+ }
210
+ for (const target of targets)
211
+ images?.add(target);
136
212
  return { contents: result.text, loader: 'text' };
137
213
  }
214
+ /** The files an image import may name, and an SVG, which the loader refuses with a message of its own. */
215
+ const IMAGE_FILTER = new RegExp(`\\.(${[...Object.keys(MARKDOWN_IMAGE_TYPES), '.svg'].map((e) => e.slice(1)).join('|')})$`, 'i');
216
+ /** The `pluginData` of a plugin's own `b.resolve` call, so no plugin callback resolves its own lookup again. */
217
+ const RESOLVING = Symbol('resolving');
218
+ /**
219
+ * An `onResolve` callback for image imports that resolves them as esbuild would, and remembers the importing file
220
+ * so `loadImage` can name it. Anything it can't resolve is left to the other callbacks and esbuild's own error.
221
+ */
222
+ function imageResolver(b) {
223
+ return async (args) => {
224
+ if (args.kind === 'entry-point' || args.pluginData === RESOLVING)
225
+ return undefined;
226
+ const found = await b.resolve(fileUrlPath(args.path)?.path ?? args.path, {
227
+ kind: args.kind,
228
+ importer: args.importer,
229
+ resolveDir: args.resolveDir,
230
+ pluginData: RESOLVING,
231
+ });
232
+ if (found.errors.length > 0 || found.external || found.namespace !== 'file')
233
+ return undefined;
234
+ const pluginData = { importer: args.importer };
235
+ return { path: found.path, pluginData };
236
+ };
237
+ }
238
+ /**
239
+ * An image file at `file`, imported by `importer`, as a JSON module whose default export is its `CodeImage`, measured
240
+ * here so render never reads it. Refuses an image whose real path isn't inside the site's folder `base` with
241
+ * `error.imageImportOutside`, an SVG (by its name or its bytes) with `error.imageImportSvg`, bytes that aren't
242
+ * the picture its extension names with `error.imageImportMismatch`, and a picture sharp can't measure with
243
+ * `error.imageImportUnreadable`. `images` is given the `source` of an image that passes.
244
+ */
245
+ async function loadImage(file, base, importer, images) {
246
+ const params = { file: shownPath(base, importer ?? file), image: relative(realpathSync(base), file) };
247
+ const refuse = (id) => ({ errors: [{ text: t(id, params) }] });
248
+ const real = realInsideSync(file, pathToFileURL(base).href + '/');
249
+ if (real === null)
250
+ return refuse('error.imageImportOutside');
251
+ const ext = extname(file).toLowerCase();
252
+ if (ext === '.svg')
253
+ return refuse('error.imageImportSvg');
254
+ const bytes = await readFile(real);
255
+ const mime = detectType(bytes, file);
256
+ if (mime === 'image/svg+xml')
257
+ return refuse('error.imageImportSvg');
258
+ const expected = MARKDOWN_IMAGE_TYPES[ext];
259
+ if (expected === undefined || mime !== expected)
260
+ return refuse('error.imageImportMismatch');
261
+ let meta;
262
+ try {
263
+ meta = await sharp(bytes).metadata();
264
+ }
265
+ catch {
266
+ return refuse('error.imageImportUnreadable');
267
+ }
268
+ if (!meta.width || !meta.height)
269
+ return refuse('error.imageImportUnreadable');
270
+ const turned = meta.orientation !== undefined && meta.orientation >= 5 && meta.orientation <= 8;
271
+ const image = {
272
+ kind: 'codeImage',
273
+ source: pathToFileURL(file).href,
274
+ sha: createHash('sha256').update(bytes).digest('hex'),
275
+ ext,
276
+ mime,
277
+ width: turned ? meta.height : meta.width,
278
+ height: turned ? meta.width : meta.height,
279
+ };
280
+ images?.add(image.source);
281
+ return { contents: JSON.stringify(image), loader: 'json' };
282
+ }
283
+ /** The `onLoad` callback for image imports, for the site's folder `base`; `images` collects their sources. */
284
+ function imageLoader(base, images) {
285
+ return (args) => {
286
+ if (args.namespace !== 'file')
287
+ return undefined;
288
+ return loadImage(args.path, base, args.pluginData?.importer, images);
289
+ };
290
+ }
138
291
  /** The esbuild options `bundleSite` and `bundleConfig` share. */
139
292
  function buildOptions(configFile, outFile, plugin) {
140
293
  return {
@@ -163,12 +316,12 @@ export async function bundleConfig(configFile, outFile) {
163
316
  // The running copy's own folder (`src/` or `dist/`): a file in it is imported, never bundled as a second copy.
164
317
  const inlayDir = dirname(INLAY_ENTRIES.inlaycms ?? '');
165
318
  const base = dirname(resolve(configFile));
166
- const resolving = Symbol('resolving');
167
319
  const plugin = {
168
320
  name: 'inlay-config',
169
321
  setup(b) {
322
+ b.onResolve({ filter: IMAGE_FILTER }, imageResolver(b));
170
323
  b.onResolve({ filter: /.*/ }, async (args) => {
171
- if (args.kind === 'entry-point' || args.pluginData === resolving)
324
+ if (args.kind === 'entry-point' || args.pluginData === RESOLVING)
172
325
  return undefined;
173
326
  const running = INLAY_ENTRIES[args.path];
174
327
  if (running !== undefined)
@@ -178,7 +331,7 @@ export async function bundleConfig(configFile, outFile) {
178
331
  kind: args.kind,
179
332
  importer: args.importer,
180
333
  resolveDir: args.resolveDir,
181
- pluginData: resolving,
334
+ pluginData: RESOLVING,
182
335
  });
183
336
  if (found.errors.length > 0)
184
337
  return url;
@@ -194,6 +347,7 @@ export async function bundleConfig(configFile, outFile) {
194
347
  return withOwnUrl(await readFile(args.path, 'utf8'), args.path, loader, await tsconfigFor(dirname(args.path)));
195
348
  });
196
349
  b.onLoad({ filter: /\.md$/ }, (args) => (args.namespace === 'file' ? loadMarkdown(args.path, base) : undefined));
350
+ b.onLoad({ filter: IMAGE_FILTER }, imageLoader(base));
197
351
  },
198
352
  };
199
353
  try {
@@ -211,9 +365,11 @@ export async function bundleConfig(configFile, outFile) {
211
365
  * any other import left outside the bundle (`inlaycms` itself included) with `error.packImport`, and site code
212
366
  * (not installed packages) that reaches for the server with `error.packForbidden`; other build failures are
213
367
  * `error.packBundle`. These checks catch mistakes: the release's signature is what makes it trusted. Returns the
214
- * imports left in the bundle.
368
+ * imports left in the bundle, and the `file:` URLs of the images site code names: those its `.md` files name, and
369
+ * those it imports.
215
370
  */
216
371
  export async function bundleSite(configFile, outFile) {
372
+ const images = new Set();
217
373
  const base = dirname(resolve(configFile));
218
374
  const shown = (file) => shownPath(base, file);
219
375
  const refused = [];
@@ -222,6 +378,7 @@ export async function bundleSite(configFile, outFile) {
222
378
  const guard = {
223
379
  name: 'inlay-release',
224
380
  setup(b) {
381
+ b.onResolve({ filter: IMAGE_FILTER }, imageResolver(b));
225
382
  b.onResolve({ filter: /.*/ }, (args) => {
226
383
  if (args.kind === 'entry-point')
227
384
  return undefined;
@@ -245,7 +402,8 @@ export async function bundleSite(configFile, outFile) {
245
402
  }
246
403
  return withOwnUrl(text, args.path, loader, await tsconfigFor(dirname(args.path)));
247
404
  });
248
- b.onLoad({ filter: /\.md$/ }, (args) => (args.namespace === 'file' ? loadMarkdown(args.path, base) : undefined));
405
+ b.onLoad({ filter: /\.md$/ }, (args) => (args.namespace === 'file' ? loadMarkdown(args.path, base, images) : undefined));
406
+ b.onLoad({ filter: IMAGE_FILTER }, imageLoader(base, images));
249
407
  },
250
408
  };
251
409
  let result;
@@ -273,5 +431,5 @@ export async function bundleSite(configFile, outFile) {
273
431
  throw new InlayError('release', 'error.packImport', { file: shown(resolve(configFile)), specifier });
274
432
  }
275
433
  }
276
- return { imports: [...imports] };
434
+ return { imports: [...imports], codeImages: [...images].sort() };
277
435
  }
@@ -1,4 +1,5 @@
1
1
  import { z } from 'zod';
2
+ import { CONSENT_CATEGORIES } from '../registry/integration.js';
2
3
  import type { Registry } from '../registry/registry.js';
3
4
  export declare const MANIFEST_FORMAT = 1;
4
5
  export type ManifestRedirect = {
@@ -6,6 +7,13 @@ export type ManifestRedirect = {
6
7
  to: string;
7
8
  status: 301 | 302;
8
9
  };
10
+ export type ManifestCsp = Record<string, string[]>;
11
+ export type ManifestIntegration = {
12
+ name: string;
13
+ label: string;
14
+ consent?: (typeof CONSENT_CATEGORIES)[number];
15
+ csp?: ManifestCsp;
16
+ };
9
17
  /** What `manifest.json` in a release says; `manifest.sig` signs its bytes. */
10
18
  export interface ReleaseManifest {
11
19
  format: 1;
@@ -19,10 +27,14 @@ export interface ReleaseManifest {
19
27
  secrets: string[];
20
28
  /** Every file in the release except the manifest and its signature, to its sha256 (hex). */
21
29
  files: Record<string, string>;
22
- /** Each shipped image or file as the site names it, to where the release keeps it (`content/<sha256><ext>`). */
30
+ /**
31
+ * Each shipped image or file as the site names it, to where the release keeps it (`content/<sha256><ext>`).
32
+ * `code` marks an image site code names (a `.md` file it imports, or an image it imports): only those are served at `/media/files/`.
33
+ */
23
34
  content: Array<{
24
35
  source: string;
25
36
  path: string;
37
+ code?: true;
26
38
  }>;
27
39
  /** The JSON Schema of each type's stored data, by type name, as the export manifest has it. */
28
40
  schema: Record<string, unknown>;
@@ -45,6 +57,10 @@ export interface ReleaseManifest {
45
57
  }>;
46
58
  /** The site's code redirects in stored form; absent in manifests made before 0.3, which means none. */
47
59
  redirects?: ManifestRedirect[];
60
+ /** The site's integrations; absent when it has none, and in manifests made before integrations. */
61
+ integrations?: ManifestIntegration[];
62
+ /** The sources the site's own `csp` adds, by directive; absent when empty. */
63
+ csp?: ManifestCsp;
48
64
  locales: string[];
49
65
  /** Each type's kind and slot names, by type name. */
50
66
  types: Record<string, {
@@ -65,6 +81,7 @@ export declare const manifestSchema: z.ZodObject<{
65
81
  content: z.ZodArray<z.ZodObject<{
66
82
  source: z.ZodString;
67
83
  path: z.ZodString;
84
+ code: z.ZodOptional<z.ZodLiteral<true>>;
68
85
  }, z.core.$strict>>;
69
86
  schema: z.ZodRecord<z.ZodString, z.ZodRecord<z.ZodString, z.ZodUnknown>>;
70
87
  shipped: z.ZodArray<z.ZodObject<{
@@ -84,6 +101,17 @@ export declare const manifestSchema: z.ZodObject<{
84
101
  to: z.ZodString;
85
102
  status: z.ZodUnion<readonly [z.ZodLiteral<301>, z.ZodLiteral<302>]>;
86
103
  }, z.core.$strict>>>;
104
+ integrations: z.ZodOptional<z.ZodArray<z.ZodObject<{
105
+ name: z.ZodString;
106
+ label: z.ZodString;
107
+ consent: z.ZodOptional<z.ZodEnum<{
108
+ analytics: "analytics";
109
+ functional: "functional";
110
+ marketing: "marketing";
111
+ }>>;
112
+ csp: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodArray<z.ZodString>>>;
113
+ }, z.core.$strict>>>;
114
+ csp: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodArray<z.ZodString>>>;
87
115
  locales: z.ZodArray<z.ZodString>;
88
116
  types: z.ZodRecord<z.ZodString, z.ZodObject<{
89
117
  kind: z.ZodEnum<{