@nova-energy/openamx 0.0.0-stage → 0.11.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.
- package/COMMERCIAL-LICENSE.md +74 -0
- package/LICENSE.md +660 -0
- package/README.md +537 -3
- package/dist/ast/types.js +2 -0
- package/dist/cli.js +197 -0
- package/dist/diagnostics/errors.js +94 -0
- package/dist/editor/completion.js +313 -0
- package/dist/editor/highlighting.js +224 -0
- package/dist/editor/moduleAnalysis.js +206 -0
- package/dist/editor/refactoring.js +46 -0
- package/dist/editor/sourceRanges.js +50 -0
- package/dist/editor/symbols.js +203 -0
- package/dist/formatter/formatAmx.js +79 -0
- package/dist/index.js +10 -0
- package/dist/parser/parseDocument.js +114 -0
- package/dist/parser/parseExpression.js +768 -0
- package/dist/parser/parseFor.js +53 -0
- package/dist/parser/parseFrontMatter.js +65 -0
- package/dist/parser/parseStatements.js +667 -0
- package/dist/parser/stringScanner.js +71 -0
- package/dist/renderer/chartModel.js +476 -0
- package/dist/renderer/narrativeModel.js +561 -0
- package/dist/renderer/renderHtml.js +521 -0
- package/dist/renderer/reportDocx.js +725 -0
- package/dist/renderer/reportPaths.js +31 -0
- package/dist/renderer/reportPdf.js +314 -0
- package/dist/renderer/reportPreparation.js +196 -0
- package/dist/runtime/csvTextSerialization.js +8 -0
- package/dist/runtime/dataText.js +191 -0
- package/dist/runtime/docxDestination.js +55 -0
- package/dist/runtime/environment.js +105 -0
- package/dist/runtime/evaluateDocument.js +32 -0
- package/dist/runtime/evaluateExpression.js +888 -0
- package/dist/runtime/externalUnits.js +91 -0
- package/dist/runtime/inputData.js +508 -0
- package/dist/runtime/measurement.js +110 -0
- package/dist/runtime/moduleLoader.js +279 -0
- package/dist/runtime/outputData.js +303 -0
- package/dist/runtime/pdfDestination.js +57 -0
- package/dist/runtime/standardLibrary.js +145 -0
- package/dist/typechecker/checkDocument.js +1282 -0
- package/dist/typechecker/declarationRegistry.js +7 -0
- package/dist/typechecker/dimensionTypes.js +1 -0
- package/package.json +33 -4
|
@@ -0,0 +1,561 @@
|
|
|
1
|
+
import { existsSync, lstatSync, readFileSync, realpathSync, statSync } from 'node:fs';
|
|
2
|
+
import { dirname, extname, resolve, sep } from 'node:path';
|
|
3
|
+
import sharp from 'sharp';
|
|
4
|
+
import { Marked } from 'marked';
|
|
5
|
+
import { AmxError } from '../diagnostics/errors';
|
|
6
|
+
import { canonicalDirectory, hasSymlink, isContained } from './reportPaths';
|
|
7
|
+
const MAX_IMAGE_BYTES = 4 * 1024 * 1024;
|
|
8
|
+
const MAX_IMAGE_PIXELS = 4_000_000;
|
|
9
|
+
const LOCAL_LINK_EXTENSIONS = new Set(['.pdf', '.png', '.jpg', '.jpeg', '.txt', '.csv', '.json']);
|
|
10
|
+
const markdown = new Marked({ gfm: true, breaks: true });
|
|
11
|
+
function fencedCodeContent(raw) {
|
|
12
|
+
const openingLineEnd = raw.indexOf('\n');
|
|
13
|
+
if (openingLineEnd === -1)
|
|
14
|
+
return raw;
|
|
15
|
+
const end = raw.endsWith('\n') ? raw.length - 1 : raw.length;
|
|
16
|
+
const closingLineStart = raw.lastIndexOf('\n', end - 1) + 1;
|
|
17
|
+
return raw.slice(openingLineEnd + 1, closingLineStart);
|
|
18
|
+
}
|
|
19
|
+
export async function prepareNarratives(sources, options) {
|
|
20
|
+
const headingIds = new Set();
|
|
21
|
+
const pending = [];
|
|
22
|
+
for (const source of sources) {
|
|
23
|
+
const interpolation = interpolateSource(source.content, options.interpolate, source.line);
|
|
24
|
+
const diagnostics = [];
|
|
25
|
+
const context = { interpolation, options, headingIds, diagnostics };
|
|
26
|
+
const blocks = await buildBlocks(markdown.lexer(interpolation.markdown), context);
|
|
27
|
+
pending.push({ text: interpolation.text, blocks, diagnostics });
|
|
28
|
+
}
|
|
29
|
+
const targets = new Set();
|
|
30
|
+
for (const narrative of pending)
|
|
31
|
+
collectHeadingIds(narrative.blocks, targets);
|
|
32
|
+
return Object.freeze(pending.map(narrative => freezeDeep({
|
|
33
|
+
text: narrative.text,
|
|
34
|
+
blocks: resolveInternalLinks(narrative.blocks, targets),
|
|
35
|
+
diagnostics: narrative.diagnostics
|
|
36
|
+
})));
|
|
37
|
+
}
|
|
38
|
+
export function fitNarrativeImage(image, bounds) {
|
|
39
|
+
if (!Number.isFinite(bounds.maxWidth) || !Number.isFinite(bounds.maxHeight) || bounds.maxWidth <= 0 || bounds.maxHeight <= 0) {
|
|
40
|
+
throw new RangeError('Narrative image bounds must be finite positive numbers');
|
|
41
|
+
}
|
|
42
|
+
if (!Number.isFinite(image.width) || !Number.isFinite(image.height) || image.width <= 0 || image.height <= 0) {
|
|
43
|
+
throw new RangeError('Narrative image dimensions must be finite positive numbers');
|
|
44
|
+
}
|
|
45
|
+
const scale = Math.min(1, bounds.maxWidth / image.width, bounds.maxHeight / image.height);
|
|
46
|
+
return Object.freeze({ width: image.width * scale, height: image.height * scale });
|
|
47
|
+
}
|
|
48
|
+
function interpolateSource(source, interpolate, line) {
|
|
49
|
+
const pattern = /\{\{\s*([\s\S]*?)\s*\}\}/g;
|
|
50
|
+
let prefix = '\uE000OPENAMX_INTERPOLATION-';
|
|
51
|
+
while (source.includes(prefix))
|
|
52
|
+
prefix += 'X';
|
|
53
|
+
const interpolations = [];
|
|
54
|
+
const markdownSource = source.replace(pattern, (whole, expression) => {
|
|
55
|
+
const marker = `${prefix}${interpolations.length}\uE001`;
|
|
56
|
+
const value = expression.trim() ? interpolate(expression.trim(), line) : '';
|
|
57
|
+
interpolations.push({ marker, value, source: whole.replace(/\r\n/g, '\n') });
|
|
58
|
+
return marker;
|
|
59
|
+
});
|
|
60
|
+
let index = 0;
|
|
61
|
+
const text = source.replace(pattern, () => interpolations[index++]?.value ?? '');
|
|
62
|
+
const markerPattern = new RegExp(`${escapeRegExp(prefix)}(\\d+)\\uE001`, 'g');
|
|
63
|
+
const replaceMarkers = (value, replacement) => value.replace(markerPattern, (_marker, markerIndex) => {
|
|
64
|
+
const item = interpolations[Number(markerIndex)];
|
|
65
|
+
return item ? replacement(item) : _marker;
|
|
66
|
+
});
|
|
67
|
+
return {
|
|
68
|
+
markdown: markdownSource.replace(/\r\n/g, '\n'),
|
|
69
|
+
text,
|
|
70
|
+
textValue: value => replaceMarkers(value, item => item.value),
|
|
71
|
+
sourceValue: value => replaceMarkers(value, item => item.source)
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
async function buildBlocks(tokens, context) {
|
|
75
|
+
const blocks = [];
|
|
76
|
+
for (const token of tokens) {
|
|
77
|
+
switch (token.type) {
|
|
78
|
+
case 'space':
|
|
79
|
+
case 'def':
|
|
80
|
+
break;
|
|
81
|
+
case 'heading': {
|
|
82
|
+
const heading = token;
|
|
83
|
+
const children = await buildInlines(heading.tokens, context);
|
|
84
|
+
blocks.push({ type: 'heading', depth: heading.depth, id: uniqueHeadingId(children, context.headingIds), children });
|
|
85
|
+
break;
|
|
86
|
+
}
|
|
87
|
+
case 'paragraph': {
|
|
88
|
+
const paragraph = token;
|
|
89
|
+
blocks.push({ type: 'paragraph', children: await buildInlines(paragraph.tokens, context) });
|
|
90
|
+
break;
|
|
91
|
+
}
|
|
92
|
+
case 'text': {
|
|
93
|
+
const text = token;
|
|
94
|
+
const children = text.tokens
|
|
95
|
+
? await buildInlines(text.tokens, context)
|
|
96
|
+
: textNodes(context.interpolation.textValue(text.text));
|
|
97
|
+
blocks.push({ type: 'paragraph', children });
|
|
98
|
+
break;
|
|
99
|
+
}
|
|
100
|
+
case 'code': {
|
|
101
|
+
const code = token;
|
|
102
|
+
if (code.codeBlockStyle === 'indented') {
|
|
103
|
+
fail('AMX6001', 'Narrative code blocks must use fenced Markdown', context.options.file);
|
|
104
|
+
}
|
|
105
|
+
const block = { type: 'code', text: context.interpolation.sourceValue(fencedCodeContent(code.raw)) };
|
|
106
|
+
if (code.lang)
|
|
107
|
+
block.language = code.lang;
|
|
108
|
+
blocks.push(block);
|
|
109
|
+
break;
|
|
110
|
+
}
|
|
111
|
+
case 'list': {
|
|
112
|
+
const list = token;
|
|
113
|
+
const items = [];
|
|
114
|
+
for (const item of list.items) {
|
|
115
|
+
const preparedItem = {
|
|
116
|
+
blocks: await buildBlocks(item.tokens, context)
|
|
117
|
+
};
|
|
118
|
+
if (item.checked !== undefined)
|
|
119
|
+
preparedItem.checked = item.checked;
|
|
120
|
+
items.push(preparedItem);
|
|
121
|
+
}
|
|
122
|
+
const block = { type: 'list', ordered: list.ordered, items };
|
|
123
|
+
if (typeof list.start === 'number')
|
|
124
|
+
block.start = list.start;
|
|
125
|
+
blocks.push(block);
|
|
126
|
+
break;
|
|
127
|
+
}
|
|
128
|
+
case 'blockquote': {
|
|
129
|
+
const quote = token;
|
|
130
|
+
blocks.push({ type: 'blockquote', blocks: await buildBlocks(quote.tokens, context) });
|
|
131
|
+
break;
|
|
132
|
+
}
|
|
133
|
+
case 'table': {
|
|
134
|
+
const table = token;
|
|
135
|
+
const header = [];
|
|
136
|
+
for (const cell of table.header)
|
|
137
|
+
header.push(await buildInlines(cell.tokens, context));
|
|
138
|
+
const rows = [];
|
|
139
|
+
for (const row of table.rows) {
|
|
140
|
+
const preparedRow = [];
|
|
141
|
+
for (const cell of row)
|
|
142
|
+
preparedRow.push(await buildInlines(cell.tokens, context));
|
|
143
|
+
rows.push(preparedRow);
|
|
144
|
+
}
|
|
145
|
+
blocks.push({ type: 'table', align: table.align, header, rows });
|
|
146
|
+
break;
|
|
147
|
+
}
|
|
148
|
+
case 'hr':
|
|
149
|
+
blocks.push({ type: 'horizontalRule' });
|
|
150
|
+
break;
|
|
151
|
+
case 'html': {
|
|
152
|
+
const html = token;
|
|
153
|
+
if (html.block && isPageBreakDirective(html.text)) {
|
|
154
|
+
blocks.push({ type: 'pageBreak' });
|
|
155
|
+
break;
|
|
156
|
+
}
|
|
157
|
+
blocks.push({
|
|
158
|
+
type: 'paragraph',
|
|
159
|
+
children: literalTextNodes(context.interpolation.textValue(html.text.replace(/\n+$/g, '')))
|
|
160
|
+
});
|
|
161
|
+
break;
|
|
162
|
+
}
|
|
163
|
+
default:
|
|
164
|
+
throw new AmxError({
|
|
165
|
+
code: 'AMX6001',
|
|
166
|
+
message: `Unsupported Markdown block token '${token.type}'`,
|
|
167
|
+
file: context.options.file
|
|
168
|
+
});
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
return blocks;
|
|
172
|
+
}
|
|
173
|
+
async function buildInlines(tokens, context) {
|
|
174
|
+
const inlines = [];
|
|
175
|
+
for (const token of tokens) {
|
|
176
|
+
switch (token.type) {
|
|
177
|
+
case 'text': {
|
|
178
|
+
const text = token;
|
|
179
|
+
if (text.tokens)
|
|
180
|
+
inlines.push(...await buildInlines(text.tokens, context));
|
|
181
|
+
else
|
|
182
|
+
inlines.push(...textNodes(context.interpolation.textValue(text.text)));
|
|
183
|
+
break;
|
|
184
|
+
}
|
|
185
|
+
case 'escape': {
|
|
186
|
+
const escaped = token;
|
|
187
|
+
inlines.push(...textNodes(context.interpolation.textValue(escaped.text)));
|
|
188
|
+
break;
|
|
189
|
+
}
|
|
190
|
+
case 'strong':
|
|
191
|
+
case 'em':
|
|
192
|
+
case 'del': {
|
|
193
|
+
const nested = token;
|
|
194
|
+
const type = token.type === 'strong' ? 'strong' : token.type === 'em' ? 'emphasis' : 'delete';
|
|
195
|
+
inlines.push({ type, children: await buildInlines(nested.tokens, context) });
|
|
196
|
+
break;
|
|
197
|
+
}
|
|
198
|
+
case 'codespan': {
|
|
199
|
+
const code = token;
|
|
200
|
+
inlines.push({ type: 'inlineCode', text: context.interpolation.sourceValue(codeSpanContent(code.raw)) });
|
|
201
|
+
break;
|
|
202
|
+
}
|
|
203
|
+
case 'br':
|
|
204
|
+
inlines.push({ type: 'lineBreak' });
|
|
205
|
+
break;
|
|
206
|
+
case 'link': {
|
|
207
|
+
const link = token;
|
|
208
|
+
const children = await buildInlines(link.tokens, context);
|
|
209
|
+
const preparedLink = prepareLink(context.interpolation.sourceValue(link.href), link.title ?? undefined, context);
|
|
210
|
+
if (!preparedLink)
|
|
211
|
+
inlines.push(...children);
|
|
212
|
+
else
|
|
213
|
+
inlines.push({ type: 'link', link: preparedLink, children });
|
|
214
|
+
break;
|
|
215
|
+
}
|
|
216
|
+
case 'image': {
|
|
217
|
+
const image = token;
|
|
218
|
+
const alt = context.interpolation.textValue(image.text).trim();
|
|
219
|
+
const preparedImage = await prepareImage(context.interpolation.sourceValue(image.href), alt, context);
|
|
220
|
+
const prepared = { type: 'image', image: preparedImage };
|
|
221
|
+
if (image.title !== null)
|
|
222
|
+
prepared.title = image.title;
|
|
223
|
+
inlines.push(prepared);
|
|
224
|
+
break;
|
|
225
|
+
}
|
|
226
|
+
case 'html': {
|
|
227
|
+
const html = token;
|
|
228
|
+
inlines.push(...literalTextNodes(context.interpolation.textValue(html.text)));
|
|
229
|
+
break;
|
|
230
|
+
}
|
|
231
|
+
default:
|
|
232
|
+
throw new AmxError({
|
|
233
|
+
code: 'AMX6001',
|
|
234
|
+
message: `Unsupported Markdown inline token '${token.type}'`,
|
|
235
|
+
file: context.options.file
|
|
236
|
+
});
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
return inlines;
|
|
240
|
+
}
|
|
241
|
+
function prepareLink(href, title, context) {
|
|
242
|
+
let link;
|
|
243
|
+
if (href.startsWith('#')) {
|
|
244
|
+
let targetId;
|
|
245
|
+
try {
|
|
246
|
+
targetId = decodeURIComponent(href.slice(1));
|
|
247
|
+
}
|
|
248
|
+
catch {
|
|
249
|
+
return rejectLink(context, 'invalid-internal-fragment');
|
|
250
|
+
}
|
|
251
|
+
link = { type: 'internal', targetId, ...(title === undefined ? {} : { title }) };
|
|
252
|
+
}
|
|
253
|
+
else if (/^https?:\/\//i.test(href)) {
|
|
254
|
+
let url;
|
|
255
|
+
try {
|
|
256
|
+
url = new URL(href);
|
|
257
|
+
}
|
|
258
|
+
catch {
|
|
259
|
+
return rejectLink(context, 'invalid-external-target');
|
|
260
|
+
}
|
|
261
|
+
if ((url.protocol !== 'http:' && url.protocol !== 'https:') || url.username || url.password) {
|
|
262
|
+
return rejectLink(context, 'invalid-external-target');
|
|
263
|
+
}
|
|
264
|
+
link = { type: 'external', href: url.href, ...(title === undefined ? {} : { title }) };
|
|
265
|
+
}
|
|
266
|
+
else if (/^[A-Za-z][A-Za-z\d+.-]*:/.test(href) || href.startsWith('//')) {
|
|
267
|
+
return rejectLink(context, 'unsupported-scheme');
|
|
268
|
+
}
|
|
269
|
+
else {
|
|
270
|
+
try {
|
|
271
|
+
const path = parseRelativeTarget(href, context.options.file);
|
|
272
|
+
if (!LOCAL_LINK_EXTENSIONS.has(extension(path.path)))
|
|
273
|
+
return rejectLink(context, 'invalid-local-target');
|
|
274
|
+
const source = sourceContext(context);
|
|
275
|
+
resolveContainedFile(source, path.path, context.options.file, 'Narrative local link must target a contained regular file');
|
|
276
|
+
link = {
|
|
277
|
+
type: 'local',
|
|
278
|
+
path: path.path,
|
|
279
|
+
sourceBase: 'document-directory',
|
|
280
|
+
...(path.query === undefined ? {} : { query: path.query }),
|
|
281
|
+
...(path.fragment === undefined ? {} : { fragment: path.fragment }),
|
|
282
|
+
...(title === undefined ? {} : { title })
|
|
283
|
+
};
|
|
284
|
+
}
|
|
285
|
+
catch (error) {
|
|
286
|
+
if (!(error instanceof AmxError))
|
|
287
|
+
throw error;
|
|
288
|
+
return rejectLink(context, 'invalid-local-target');
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
return link;
|
|
292
|
+
}
|
|
293
|
+
async function prepareImage(href, alt, context) {
|
|
294
|
+
if (!alt)
|
|
295
|
+
fail('AMX6001', 'Narrative images require descriptive alt text', context.options.file);
|
|
296
|
+
const path = parseRelativeTarget(href, context.options.file);
|
|
297
|
+
if (path.query !== undefined || path.fragment !== undefined) {
|
|
298
|
+
fail('AMX6001', 'Narrative image paths cannot include a query or fragment', context.options.file);
|
|
299
|
+
}
|
|
300
|
+
const extensionName = extension(path.path);
|
|
301
|
+
const expectedFormat = extensionName === '.png' ? 'png' : extensionName === '.jpg' || extensionName === '.jpeg' ? 'jpeg' : undefined;
|
|
302
|
+
if (!expectedFormat)
|
|
303
|
+
fail('AMX6001', 'Narrative images must be local PNG or JPEG files', context.options.file);
|
|
304
|
+
const source = sourceContext(context);
|
|
305
|
+
const candidate = resolveContainedFile(source, path.path, context.options.file, 'Narrative image must be a contained regular file');
|
|
306
|
+
const inputStat = statSync(candidate);
|
|
307
|
+
if (inputStat.size > MAX_IMAGE_BYTES) {
|
|
308
|
+
fail('AMX6001', 'Narrative image exceeds the 4 MiB input limit', context.options.file);
|
|
309
|
+
}
|
|
310
|
+
const bytes = readFileSync(candidate);
|
|
311
|
+
if (bytes.byteLength > MAX_IMAGE_BYTES) {
|
|
312
|
+
fail('AMX6001', 'Narrative image exceeds the 4 MiB input limit', context.options.file);
|
|
313
|
+
}
|
|
314
|
+
if (!hasExpectedSignature(bytes, expectedFormat)) {
|
|
315
|
+
fail('AMX6001', 'Narrative image extension does not match PNG or JPEG content', context.options.file);
|
|
316
|
+
}
|
|
317
|
+
const image = sharp(bytes, { animated: true, limitInputPixels: MAX_IMAGE_PIXELS });
|
|
318
|
+
let metadata;
|
|
319
|
+
try {
|
|
320
|
+
metadata = await image.metadata();
|
|
321
|
+
}
|
|
322
|
+
catch (error) {
|
|
323
|
+
if (error instanceof AmxError)
|
|
324
|
+
throw error;
|
|
325
|
+
fail('AMX6001', 'Narrative image is not a supported PNG or JPEG file', context.options.file);
|
|
326
|
+
}
|
|
327
|
+
if (metadata.format !== expectedFormat) {
|
|
328
|
+
fail('AMX6001', 'Narrative image extension does not match its image format', context.options.file);
|
|
329
|
+
}
|
|
330
|
+
if (!metadata.width || !metadata.height || metadata.width * metadata.height > MAX_IMAGE_PIXELS || (metadata.pages ?? 1) > 1) {
|
|
331
|
+
fail('AMX6001', 'Narrative image dimensions or frame count are invalid', context.options.file);
|
|
332
|
+
}
|
|
333
|
+
let sanitized;
|
|
334
|
+
try {
|
|
335
|
+
const output = sharp(bytes, { animated: false, limitInputPixels: MAX_IMAGE_PIXELS }).rotate();
|
|
336
|
+
sanitized = expectedFormat === 'png'
|
|
337
|
+
? await output.png().toBuffer({ resolveWithObject: true })
|
|
338
|
+
: await output.jpeg({ quality: 90 }).toBuffer({ resolveWithObject: true });
|
|
339
|
+
}
|
|
340
|
+
catch (error) {
|
|
341
|
+
if (error instanceof AmxError)
|
|
342
|
+
throw error;
|
|
343
|
+
fail('AMX6001', 'Narrative image could not be sanitized', context.options.file);
|
|
344
|
+
}
|
|
345
|
+
if (sanitized.data.byteLength > MAX_IMAGE_BYTES) {
|
|
346
|
+
fail('AMX6002', 'Sanitized narrative image exceeds the 4 MiB output limit', context.options.file);
|
|
347
|
+
}
|
|
348
|
+
if (sanitized.info.format !== expectedFormat) {
|
|
349
|
+
fail('AMX6001', 'Sanitized narrative image has an unexpected format', context.options.file);
|
|
350
|
+
}
|
|
351
|
+
const mime = expectedFormat === 'png' ? 'image/png' : 'image/jpeg';
|
|
352
|
+
return Object.freeze({
|
|
353
|
+
format: expectedFormat,
|
|
354
|
+
dataUri: `data:${mime};base64,${sanitized.data.toString('base64')}`,
|
|
355
|
+
width: sanitized.info.width,
|
|
356
|
+
height: sanitized.info.height,
|
|
357
|
+
inputBytes: bytes.byteLength,
|
|
358
|
+
outputBytes: sanitized.data.byteLength,
|
|
359
|
+
alt
|
|
360
|
+
});
|
|
361
|
+
}
|
|
362
|
+
function sourceContext(context) {
|
|
363
|
+
if (context.sourceContext)
|
|
364
|
+
return context.sourceContext;
|
|
365
|
+
if (!context.options.file) {
|
|
366
|
+
fail('AMX6001', 'Relative narrative links and images require a source document path', context.options.file);
|
|
367
|
+
}
|
|
368
|
+
const directory = canonicalDirectory(dirname(resolve(context.options.file)), 'Narrative source document directory must be an existing directory');
|
|
369
|
+
const root = context.options.projectRoot
|
|
370
|
+
? canonicalDirectory(context.options.projectRoot)
|
|
371
|
+
: directory;
|
|
372
|
+
if (!isSameOrContained(root, directory)) {
|
|
373
|
+
fail('AMX6001', 'Narrative source document must be contained within the permitted project root', context.options.file);
|
|
374
|
+
}
|
|
375
|
+
context.sourceContext = { root, directory };
|
|
376
|
+
return context.sourceContext;
|
|
377
|
+
}
|
|
378
|
+
function resolveContainedFile(source, relativePath, file, message) {
|
|
379
|
+
const candidate = resolve(source.directory, ...relativePath.split('/'));
|
|
380
|
+
if (!isContained(source.root, candidate) || hasSymlink(source.root, candidate) || !existsSync(candidate) || !lstatSync(candidate).isFile()) {
|
|
381
|
+
fail('AMX6001', message, file);
|
|
382
|
+
}
|
|
383
|
+
const canonical = realpathSync(candidate);
|
|
384
|
+
if (!isContained(source.root, canonical))
|
|
385
|
+
fail('AMX6001', message, file);
|
|
386
|
+
return canonical;
|
|
387
|
+
}
|
|
388
|
+
function parseRelativeTarget(href, file) {
|
|
389
|
+
const hashIndex = href.indexOf('#');
|
|
390
|
+
const beforeFragment = hashIndex === -1 ? href : href.slice(0, hashIndex);
|
|
391
|
+
const fragment = hashIndex === -1 ? undefined : href.slice(hashIndex + 1);
|
|
392
|
+
const queryIndex = beforeFragment.indexOf('?');
|
|
393
|
+
const encodedPath = queryIndex === -1 ? beforeFragment : beforeFragment.slice(0, queryIndex);
|
|
394
|
+
const query = queryIndex === -1 ? undefined : beforeFragment.slice(queryIndex + 1);
|
|
395
|
+
let decodedPath;
|
|
396
|
+
try {
|
|
397
|
+
decodedPath = decodeURIComponent(encodedPath);
|
|
398
|
+
}
|
|
399
|
+
catch {
|
|
400
|
+
fail('AMX6001', 'Narrative local path contains invalid percent encoding', file);
|
|
401
|
+
}
|
|
402
|
+
if (!decodedPath || decodedPath.startsWith('/') || decodedPath.includes('\\') || /^[A-Za-z]:/.test(decodedPath) || /[\u0000-\u001f\u007f]/u.test(decodedPath)) {
|
|
403
|
+
fail('AMX6001', 'Narrative local paths must be relative to the source document', file);
|
|
404
|
+
}
|
|
405
|
+
const segments = decodedPath.split('/');
|
|
406
|
+
if (segments.some((segment, index) => segment === '' && index !== segments.length - 1)) {
|
|
407
|
+
fail('AMX6001', 'Narrative local paths cannot contain empty path segments', file);
|
|
408
|
+
}
|
|
409
|
+
const normalizedPath = segments.filter(segment => segment !== '' && segment !== '.').join('/');
|
|
410
|
+
if (!normalizedPath)
|
|
411
|
+
fail('AMX6001', 'Narrative local path must identify a file', file);
|
|
412
|
+
return {
|
|
413
|
+
path: normalizedPath,
|
|
414
|
+
...(query === undefined ? {} : { query }),
|
|
415
|
+
...(fragment === undefined ? {} : { fragment })
|
|
416
|
+
};
|
|
417
|
+
}
|
|
418
|
+
function isPageBreakDirective(text) {
|
|
419
|
+
return /^[\t ]*<!-- page-break -->[\t ]*\n*$/u.test(text);
|
|
420
|
+
}
|
|
421
|
+
function codeSpanContent(raw) {
|
|
422
|
+
const delimiter = raw.match(/^`+/u)?.[0];
|
|
423
|
+
if (!delimiter || !raw.endsWith(delimiter))
|
|
424
|
+
return raw;
|
|
425
|
+
return raw.slice(delimiter.length, -delimiter.length);
|
|
426
|
+
}
|
|
427
|
+
function uniqueHeadingId(children, used) {
|
|
428
|
+
const plain = inlinePlainText(children)
|
|
429
|
+
.normalize('NFKD')
|
|
430
|
+
.replace(/\p{M}/gu, '')
|
|
431
|
+
.toLowerCase()
|
|
432
|
+
.replace(/[^\p{L}\p{N}]+/gu, '-')
|
|
433
|
+
.replace(/^-+|-+$/gu, '');
|
|
434
|
+
const base = plain || 'section';
|
|
435
|
+
let candidate = base;
|
|
436
|
+
let suffix = 2;
|
|
437
|
+
while (used.has(candidate))
|
|
438
|
+
candidate = `${base}-${suffix++}`;
|
|
439
|
+
used.add(candidate);
|
|
440
|
+
return candidate;
|
|
441
|
+
}
|
|
442
|
+
function inlinePlainText(inlines) {
|
|
443
|
+
return inlines.map(inline => {
|
|
444
|
+
if (inline.type === 'text' || inline.type === 'inlineCode')
|
|
445
|
+
return inline.text;
|
|
446
|
+
if (inline.type === 'lineBreak')
|
|
447
|
+
return ' ';
|
|
448
|
+
if (inline.type === 'image')
|
|
449
|
+
return inline.image.alt;
|
|
450
|
+
return inlinePlainText(inline.children);
|
|
451
|
+
}).join('');
|
|
452
|
+
}
|
|
453
|
+
function collectHeadingIds(blocks, ids) {
|
|
454
|
+
for (const block of blocks) {
|
|
455
|
+
if (block.type === 'heading')
|
|
456
|
+
ids.add(block.id);
|
|
457
|
+
else if (block.type === 'blockquote')
|
|
458
|
+
collectHeadingIds(block.blocks, ids);
|
|
459
|
+
else if (block.type === 'list') {
|
|
460
|
+
for (const item of block.items)
|
|
461
|
+
collectHeadingIds(item.blocks, ids);
|
|
462
|
+
}
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
function rejectLink(context, reason) {
|
|
466
|
+
context.diagnostics.push({ type: 'rejectedLink', reason });
|
|
467
|
+
return undefined;
|
|
468
|
+
}
|
|
469
|
+
function resolveInternalLinks(blocks, ids) {
|
|
470
|
+
const resolved = [];
|
|
471
|
+
for (const block of blocks) {
|
|
472
|
+
if (block.type === 'heading' || block.type === 'paragraph') {
|
|
473
|
+
if (block.type === 'heading') {
|
|
474
|
+
resolved.push({ type: 'heading', depth: block.depth, id: block.id, children: resolveInlineLinks(block.children, ids) });
|
|
475
|
+
}
|
|
476
|
+
else {
|
|
477
|
+
resolved.push({ type: 'paragraph', children: resolveInlineLinks(block.children, ids) });
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
else if (block.type === 'blockquote') {
|
|
481
|
+
resolved.push({ type: 'blockquote', blocks: resolveInternalLinks(block.blocks, ids) });
|
|
482
|
+
}
|
|
483
|
+
else if (block.type === 'list') {
|
|
484
|
+
resolved.push({
|
|
485
|
+
type: 'list',
|
|
486
|
+
ordered: block.ordered,
|
|
487
|
+
items: block.items.map(item => ({
|
|
488
|
+
...(item.checked === undefined ? {} : { checked: item.checked }),
|
|
489
|
+
blocks: resolveInternalLinks(item.blocks, ids)
|
|
490
|
+
})),
|
|
491
|
+
...(block.start === undefined ? {} : { start: block.start })
|
|
492
|
+
});
|
|
493
|
+
}
|
|
494
|
+
else if (block.type === 'table') {
|
|
495
|
+
resolved.push({
|
|
496
|
+
type: 'table',
|
|
497
|
+
align: block.align,
|
|
498
|
+
header: block.header.map(cell => resolveInlineLinks(cell, ids)),
|
|
499
|
+
rows: block.rows.map(row => row.map(cell => resolveInlineLinks(cell, ids)))
|
|
500
|
+
});
|
|
501
|
+
}
|
|
502
|
+
else {
|
|
503
|
+
resolved.push(block);
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
return resolved;
|
|
507
|
+
}
|
|
508
|
+
function resolveInlineLinks(inlines, ids) {
|
|
509
|
+
return inlines.flatMap(inline => {
|
|
510
|
+
if (inline.type === 'link' && inline.link.type === 'internal' && !ids.has(inline.link.targetId)) {
|
|
511
|
+
return resolveInlineLinks(inline.children, ids);
|
|
512
|
+
}
|
|
513
|
+
if (inline.type === 'link' || inline.type === 'strong' || inline.type === 'emphasis' || inline.type === 'delete') {
|
|
514
|
+
return [{ ...inline, children: resolveInlineLinks(inline.children, ids) }];
|
|
515
|
+
}
|
|
516
|
+
return [inline];
|
|
517
|
+
});
|
|
518
|
+
}
|
|
519
|
+
function textNodes(text) {
|
|
520
|
+
return text ? [{ type: 'text', text }] : [];
|
|
521
|
+
}
|
|
522
|
+
function literalTextNodes(text) {
|
|
523
|
+
const nodes = [];
|
|
524
|
+
for (const [index, line] of text.split('\n').entries()) {
|
|
525
|
+
if (index > 0)
|
|
526
|
+
nodes.push({ type: 'lineBreak' });
|
|
527
|
+
nodes.push(...textNodes(line));
|
|
528
|
+
}
|
|
529
|
+
return nodes;
|
|
530
|
+
}
|
|
531
|
+
function extension(path) {
|
|
532
|
+
return extname(path.replace(/\//g, sep)).toLowerCase();
|
|
533
|
+
}
|
|
534
|
+
function hasExpectedSignature(bytes, format) {
|
|
535
|
+
if (format === 'png') {
|
|
536
|
+
return bytes.byteLength >= 8 &&
|
|
537
|
+
bytes[0] === 0x89 && bytes[1] === 0x50 && bytes[2] === 0x4e && bytes[3] === 0x47 &&
|
|
538
|
+
bytes[4] === 0x0d && bytes[5] === 0x0a && bytes[6] === 0x1a && bytes[7] === 0x0a;
|
|
539
|
+
}
|
|
540
|
+
return bytes.byteLength >= 3 && bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff;
|
|
541
|
+
}
|
|
542
|
+
function isSameOrContained(root, candidate) {
|
|
543
|
+
return resolve(root) === resolve(candidate) || isContained(root, candidate);
|
|
544
|
+
}
|
|
545
|
+
function escapeRegExp(value) {
|
|
546
|
+
return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
547
|
+
}
|
|
548
|
+
function freezeDeep(value) {
|
|
549
|
+
if (Array.isArray(value)) {
|
|
550
|
+
value.forEach(item => freezeDeep(item));
|
|
551
|
+
return Object.freeze(value);
|
|
552
|
+
}
|
|
553
|
+
if (value && typeof value === 'object' && !Object.isFrozen(value)) {
|
|
554
|
+
Object.values(value).forEach(item => freezeDeep(item));
|
|
555
|
+
return Object.freeze(value);
|
|
556
|
+
}
|
|
557
|
+
return value;
|
|
558
|
+
}
|
|
559
|
+
function fail(code, message, file) {
|
|
560
|
+
throw new AmxError({ code, message, file });
|
|
561
|
+
}
|