reactive-md 0.5.3 → 0.6.1

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 (141) hide show
  1. package/CHANGELOG-ch.md +195 -165
  2. package/CHANGELOG.md +195 -165
  3. package/CONTRIBUTING-ch.md +67 -62
  4. package/CONTRIBUTING.md +69 -64
  5. package/README-ch.md +157 -155
  6. package/README-en.md +184 -181
  7. package/README.md +184 -181
  8. package/SECURITY-ch.md +81 -81
  9. package/SECURITY.md +81 -81
  10. package/THIRD_PARTY_NOTICES.md +585 -1
  11. package/bin/reactive-md.mjs +39 -39
  12. package/cli/args.mjs +181 -181
  13. package/cli/assets.mjs +390 -390
  14. package/cli/build.mjs +268 -268
  15. package/cli/document.mjs +130 -130
  16. package/cli/errors.mjs +61 -61
  17. package/cli/fs-utils.mjs +133 -133
  18. package/cli/glob.mjs +203 -203
  19. package/cli/help.mjs +138 -138
  20. package/cli/lint.mjs +177 -177
  21. package/cli/main.mjs +55 -55
  22. package/cli/migrate.mjs +368 -368
  23. package/cli/package.mjs +210 -210
  24. package/dist-library/{authoring-DJJjKYg9.js → authoring-BEVyth5X.js} +58 -58
  25. package/dist-library/compiler-Cm3ppMxG.js +46044 -0
  26. package/dist-library/react-Bh7_oxZp.js +59655 -0
  27. package/dist-library/reactive-md-authoring.js +2 -2
  28. package/dist-library/reactive-md-editor.js +13 -0
  29. package/dist-library/reactive-md-print.css +284 -284
  30. package/dist-library/reactive-md-react-unstyled.js +1 -1
  31. package/dist-library/reactive-md-react.js +1 -1
  32. package/dist-library/reactive-md.css +1 -1
  33. package/dist-library/reactive-md.js +123 -123
  34. package/dist-library/{runtime-DXtle_6c.js → runtime-DlFYQ4s_.js} +151 -151
  35. package/dist-library/types/editor/types.d.ts +2 -0
  36. package/dist-library/types/local/code-block.d.ts +3 -1
  37. package/dist-library/types/local/code-languages.d.ts +7 -0
  38. package/dist-library/types/local/compiled-data.d.ts +6 -0
  39. package/dist-library/types/local/compiler.d.ts +1 -0
  40. package/dist-library/types/local/diagnostics.d.ts +31 -0
  41. package/dist-library/types/local/diagram-layout.d.ts +69 -0
  42. package/dist-library/types/local/html-names.d.ts +6 -0
  43. package/dist-library/types/local/html-table.d.ts +25 -0
  44. package/dist-library/types/local/math-display.d.ts +22 -22
  45. package/dist-library/types/local/math-view.d.ts +6 -7
  46. package/dist-library/types/local/table-surface.d.ts +10 -0
  47. package/dist-library/types/local/types.d.ts +2 -0
  48. package/dist-library/types/local/visuals.d.ts +9 -0
  49. package/dist-standalone/reactive-md-standalone.css +1 -1
  50. package/dist-standalone/reactive-md-standalone.js +331 -51
  51. package/docs/README.md +84 -0
  52. package/docs/{compatibility-ch.md → compatibility/compatibility-ch.md} +121 -109
  53. package/docs/{compatibility-en.md → compatibility/compatibility-en.md} +121 -109
  54. package/docs/{source-versioning-ch.md → compatibility/source-versioning-ch.md} +159 -159
  55. package/docs/{source-versioning-en.md → compatibility/source-versioning-en.md} +159 -159
  56. package/docs/{component-development-ch.md → development/component-development-ch.md} +210 -210
  57. package/docs/{component-development-en.md → development/component-development-en.md} +210 -210
  58. package/docs/{component-protocol-ch.md → development/component-protocol-ch.md} +747 -747
  59. package/docs/{component-protocol-en.md → development/component-protocol-en.md} +747 -747
  60. package/docs/{performance-ch.md → development/performance-ch.md} +76 -76
  61. package/docs/{performance-en.md → development/performance-en.md} +76 -76
  62. package/docs/{releasing-ch.md → development/releasing-ch.md} +108 -108
  63. package/docs/{releasing-en.md → development/releasing-en.md} +108 -108
  64. package/docs/guides/local-guide-ch.md +513 -0
  65. package/docs/guides/local-guide-en.md +513 -0
  66. package/docs/{author-tools-ch.md → integration/author-tools-ch.md} +57 -57
  67. package/docs/{author-tools-en.md → integration/author-tools-en.md} +57 -57
  68. package/docs/{editor-ch.md → integration/editor-ch.md} +7 -6
  69. package/docs/{editor-en.md → integration/editor-en.md} +7 -6
  70. package/docs/{local-integration-ch.md → integration/local-integration-ch.md} +33 -15
  71. package/docs/{local-integration-en.md → integration/local-integration-en.md} +33 -15
  72. package/docs/{shareable-export-ch.md → integration/shareable-export-ch.md} +221 -209
  73. package/docs/{shareable-export-en.md → integration/shareable-export-en.md} +223 -211
  74. package/docs/{computations-formatting-ch.md → reference/computations-formatting-ch.md} +87 -87
  75. package/docs/{computations-formatting-en.md → reference/computations-formatting-en.md} +87 -87
  76. package/docs/{constraints-collections-ch.md → reference/constraints-collections-ch.md} +84 -84
  77. package/docs/{constraints-collections-en.md → reference/constraints-collections-en.md} +84 -84
  78. package/docs/{diagnostics-counting-ch.md → reference/diagnostics-counting-ch.md} +104 -84
  79. package/docs/{diagnostics-counting-en.md → reference/diagnostics-counting-en.md} +104 -84
  80. package/docs/{html-compatibility-ch.md → reference/html-compatibility-ch.md} +42 -4
  81. package/docs/{html-compatibility-en.md → reference/html-compatibility-en.md} +42 -4
  82. package/docs/{local-components-v2-ch.md → reference/local-components-v2-ch.md} +138 -138
  83. package/docs/{local-components-v2-en.md → reference/local-components-v2-en.md} +104 -104
  84. package/docs/{local-interaction-syntax-ch.md → reference/local-interaction-syntax-ch.md} +515 -492
  85. package/docs/{local-interaction-syntax-en.md → reference/local-interaction-syntax-en.md} +511 -488
  86. package/docs/{theme-protocol-ch.md → reference/theme-protocol-ch.md} +107 -107
  87. package/docs/{theme-protocol-en.md → reference/theme-protocol-en.md} +107 -107
  88. package/docs/{release-0.4.0-ch.md → releases/release-0.4.0-ch.md} +89 -89
  89. package/docs/{release-0.4.0-en.md → releases/release-0.4.0-en.md} +89 -89
  90. package/docs/{release-0.4.1-ch.md → releases/release-0.4.1-ch.md} +23 -23
  91. package/docs/{release-0.4.1-en.md → releases/release-0.4.1-en.md} +23 -23
  92. package/docs/{release-0.5.0-ch.md → releases/release-0.5.0-ch.md} +4 -4
  93. package/docs/{release-0.5.0-en.md → releases/release-0.5.0-en.md} +4 -4
  94. package/docs/{release-0.5.1-ch.md → releases/release-0.5.1-ch.md} +4 -4
  95. package/docs/{release-0.5.1-en.md → releases/release-0.5.1-en.md} +4 -4
  96. package/docs/{release-0.5.2-ch.md → releases/release-0.5.2-ch.md} +3 -3
  97. package/docs/{release-0.5.2-en.md → releases/release-0.5.2-en.md} +3 -3
  98. package/docs/{release-0.5.3-ch.md → releases/release-0.5.3-ch.md} +1 -1
  99. package/docs/{release-0.5.3-en.md → releases/release-0.5.3-en.md} +1 -1
  100. package/docs/releases/release-0.6.0-ch.md +57 -0
  101. package/docs/releases/release-0.6.0-en.md +57 -0
  102. package/docs/releases/release-0.6.1-ch.md +27 -0
  103. package/docs/releases/release-0.6.1-en.md +27 -0
  104. package/examples/conformance/README.md +53 -53
  105. package/examples/conformance/component-protocol-1.json +482 -482
  106. package/examples/conformance/component-protocol-1.schema.json +76 -76
  107. package/examples/conformance/local-draft-1.json +50 -50
  108. package/examples/conformance/local-draft-2.json +212 -212
  109. package/examples/integration/README.md +47 -45
  110. package/examples/integration/core/index.mjs +32 -32
  111. package/examples/integration/worker/index.html +19 -19
  112. package/examples/integration/worker/main.js +61 -61
  113. package/examples/integration/worker/package.json +13 -13
  114. package/examples/integration/worker/worker.js +3 -3
  115. package/examples/local/README.md +74 -74
  116. package/examples/local/charts.reactive.md +73 -73
  117. package/examples/local/html-compat.reactive.md +19 -0
  118. package/examples/local/recipes/invoice-zh.reactive.md +36 -36
  119. package/examples/local/recipes/invoice.reactive.md +36 -36
  120. package/examples/local/recipes/workshop-zh.reactive.md +33 -33
  121. package/examples/local/recipes/workshop.reactive.md +33 -33
  122. package/examples/local/showcase/README.md +25 -25
  123. package/examples/local/showcase/explore.reactive.md +102 -102
  124. package/examples/local/showcase/flow.reactive.md +86 -86
  125. package/examples/local/showcase/forms.reactive.md +126 -126
  126. package/examples/local/showcase/functions.reactive.md +119 -119
  127. package/examples/local/showcase/layout.reactive.md +100 -100
  128. package/examples/local/showcase/statistics.reactive.md +108 -108
  129. package/examples/local/showcase/tasks.reactive.md +89 -89
  130. package/examples/local/showcase/zh/explore.reactive.md +102 -102
  131. package/examples/local/showcase/zh/flow.reactive.md +86 -86
  132. package/examples/local/showcase/zh/forms.reactive.md +126 -126
  133. package/examples/local/showcase/zh/functions.reactive.md +119 -119
  134. package/examples/local/showcase/zh/layout.reactive.md +100 -100
  135. package/examples/local/showcase/zh/statistics.reactive.md +108 -108
  136. package/examples/local/showcase/zh/tasks.reactive.md +89 -89
  137. package/package.json +152 -145
  138. package/dist-library/compiler-UyPwGzJZ.js +0 -22109
  139. package/dist-library/react-fizgU3i8.js +0 -12764
  140. package/docs/local-guide-ch.md +0 -967
  141. package/docs/local-guide-en.md +0 -967
package/cli/assets.mjs CHANGED
@@ -1,390 +1,390 @@
1
- import { createHash } from 'node:crypto';
2
- import { readFile, realpath, stat } from 'node:fs/promises';
3
- import path from 'node:path';
4
- import { CliError, EXIT, fsFailure } from './errors.mjs';
5
-
6
- /** 8 MiB of decoded image bytes per asset. */
7
- export const MAX_ASSET_BYTES = 8 * 1024 * 1024;
8
- /** 24 MiB of decoded bytes across all distinct assets. */
9
- export const MAX_TOTAL_ASSET_BYTES = 24 * 1024 * 1024;
10
- /** At most 64 distinct image payloads. */
11
- export const MAX_ASSETS = 64;
12
-
13
- const CONTROL_CHARACTERS = /[\u0000-\u001f\u007f-\u009f]/;
14
- const URL_SCHEME = /^([a-z][a-z0-9+.-]*):/i;
15
- const WINDOWS_DRIVE_PATH = /^[a-z]:[\\/]/i;
16
-
17
- /**
18
- * Keep rejected URLs printable in diagnostics without allowing terminal
19
- * control sequences or unbounded output.
20
- *
21
- * @param {unknown} value
22
- */
23
- export function displayAssetUrl(value) {
24
- const text = typeof value === 'string' ? value : String(value ?? '');
25
- const clipped = text.length > 200 ? `${text.slice(0, 197)}...` : text;
26
- return clipped.replace(CONTROL_CHARACTERS, (character) => (
27
- `\\u${character.charCodeAt(0).toString(16).padStart(4, '0')}`
28
- ));
29
- }
30
-
31
- /** @param {unknown} url @param {string} detail */
32
- function assetFailure(url, detail) {
33
- return new CliError(
34
- `Image "${displayAssetUrl(url)}": ${detail} Use --assets omit to export without images, `
35
- + 'or place the file next to the document (or under --asset-root) and reference it with a relative URL.',
36
- EXIT.ASSET,
37
- );
38
- }
39
-
40
- /**
41
- * Validate an image URL before touching the filesystem. Only host-explicit
42
- * relative paths are accepted; remote URLs are never fetched.
43
- *
44
- * @param {unknown} rawUrl
45
- * @returns {{ok: true, url: string, path: string} | {ok: false, reason: string, message: string}}
46
- */
47
- export function classifyAssetUrl(rawUrl) {
48
- const url = typeof rawUrl === 'string' ? rawUrl.trim() : '';
49
- const fail = (reason, message) => ({ ok: false, reason, message });
50
-
51
- if (!url) {
52
- return fail('empty', 'The image URL is empty or missing.');
53
- }
54
- if (CONTROL_CHARACTERS.test(url)) {
55
- return fail('control', 'The image URL contains NUL or control characters.');
56
- }
57
- if (url.includes('\\')) {
58
- return fail('backslash', 'Backslash paths are not allowed; use a relative URL with "/" separators.');
59
- }
60
- if (url.startsWith('//')) {
61
- return fail('protocol-relative', 'Protocol-relative image URLs are not allowed.');
62
- }
63
- if (WINDOWS_DRIVE_PATH.test(url)) {
64
- return fail('absolute', 'Absolute image paths are not allowed.');
65
- }
66
- const scheme = URL_SCHEME.exec(url);
67
- if (scheme) {
68
- const name = scheme[1].toLowerCase();
69
- if (name === 'http' || name === 'https') {
70
- return fail('remote', 'Remote images are never fetched; download the image and use a relative path.');
71
- }
72
- return fail('scheme', `The "${name}:" URL scheme is not supported; only relative file assets are allowed.`);
73
- }
74
- if (url.startsWith('/')) {
75
- return fail('absolute', 'Absolute image paths are not allowed.');
76
- }
77
-
78
- // Query strings and fragments belong to the URL, not the local file name.
79
- let end = url.length;
80
- for (const marker of ['?', '#']) {
81
- const index = url.indexOf(marker);
82
- if (index !== -1 && index < end) end = index;
83
- }
84
- const rawPath = url.slice(0, end);
85
- if (!rawPath) {
86
- return fail('empty', 'The image URL does not contain a file path.');
87
- }
88
-
89
- let decoded;
90
- try {
91
- decoded = decodeURIComponent(rawPath);
92
- } catch {
93
- return fail('encoding', 'The image URL contains malformed percent-encoding.');
94
- }
95
- if (!decoded) {
96
- return fail('empty', 'The image URL does not contain a file path.');
97
- }
98
- if (CONTROL_CHARACTERS.test(decoded)) {
99
- return fail('control', 'The decoded image path contains NUL or control characters.');
100
- }
101
- if (decoded.includes('\\')) {
102
- return fail('backslash', 'The decoded image path contains a backslash.');
103
- }
104
- if (decoded.startsWith('/') || WINDOWS_DRIVE_PATH.test(decoded) || URL_SCHEME.test(decoded)) {
105
- return fail('absolute', 'The decoded image path is absolute or uses a URL scheme.');
106
- }
107
-
108
- return { ok: true, url, path: decoded };
109
- }
110
-
111
- /** @param {Uint8Array} bytes @param {number} start @param {string} text */
112
- function hasAscii(bytes, start, text) {
113
- if (bytes.length < start + text.length) return false;
114
- for (let index = 0; index < text.length; index += 1) {
115
- if (bytes[start + index] !== text.charCodeAt(index)) return false;
116
- }
117
- return true;
118
- }
119
-
120
- /**
121
- * Identify a supported raster image by magic bytes. The extension and any
122
- * caller-supplied MIME are ignored.
123
- *
124
- * @param {Uint8Array | null | undefined} bytes
125
- * @returns {'image/png' | 'image/jpeg' | 'image/gif' | 'image/webp' | null}
126
- */
127
- export function detectImageMime(bytes) {
128
- if (!bytes || bytes.length < 3) return null;
129
- if (
130
- bytes.length >= 8
131
- && bytes[0] === 0x89 && bytes[1] === 0x50 && bytes[2] === 0x4e && bytes[3] === 0x47
132
- && bytes[4] === 0x0d && bytes[5] === 0x0a && bytes[6] === 0x1a && bytes[7] === 0x0a
133
- ) {
134
- return 'image/png';
135
- }
136
- if (bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff) return 'image/jpeg';
137
- if (hasAscii(bytes, 0, 'GIF87a') || hasAscii(bytes, 0, 'GIF89a')) return 'image/gif';
138
- if (
139
- bytes.length >= 12
140
- && hasAscii(bytes, 0, 'RIFF')
141
- && hasAscii(bytes, 8, 'WEBP')
142
- ) {
143
- return 'image/webp';
144
- }
145
- return null;
146
- }
147
-
148
- /**
149
- * Used only to explain why an unrecognized file was rejected. SVG is never a
150
- * supported image format, even when it contains no XML declaration.
151
- *
152
- * @param {Uint8Array | null | undefined} bytes
153
- */
154
- export function looksLikeSvg(bytes) {
155
- if (!bytes || bytes.length === 0) return false;
156
- const length = Math.min(bytes.length, 4096);
157
- const head = Buffer.from(bytes.subarray(0, length))
158
- .toString('utf8')
159
- .replace(/^\uFEFF/, '')
160
- .trimStart()
161
- .toLowerCase();
162
- return head.startsWith('<svg') || head.includes('<svg');
163
- }
164
-
165
- /**
166
- * Collect image nodes in document order, including nested blocks.
167
- * @param {any[] | undefined} nodes
168
- * @returns {any[]}
169
- */
170
- export function collectImageNodes(nodes) {
171
- const images = [];
172
- const walk = (list) => {
173
- if (!Array.isArray(list)) return;
174
- for (const node of list) {
175
- if (node?.type === 'image') images.push(node);
176
- if (Array.isArray(node?.children)) walk(node.children);
177
- }
178
- };
179
- walk(nodes);
180
- return images;
181
- }
182
-
183
- /**
184
- * @param {string} root
185
- * @param {string} candidate
186
- */
187
- export function isPathInside(root, candidate) {
188
- const relative = path.relative(root, candidate);
189
- if (relative === '') return true;
190
- if (path.isAbsolute(relative)) return false;
191
- return relative !== '..' && !relative.startsWith(`..${path.sep}`);
192
- }
193
-
194
- /**
195
- * Try the document directory first, then an optional asset root. Resolution is
196
- * based on the real path so `..` segments and symlinks cannot escape a root.
197
- *
198
- * @param {string} relativePath
199
- * @param {{base: string, root: string}[]} roots
200
- */
201
- async function locateAsset(relativePath, roots) {
202
- let sawOutside = false;
203
- let sawDirectory = false;
204
- let sawUnreadable = false;
205
-
206
- for (const entry of roots) {
207
- const candidate = path.resolve(entry.base, relativePath);
208
- let real;
209
- try {
210
- real = await realpath(candidate);
211
- } catch (error) {
212
- const code = error && typeof error === 'object' && 'code' in error ? error.code : null;
213
- if (code !== 'ENOENT' && code !== 'ENOTDIR') sawUnreadable = true;
214
- continue;
215
- }
216
- if (!isPathInside(entry.root, real)) {
217
- sawOutside = true;
218
- continue;
219
- }
220
- let info;
221
- try {
222
- info = await stat(real);
223
- } catch {
224
- sawUnreadable = true;
225
- continue;
226
- }
227
- if (!info.isFile()) {
228
- sawDirectory = true;
229
- continue;
230
- }
231
- return { ok: true, realPath: real, size: info.size };
232
- }
233
-
234
- if (sawDirectory) {
235
- return { ok: false, message: 'The resolved path is a directory, not a file.' };
236
- }
237
- if (sawOutside) {
238
- return {
239
- ok: false,
240
- message: 'The resolved file is outside the allowed roots; path traversal and symlink escapes are not allowed.',
241
- };
242
- }
243
- if (sawUnreadable) {
244
- return { ok: false, message: 'The file could not be resolved or inspected.' };
245
- }
246
- return { ok: false, message: 'The file was not found relative to the document or --asset-root.' };
247
- }
248
-
249
- /**
250
- * Resolve and verify every image referenced by the compiled document, then
251
- * inline the accepted files as data URLs. Nothing is fetched from the network
252
- * and no URL is ever read from `--asset-root` as a remote base.
253
- *
254
- * @param {{document: {nodes?: any[]}, inputPath: string, assetRoot?: string}} options
255
- */
256
- export async function collectInlineAssets({ document, inputPath, assetRoot }) {
257
- const documentDirectory = path.dirname(path.resolve(inputPath));
258
- let documentRoot;
259
- try {
260
- documentRoot = await realpath(documentDirectory);
261
- } catch (error) {
262
- throw fsFailure('Cannot resolve document directory', documentDirectory, error, EXIT.IO);
263
- }
264
-
265
- /** @type {{base: string, root: string}[]} */
266
- const roots = [{ base: documentDirectory, root: documentRoot }];
267
-
268
- if (assetRoot !== undefined) {
269
- const absoluteAssetRoot = path.resolve(assetRoot);
270
- let info;
271
- try {
272
- info = await stat(absoluteAssetRoot);
273
- } catch (error) {
274
- throw fsFailure('Asset root does not exist', absoluteAssetRoot, error, EXIT.IO);
275
- }
276
- if (!info.isDirectory()) {
277
- throw new CliError(`Asset root is not a directory: "${absoluteAssetRoot}".`, EXIT.IO);
278
- }
279
- let assetRootReal;
280
- try {
281
- assetRootReal = await realpath(absoluteAssetRoot);
282
- } catch (error) {
283
- throw fsFailure('Cannot resolve asset root', absoluteAssetRoot, error, EXIT.IO);
284
- }
285
- roots.push({ base: absoluteAssetRoot, root: assetRootReal });
286
- }
287
-
288
- const imageNodes = collectImageNodes(document?.nodes);
289
- /** @type {Map<string, string>} */
290
- const byUrl = new Map();
291
- /** @type {Map<string, string>} */
292
- const contents = new Map();
293
- let totalBytes = 0;
294
-
295
- for (const node of imageNodes) {
296
- const classified = classifyAssetUrl(node.url);
297
- if (!classified.ok) {
298
- throw assetFailure(node.url, classified.message);
299
- }
300
- const key = classified.url;
301
- if (byUrl.has(key)) continue;
302
-
303
- const located = await locateAsset(classified.path, roots);
304
- if (!located.ok) {
305
- throw assetFailure(key, located.message);
306
- }
307
- if (located.size > MAX_ASSET_BYTES) {
308
- throw assetFailure(
309
- key,
310
- `The file is ${located.size} bytes, larger than the 8 MiB (${MAX_ASSET_BYTES} byte) per-image limit.`,
311
- );
312
- }
313
-
314
- let bytes;
315
- try {
316
- bytes = await readFile(located.realPath);
317
- } catch {
318
- throw assetFailure(key, 'The file exists but could not be read.');
319
- }
320
- if (bytes.length > MAX_ASSET_BYTES) {
321
- throw assetFailure(
322
- key,
323
- `The file grew beyond the 8 MiB (${MAX_ASSET_BYTES} byte) per-image limit while it was read.`,
324
- );
325
- }
326
-
327
- const hash = createHash('sha256').update(bytes).digest('hex');
328
- const existing = contents.get(hash);
329
- if (existing) {
330
- byUrl.set(key, existing);
331
- continue;
332
- }
333
-
334
- const mime = detectImageMime(bytes);
335
- if (!mime) {
336
- if (looksLikeSvg(bytes)) {
337
- throw assetFailure(key, 'SVG images are not supported; use PNG, JPEG, GIF or WebP.');
338
- }
339
- throw assetFailure(
340
- key,
341
- 'The file is not a supported raster image; use PNG, JPEG, GIF or WebP (identified from file contents, not the extension).',
342
- );
343
- }
344
-
345
- if (contents.size >= MAX_ASSETS) {
346
- throw assetFailure(key, `The document references more than ${MAX_ASSETS} distinct image assets.`);
347
- }
348
- if (totalBytes + bytes.length > MAX_TOTAL_ASSET_BYTES) {
349
- throw assetFailure(
350
- key,
351
- `Inlined images would exceed the 24 MiB (${MAX_TOTAL_ASSET_BYTES} byte) total limit `
352
- + `(${totalBytes} bytes already accepted, this file is ${bytes.length} bytes).`,
353
- );
354
- }
355
-
356
- const dataUrl = `data:${mime};base64,${bytes.toString('base64')}`;
357
- contents.set(hash, dataUrl);
358
- totalBytes += bytes.length;
359
- byUrl.set(key, dataUrl);
360
- }
361
-
362
- return {
363
- byUrl,
364
- imageCount: byUrl.size,
365
- assetCount: contents.size,
366
- totalBytes,
367
- };
368
- }
369
-
370
- /**
371
- * Host URL policy for the React renderer. Links keep the renderer's existing
372
- * protocol checks. Images are true only for URLs that were verified and
373
- * inlined; imageResolver maps exactly those URLs to their data URI.
374
- *
375
- * @param {Map<string, string>} byUrl
376
- */
377
- export function createAssetPolicy(byUrl) {
378
- const images = byUrl instanceof Map ? byUrl : new Map();
379
- return {
380
- /** @param {string} url @param {'image' | 'link'} kind */
381
- urlPolicy(url, kind) {
382
- if (kind === 'link') return true;
383
- return kind === 'image' && typeof url === 'string' && images.has(url);
384
- },
385
- /** @param {string} url */
386
- imageResolver(url) {
387
- return typeof url === 'string' ? images.get(url) ?? null : null;
388
- },
389
- };
390
- }
1
+ import { createHash } from 'node:crypto';
2
+ import { readFile, realpath, stat } from 'node:fs/promises';
3
+ import path from 'node:path';
4
+ import { CliError, EXIT, fsFailure } from './errors.mjs';
5
+
6
+ /** 8 MiB of decoded image bytes per asset. */
7
+ export const MAX_ASSET_BYTES = 8 * 1024 * 1024;
8
+ /** 24 MiB of decoded bytes across all distinct assets. */
9
+ export const MAX_TOTAL_ASSET_BYTES = 24 * 1024 * 1024;
10
+ /** At most 64 distinct image payloads. */
11
+ export const MAX_ASSETS = 64;
12
+
13
+ const CONTROL_CHARACTERS = /[\u0000-\u001f\u007f-\u009f]/;
14
+ const URL_SCHEME = /^([a-z][a-z0-9+.-]*):/i;
15
+ const WINDOWS_DRIVE_PATH = /^[a-z]:[\\/]/i;
16
+
17
+ /**
18
+ * Keep rejected URLs printable in diagnostics without allowing terminal
19
+ * control sequences or unbounded output.
20
+ *
21
+ * @param {unknown} value
22
+ */
23
+ export function displayAssetUrl(value) {
24
+ const text = typeof value === 'string' ? value : String(value ?? '');
25
+ const clipped = text.length > 200 ? `${text.slice(0, 197)}...` : text;
26
+ return clipped.replace(CONTROL_CHARACTERS, (character) => (
27
+ `\\u${character.charCodeAt(0).toString(16).padStart(4, '0')}`
28
+ ));
29
+ }
30
+
31
+ /** @param {unknown} url @param {string} detail */
32
+ function assetFailure(url, detail) {
33
+ return new CliError(
34
+ `Image "${displayAssetUrl(url)}": ${detail} Use --assets omit to export without images, `
35
+ + 'or place the file next to the document (or under --asset-root) and reference it with a relative URL.',
36
+ EXIT.ASSET,
37
+ );
38
+ }
39
+
40
+ /**
41
+ * Validate an image URL before touching the filesystem. Only host-explicit
42
+ * relative paths are accepted; remote URLs are never fetched.
43
+ *
44
+ * @param {unknown} rawUrl
45
+ * @returns {{ok: true, url: string, path: string} | {ok: false, reason: string, message: string}}
46
+ */
47
+ export function classifyAssetUrl(rawUrl) {
48
+ const url = typeof rawUrl === 'string' ? rawUrl.trim() : '';
49
+ const fail = (reason, message) => ({ ok: false, reason, message });
50
+
51
+ if (!url) {
52
+ return fail('empty', 'The image URL is empty or missing.');
53
+ }
54
+ if (CONTROL_CHARACTERS.test(url)) {
55
+ return fail('control', 'The image URL contains NUL or control characters.');
56
+ }
57
+ if (url.includes('\\')) {
58
+ return fail('backslash', 'Backslash paths are not allowed; use a relative URL with "/" separators.');
59
+ }
60
+ if (url.startsWith('//')) {
61
+ return fail('protocol-relative', 'Protocol-relative image URLs are not allowed.');
62
+ }
63
+ if (WINDOWS_DRIVE_PATH.test(url)) {
64
+ return fail('absolute', 'Absolute image paths are not allowed.');
65
+ }
66
+ const scheme = URL_SCHEME.exec(url);
67
+ if (scheme) {
68
+ const name = scheme[1].toLowerCase();
69
+ if (name === 'http' || name === 'https') {
70
+ return fail('remote', 'Remote images are never fetched; download the image and use a relative path.');
71
+ }
72
+ return fail('scheme', `The "${name}:" URL scheme is not supported; only relative file assets are allowed.`);
73
+ }
74
+ if (url.startsWith('/')) {
75
+ return fail('absolute', 'Absolute image paths are not allowed.');
76
+ }
77
+
78
+ // Query strings and fragments belong to the URL, not the local file name.
79
+ let end = url.length;
80
+ for (const marker of ['?', '#']) {
81
+ const index = url.indexOf(marker);
82
+ if (index !== -1 && index < end) end = index;
83
+ }
84
+ const rawPath = url.slice(0, end);
85
+ if (!rawPath) {
86
+ return fail('empty', 'The image URL does not contain a file path.');
87
+ }
88
+
89
+ let decoded;
90
+ try {
91
+ decoded = decodeURIComponent(rawPath);
92
+ } catch {
93
+ return fail('encoding', 'The image URL contains malformed percent-encoding.');
94
+ }
95
+ if (!decoded) {
96
+ return fail('empty', 'The image URL does not contain a file path.');
97
+ }
98
+ if (CONTROL_CHARACTERS.test(decoded)) {
99
+ return fail('control', 'The decoded image path contains NUL or control characters.');
100
+ }
101
+ if (decoded.includes('\\')) {
102
+ return fail('backslash', 'The decoded image path contains a backslash.');
103
+ }
104
+ if (decoded.startsWith('/') || WINDOWS_DRIVE_PATH.test(decoded) || URL_SCHEME.test(decoded)) {
105
+ return fail('absolute', 'The decoded image path is absolute or uses a URL scheme.');
106
+ }
107
+
108
+ return { ok: true, url, path: decoded };
109
+ }
110
+
111
+ /** @param {Uint8Array} bytes @param {number} start @param {string} text */
112
+ function hasAscii(bytes, start, text) {
113
+ if (bytes.length < start + text.length) return false;
114
+ for (let index = 0; index < text.length; index += 1) {
115
+ if (bytes[start + index] !== text.charCodeAt(index)) return false;
116
+ }
117
+ return true;
118
+ }
119
+
120
+ /**
121
+ * Identify a supported raster image by magic bytes. The extension and any
122
+ * caller-supplied MIME are ignored.
123
+ *
124
+ * @param {Uint8Array | null | undefined} bytes
125
+ * @returns {'image/png' | 'image/jpeg' | 'image/gif' | 'image/webp' | null}
126
+ */
127
+ export function detectImageMime(bytes) {
128
+ if (!bytes || bytes.length < 3) return null;
129
+ if (
130
+ bytes.length >= 8
131
+ && bytes[0] === 0x89 && bytes[1] === 0x50 && bytes[2] === 0x4e && bytes[3] === 0x47
132
+ && bytes[4] === 0x0d && bytes[5] === 0x0a && bytes[6] === 0x1a && bytes[7] === 0x0a
133
+ ) {
134
+ return 'image/png';
135
+ }
136
+ if (bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff) return 'image/jpeg';
137
+ if (hasAscii(bytes, 0, 'GIF87a') || hasAscii(bytes, 0, 'GIF89a')) return 'image/gif';
138
+ if (
139
+ bytes.length >= 12
140
+ && hasAscii(bytes, 0, 'RIFF')
141
+ && hasAscii(bytes, 8, 'WEBP')
142
+ ) {
143
+ return 'image/webp';
144
+ }
145
+ return null;
146
+ }
147
+
148
+ /**
149
+ * Used only to explain why an unrecognized file was rejected. SVG is never a
150
+ * supported image format, even when it contains no XML declaration.
151
+ *
152
+ * @param {Uint8Array | null | undefined} bytes
153
+ */
154
+ export function looksLikeSvg(bytes) {
155
+ if (!bytes || bytes.length === 0) return false;
156
+ const length = Math.min(bytes.length, 4096);
157
+ const head = Buffer.from(bytes.subarray(0, length))
158
+ .toString('utf8')
159
+ .replace(/^\uFEFF/, '')
160
+ .trimStart()
161
+ .toLowerCase();
162
+ return head.startsWith('<svg') || head.includes('<svg');
163
+ }
164
+
165
+ /**
166
+ * Collect image nodes in document order, including nested blocks.
167
+ * @param {any[] | undefined} nodes
168
+ * @returns {any[]}
169
+ */
170
+ export function collectImageNodes(nodes) {
171
+ const images = [];
172
+ const walk = (list) => {
173
+ if (!Array.isArray(list)) return;
174
+ for (const node of list) {
175
+ if (node?.type === 'image') images.push(node);
176
+ if (Array.isArray(node?.children)) walk(node.children);
177
+ }
178
+ };
179
+ walk(nodes);
180
+ return images;
181
+ }
182
+
183
+ /**
184
+ * @param {string} root
185
+ * @param {string} candidate
186
+ */
187
+ export function isPathInside(root, candidate) {
188
+ const relative = path.relative(root, candidate);
189
+ if (relative === '') return true;
190
+ if (path.isAbsolute(relative)) return false;
191
+ return relative !== '..' && !relative.startsWith(`..${path.sep}`);
192
+ }
193
+
194
+ /**
195
+ * Try the document directory first, then an optional asset root. Resolution is
196
+ * based on the real path so `..` segments and symlinks cannot escape a root.
197
+ *
198
+ * @param {string} relativePath
199
+ * @param {{base: string, root: string}[]} roots
200
+ */
201
+ async function locateAsset(relativePath, roots) {
202
+ let sawOutside = false;
203
+ let sawDirectory = false;
204
+ let sawUnreadable = false;
205
+
206
+ for (const entry of roots) {
207
+ const candidate = path.resolve(entry.base, relativePath);
208
+ let real;
209
+ try {
210
+ real = await realpath(candidate);
211
+ } catch (error) {
212
+ const code = error && typeof error === 'object' && 'code' in error ? error.code : null;
213
+ if (code !== 'ENOENT' && code !== 'ENOTDIR') sawUnreadable = true;
214
+ continue;
215
+ }
216
+ if (!isPathInside(entry.root, real)) {
217
+ sawOutside = true;
218
+ continue;
219
+ }
220
+ let info;
221
+ try {
222
+ info = await stat(real);
223
+ } catch {
224
+ sawUnreadable = true;
225
+ continue;
226
+ }
227
+ if (!info.isFile()) {
228
+ sawDirectory = true;
229
+ continue;
230
+ }
231
+ return { ok: true, realPath: real, size: info.size };
232
+ }
233
+
234
+ if (sawDirectory) {
235
+ return { ok: false, message: 'The resolved path is a directory, not a file.' };
236
+ }
237
+ if (sawOutside) {
238
+ return {
239
+ ok: false,
240
+ message: 'The resolved file is outside the allowed roots; path traversal and symlink escapes are not allowed.',
241
+ };
242
+ }
243
+ if (sawUnreadable) {
244
+ return { ok: false, message: 'The file could not be resolved or inspected.' };
245
+ }
246
+ return { ok: false, message: 'The file was not found relative to the document or --asset-root.' };
247
+ }
248
+
249
+ /**
250
+ * Resolve and verify every image referenced by the compiled document, then
251
+ * inline the accepted files as data URLs. Nothing is fetched from the network
252
+ * and no URL is ever read from `--asset-root` as a remote base.
253
+ *
254
+ * @param {{document: {nodes?: any[]}, inputPath: string, assetRoot?: string}} options
255
+ */
256
+ export async function collectInlineAssets({ document, inputPath, assetRoot }) {
257
+ const documentDirectory = path.dirname(path.resolve(inputPath));
258
+ let documentRoot;
259
+ try {
260
+ documentRoot = await realpath(documentDirectory);
261
+ } catch (error) {
262
+ throw fsFailure('Cannot resolve document directory', documentDirectory, error, EXIT.IO);
263
+ }
264
+
265
+ /** @type {{base: string, root: string}[]} */
266
+ const roots = [{ base: documentDirectory, root: documentRoot }];
267
+
268
+ if (assetRoot !== undefined) {
269
+ const absoluteAssetRoot = path.resolve(assetRoot);
270
+ let info;
271
+ try {
272
+ info = await stat(absoluteAssetRoot);
273
+ } catch (error) {
274
+ throw fsFailure('Asset root does not exist', absoluteAssetRoot, error, EXIT.IO);
275
+ }
276
+ if (!info.isDirectory()) {
277
+ throw new CliError(`Asset root is not a directory: "${absoluteAssetRoot}".`, EXIT.IO);
278
+ }
279
+ let assetRootReal;
280
+ try {
281
+ assetRootReal = await realpath(absoluteAssetRoot);
282
+ } catch (error) {
283
+ throw fsFailure('Cannot resolve asset root', absoluteAssetRoot, error, EXIT.IO);
284
+ }
285
+ roots.push({ base: absoluteAssetRoot, root: assetRootReal });
286
+ }
287
+
288
+ const imageNodes = collectImageNodes(document?.nodes);
289
+ /** @type {Map<string, string>} */
290
+ const byUrl = new Map();
291
+ /** @type {Map<string, string>} */
292
+ const contents = new Map();
293
+ let totalBytes = 0;
294
+
295
+ for (const node of imageNodes) {
296
+ const classified = classifyAssetUrl(node.url);
297
+ if (!classified.ok) {
298
+ throw assetFailure(node.url, classified.message);
299
+ }
300
+ const key = classified.url;
301
+ if (byUrl.has(key)) continue;
302
+
303
+ const located = await locateAsset(classified.path, roots);
304
+ if (!located.ok) {
305
+ throw assetFailure(key, located.message);
306
+ }
307
+ if (located.size > MAX_ASSET_BYTES) {
308
+ throw assetFailure(
309
+ key,
310
+ `The file is ${located.size} bytes, larger than the 8 MiB (${MAX_ASSET_BYTES} byte) per-image limit.`,
311
+ );
312
+ }
313
+
314
+ let bytes;
315
+ try {
316
+ bytes = await readFile(located.realPath);
317
+ } catch {
318
+ throw assetFailure(key, 'The file exists but could not be read.');
319
+ }
320
+ if (bytes.length > MAX_ASSET_BYTES) {
321
+ throw assetFailure(
322
+ key,
323
+ `The file grew beyond the 8 MiB (${MAX_ASSET_BYTES} byte) per-image limit while it was read.`,
324
+ );
325
+ }
326
+
327
+ const hash = createHash('sha256').update(bytes).digest('hex');
328
+ const existing = contents.get(hash);
329
+ if (existing) {
330
+ byUrl.set(key, existing);
331
+ continue;
332
+ }
333
+
334
+ const mime = detectImageMime(bytes);
335
+ if (!mime) {
336
+ if (looksLikeSvg(bytes)) {
337
+ throw assetFailure(key, 'SVG images are not supported; use PNG, JPEG, GIF or WebP.');
338
+ }
339
+ throw assetFailure(
340
+ key,
341
+ 'The file is not a supported raster image; use PNG, JPEG, GIF or WebP (identified from file contents, not the extension).',
342
+ );
343
+ }
344
+
345
+ if (contents.size >= MAX_ASSETS) {
346
+ throw assetFailure(key, `The document references more than ${MAX_ASSETS} distinct image assets.`);
347
+ }
348
+ if (totalBytes + bytes.length > MAX_TOTAL_ASSET_BYTES) {
349
+ throw assetFailure(
350
+ key,
351
+ `Inlined images would exceed the 24 MiB (${MAX_TOTAL_ASSET_BYTES} byte) total limit `
352
+ + `(${totalBytes} bytes already accepted, this file is ${bytes.length} bytes).`,
353
+ );
354
+ }
355
+
356
+ const dataUrl = `data:${mime};base64,${bytes.toString('base64')}`;
357
+ contents.set(hash, dataUrl);
358
+ totalBytes += bytes.length;
359
+ byUrl.set(key, dataUrl);
360
+ }
361
+
362
+ return {
363
+ byUrl,
364
+ imageCount: byUrl.size,
365
+ assetCount: contents.size,
366
+ totalBytes,
367
+ };
368
+ }
369
+
370
+ /**
371
+ * Host URL policy for the React renderer. Links keep the renderer's existing
372
+ * protocol checks. Images are true only for URLs that were verified and
373
+ * inlined; imageResolver maps exactly those URLs to their data URI.
374
+ *
375
+ * @param {Map<string, string>} byUrl
376
+ */
377
+ export function createAssetPolicy(byUrl) {
378
+ const images = byUrl instanceof Map ? byUrl : new Map();
379
+ return {
380
+ /** @param {string} url @param {'image' | 'link'} kind */
381
+ urlPolicy(url, kind) {
382
+ if (kind === 'link') return true;
383
+ return kind === 'image' && typeof url === 'string' && images.has(url);
384
+ },
385
+ /** @param {string} url */
386
+ imageResolver(url) {
387
+ return typeof url === 'string' ? images.get(url) ?? null : null;
388
+ },
389
+ };
390
+ }