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/migrate.mjs CHANGED
@@ -1,368 +1,368 @@
1
- import { readFile, writeFile } from 'node:fs/promises';
2
- import path from 'node:path';
3
- import { displayPath, formatDiagnostic } from './document.mjs';
4
- import { CliError, EXIT, fsFailure, usageError } from './errors.mjs';
5
- import { assertDistinctPaths } from './fs-utils.mjs';
6
- import { migrateHelp } from './help.mjs';
7
- import { loadCore } from './package.mjs';
8
-
9
- const FROM_VERSIONS = ['local-draft-1', 'local-draft-2'];
10
-
11
- const MESSAGES = {
12
- missingInput: {
13
- en: (_value, help) => `Supply one input document or - for stdin.\n${help}`,
14
- zh: (_value, help) => `请提供一个输入文档,或用 - 读取标准输入。\n${help}`,
15
- },
16
- multipleInputs: {
17
- en: (value, help) => `Expected one input document, received ${value}.\n${help}`,
18
- zh: (value, help) => `只能提供一个输入文档,实际收到 ${value} 个。\n${help}`,
19
- },
20
- emptyInput: {
21
- en: (_value, help) => `The input path must not be empty.\n${help}`,
22
- zh: (_value, help) => `输入路径不能为空。\n${help}`,
23
- },
24
- unknownOption: {
25
- en: (value, help) => `Unknown option: ${value}\n${help}`,
26
- zh: (value, help) => `未知选项:${value}\n${help}`,
27
- },
28
- missingValue: {
29
- en: (value, help) => `Option "${value}" requires a value.\n${help}`,
30
- zh: (value, help) => `选项 "${value}" 需要一个值。\n${help}`,
31
- },
32
- emptyValue: {
33
- en: (value, help) => `Option "${value}" requires a non-empty value.\n${help}`,
34
- zh: (value, help) => `选项 "${value}" 的值不能为空。\n${help}`,
35
- },
36
- invalidFrom: {
37
- en: (value, help) => `Invalid --from value: ${value}. Use ${FROM_VERSIONS.join(' or ')}.\n${help}`,
38
- zh: (value, help) => `--from 的值无效:${value}。请使用 ${FROM_VERSIONS.join(' 或 ')}。\n${help}`,
39
- },
40
- invalidLocale: {
41
- en: (value, help) => `Invalid --locale value: ${value}. Use en or zh.\n${help}`,
42
- zh: (value, help) => `--locale 的值无效:${value}。请使用 en 或 zh。\n${help}`,
43
- },
44
- checkWithOutput: {
45
- en: (_value, help) => `--check never writes output; remove --output.\n${help}`,
46
- zh: (_value, help) => `--check 不写入文件;请去掉 --output。\n${help}`,
47
- },
48
- readFailed: {
49
- en: (value) => `Cannot read input: ${value}`,
50
- zh: (value) => `无法读取输入:${value}`,
51
- },
52
- blocked: {
53
- en: (value) => `Migration blocked by ${value} diagnostic(s).`,
54
- zh: (value) => `迁移被 ${value} 条诊断阻止。`,
55
- },
56
- notApplied: {
57
- en: (value) => `Migration was not applied: ${value}.`,
58
- zh: (value) => `未执行迁移:${value}。`,
59
- },
60
- needed: {
61
- en: (value) => `Migration needed: ${value}.`,
62
- zh: (value) => `需要迁移:${value}。`,
63
- },
64
- current: {
65
- en: (value) => `Already current: ${value}.`,
66
- zh: (value) => `已是最新版本:${value}。`,
67
- },
68
- };
69
-
70
- function message(kind, locale, value, help) {
71
- return MESSAGES[kind][locale === 'zh' ? 'zh' : 'en'](value, help);
72
- }
73
-
74
- /** Extract --locale before validation so usage errors use the requested language. */
75
- function extractLocale(args) {
76
- let locale = 'en';
77
- let invalid;
78
- const rest = [];
79
- let pathsOnly = false;
80
- for (let index = 0; index < args.length; index += 1) {
81
- const arg = args[index];
82
- if (!pathsOnly && arg === '--') {
83
- pathsOnly = true;
84
- rest.push(arg);
85
- continue;
86
- }
87
- if (!pathsOnly && arg === '--locale') {
88
- const value = args[index + 1];
89
- if (value !== 'en' && value !== 'zh') {
90
- invalid = value === undefined ? '' : value;
91
- break;
92
- }
93
- locale = value;
94
- index += 1;
95
- continue;
96
- }
97
- if (!pathsOnly && arg.startsWith('--locale=')) {
98
- const value = arg.slice('--locale='.length);
99
- if (value !== 'en' && value !== 'zh') {
100
- invalid = value;
101
- break;
102
- }
103
- locale = value;
104
- continue;
105
- }
106
- rest.push(arg);
107
- }
108
- return { locale, invalid, args: rest };
109
- }
110
-
111
- /** @param {string[]} args @param {object} help @param {'en'|'zh'} locale */
112
- function parseArgs(args, help, locale) {
113
- const positionals = [];
114
- const options = { check: false, json: false, acceptSemanticChanges: false, help: false };
115
- let literal = false;
116
-
117
- for (let index = 0; index < args.length; index += 1) {
118
- const token = args[index];
119
- if (literal) {
120
- positionals.push(token);
121
- continue;
122
- }
123
- if (token === '--') {
124
- literal = true;
125
- continue;
126
- }
127
- if (token === '-' || !token.startsWith('-')) {
128
- positionals.push(token);
129
- continue;
130
- }
131
- if (token === '-h' || token === '--help') {
132
- options.help = true;
133
- continue;
134
- }
135
- if (token === '--check') {
136
- options.check = true;
137
- continue;
138
- }
139
- if (token === '--json') {
140
- options.json = true;
141
- continue;
142
- }
143
- if (token === '--accept-semantic-changes') {
144
- options.acceptSemanticChanges = true;
145
- continue;
146
- }
147
-
148
- let name = token;
149
- let inlineValue;
150
- if (token.startsWith('--')) {
151
- const equals = token.indexOf('=');
152
- if (equals > 2) {
153
- name = token.slice(0, equals);
154
- inlineValue = token.slice(equals + 1);
155
- }
156
- }
157
- if (name !== '-o' && name !== '--output' && name !== '--from') {
158
- throw usageError(message('unknownOption', locale, name, help));
159
- }
160
- let value = inlineValue;
161
- if (value === undefined) {
162
- if (index + 1 >= args.length) {
163
- throw usageError(message('missingValue', locale, name, help));
164
- }
165
- value = args[index + 1];
166
- index += 1;
167
- }
168
- if (typeof value !== 'string' || value.trim() === '') {
169
- throw usageError(message('emptyValue', locale, name, help));
170
- }
171
- if (name === '--from') {
172
- if (!FROM_VERSIONS.includes(value)) {
173
- throw usageError(message('invalidFrom', locale, value, help));
174
- }
175
- options.from = value;
176
- } else {
177
- options.output = value;
178
- }
179
- }
180
-
181
- return { positionals, options };
182
- }
183
-
184
- async function readStdin() {
185
- process.stdin.setEncoding('utf8');
186
- let source = '';
187
- for await (const chunk of process.stdin) source += chunk;
188
- return source;
189
- }
190
-
191
- /**
192
- * Exclusive creation: never overwrite an existing file, including the input.
193
- * @param {string} inputPath `-` for stdin
194
- * @param {string} outputPath
195
- * @param {string} content
196
- */
197
- async function writeNewFile(inputPath, outputPath, content) {
198
- const absolute = path.resolve(outputPath);
199
- if (inputPath !== '-') await assertDistinctPaths(inputPath, absolute);
200
- try {
201
- await writeFile(absolute, content, { encoding: 'utf8', flag: 'wx' });
202
- } catch (error) {
203
- const code = error && typeof error === 'object' && 'code' in error ? error.code : null;
204
- if (code === 'EEXIST') {
205
- throw new CliError(`Output file already exists: "${absolute}". Migration never overwrites files.`, EXIT.USAGE, { cause: error });
206
- }
207
- throw fsFailure('Cannot write output file', absolute, error, EXIT.USAGE);
208
- }
209
- }
210
-
211
- /**
212
- * `reactive-md migrate <file|->`
213
- *
214
- * @param {string[]} args Arguments after the `migrate` command.
215
- * @param {{packageRoot: string, stdout: NodeJS.WritableStream, stderr: NodeJS.WritableStream}} context
216
- */
217
- export async function runMigrate(args, { packageRoot, stdout, stderr }) {
218
- const { locale, invalid, args: rest } = extractLocale(args);
219
- const help = migrateHelp(locale);
220
- if (invalid !== undefined) {
221
- stderr.write(message('invalidLocale', locale, invalid, help));
222
- return EXIT.USAGE;
223
- }
224
-
225
- let parsed;
226
- try {
227
- parsed = parseArgs(rest, help, locale);
228
- } catch (error) {
229
- if (error instanceof CliError) {
230
- stderr.write(`${error.message}\n`);
231
- return error.exitCode;
232
- }
233
- throw error;
234
- }
235
- const { positionals, options } = parsed;
236
-
237
- if (options.help) {
238
- stdout.write(help);
239
- return EXIT.OK;
240
- }
241
- if (positionals.length === 0) {
242
- stderr.write(message('missingInput', locale, '', help));
243
- return EXIT.USAGE;
244
- }
245
- if (positionals.length > 1) {
246
- stderr.write(message('multipleInputs', locale, positionals.length, help));
247
- return EXIT.USAGE;
248
- }
249
- const input = positionals[0];
250
- if (input.trim() === '') {
251
- stderr.write(message('emptyInput', locale, '', help));
252
- return EXIT.USAGE;
253
- }
254
- if (options.check && options.output !== undefined) {
255
- stderr.write(message('checkWithOutput', locale, '', help));
256
- return EXIT.USAGE;
257
- }
258
-
259
- let source;
260
- if (input === '-') {
261
- source = await readStdin();
262
- } else {
263
- try {
264
- source = await readFile(input, 'utf8');
265
- } catch (error) {
266
- const detail = locale === 'zh'
267
- ? (typeof error?.code === 'string' ? error.code : '读取失败')
268
- : (error instanceof Error ? error.message : String(error));
269
- stderr.write(`${message('readFailed', locale, detail)}\n`);
270
- return EXIT.USAGE;
271
- }
272
- }
273
-
274
- const required = options.check
275
- ? ['checkLocalUpgrade', 'formatLocalDiagnostic']
276
- : ['migrateLocalSource', 'formatLocalDiagnostic'];
277
- const core = await loadCore(packageRoot, required);
278
- const coreOptions = {};
279
- if (options.from !== undefined) coreOptions.fromVersion = options.from;
280
- if (options.acceptSemanticChanges) coreOptions.allowSemanticChanges = true;
281
-
282
- const result = options.check
283
- ? core.checkLocalUpgrade(source, coreOptions)
284
- : core.migrateLocalSource(source, coreOptions);
285
- if (!result || typeof result !== 'object' || !Array.isArray(result.diagnostics)) {
286
- throw new CliError('The core build returned an invalid migration result. Run "npm run build" again.', EXIT.DOCUMENT);
287
- }
288
- if (!options.check && typeof result.source !== 'string') {
289
- throw new CliError('The core build returned a migration result without source. Run "npm run build" again.', EXIT.DOCUMENT);
290
- }
291
-
292
- const label = input === '-' ? '<stdin>' : displayPath(input);
293
- const diagnostics = result.diagnostics.map((diagnostic) => ({
294
- ...diagnostic,
295
- message: core.formatLocalDiagnostic(diagnostic, locale),
296
- }));
297
- const ok = result.ok === true;
298
-
299
- if (options.json) {
300
- const report = {
301
- file: label,
302
- mode: options.check ? 'check' : 'migrate',
303
- ok,
304
- fromVersion: result.fromVersion,
305
- toVersion: result.toVersion,
306
- needsMigration: result.needsMigration === true,
307
- diagnostics,
308
- };
309
- if (options.check) {
310
- stdout.write(`${JSON.stringify(report, null, 2)}\n`);
311
- return !ok || result.needsMigration === true ? 1 : 0;
312
- }
313
- report.changed = result.changed === true;
314
- report.edits = Array.isArray(result.edits) ? result.edits : [];
315
- if (!ok) {
316
- stdout.write(`${JSON.stringify(report, null, 2)}\n`);
317
- return 1;
318
- }
319
- if (options.output !== undefined) {
320
- report.output = path.resolve(options.output);
321
- await writeNewFile(input, options.output, result.source);
322
- } else {
323
- report.source = result.source;
324
- }
325
- stdout.write(`${JSON.stringify(report, null, 2)}\n`);
326
- return EXIT.OK;
327
- }
328
-
329
- if (options.check) {
330
- for (const diagnostic of diagnostics) {
331
- stdout.write(`${formatDiagnostic(label, diagnostic)}\n`);
332
- }
333
- if (!ok) {
334
- if (diagnostics.length === 0) {
335
- stdout.write(`${message('notApplied', locale, label)}\n`);
336
- } else {
337
- stdout.write(`${message('blocked', locale, diagnostics.filter((item) => item.severity === 'error').length || diagnostics.length)}\n`);
338
- }
339
- return 1;
340
- }
341
- if (result.needsMigration === true) {
342
- stdout.write(`${message('needed', locale, `${result.fromVersion} -> ${result.toVersion}`)}\n`);
343
- return 1;
344
- }
345
- stdout.write(`${message('current', locale, result.toVersion)}\n`);
346
- return EXIT.OK;
347
- }
348
-
349
- if (!ok) {
350
- for (const diagnostic of diagnostics) {
351
- stderr.write(`${formatDiagnostic(label, diagnostic)}\n`);
352
- }
353
- if (diagnostics.length === 0) {
354
- stderr.write(`reactive-md: ${message('notApplied', locale, label)}\n`);
355
- }
356
- return 1;
357
- }
358
-
359
- for (const diagnostic of diagnostics) {
360
- if (diagnostic.severity === 'warning') stderr.write(`${formatDiagnostic(label, diagnostic)}\n`);
361
- }
362
- if (options.output !== undefined) {
363
- await writeNewFile(input, options.output, result.source);
364
- } else {
365
- stdout.write(result.source);
366
- }
367
- return EXIT.OK;
368
- }
1
+ import { readFile, writeFile } from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { displayPath, formatDiagnostic } from './document.mjs';
4
+ import { CliError, EXIT, fsFailure, usageError } from './errors.mjs';
5
+ import { assertDistinctPaths } from './fs-utils.mjs';
6
+ import { migrateHelp } from './help.mjs';
7
+ import { loadCore } from './package.mjs';
8
+
9
+ const FROM_VERSIONS = ['local-draft-1', 'local-draft-2'];
10
+
11
+ const MESSAGES = {
12
+ missingInput: {
13
+ en: (_value, help) => `Supply one input document or - for stdin.\n${help}`,
14
+ zh: (_value, help) => `请提供一个输入文档,或用 - 读取标准输入。\n${help}`,
15
+ },
16
+ multipleInputs: {
17
+ en: (value, help) => `Expected one input document, received ${value}.\n${help}`,
18
+ zh: (value, help) => `只能提供一个输入文档,实际收到 ${value} 个。\n${help}`,
19
+ },
20
+ emptyInput: {
21
+ en: (_value, help) => `The input path must not be empty.\n${help}`,
22
+ zh: (_value, help) => `输入路径不能为空。\n${help}`,
23
+ },
24
+ unknownOption: {
25
+ en: (value, help) => `Unknown option: ${value}\n${help}`,
26
+ zh: (value, help) => `未知选项:${value}\n${help}`,
27
+ },
28
+ missingValue: {
29
+ en: (value, help) => `Option "${value}" requires a value.\n${help}`,
30
+ zh: (value, help) => `选项 "${value}" 需要一个值。\n${help}`,
31
+ },
32
+ emptyValue: {
33
+ en: (value, help) => `Option "${value}" requires a non-empty value.\n${help}`,
34
+ zh: (value, help) => `选项 "${value}" 的值不能为空。\n${help}`,
35
+ },
36
+ invalidFrom: {
37
+ en: (value, help) => `Invalid --from value: ${value}. Use ${FROM_VERSIONS.join(' or ')}.\n${help}`,
38
+ zh: (value, help) => `--from 的值无效:${value}。请使用 ${FROM_VERSIONS.join(' 或 ')}。\n${help}`,
39
+ },
40
+ invalidLocale: {
41
+ en: (value, help) => `Invalid --locale value: ${value}. Use en or zh.\n${help}`,
42
+ zh: (value, help) => `--locale 的值无效:${value}。请使用 en 或 zh。\n${help}`,
43
+ },
44
+ checkWithOutput: {
45
+ en: (_value, help) => `--check never writes output; remove --output.\n${help}`,
46
+ zh: (_value, help) => `--check 不写入文件;请去掉 --output。\n${help}`,
47
+ },
48
+ readFailed: {
49
+ en: (value) => `Cannot read input: ${value}`,
50
+ zh: (value) => `无法读取输入:${value}`,
51
+ },
52
+ blocked: {
53
+ en: (value) => `Migration blocked by ${value} diagnostic(s).`,
54
+ zh: (value) => `迁移被 ${value} 条诊断阻止。`,
55
+ },
56
+ notApplied: {
57
+ en: (value) => `Migration was not applied: ${value}.`,
58
+ zh: (value) => `未执行迁移:${value}。`,
59
+ },
60
+ needed: {
61
+ en: (value) => `Migration needed: ${value}.`,
62
+ zh: (value) => `需要迁移:${value}。`,
63
+ },
64
+ current: {
65
+ en: (value) => `Already current: ${value}.`,
66
+ zh: (value) => `已是最新版本:${value}。`,
67
+ },
68
+ };
69
+
70
+ function message(kind, locale, value, help) {
71
+ return MESSAGES[kind][locale === 'zh' ? 'zh' : 'en'](value, help);
72
+ }
73
+
74
+ /** Extract --locale before validation so usage errors use the requested language. */
75
+ function extractLocale(args) {
76
+ let locale = 'en';
77
+ let invalid;
78
+ const rest = [];
79
+ let pathsOnly = false;
80
+ for (let index = 0; index < args.length; index += 1) {
81
+ const arg = args[index];
82
+ if (!pathsOnly && arg === '--') {
83
+ pathsOnly = true;
84
+ rest.push(arg);
85
+ continue;
86
+ }
87
+ if (!pathsOnly && arg === '--locale') {
88
+ const value = args[index + 1];
89
+ if (value !== 'en' && value !== 'zh') {
90
+ invalid = value === undefined ? '' : value;
91
+ break;
92
+ }
93
+ locale = value;
94
+ index += 1;
95
+ continue;
96
+ }
97
+ if (!pathsOnly && arg.startsWith('--locale=')) {
98
+ const value = arg.slice('--locale='.length);
99
+ if (value !== 'en' && value !== 'zh') {
100
+ invalid = value;
101
+ break;
102
+ }
103
+ locale = value;
104
+ continue;
105
+ }
106
+ rest.push(arg);
107
+ }
108
+ return { locale, invalid, args: rest };
109
+ }
110
+
111
+ /** @param {string[]} args @param {object} help @param {'en'|'zh'} locale */
112
+ function parseArgs(args, help, locale) {
113
+ const positionals = [];
114
+ const options = { check: false, json: false, acceptSemanticChanges: false, help: false };
115
+ let literal = false;
116
+
117
+ for (let index = 0; index < args.length; index += 1) {
118
+ const token = args[index];
119
+ if (literal) {
120
+ positionals.push(token);
121
+ continue;
122
+ }
123
+ if (token === '--') {
124
+ literal = true;
125
+ continue;
126
+ }
127
+ if (token === '-' || !token.startsWith('-')) {
128
+ positionals.push(token);
129
+ continue;
130
+ }
131
+ if (token === '-h' || token === '--help') {
132
+ options.help = true;
133
+ continue;
134
+ }
135
+ if (token === '--check') {
136
+ options.check = true;
137
+ continue;
138
+ }
139
+ if (token === '--json') {
140
+ options.json = true;
141
+ continue;
142
+ }
143
+ if (token === '--accept-semantic-changes') {
144
+ options.acceptSemanticChanges = true;
145
+ continue;
146
+ }
147
+
148
+ let name = token;
149
+ let inlineValue;
150
+ if (token.startsWith('--')) {
151
+ const equals = token.indexOf('=');
152
+ if (equals > 2) {
153
+ name = token.slice(0, equals);
154
+ inlineValue = token.slice(equals + 1);
155
+ }
156
+ }
157
+ if (name !== '-o' && name !== '--output' && name !== '--from') {
158
+ throw usageError(message('unknownOption', locale, name, help));
159
+ }
160
+ let value = inlineValue;
161
+ if (value === undefined) {
162
+ if (index + 1 >= args.length) {
163
+ throw usageError(message('missingValue', locale, name, help));
164
+ }
165
+ value = args[index + 1];
166
+ index += 1;
167
+ }
168
+ if (typeof value !== 'string' || value.trim() === '') {
169
+ throw usageError(message('emptyValue', locale, name, help));
170
+ }
171
+ if (name === '--from') {
172
+ if (!FROM_VERSIONS.includes(value)) {
173
+ throw usageError(message('invalidFrom', locale, value, help));
174
+ }
175
+ options.from = value;
176
+ } else {
177
+ options.output = value;
178
+ }
179
+ }
180
+
181
+ return { positionals, options };
182
+ }
183
+
184
+ async function readStdin() {
185
+ process.stdin.setEncoding('utf8');
186
+ let source = '';
187
+ for await (const chunk of process.stdin) source += chunk;
188
+ return source;
189
+ }
190
+
191
+ /**
192
+ * Exclusive creation: never overwrite an existing file, including the input.
193
+ * @param {string} inputPath `-` for stdin
194
+ * @param {string} outputPath
195
+ * @param {string} content
196
+ */
197
+ async function writeNewFile(inputPath, outputPath, content) {
198
+ const absolute = path.resolve(outputPath);
199
+ if (inputPath !== '-') await assertDistinctPaths(inputPath, absolute);
200
+ try {
201
+ await writeFile(absolute, content, { encoding: 'utf8', flag: 'wx' });
202
+ } catch (error) {
203
+ const code = error && typeof error === 'object' && 'code' in error ? error.code : null;
204
+ if (code === 'EEXIST') {
205
+ throw new CliError(`Output file already exists: "${absolute}". Migration never overwrites files.`, EXIT.USAGE, { cause: error });
206
+ }
207
+ throw fsFailure('Cannot write output file', absolute, error, EXIT.USAGE);
208
+ }
209
+ }
210
+
211
+ /**
212
+ * `reactive-md migrate <file|->`
213
+ *
214
+ * @param {string[]} args Arguments after the `migrate` command.
215
+ * @param {{packageRoot: string, stdout: NodeJS.WritableStream, stderr: NodeJS.WritableStream}} context
216
+ */
217
+ export async function runMigrate(args, { packageRoot, stdout, stderr }) {
218
+ const { locale, invalid, args: rest } = extractLocale(args);
219
+ const help = migrateHelp(locale);
220
+ if (invalid !== undefined) {
221
+ stderr.write(message('invalidLocale', locale, invalid, help));
222
+ return EXIT.USAGE;
223
+ }
224
+
225
+ let parsed;
226
+ try {
227
+ parsed = parseArgs(rest, help, locale);
228
+ } catch (error) {
229
+ if (error instanceof CliError) {
230
+ stderr.write(`${error.message}\n`);
231
+ return error.exitCode;
232
+ }
233
+ throw error;
234
+ }
235
+ const { positionals, options } = parsed;
236
+
237
+ if (options.help) {
238
+ stdout.write(help);
239
+ return EXIT.OK;
240
+ }
241
+ if (positionals.length === 0) {
242
+ stderr.write(message('missingInput', locale, '', help));
243
+ return EXIT.USAGE;
244
+ }
245
+ if (positionals.length > 1) {
246
+ stderr.write(message('multipleInputs', locale, positionals.length, help));
247
+ return EXIT.USAGE;
248
+ }
249
+ const input = positionals[0];
250
+ if (input.trim() === '') {
251
+ stderr.write(message('emptyInput', locale, '', help));
252
+ return EXIT.USAGE;
253
+ }
254
+ if (options.check && options.output !== undefined) {
255
+ stderr.write(message('checkWithOutput', locale, '', help));
256
+ return EXIT.USAGE;
257
+ }
258
+
259
+ let source;
260
+ if (input === '-') {
261
+ source = await readStdin();
262
+ } else {
263
+ try {
264
+ source = await readFile(input, 'utf8');
265
+ } catch (error) {
266
+ const detail = locale === 'zh'
267
+ ? (typeof error?.code === 'string' ? error.code : '读取失败')
268
+ : (error instanceof Error ? error.message : String(error));
269
+ stderr.write(`${message('readFailed', locale, detail)}\n`);
270
+ return EXIT.USAGE;
271
+ }
272
+ }
273
+
274
+ const required = options.check
275
+ ? ['checkLocalUpgrade', 'formatLocalDiagnostic']
276
+ : ['migrateLocalSource', 'formatLocalDiagnostic'];
277
+ const core = await loadCore(packageRoot, required);
278
+ const coreOptions = {};
279
+ if (options.from !== undefined) coreOptions.fromVersion = options.from;
280
+ if (options.acceptSemanticChanges) coreOptions.allowSemanticChanges = true;
281
+
282
+ const result = options.check
283
+ ? core.checkLocalUpgrade(source, coreOptions)
284
+ : core.migrateLocalSource(source, coreOptions);
285
+ if (!result || typeof result !== 'object' || !Array.isArray(result.diagnostics)) {
286
+ throw new CliError('The core build returned an invalid migration result. Run "npm run build" again.', EXIT.DOCUMENT);
287
+ }
288
+ if (!options.check && typeof result.source !== 'string') {
289
+ throw new CliError('The core build returned a migration result without source. Run "npm run build" again.', EXIT.DOCUMENT);
290
+ }
291
+
292
+ const label = input === '-' ? '<stdin>' : displayPath(input);
293
+ const diagnostics = result.diagnostics.map((diagnostic) => ({
294
+ ...diagnostic,
295
+ message: core.formatLocalDiagnostic(diagnostic, locale),
296
+ }));
297
+ const ok = result.ok === true;
298
+
299
+ if (options.json) {
300
+ const report = {
301
+ file: label,
302
+ mode: options.check ? 'check' : 'migrate',
303
+ ok,
304
+ fromVersion: result.fromVersion,
305
+ toVersion: result.toVersion,
306
+ needsMigration: result.needsMigration === true,
307
+ diagnostics,
308
+ };
309
+ if (options.check) {
310
+ stdout.write(`${JSON.stringify(report, null, 2)}\n`);
311
+ return !ok || result.needsMigration === true ? 1 : 0;
312
+ }
313
+ report.changed = result.changed === true;
314
+ report.edits = Array.isArray(result.edits) ? result.edits : [];
315
+ if (!ok) {
316
+ stdout.write(`${JSON.stringify(report, null, 2)}\n`);
317
+ return 1;
318
+ }
319
+ if (options.output !== undefined) {
320
+ report.output = path.resolve(options.output);
321
+ await writeNewFile(input, options.output, result.source);
322
+ } else {
323
+ report.source = result.source;
324
+ }
325
+ stdout.write(`${JSON.stringify(report, null, 2)}\n`);
326
+ return EXIT.OK;
327
+ }
328
+
329
+ if (options.check) {
330
+ for (const diagnostic of diagnostics) {
331
+ stdout.write(`${formatDiagnostic(label, diagnostic)}\n`);
332
+ }
333
+ if (!ok) {
334
+ if (diagnostics.length === 0) {
335
+ stdout.write(`${message('notApplied', locale, label)}\n`);
336
+ } else {
337
+ stdout.write(`${message('blocked', locale, diagnostics.filter((item) => item.severity === 'error').length || diagnostics.length)}\n`);
338
+ }
339
+ return 1;
340
+ }
341
+ if (result.needsMigration === true) {
342
+ stdout.write(`${message('needed', locale, `${result.fromVersion} -> ${result.toVersion}`)}\n`);
343
+ return 1;
344
+ }
345
+ stdout.write(`${message('current', locale, result.toVersion)}\n`);
346
+ return EXIT.OK;
347
+ }
348
+
349
+ if (!ok) {
350
+ for (const diagnostic of diagnostics) {
351
+ stderr.write(`${formatDiagnostic(label, diagnostic)}\n`);
352
+ }
353
+ if (diagnostics.length === 0) {
354
+ stderr.write(`reactive-md: ${message('notApplied', locale, label)}\n`);
355
+ }
356
+ return 1;
357
+ }
358
+
359
+ for (const diagnostic of diagnostics) {
360
+ if (diagnostic.severity === 'warning') stderr.write(`${formatDiagnostic(label, diagnostic)}\n`);
361
+ }
362
+ if (options.output !== undefined) {
363
+ await writeNewFile(input, options.output, result.source);
364
+ } else {
365
+ stdout.write(result.source);
366
+ }
367
+ return EXIT.OK;
368
+ }