@nova-energy/openamx 0.0.0-stage → 0.10.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 (42) hide show
  1. package/COMMERCIAL-LICENSE.md +74 -0
  2. package/LICENSE.md +660 -0
  3. package/README.md +513 -2
  4. package/dist/ast/types.js +2 -0
  5. package/dist/cli.js +186 -0
  6. package/dist/diagnostics/errors.js +94 -0
  7. package/dist/editor/completion.js +313 -0
  8. package/dist/editor/highlighting.js +224 -0
  9. package/dist/editor/moduleAnalysis.js +206 -0
  10. package/dist/editor/refactoring.js +46 -0
  11. package/dist/editor/sourceRanges.js +50 -0
  12. package/dist/editor/symbols.js +203 -0
  13. package/dist/formatter/formatAmx.js +79 -0
  14. package/dist/index.js +10 -0
  15. package/dist/parser/parseDocument.js +114 -0
  16. package/dist/parser/parseExpression.js +768 -0
  17. package/dist/parser/parseFor.js +53 -0
  18. package/dist/parser/parseFrontMatter.js +65 -0
  19. package/dist/parser/parseStatements.js +667 -0
  20. package/dist/parser/stringScanner.js +71 -0
  21. package/dist/renderer/chartModel.js +476 -0
  22. package/dist/renderer/renderHtml.js +383 -0
  23. package/dist/renderer/reportDocx.js +163 -0
  24. package/dist/renderer/reportPdf.js +202 -0
  25. package/dist/renderer/reportPreparation.js +208 -0
  26. package/dist/runtime/csvTextSerialization.js +8 -0
  27. package/dist/runtime/dataText.js +191 -0
  28. package/dist/runtime/docxDestination.js +55 -0
  29. package/dist/runtime/environment.js +105 -0
  30. package/dist/runtime/evaluateDocument.js +32 -0
  31. package/dist/runtime/evaluateExpression.js +888 -0
  32. package/dist/runtime/externalUnits.js +91 -0
  33. package/dist/runtime/inputData.js +508 -0
  34. package/dist/runtime/measurement.js +110 -0
  35. package/dist/runtime/moduleLoader.js +279 -0
  36. package/dist/runtime/outputData.js +303 -0
  37. package/dist/runtime/pdfDestination.js +57 -0
  38. package/dist/runtime/standardLibrary.js +145 -0
  39. package/dist/typechecker/checkDocument.js +1282 -0
  40. package/dist/typechecker/declarationRegistry.js +7 -0
  41. package/dist/typechecker/dimensionTypes.js +1 -0
  42. package/package.json +33 -4
@@ -0,0 +1,202 @@
1
+ import * as echarts from 'echarts';
2
+ import pdfmake from 'pdfmake';
3
+ import { existsSync } from 'node:fs';
4
+ import { createRequire } from 'node:module';
5
+ import { dirname, resolve } from 'node:path';
6
+ import { fileURLToPath } from 'node:url';
7
+ import { createChartViewModel } from './chartModel';
8
+ const packagedFontRoot = fileURLToPath(new URL('./pdfmake-fonts/', import.meta.url));
9
+ const fontRoot = existsSync(resolve(packagedFontRoot, 'Roboto-Regular.ttf'))
10
+ ? packagedFontRoot
11
+ : resolve(dirname(createRequire(import.meta.url).resolve('pdfmake')), '../fonts/Roboto');
12
+ pdfmake.setUrlAccessPolicy(() => false);
13
+ pdfmake.setLocalAccessPolicy((filePath) => filePath.startsWith(fontRoot));
14
+ pdfmake.setFonts({
15
+ Roboto: {
16
+ normal: resolve(fontRoot, 'Roboto-Regular.ttf'),
17
+ bold: resolve(fontRoot, 'Roboto-Medium.ttf'),
18
+ italics: resolve(fontRoot, 'Roboto-Italic.ttf'),
19
+ bolditalics: resolve(fontRoot, 'Roboto-MediumItalic.ttf')
20
+ }
21
+ });
22
+ export function preparePdfReport(report, renderChart = renderStaticChart) {
23
+ return preparePreparedPdfReport(report, renderChart);
24
+ }
25
+ export async function serializePdfReport(report) {
26
+ const pdf = pdfmake.createPdf(report.definition);
27
+ const buffer = await pdf.getBuffer();
28
+ return Uint8Array.from(buffer);
29
+ }
30
+ function preparePreparedPdfReport(report, renderChart) {
31
+ const content = [];
32
+ const identity = report.identity;
33
+ const metadata = [
34
+ identity.organization,
35
+ identity.author && `Author: ${identity.author}`,
36
+ identity.status && `Status: ${identity.status}`,
37
+ identity.classification && `Classification: ${identity.classification}`
38
+ ].filter((value) => Boolean(value));
39
+ if (identity.logo || metadata.length > 0) {
40
+ content.push({
41
+ columns: [
42
+ identity.logo ? { image: identity.logo.dataUri, fit: [120, 48], alt: identity.logo.alt } : {},
43
+ { stack: metadata.map(text => ({ text, style: 'metadata' })) }
44
+ ],
45
+ columnGap: 12,
46
+ margin: [0, 0, 0, 16]
47
+ });
48
+ }
49
+ for (const item of report.items) {
50
+ if (item.type === 'narrative')
51
+ addNarrativeText(content, item.text);
52
+ else if (item.type === 'source')
53
+ content.push({ text: item.text, style: 'source' });
54
+ else
55
+ addEmission(content, item.emission, identity, renderChart);
56
+ }
57
+ return {
58
+ definition: {
59
+ info: { title: report.title, author: identity.author ?? 'OpenAMX' },
60
+ pageSize: 'A4',
61
+ pageMargins: [51, 51, 51, 51],
62
+ defaultStyle: { font: 'Roboto', fontSize: 9, color: '#18282D' },
63
+ footer: (currentPage, pageCount) => ({ text: [identity.footer, `${currentPage} / ${pageCount}`].filter(Boolean).join(' | '), alignment: 'right', margin: [0, 0, 51, 24], fontSize: 8 }),
64
+ styles: {
65
+ title: { fontSize: 20, bold: true, color: identity.accent, margin: [0, 0, 0, 10] },
66
+ heading: { fontSize: 14, bold: true, color: identity.accent, margin: [0, 14, 0, 6] },
67
+ source: { font: 'Roboto', fontSize: 8, color: '#405459', margin: [0, 5, 0, 10] },
68
+ caption: { fontSize: 8, color: '#405459', margin: [0, 3, 0, 6] },
69
+ metadata: { fontSize: 9, color: '#18282D', margin: [0, 0, 0, 2] }
70
+ },
71
+ content
72
+ }
73
+ };
74
+ }
75
+ function addNarrativeText(content, narrative) {
76
+ const lines = narrative.split(/\r?\n/);
77
+ let paragraph = [];
78
+ const flush = () => {
79
+ if (paragraph.length > 0)
80
+ content.push({ text: paragraph.join(' '), margin: [0, 0, 0, 7] });
81
+ paragraph = [];
82
+ };
83
+ for (const line of lines) {
84
+ if (line.trim() === '<!-- page-break -->') {
85
+ flush();
86
+ content.push({ text: '', pageBreak: 'before' });
87
+ }
88
+ else if (/^#{1,6}\s+/.test(line)) {
89
+ flush();
90
+ content.push({ text: line.replace(/^#{1,6}\s+/, ''), style: line.startsWith('# ') ? 'title' : 'heading' });
91
+ }
92
+ else if (line.trim() === '') {
93
+ flush();
94
+ }
95
+ else {
96
+ paragraph.push(line.trim());
97
+ }
98
+ }
99
+ flush();
100
+ }
101
+ function addEmission(content, emission, identity, renderChart) {
102
+ if (emission.kind === 'table')
103
+ addTable(content, emission);
104
+ else
105
+ addChart(content, emission, identity, renderChart);
106
+ }
107
+ function addTable(content, emission) {
108
+ const title = emission.declaration.options.find(option => option.type === 'viewTitleOption');
109
+ const columns = emission.declaration.options.filter(option => option.type === 'tableColumnOption');
110
+ const caption = title?.type === 'viewTitleOption' ? title.value : emission.name;
111
+ const body = [
112
+ columns.map(column => ({ text: column.label, bold: true, fillColor: '#e7eee8' })),
113
+ ...emission.data.map(value => columns.map(column => valueToString(isRecord(value) ? value[column.field] : null)))
114
+ ];
115
+ content.push({ text: caption, style: 'heading' });
116
+ content.push({ table: { headerRows: 1, keepWithHeaderRows: 1, widths: columns.map(() => '*'), body }, layout: 'lightHorizontalLines', fontSize: 8 });
117
+ }
118
+ function addChart(content, emission, identity, renderChart) {
119
+ const model = createChartViewModel(emission, identity);
120
+ content.push({
121
+ stack: [
122
+ { text: model.title, style: 'heading' },
123
+ { text: model.description, style: 'caption' },
124
+ { svg: renderChart(model), width: 470 }
125
+ ],
126
+ unbreakable: true
127
+ });
128
+ content.push({
129
+ table: {
130
+ headerRows: 1,
131
+ widths: model.table.headings.map(() => '*'),
132
+ body: [
133
+ model.table.headings.map(text => ({ text, bold: true, fillColor: '#e7eee8' })),
134
+ ...model.table.rows.map(row => row.values.map(valueToString))
135
+ ]
136
+ },
137
+ layout: 'lightHorizontalLines',
138
+ fontSize: 8
139
+ });
140
+ }
141
+ function renderStaticChart(model) {
142
+ const chart = echarts.init(null, undefined, {
143
+ renderer: 'svg',
144
+ ssr: true,
145
+ width: model.dimensions.width,
146
+ height: model.dimensions.height
147
+ });
148
+ try {
149
+ const tooltip = model.option.tooltip;
150
+ chart.setOption({
151
+ ...model.option,
152
+ animation: false,
153
+ title: { ...model.option.title, show: false },
154
+ xAxis: centerNamedAxis(model.option.xAxis, model.emptyState !== undefined),
155
+ yAxis: centerNamedAxis(model.option.yAxis, model.emptyState !== undefined),
156
+ tooltip: Array.isArray(tooltip)
157
+ ? tooltip.map(item => ({ ...item, show: false }))
158
+ : { ...tooltip, show: false }
159
+ });
160
+ const svg = chart.renderToSVGString();
161
+ assertSupportedSvg(svg);
162
+ return svg;
163
+ }
164
+ finally {
165
+ chart.dispose();
166
+ }
167
+ }
168
+ function centerNamedAxis(axis, hide) {
169
+ const adjust = (item) => {
170
+ if (item === null || typeof item !== 'object')
171
+ return item;
172
+ const named = 'name' in item && typeof item.name === 'string'
173
+ ? { ...item, nameLocation: 'middle' }
174
+ : { ...item };
175
+ if (!hide)
176
+ return named;
177
+ return {
178
+ ...named,
179
+ show: false,
180
+ axisLine: { ...('axisLine' in named && named.axisLine && typeof named.axisLine === 'object' ? named.axisLine : {}), show: false }
181
+ };
182
+ };
183
+ return Array.isArray(axis) ? axis.map(adjust) : adjust(axis);
184
+ }
185
+ function assertSupportedSvg(svg) {
186
+ const supportedElements = new Set(['svg', 'g', 'path', 'rect', 'circle', 'text', 'defs', 'clipPath', 'style']);
187
+ const elements = [...svg.matchAll(/<([A-Za-z][A-Za-z0-9:-]*)\b/g)].map(match => match[1]);
188
+ const unsupported = [...new Set(elements.filter(element => !supportedElements.has(element)))];
189
+ if (!svg.startsWith('<svg') || unsupported.length > 0) {
190
+ throw new Error(`ECharts PDF SVG uses unsupported output${unsupported.length ? `: ${unsupported.join(', ')}` : ''}`);
191
+ }
192
+ }
193
+ function isRecord(value) {
194
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
195
+ }
196
+ function valueToString(value) {
197
+ if (value === null || value === undefined)
198
+ return '';
199
+ if (Array.isArray(value))
200
+ return value.map(valueToString).join(', ');
201
+ return String(value);
202
+ }
@@ -0,0 +1,208 @@
1
+ import { existsSync, lstatSync, readFileSync, realpathSync, statSync } from 'node:fs';
2
+ import { relative, resolve, sep } from 'node:path';
3
+ import sharp from 'sharp';
4
+ import { AmxError } from '../diagnostics/errors';
5
+ import { formatAmx } from '../formatter/formatAmx';
6
+ import { parseExpression } from '../parser/parseExpression';
7
+ import { evaluateExpression } from '../runtime/evaluateExpression';
8
+ import { isMeasurement } from '../runtime/measurement';
9
+ const REPORT_FIELDS = new Set(['organization', 'logo', 'logoAlt', 'accent', 'author', 'status', 'classification', 'footer', 'sourceVisible']);
10
+ const TEXT_LIMITS = { organization: 120, logoAlt: 120, author: 120, status: 80, classification: 80, footer: 300 };
11
+ export async function prepareReport(doc, env, options = {}) {
12
+ const projectReport = readProjectReport(options.projectRoot);
13
+ const frontMatter = asRecord((doc.metadata ?? {}).report, 'Invalid report frontmatter', options.file);
14
+ validateReport(projectReport, '.openamx/project.json', options.projectRoot);
15
+ validateReport(frontMatter, 'frontmatter', options.file);
16
+ const identity = await resolveIdentity(projectReport, frontMatter, options);
17
+ const emissionsByNode = new Map();
18
+ for (const emission of env.viewEmissions) {
19
+ const emissions = emissionsByNode.get(emission.documentNodeIndex) ?? [];
20
+ emissions.push(emission);
21
+ emissionsByNode.set(emission.documentNodeIndex, emissions);
22
+ }
23
+ const items = [];
24
+ for (const [index, node] of doc.nodes.entries()) {
25
+ if (node.type === 'narrative') {
26
+ items.push(Object.freeze({ type: 'narrative', text: substituteInlines(node.content, env, options.file, node.source?.line) }));
27
+ continue;
28
+ }
29
+ if (node.type !== 'executableCodeBlock')
30
+ continue;
31
+ if (identity.sourceVisible)
32
+ items.push(Object.freeze({ type: 'source', text: formatAmx(node.content) }));
33
+ for (const emission of emissionsByNode.get(index) ?? [])
34
+ items.push(Object.freeze({ type: 'view', emission }));
35
+ }
36
+ const metadata = doc.metadata ?? {};
37
+ const title = typeof metadata.title === 'string' && metadata.title.trim() ? metadata.title.trim() : 'OpenAMX Document';
38
+ return Object.freeze({ title, identity, items: Object.freeze(items) });
39
+ }
40
+ function readProjectReport(projectRoot) {
41
+ if (!projectRoot)
42
+ return {};
43
+ const root = canonicalDirectory(projectRoot);
44
+ const configPath = resolve(root, '.openamx', 'project.json');
45
+ if (!existsSync(configPath))
46
+ return {};
47
+ let config;
48
+ try {
49
+ config = asRecord(JSON.parse(readFileSync(configPath, 'utf8')), 'Invalid project configuration', configPath);
50
+ }
51
+ catch (error) {
52
+ if (error instanceof AmxError)
53
+ throw error;
54
+ fail('AMX6001', 'Invalid project configuration', configPath);
55
+ }
56
+ for (const key of Object.keys(config)) {
57
+ if (!['version', 'inputs', 'report'].includes(key))
58
+ fail('AMX6001', `Unknown project configuration key '${key}'`, configPath);
59
+ }
60
+ if (config.version !== 1 || !asPlainRecord(config.inputs))
61
+ fail('AMX6001', 'Project configuration requires version 1 and an inputs mapping', configPath);
62
+ return config.report === undefined ? {} : asRecord(config.report, 'Project report must be an object', configPath);
63
+ }
64
+ export function validateReportSettings(report, projectRoot, file) {
65
+ validateReport(report, file ?? '.openamx/project.json', file);
66
+ if (report.logo === undefined)
67
+ return Promise.resolve();
68
+ if (typeof report.logo !== 'string')
69
+ return Promise.resolve();
70
+ return prepareLogo(report.logo, String(report.logoAlt ?? ''), projectRoot, file).then(() => undefined);
71
+ }
72
+ function validateReport(report, location, file) {
73
+ for (const [key, value] of Object.entries(report)) {
74
+ if (!REPORT_FIELDS.has(key))
75
+ fail('AMX6001', `Unknown report field '${key}'`, file ?? location);
76
+ if (key === 'sourceVisible') {
77
+ if (typeof value !== 'boolean')
78
+ fail('AMX6001', 'Report sourceVisible must be a Boolean', file ?? location);
79
+ continue;
80
+ }
81
+ if (typeof value !== 'string')
82
+ fail('AMX6001', `Report ${key} must be a string`, file ?? location);
83
+ const text = value.trim();
84
+ if (!text || /[\u0000-\u001f\u007f\u202a-\u202e\u2066-\u2069]/u.test(text))
85
+ fail('AMX6001', `Report ${key} contains invalid text`, file ?? location);
86
+ if (TEXT_LIMITS[key] !== undefined && [...text].length > TEXT_LIMITS[key])
87
+ fail('AMX6001', `Report ${key} exceeds its length limit`, file ?? location);
88
+ }
89
+ if (report.logoAlt !== undefined && report.logo === undefined)
90
+ fail('AMX6001', 'Report logoAlt requires a logo', file ?? location);
91
+ if (report.accent !== undefined && (typeof report.accent !== 'string' || !/^#[0-9A-Fa-f]{6}$/.test(report.accent)))
92
+ fail('AMX6001', 'Report accent must use #RRGGBB', file ?? location);
93
+ }
94
+ async function resolveIdentity(projectReport, frontMatter, options) {
95
+ if (frontMatter.logo !== undefined && frontMatter.logoAlt === undefined)
96
+ fail('AMX6001', 'A frontmatter logo override requires logoAlt', options.file);
97
+ const merged = { ...projectReport, ...frontMatter };
98
+ const logoPath = typeof merged.logo === 'string' ? merged.logo.trim() : undefined;
99
+ const logo = logoPath ? await prepareLogo(logoPath, String(merged.logoAlt ?? ''), options.projectRoot, options.file) : undefined;
100
+ return Object.freeze({
101
+ organization: text(merged.organization),
102
+ logo,
103
+ accent: effectiveReportAccent(text(merged.accent) ?? '#146C94'),
104
+ author: text(merged.author),
105
+ status: text(merged.status),
106
+ classification: text(merged.classification),
107
+ footer: text(merged.footer),
108
+ sourceVisible: merged.sourceVisible === undefined ? true : merged.sourceVisible
109
+ });
110
+ }
111
+ async function prepareLogo(path, alt, projectRoot, file) {
112
+ if (!projectRoot)
113
+ fail('AMX6001', 'A report logo requires an explicit project root', file);
114
+ if (!alt.trim())
115
+ fail('AMX6001', 'A report logo requires descriptive logoAlt', file);
116
+ if (!/^[A-Za-z0-9._/-]+\.(png|jpg)$/.test(path) || path.includes('..') || path.includes('//') || path.startsWith('/') || path.includes('\\'))
117
+ fail('AMX6001', 'Report logo must be a contained .png or .jpg path', file);
118
+ const root = canonicalDirectory(projectRoot);
119
+ const candidate = resolve(root, path);
120
+ if (!isContained(root, candidate) || hasSymlink(root, candidate) || !existsSync(candidate) || !lstatSync(candidate).isFile())
121
+ fail('AMX6001', 'Report logo must be a contained regular file', file);
122
+ const bytes = readFileSync(candidate);
123
+ if (bytes.byteLength > 256 * 1024)
124
+ fail('AMX6001', 'Report logo exceeds 256 KiB', file);
125
+ try {
126
+ const image = sharp(bytes, { animated: false, limitInputPixels: 1_048_576 });
127
+ const metadata = await image.metadata();
128
+ const expectedFormat = path.endsWith('.jpg') ? 'jpeg' : 'png';
129
+ if (metadata.format !== expectedFormat)
130
+ fail('AMX6001', 'Report logo file extension does not match its image format', file);
131
+ if (!metadata.width || !metadata.height || metadata.width > 1024 || metadata.height > 1024 || metadata.width * metadata.height > 1_048_576 || (metadata.pages ?? 1) > 1)
132
+ fail('AMX6001', 'Report logo dimensions are invalid', file);
133
+ const sanitized = await image.rotate().png().toBuffer();
134
+ if (sanitized.byteLength > 1024 * 1024)
135
+ fail('AMX6002', 'Sanitized report logo exceeds 1 MiB', file);
136
+ return Object.freeze({ bytes: Uint8Array.from(sanitized), alt: alt.trim(), dataUri: `data:image/png;base64,${sanitized.toString('base64')}` });
137
+ }
138
+ catch (error) {
139
+ if (error instanceof AmxError)
140
+ throw error;
141
+ fail('AMX6001', 'Report logo is not a supported image', file);
142
+ }
143
+ }
144
+ function substituteInlines(content, env, file, line) {
145
+ return content.replace(/\{\{\s*([\s\S]*?)\s*\}\}/g, (_full, expression) => {
146
+ if (!expression.trim())
147
+ return '';
148
+ return valueToString(evaluateExpression(parseExpression(expression.trim(), line === undefined ? undefined : { line, column: 1 }), env, file));
149
+ });
150
+ }
151
+ function valueToString(value) {
152
+ if (value === null || value === undefined)
153
+ return '';
154
+ if (Array.isArray(value))
155
+ return value.map(valueToString).join(', ');
156
+ if (isMeasurement(value))
157
+ return `${String(value.value)} ${value.unit.text}`;
158
+ return String(value);
159
+ }
160
+ function asRecord(value, message, file) {
161
+ if (value === undefined)
162
+ return {};
163
+ if (!asPlainRecord(value))
164
+ fail('AMX6001', message, file);
165
+ return value;
166
+ }
167
+ function asPlainRecord(value) {
168
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
169
+ }
170
+ function text(value) {
171
+ return typeof value === 'string' ? value.trim() || undefined : undefined;
172
+ }
173
+ export function effectiveReportAccent(accent) {
174
+ const channels = [accent.slice(1, 3), accent.slice(3, 5), accent.slice(5, 7)].map(value => Number.parseInt(value, 16) / 255);
175
+ const luminance = channels.map(value => value <= 0.04045 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4)
176
+ .reduce((total, value, index) => total + value * [0.2126, 0.7152, 0.0722][index], 0);
177
+ return (1.05 / (luminance + 0.05)) >= 4.5 ? accent : '#146C94';
178
+ }
179
+ function canonicalDirectory(path) {
180
+ try {
181
+ const canonical = realpathSync(path);
182
+ if (!statSync(canonical).isDirectory())
183
+ fail('AMX6001', 'Project root must be an existing directory', path);
184
+ return canonical;
185
+ }
186
+ catch (error) {
187
+ if (error instanceof AmxError)
188
+ throw error;
189
+ fail('AMX6001', 'Project root must be an existing directory', path);
190
+ }
191
+ }
192
+ function isContained(root, candidate) {
193
+ const relation = relative(root, candidate);
194
+ return relation !== '..' && !relation.startsWith(`..${sep}`) && relation !== '';
195
+ }
196
+ function hasSymlink(root, candidate) {
197
+ const relation = relative(root, candidate);
198
+ let current = root;
199
+ for (const segment of relation.split(sep)) {
200
+ current = resolve(current, segment);
201
+ if (existsSync(current) && lstatSync(current).isSymbolicLink())
202
+ return true;
203
+ }
204
+ return false;
205
+ }
206
+ function fail(code, message, file) {
207
+ throw new AmxError({ code, message, file });
208
+ }
@@ -0,0 +1,8 @@
1
+ export function serializeCsvText(rows) {
2
+ const records = rows.map(row => row.map(cell => {
3
+ const value = cell.value;
4
+ const quote = cell.quoted || value === '' || /[",\r\n]/.test(value) || /^\s|\s$/.test(value);
5
+ return quote ? `"${value.replace(/"/g, '""')}"` : value;
6
+ }).join(','));
7
+ return `${records.join('\n')}\n`;
8
+ }
@@ -0,0 +1,191 @@
1
+ import { parse as parseCsv } from 'csv-parse/sync';
2
+ class StrictJsonParser {
3
+ text;
4
+ offset = 0;
5
+ constructor(text) {
6
+ this.text = text;
7
+ }
8
+ parse() {
9
+ this.skipWhitespace();
10
+ const value = this.parseValue('');
11
+ this.skipWhitespace();
12
+ if (this.offset !== this.text.length)
13
+ this.fail('Unexpected content after JSON value');
14
+ return value;
15
+ }
16
+ parseValue(dataPath) {
17
+ this.skipWhitespace();
18
+ const character = this.text[this.offset];
19
+ if (character === '{')
20
+ return this.parseObject(dataPath);
21
+ if (character === '[')
22
+ return this.parseArray(dataPath);
23
+ if (character === '"')
24
+ return this.parseString();
25
+ if (character === 't')
26
+ return this.parseLiteral('true', true);
27
+ if (character === 'f')
28
+ return this.parseLiteral('false', false);
29
+ if (character === 'n')
30
+ return this.parseLiteral('null', null);
31
+ if (character === '-' || (character >= '0' && character <= '9'))
32
+ return this.parseNumber();
33
+ this.fail('Expected a JSON value', dataPath);
34
+ }
35
+ parseObject(dataPath) {
36
+ this.offset++;
37
+ this.skipWhitespace();
38
+ const result = {};
39
+ const keys = new Set();
40
+ if (this.consume('}'))
41
+ return result;
42
+ while (true) {
43
+ this.skipWhitespace();
44
+ if (this.text[this.offset] !== '"')
45
+ this.fail('Expected a quoted object key', dataPath);
46
+ const keyOffset = this.offset;
47
+ const key = this.parseString();
48
+ const propertyPath = `${dataPath}/${key.replace(/~/g, '~0').replace(/\//g, '~1')}`;
49
+ if (keys.has(key))
50
+ throw { message: `Duplicate JSON object key '${key}'`, offset: keyOffset, duplicate: true, dataPath: propertyPath };
51
+ keys.add(key);
52
+ this.skipWhitespace();
53
+ if (!this.consume(':'))
54
+ this.fail("Expected ':' after object key", propertyPath);
55
+ Object.defineProperty(result, key, {
56
+ value: this.parseValue(propertyPath), enumerable: true, configurable: true, writable: true
57
+ });
58
+ this.skipWhitespace();
59
+ if (this.consume('}'))
60
+ return result;
61
+ if (!this.consume(','))
62
+ this.fail("Expected ',' or '}' in object", dataPath);
63
+ }
64
+ }
65
+ parseArray(dataPath) {
66
+ this.offset++;
67
+ this.skipWhitespace();
68
+ const result = [];
69
+ if (this.consume(']'))
70
+ return result;
71
+ while (true) {
72
+ result.push(this.parseValue(`${dataPath}/${result.length}`));
73
+ this.skipWhitespace();
74
+ if (this.consume(']'))
75
+ return result;
76
+ if (!this.consume(','))
77
+ this.fail("Expected ',' or ']' in array", dataPath);
78
+ }
79
+ }
80
+ parseString() {
81
+ const start = this.offset++;
82
+ while (this.offset < this.text.length) {
83
+ const code = this.text.charCodeAt(this.offset++);
84
+ if (code === 0x22) {
85
+ try {
86
+ return JSON.parse(this.text.slice(start, this.offset));
87
+ }
88
+ catch {
89
+ this.fail('Invalid JSON string');
90
+ }
91
+ }
92
+ if (code < 0x20)
93
+ this.fail('Unescaped control character in JSON string');
94
+ if (code === 0x5c) {
95
+ const escape = this.text[this.offset++];
96
+ if (escape === 'u') {
97
+ const hex = this.text.slice(this.offset, this.offset + 4);
98
+ if (!/^[0-9A-Fa-f]{4}$/.test(hex))
99
+ this.fail('Invalid Unicode escape');
100
+ this.offset += 4;
101
+ }
102
+ else if (!['"', '\\', '/', 'b', 'f', 'n', 'r', 't'].includes(escape)) {
103
+ this.fail('Invalid JSON escape');
104
+ }
105
+ }
106
+ }
107
+ this.fail('Unterminated JSON string');
108
+ }
109
+ parseNumber() {
110
+ const match = this.text.slice(this.offset).match(/^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?/);
111
+ if (!match)
112
+ this.fail('Invalid JSON number');
113
+ this.offset += match[0].length;
114
+ return Number(match[0]);
115
+ }
116
+ parseLiteral(literal, value) {
117
+ if (!this.text.startsWith(literal, this.offset))
118
+ this.fail(`Invalid JSON token '${this.text[this.offset] ?? ''}'`);
119
+ this.offset += literal.length;
120
+ return value;
121
+ }
122
+ skipWhitespace() {
123
+ while (/[\t\n\r ]/.test(this.text[this.offset] ?? '\0'))
124
+ this.offset++;
125
+ }
126
+ consume(character) {
127
+ if (this.text[this.offset] !== character)
128
+ return false;
129
+ this.offset++;
130
+ return true;
131
+ }
132
+ fail(message, dataPath) {
133
+ throw { message, offset: this.offset, dataPath };
134
+ }
135
+ }
136
+ function safeText(value) {
137
+ return value.replace(/[\x00-\x1f\x7f]/g, character => `\\u${character.charCodeAt(0).toString(16).padStart(4, '0')}`).slice(0, 160);
138
+ }
139
+ function lineAt(text, offset) {
140
+ return text.slice(0, offset).split('\n').length;
141
+ }
142
+ function hasBareCarriageReturn(text) {
143
+ let quoted = false;
144
+ for (let index = 0; index < text.length; index++) {
145
+ if (text[index] === '"') {
146
+ if (quoted && text[index + 1] === '"')
147
+ index++;
148
+ else
149
+ quoted = !quoted;
150
+ }
151
+ else if (text[index] === '\r' && !quoted && text[index + 1] !== '\n') {
152
+ return true;
153
+ }
154
+ }
155
+ return false;
156
+ }
157
+ export function parseStrictJsonText(text) {
158
+ try {
159
+ return { value: new StrictJsonParser(text).parse() };
160
+ }
161
+ catch (error) {
162
+ const issue = error;
163
+ return { issue: {
164
+ message: typeof issue.message === 'string' ? issue.message : 'Malformed JSON',
165
+ offset: Number.isSafeInteger(issue.offset) ? issue.offset : 0,
166
+ duplicate: issue.duplicate,
167
+ dataPath: issue.dataPath
168
+ } };
169
+ }
170
+ }
171
+ export function parseStrictCsvText(text) {
172
+ if (hasBareCarriageReturn(text)) {
173
+ const offset = text.indexOf('\r');
174
+ return { issue: { message: 'Bare CR record separators are not valid CSV', offset, line: lineAt(text, offset) } };
175
+ }
176
+ try {
177
+ const rows = parseCsv(text, {
178
+ bom: true,
179
+ columns: false,
180
+ skip_empty_lines: false,
181
+ relax_column_count: true,
182
+ record_delimiter: ['\r\n', '\n'],
183
+ cast: (value, field) => ({ value, quoted: field.quoting })
184
+ });
185
+ return { value: rows };
186
+ }
187
+ catch (error) {
188
+ const csvError = error;
189
+ return { issue: { message: `Malformed CSV: ${safeText(csvError.message ?? 'parse error')}`, line: csvError.lines } };
190
+ }
191
+ }
@@ -0,0 +1,55 @@
1
+ import { lstat, open, realpath, rename, unlink } from 'node:fs/promises';
2
+ import * as path from 'node:path';
3
+ import { outputError } from '../diagnostics/errors';
4
+ export async function prepareDocxDestination(destination, entryPath, inputMappings) {
5
+ if (!destination)
6
+ outputError('AMX6001', 'DOCX export requires --out <path>');
7
+ if (path.extname(destination) !== '.docx')
8
+ outputError('AMX6001', 'DOCX destination must use the exact lowercase .docx extension');
9
+ const absolute = path.resolve(destination);
10
+ const parent = path.dirname(absolute);
11
+ let canonicalParent;
12
+ try {
13
+ canonicalParent = await realpath(parent);
14
+ }
15
+ catch {
16
+ outputError('AMX6001', `DOCX destination parent '${parent}' does not exist`);
17
+ }
18
+ const canonicalDestination = path.join(canonicalParent, path.basename(absolute));
19
+ const conflicts = [path.resolve(entryPath), ...(inputMappings ?? []).map(mapping => mapping.slice(mapping.indexOf('=') + 1))]
20
+ .map(candidate => path.resolve(candidate));
21
+ if (conflicts.includes(canonicalDestination))
22
+ outputError('AMX6001', `DOCX destination '${canonicalDestination}' conflicts with an input or entry module`);
23
+ try {
24
+ const existing = await lstat(canonicalDestination);
25
+ if (existing.isSymbolicLink())
26
+ outputError('AMX6001', `DOCX destination '${canonicalDestination}' must not be a symlink`);
27
+ if (!existing.isFile())
28
+ outputError('AMX6001', `DOCX destination '${canonicalDestination}' is not a regular file`);
29
+ }
30
+ catch (error) {
31
+ if (error.code !== 'ENOENT')
32
+ outputError('AMX6001', `Cannot inspect DOCX destination '${canonicalDestination}'`);
33
+ }
34
+ return { path: canonicalDestination, parent: canonicalParent };
35
+ }
36
+ export async function writeDocxAtomically(destination, bytes, beforeCommit) {
37
+ const temporary = path.join(destination.parent, `.${path.basename(destination.path)}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`);
38
+ let handle;
39
+ try {
40
+ handle = await open(temporary, 'wx');
41
+ await handle.write(bytes);
42
+ await handle.sync();
43
+ await handle.close();
44
+ handle = undefined;
45
+ beforeCommit?.();
46
+ await rename(temporary, destination.path);
47
+ }
48
+ catch (error) {
49
+ if (handle)
50
+ await handle.close().catch(() => undefined);
51
+ await unlink(temporary).catch(() => undefined);
52
+ const detail = error instanceof Error ? error.message : String(error);
53
+ outputError('AMX6002', `Failed to write DOCX '${destination.path}': ${detail}`);
54
+ }
55
+ }