reactive-md 0.3.1 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (172) hide show
  1. package/CHANGELOG-ch.md +96 -0
  2. package/CHANGELOG.md +82 -39
  3. package/CONTRIBUTING-ch.md +62 -0
  4. package/CONTRIBUTING.md +64 -65
  5. package/README-ch.md +122 -0
  6. package/README-en.md +146 -0
  7. package/README.md +146 -89
  8. package/SECURITY-ch.md +80 -0
  9. package/SECURITY.md +58 -49
  10. package/THIRD_PARTY_NOTICES.md +85 -1
  11. package/bin/reactive-md.mjs +40 -0
  12. package/cli/args.mjs +181 -0
  13. package/cli/assets.mjs +390 -0
  14. package/cli/build.mjs +268 -0
  15. package/cli/document.mjs +130 -0
  16. package/cli/errors.mjs +61 -0
  17. package/cli/fs-utils.mjs +133 -0
  18. package/cli/glob.mjs +203 -0
  19. package/cli/help.mjs +138 -0
  20. package/cli/lint.mjs +177 -0
  21. package/cli/main.mjs +55 -0
  22. package/cli/migrate.mjs +368 -0
  23. package/cli/package.mjs +209 -0
  24. package/dist-library/reactive-md-react.js +3425 -1647
  25. package/dist-library/reactive-md.css +1 -1
  26. package/dist-library/reactive-md.js +1798 -4
  27. package/dist-library/runtime-DtjdPXxJ.js +15410 -0
  28. package/dist-library/types/index.d.ts +1 -0
  29. package/dist-library/types/local/LocalDocumentView.d.ts +66 -3
  30. package/dist-library/types/local/authoring.d.ts +63 -0
  31. package/dist-library/types/local/collection-functions.d.ts +4 -0
  32. package/dist-library/types/local/colors.d.ts +2 -0
  33. package/dist-library/types/local/computations.d.ts +53 -0
  34. package/dist-library/types/local/data-functions.d.ts +22 -0
  35. package/dist-library/types/local/data-table.d.ts +65 -0
  36. package/dist-library/types/local/dates.d.ts +2 -0
  37. package/dist-library/types/local/dependencies.d.ts +31 -0
  38. package/dist-library/types/local/diagnostics.d.ts +1450 -0
  39. package/dist-library/types/local/expression.d.ts +13 -3
  40. package/dist-library/types/local/formatting.d.ts +41 -0
  41. package/dist-library/types/local/heading-anchors.d.ts +13 -2
  42. package/dist-library/types/local/i18n.d.ts +18 -0
  43. package/dist-library/types/local/index.d.ts +18 -1
  44. package/dist-library/types/local/limits.d.ts +32 -1
  45. package/dist-library/types/local/locale.d.ts +1 -0
  46. package/dist-library/types/local/math.d.ts +6 -1
  47. package/dist-library/types/local/parser.d.ts +10 -4
  48. package/dist-library/types/local/render-types.d.ts +5 -1
  49. package/dist-library/types/local/retention.d.ts +23 -0
  50. package/dist-library/types/local/schema.d.ts +25 -3
  51. package/dist-library/types/local/source-migration.d.ts +35 -0
  52. package/dist-library/types/local/state.d.ts +80 -0
  53. package/dist-library/types/local/text-length.d.ts +13 -0
  54. package/dist-library/types/local/theme.d.ts +30 -0
  55. package/dist-library/types/local/types.d.ts +112 -4
  56. package/dist-library/types/local/validation.d.ts +32 -0
  57. package/dist-library/types/local/version.d.ts +1 -1
  58. package/dist-library/types/local/worker.d.ts +82 -0
  59. package/dist-library/types/react/index.d.ts +4 -1
  60. package/dist-library/types/shareable.d.ts +64 -0
  61. package/dist-standalone/reactive-md-standalone.css +2 -0
  62. package/dist-standalone/reactive-md-standalone.js +57 -0
  63. package/docs/author-tools-ch.md +56 -0
  64. package/docs/author-tools-en.md +56 -0
  65. package/docs/compatibility-ch.md +103 -0
  66. package/docs/compatibility-en.md +103 -0
  67. package/docs/{component-development.md → component-development-ch.md} +210 -206
  68. package/docs/component-development-en.md +210 -0
  69. package/docs/{component-protocol.md → component-protocol-ch.md} +710 -685
  70. package/docs/component-protocol-en.md +710 -0
  71. package/docs/computations-formatting-ch.md +87 -0
  72. package/docs/computations-formatting-en.md +87 -0
  73. package/docs/constraints-collections-ch.md +84 -0
  74. package/docs/constraints-collections-en.md +84 -0
  75. package/docs/diagnostics-counting-ch.md +84 -0
  76. package/docs/diagnostics-counting-en.md +84 -0
  77. package/docs/local-components-v2-ch.md +138 -0
  78. package/docs/local-components-v2-en.md +104 -0
  79. package/docs/{local-guide.md → local-guide-ch.md} +28 -8
  80. package/docs/local-guide-en.md +961 -0
  81. package/docs/local-integration-ch.md +363 -0
  82. package/docs/local-integration-en.md +363 -0
  83. package/docs/{local-interaction-syntax.md → local-interaction-syntax-ch.md} +66 -20
  84. package/docs/local-interaction-syntax-en.md +483 -0
  85. package/docs/{performance.md → performance-ch.md} +12 -3
  86. package/docs/performance-en.md +76 -0
  87. package/docs/release-0.4.0-ch.md +89 -0
  88. package/docs/release-0.4.0-en.md +89 -0
  89. package/docs/releasing-ch.md +101 -0
  90. package/docs/releasing-en.md +101 -0
  91. package/docs/shareable-export-ch.md +205 -0
  92. package/docs/shareable-export-en.md +207 -0
  93. package/docs/source-versioning-ch.md +159 -0
  94. package/docs/source-versioning-en.md +159 -0
  95. package/docs/theme-protocol-ch.md +107 -0
  96. package/docs/theme-protocol-en.md +107 -0
  97. package/examples/conformance/README.md +33 -31
  98. package/examples/conformance/component-protocol-1.json +482 -194
  99. package/examples/conformance/component-protocol-1.schema.json +76 -76
  100. package/examples/conformance/history/v0.3.1/catalog.reactive.md +20 -0
  101. package/examples/conformance/history/v0.3.1/charts.reactive.md +73 -0
  102. package/examples/conformance/history/v0.3.1/checklist.reactive.md +32 -0
  103. package/examples/conformance/history/v0.3.1/comparison.reactive.md +47 -0
  104. package/examples/conformance/history/v0.3.1/components.reactive.md +44 -0
  105. package/examples/conformance/history/v0.3.1/counter.reactive.md +7 -0
  106. package/examples/conformance/history/v0.3.1/diagnostics.reactive.md +54 -0
  107. package/examples/conformance/history/v0.3.1/diagram.reactive.md +44 -0
  108. package/examples/conformance/history/v0.3.1/gallery.reactive.md +61 -0
  109. package/examples/conformance/history/v0.3.1/local-draft-1.json +50 -0
  110. package/examples/conformance/history/v0.3.1/parameters.reactive.md +36 -0
  111. package/examples/conformance/history/v0.3.1/planning.reactive.md +24 -0
  112. package/examples/conformance/history/v0.3.1/pricing.reactive.md +20 -0
  113. package/examples/conformance/history/v0.3.1/provenance.json +72 -0
  114. package/examples/conformance/local-draft-2.json +212 -0
  115. package/examples/integration/README.md +45 -29
  116. package/examples/integration/core/index.mjs +32 -19
  117. package/examples/integration/react/index.html +1 -1
  118. package/examples/integration/react/main.jsx +5 -5
  119. package/examples/integration/worker/index.html +19 -0
  120. package/examples/integration/worker/main.js +61 -0
  121. package/examples/integration/worker/package.json +13 -0
  122. package/examples/integration/worker/worker.js +3 -0
  123. package/examples/local/README.md +64 -58
  124. package/examples/local/catalog.reactive.md +14 -14
  125. package/examples/local/charts.reactive.md +34 -34
  126. package/examples/local/checklist.reactive.md +19 -19
  127. package/examples/local/comparison.reactive.md +23 -23
  128. package/examples/local/components.reactive.md +20 -20
  129. package/examples/local/counter.reactive.md +4 -4
  130. package/examples/local/diagnostics.reactive.md +25 -25
  131. package/examples/local/diagram.reactive.md +20 -20
  132. package/examples/local/gallery.reactive.md +31 -31
  133. package/examples/local/parameters.reactive.md +19 -19
  134. package/examples/local/planning.reactive.md +15 -15
  135. package/examples/local/pricing.reactive.md +10 -10
  136. package/examples/local/recipes/invoice-zh.reactive.md +36 -0
  137. package/examples/local/recipes/invoice.reactive.md +36 -0
  138. package/examples/local/recipes/workshop-zh.reactive.md +33 -0
  139. package/examples/local/recipes/workshop.reactive.md +33 -0
  140. package/examples/local/showcase/README.md +25 -0
  141. package/examples/local/showcase/explore.reactive.md +102 -0
  142. package/examples/local/showcase/flow.reactive.md +86 -0
  143. package/examples/local/showcase/forms.reactive.md +126 -0
  144. package/examples/local/showcase/functions.reactive.md +119 -0
  145. package/examples/local/showcase/layout.reactive.md +100 -0
  146. package/examples/local/showcase/statistics.reactive.md +108 -0
  147. package/examples/local/showcase/tasks.reactive.md +89 -0
  148. package/examples/local/showcase/zh/explore.reactive.md +102 -0
  149. package/examples/local/showcase/zh/flow.reactive.md +86 -0
  150. package/examples/local/showcase/zh/forms.reactive.md +126 -0
  151. package/examples/local/showcase/zh/functions.reactive.md +119 -0
  152. package/examples/local/showcase/zh/layout.reactive.md +100 -0
  153. package/examples/local/showcase/zh/statistics.reactive.md +108 -0
  154. package/examples/local/showcase/zh/tasks.reactive.md +89 -0
  155. package/examples/local/zh/catalog.reactive.md +20 -0
  156. package/examples/local/zh/charts.reactive.md +73 -0
  157. package/examples/local/zh/checklist.reactive.md +32 -0
  158. package/examples/local/zh/comparison.reactive.md +47 -0
  159. package/examples/local/zh/components.reactive.md +44 -0
  160. package/examples/local/zh/counter.reactive.md +7 -0
  161. package/examples/local/zh/diagnostics.reactive.md +54 -0
  162. package/examples/local/zh/diagram.reactive.md +44 -0
  163. package/examples/local/zh/gallery.reactive.md +61 -0
  164. package/examples/local/zh/parameters.reactive.md +36 -0
  165. package/examples/local/zh/planning.reactive.md +24 -0
  166. package/examples/local/zh/pricing.reactive.md +20 -0
  167. package/package.json +16 -3
  168. package/README.en.md +0 -76
  169. package/dist-library/runtime-CPzMEMcW.js +0 -11111
  170. package/docs/compatibility.md +0 -68
  171. package/docs/local-integration.md +0 -218
  172. package/docs/releasing.md +0 -92
package/cli/lint.mjs ADDED
@@ -0,0 +1,177 @@
1
+ import { readFile, stat } from 'node:fs/promises';
2
+ import { loadCore } from './package.mjs';
3
+ import { expandLintInputs } from './glob.mjs';
4
+
5
+ const HELP = {
6
+ en: `Usage: reactive-md lint [--json] [--warnings-as-errors] [--locale en|zh] <file... | ->
7
+
8
+ Check ReactiveMD documents with the language compiler. Use - for stdin.
9
+ Options: --json Print an array of file reports
10
+ --warnings-as-errors, --strict Fail on warnings as well as errors
11
+ --locale en|zh Language for messages (default: en)
12
+ -- Treat remaining arguments as file paths
13
+ --help, -h Show this help
14
+ Exit codes: 0 clean, 1 diagnostics, 2 usage or file-read error.
15
+ `,
16
+ zh: `用法:reactive-md lint [--json] [--warnings-as-errors] [--locale en|zh] <文件... | ->
17
+
18
+ 使用语言编译器检查 ReactiveMD 文档。用 - 读取标准输入。
19
+ 选项:--json 输出文件报告数组
20
+ --warnings-as-errors, --strict 警告也视为失败
21
+ --locale en|zh 诊断消息语言(默认 en)
22
+ -- 其后的参数都按文件路径处理
23
+ --help, -h 显示此帮助
24
+ 退出码:0 无问题,1 有诊断,2 用法或读取失败。
25
+ `,
26
+ };
27
+
28
+ const MESSAGES = {
29
+ unknownOption: {
30
+ en: (arg, help) => `Unknown option: ${arg}\n${help}`,
31
+ zh: (arg, help) => `未知选项:${arg}\n${help}`,
32
+ },
33
+ supplyFiles: {
34
+ en: (_value, help) => `Supply files or one stdin argument (-).\n${help}`,
35
+ zh: (_value, help) => `请提供文件或一个标准输入参数(-)。\n${help}`,
36
+ },
37
+ invalidLocale: {
38
+ en: (value, help) => `Invalid --locale value: ${value}. Use en or zh.\n${help}`,
39
+ zh: (value, help) => `--locale 的值无效:${value}。请使用 en 或 zh。\n${help}`,
40
+ },
41
+ readFailed: {
42
+ en: (detail) => `Cannot read input: ${detail}`,
43
+ zh: (detail) => `无法读取输入:${detail}`,
44
+ },
45
+ };
46
+
47
+ function message(kind, locale, value, help) {
48
+ return MESSAGES[kind][locale === 'zh' ? 'zh' : 'en'](value, help);
49
+ }
50
+
51
+ /** Extract --locale before validation so usage errors use the requested language. */
52
+ function extractLocale(args) {
53
+ let locale = 'en';
54
+ let invalid;
55
+ const rest = [];
56
+ let pathsOnly = false;
57
+ for (let index = 0; index < args.length; index += 1) {
58
+ const arg = args[index];
59
+ if (!pathsOnly && arg === '--') {
60
+ pathsOnly = true;
61
+ rest.push(arg);
62
+ continue;
63
+ }
64
+ if (!pathsOnly && arg === '--locale') {
65
+ const value = args[index + 1];
66
+ if (value !== 'en' && value !== 'zh') {
67
+ invalid = value === undefined ? '' : value;
68
+ break;
69
+ }
70
+ locale = value;
71
+ index += 1;
72
+ continue;
73
+ }
74
+ if (!pathsOnly && arg.startsWith('--locale=')) {
75
+ const value = arg.slice('--locale='.length);
76
+ if (value !== 'en' && value !== 'zh') {
77
+ invalid = value;
78
+ break;
79
+ }
80
+ locale = value;
81
+ continue;
82
+ }
83
+ rest.push(arg);
84
+ }
85
+ return { locale, invalid, args: rest };
86
+ }
87
+
88
+ export async function runLint(rawArgs, context) {
89
+ const { stdout, stderr } = context;
90
+ const { locale, invalid, args } = extractLocale(rawArgs);
91
+ const help = HELP[locale === 'zh' ? 'zh' : 'en'];
92
+ if (invalid !== undefined) {
93
+ stderr.write(message('invalidLocale', locale, invalid, help));
94
+ return 2;
95
+ }
96
+ if (args.length === 1 && ['--help', '-h'].includes(args[0])) {
97
+ stdout.write(help);
98
+ return 0;
99
+ }
100
+ if (args.shift() !== 'lint') {
101
+ stderr.write(help);
102
+ return 2;
103
+ }
104
+ let json = false;
105
+ let strict = false;
106
+ let pathsOnly = false;
107
+ const files = [];
108
+ for (const arg of args) {
109
+ if (!pathsOnly && arg === '--') { pathsOnly = true; continue; }
110
+ if (!pathsOnly && arg === '--json') { json = true; continue; }
111
+ if (!pathsOnly && (arg === '--warnings-as-errors' || arg === '--strict')) { strict = true; continue; }
112
+ if (!pathsOnly && ['--help', '-h'].includes(arg)) { stdout.write(help); return 0; }
113
+ if (!pathsOnly && arg.startsWith('-') && arg !== '-') {
114
+ stderr.write(message('unknownOption', locale, arg, help));
115
+ return 2;
116
+ }
117
+ files.push(arg);
118
+ }
119
+ if (!files.length || files.filter(file => file === '-').length > 1) {
120
+ stderr.write(message('supplyFiles', locale, '', help));
121
+ return 2;
122
+ }
123
+
124
+ const { compileLocal, formatLocalDiagnostic } = await loadCore(context.packageRoot, ['compileLocal', 'formatLocalDiagnostic']);
125
+ const localizeDiagnostic = (diagnostic) => ({
126
+ ...diagnostic,
127
+ message: formatLocalDiagnostic(diagnostic, locale),
128
+ });
129
+ const reports = [];
130
+ let exitCode = 0;
131
+ const expanded = [];
132
+ for (const file of files) {
133
+ if (file !== '-' && (/[*?]/.test(file) || (await stat(file).catch(() => null))?.isDirectory())) expanded.push(...await expandLintInputs([file]));
134
+ else expanded.push(file);
135
+ }
136
+ for (const file of expanded) {
137
+ const name = file === '-' ? '<stdin>' : file;
138
+ try {
139
+ const source = file === '-' ? await readStdin() : await readFile(file, 'utf8');
140
+ const result = compileLocal(source);
141
+ const ok = result.ok && (!strict || !result.diagnostics.length);
142
+ reports.push({ file: name, ok, diagnostics: result.diagnostics.map(localizeDiagnostic) });
143
+ if (!ok) exitCode = Math.max(exitCode, 1);
144
+ } catch (error) {
145
+ exitCode = 2;
146
+ // The file is already in the report. Keep the OS code as data in Chinese
147
+ // output instead of embedding an English operating-system sentence.
148
+ const detail = locale === 'zh'
149
+ ? (typeof error?.code === 'string' ? error.code : '读取失败')
150
+ : (error instanceof Error ? error.message : String(error));
151
+ reports.push({ file: name, ok: false, diagnostics: [{
152
+ code: 'cli.io', message: message('readFailed', locale, detail),
153
+ severity: 'error', range: { start: 0, end: 0 }, line: 1, column: 1,
154
+ }] });
155
+ }
156
+ }
157
+ if (json) {
158
+ stdout.write(`${JSON.stringify(reports, null, 2)}\n`);
159
+ } else {
160
+ for (const report of reports) {
161
+ for (const item of report.diagnostics) {
162
+ // Escape control characters so paths and messages remain one terminal line.
163
+ const clean = value => String(value).replace(/[\x00-\x1f\x7f-\x9f]/g, char => `\\u${char.charCodeAt(0).toString(16).padStart(4, '0')}`);
164
+ stdout.write(`${clean(report.file)}:${item.line}:${item.column}: ${item.severity} ${clean(item.code)} ${clean(item.message)}\n`);
165
+ }
166
+ if (!report.diagnostics.length) stdout.write(`${JSON.stringify(report.file)}: OK\n`);
167
+ }
168
+ }
169
+ return exitCode;
170
+ }
171
+
172
+ async function readStdin() {
173
+ process.stdin.setEncoding('utf8');
174
+ let source = '';
175
+ for await (const chunk of process.stdin) source += chunk;
176
+ return source;
177
+ }
package/cli/main.mjs ADDED
@@ -0,0 +1,55 @@
1
+ import { parseBuildArgs } from './args.mjs';
2
+ import { runBuild } from './build.mjs';
3
+ import { EXIT, usageError } from './errors.mjs';
4
+ import { buildHelp, mainHelp } from './help.mjs';
5
+ import { runLint } from './lint.mjs';
6
+ import { runMigrate } from './migrate.mjs';
7
+ import { readPackageInfo } from './package.mjs';
8
+
9
+ /**
10
+ * Entry point shared by bin/reactive-md.mjs. The caller supplies streams so the
11
+ * CLI stays testable without touching process state.
12
+ *
13
+ * @param {string[]} argv
14
+ * @param {{packageRoot: string, stdout: NodeJS.WritableStream, stderr: NodeJS.WritableStream}} context
15
+ */
16
+ export async function runCli(argv, context) {
17
+ const [command, ...rest] = argv;
18
+
19
+ if (command === '--version' || command === '-v' || command === '-V') {
20
+ const packageInfo = await readPackageInfo(context.packageRoot);
21
+ context.stdout.write(`${packageInfo.version}\n`);
22
+ return EXIT.OK;
23
+ }
24
+
25
+ if (command === '--help' || command === '-h') {
26
+ const packageInfo = await readPackageInfo(context.packageRoot);
27
+ context.stdout.write(mainHelp(packageInfo.version));
28
+ return EXIT.OK;
29
+ }
30
+
31
+ if (command === undefined) {
32
+ const packageInfo = await readPackageInfo(context.packageRoot);
33
+ context.stderr.write(mainHelp(packageInfo.version));
34
+ return EXIT.USAGE;
35
+ }
36
+
37
+ if (command === 'build') {
38
+ const options = parseBuildArgs(rest);
39
+ if (options.help) {
40
+ context.stdout.write(buildHelp());
41
+ return EXIT.OK;
42
+ }
43
+ return runBuild(options, context);
44
+ }
45
+
46
+ if (command === 'lint') {
47
+ return runLint(argv, context);
48
+ }
49
+
50
+ if (command === 'migrate') {
51
+ return runMigrate(rest, context);
52
+ }
53
+
54
+ throw usageError(`Unknown command "${command}". Run "reactive-md --help" for usage.`);
55
+ }
@@ -0,0 +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
+ }