reactive-md 0.6.0 → 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 (105) hide show
  1. package/CHANGELOG-ch.md +203 -194
  2. package/CHANGELOG.md +203 -194
  3. package/CONTRIBUTING-ch.md +67 -67
  4. package/CONTRIBUTING.md +69 -69
  5. package/README-ch.md +157 -157
  6. package/README-en.md +184 -184
  7. package/README.md +184 -184
  8. package/SECURITY-ch.md +81 -81
  9. package/SECURITY.md +81 -81
  10. package/THIRD_PARTY_NOTICES.md +313 -209
  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-DSC0VsNK.js → authoring-BEVyth5X.js} +1 -1
  25. package/dist-library/compiler-Cm3ppMxG.js +46044 -0
  26. package/dist-library/{react-Dk94rcOp.js → react-Bh7_oxZp.js} +20110 -20113
  27. package/dist-library/reactive-md-authoring.js +2 -2
  28. package/dist-library/reactive-md-print.css +284 -284
  29. package/dist-library/reactive-md-react-unstyled.js +1 -1
  30. package/dist-library/reactive-md-react.js +1 -1
  31. package/dist-library/reactive-md.css +1 -1
  32. package/dist-library/reactive-md.js +3 -3
  33. package/dist-library/{runtime-D8KbnCd0.js → runtime-DlFYQ4s_.js} +1 -1
  34. package/dist-library/types/local/math-display.d.ts +22 -23
  35. package/dist-library/types/local/math-view.d.ts +6 -7
  36. package/dist-standalone/reactive-md-standalone.css +1 -1
  37. package/dist-standalone/reactive-md-standalone.js +318 -62
  38. package/docs/compatibility/compatibility-ch.md +121 -119
  39. package/docs/compatibility/compatibility-en.md +121 -119
  40. package/docs/compatibility/source-versioning-ch.md +159 -159
  41. package/docs/compatibility/source-versioning-en.md +159 -159
  42. package/docs/development/component-development-ch.md +210 -210
  43. package/docs/development/component-development-en.md +210 -210
  44. package/docs/development/component-protocol-ch.md +747 -747
  45. package/docs/development/component-protocol-en.md +747 -747
  46. package/docs/development/performance-ch.md +76 -76
  47. package/docs/development/performance-en.md +76 -76
  48. package/docs/development/releasing-ch.md +108 -108
  49. package/docs/development/releasing-en.md +108 -108
  50. package/docs/integration/author-tools-ch.md +62 -62
  51. package/docs/integration/author-tools-en.md +62 -62
  52. package/docs/integration/shareable-export-ch.md +209 -209
  53. package/docs/integration/shareable-export-en.md +211 -211
  54. package/docs/reference/computations-formatting-ch.md +87 -87
  55. package/docs/reference/computations-formatting-en.md +87 -87
  56. package/docs/reference/constraints-collections-ch.md +84 -84
  57. package/docs/reference/constraints-collections-en.md +84 -84
  58. package/docs/reference/diagnostics-counting-ch.md +104 -104
  59. package/docs/reference/diagnostics-counting-en.md +104 -104
  60. package/docs/reference/local-components-v2-ch.md +138 -138
  61. package/docs/reference/local-components-v2-en.md +104 -104
  62. package/docs/reference/local-interaction-syntax-ch.md +515 -511
  63. package/docs/reference/local-interaction-syntax-en.md +511 -507
  64. package/docs/reference/theme-protocol-ch.md +107 -107
  65. package/docs/reference/theme-protocol-en.md +107 -107
  66. package/docs/releases/release-0.4.0-ch.md +89 -89
  67. package/docs/releases/release-0.4.0-en.md +89 -89
  68. package/docs/releases/release-0.4.1-ch.md +23 -23
  69. package/docs/releases/release-0.4.1-en.md +23 -23
  70. package/docs/releases/release-0.6.1-ch.md +27 -0
  71. package/docs/releases/release-0.6.1-en.md +27 -0
  72. package/examples/conformance/README.md +53 -53
  73. package/examples/conformance/component-protocol-1.json +482 -482
  74. package/examples/conformance/component-protocol-1.schema.json +76 -76
  75. package/examples/conformance/local-draft-1.json +50 -50
  76. package/examples/conformance/local-draft-2.json +212 -212
  77. package/examples/integration/README.md +47 -47
  78. package/examples/integration/core/index.mjs +32 -32
  79. package/examples/integration/worker/index.html +19 -19
  80. package/examples/integration/worker/main.js +61 -61
  81. package/examples/integration/worker/package.json +13 -13
  82. package/examples/integration/worker/worker.js +3 -3
  83. package/examples/local/README.md +74 -74
  84. package/examples/local/charts.reactive.md +73 -73
  85. package/examples/local/recipes/invoice-zh.reactive.md +36 -36
  86. package/examples/local/recipes/invoice.reactive.md +36 -36
  87. package/examples/local/recipes/workshop-zh.reactive.md +33 -33
  88. package/examples/local/recipes/workshop.reactive.md +33 -33
  89. package/examples/local/showcase/README.md +25 -25
  90. package/examples/local/showcase/explore.reactive.md +102 -102
  91. package/examples/local/showcase/flow.reactive.md +86 -86
  92. package/examples/local/showcase/forms.reactive.md +126 -126
  93. package/examples/local/showcase/functions.reactive.md +119 -119
  94. package/examples/local/showcase/layout.reactive.md +100 -100
  95. package/examples/local/showcase/statistics.reactive.md +108 -108
  96. package/examples/local/showcase/tasks.reactive.md +89 -89
  97. package/examples/local/showcase/zh/explore.reactive.md +102 -102
  98. package/examples/local/showcase/zh/flow.reactive.md +86 -86
  99. package/examples/local/showcase/zh/forms.reactive.md +126 -126
  100. package/examples/local/showcase/zh/functions.reactive.md +119 -119
  101. package/examples/local/showcase/zh/layout.reactive.md +100 -100
  102. package/examples/local/showcase/zh/statistics.reactive.md +108 -108
  103. package/examples/local/showcase/zh/tasks.reactive.md +89 -89
  104. package/package.json +152 -152
  105. package/dist-library/compiler-CRD88BMt.js +0 -24964
package/cli/help.mjs CHANGED
@@ -1,138 +1,138 @@
1
- const EXIT_CODES = `Exit codes:
2
- 0 success
3
- 2 usage or argument error
4
- 3 document compile, render, React or build-artifact error
5
- 4 input or output file I/O error
6
- 5 asset or security policy error`;
7
-
8
- /** @param {string} version */
9
- export function mainHelp(version) {
10
- return `reactive-md ${version}
11
-
12
- Usage:
13
- reactive-md build <doc.reactive.md> -o <doc.html> [options]
14
- reactive-md lint [--json] [--warnings-as-errors] [--locale en|zh] <file... | ->
15
- reactive-md migrate <file | -> [options]
16
- reactive-md build --help
17
- reactive-md lint --help
18
- reactive-md migrate --help
19
- reactive-md --version
20
-
21
- Commands:
22
- build Compile one local document into a single, self-contained HTML file.
23
- lint Compile documents and report diagnostics.
24
- migrate Migrate a document's syntax revision metadata.
25
-
26
- Run "reactive-md build --help", "reactive-md lint --help" or
27
- "reactive-md migrate --help" for the options and the document diagnostic
28
- format. "format" is not part of this release.
29
-
30
- Build ${EXIT_CODES.toLowerCase()}
31
- Lint exit codes: 0 clean, 1 diagnostics, 2 usage or file-read error.
32
- Migrate exit codes: 0 success, 1 migration needed or blocked, 2 usage or I/O error.
33
- `;
34
- }
35
-
36
- export function buildHelp() {
37
- return `Usage: reactive-md build <doc.reactive.md> -o <doc.html> [options]
38
-
39
- Compile one document with the packaged core, optionally validate a parameter
40
- state file, verify and inline local images, server-render the document with
41
- React 19, and write one UTF-8 HTML file. The output is assembled through the
42
- same shareable-HTML shell used by the interactive runtime (CSP, escaped JSON,
43
- notices and print styles included).
44
-
45
- Options:
46
- -o, --output <file> Output HTML path (required). The parent
47
- directory must already exist.
48
- --mode <interactive|static> Output mode (default interactive). Static
49
- output has no runtime script and no
50
- auto-mount payload.
51
- --state-file <file.json> Export this validated state as the baseline
52
- instead of the document's initial values.
53
- --assets <inline|omit> Image handling (default inline). "omit"
54
- skips all image reads and leaves the
55
- renderer's normal alt fallback.
56
- --asset-root <dir> Extra local directory that relative image
57
- URLs may resolve inside. URLs and remote
58
- image roots are not supported.
59
- --locale <en|zh> UI locale (default en).
60
- --color-scheme <auto|light|dark>
61
- Document color scheme (default auto).
62
- --title <text> Override the document title. By default the
63
- first heading is rendered as plain text, or
64
- the input file name is used.
65
- --strict Treat compile warnings as errors. With
66
- --assets omit, omitted images also fail.
67
- -h, --help Show this help.
68
-
69
- Interactive HTML requires React 19 and react-dom, plus the prebuilt
70
- dist-standalone IIFE. Every build requires the prebuilt dist-library artifacts.
71
- From a source checkout, run "npm run build" before building documents.
72
-
73
- ${EXIT_CODES}
74
- `;
75
- }
76
-
77
- const MIGRATE_HELP = {
78
- en: `Usage: reactive-md migrate <file | -> [options]
79
-
80
- Migrate a document's syntax revision metadata. By default the migrated source
81
- is written to stdout and the input file is left unchanged. Use - for stdin.
82
-
83
- Options:
84
- --from <local-draft-1|local-draft-2>
85
- Source revision to migrate from (default: the
86
- declared revision, or the current revision
87
- when none is declared). Unversioned
88
- historical documents require --from
89
- local-draft-1.
90
- --check Report whether migration is needed or
91
- blocked, without writing output.
92
- --json Print one structured JSON report. The
93
- migrated source appears only as a JSON field.
94
- -o, --output <file> Write the migrated source to a new file.
95
- Existing files, including the input, are
96
- refused.
97
- --accept-semantic-changes Allow migrations that change reader
98
- semantics, and report a warning.
99
- --locale <en|zh> Message language (default en).
100
- -h, --help Show this help.
101
-
102
- Migration replaces only the metadata comment. It preserves the body, BOM and
103
- line endings and is idempotent. A blocked migration leaves the source
104
- unchanged. Migration never rewrites state files; export fresh state after a
105
- source digest change.
106
-
107
- Exit codes: 0 success, 1 migration needed or blocked, 2 usage or I/O error.
108
- `,
109
- zh: `用法:reactive-md migrate <文件 | -> [选项]
110
-
111
- 迁移文档的语法修订版本元数据。默认将迁移后的源文本写到标准输出,不修改输入
112
- 文件。用 - 读取标准输入。
113
-
114
- 选项:
115
- --from <local-draft-1|local-draft-2>
116
- 迁移的起始修订版本(默认取文档声明的版本;
117
- 未声明时取当前版本)。未声明的历史文档必须
118
- 指定 --from local-draft-1。
119
- --check 只报告是否需要迁移或被阻止,不写输出。
120
- --json 输出一个结构化 JSON 报告。迁移后的源文本
121
- 只作为 JSON 字段出现。
122
- -o, --output <文件> 将迁移后的源文本写入新文件。已存在的文件
123
- (包括输入文件)一律拒绝。
124
- --accept-semantic-changes 允许会改变读者语义的迁移,并给出警告。
125
- --locale <en|zh> 消息语言(默认 en)。
126
- -h, --help 显示此帮助。
127
-
128
- 迁移只替换元数据注释,保留正文、BOM 和换行符,并且幂等。迁移被阻止时源文本
129
- 保持不变。迁移不改写状态文件;源摘要变化后请重新导出状态。
130
-
131
- 退出码:0 成功,1 需要迁移或被阻止,2 用法或 I/O 错误。
132
- `,
133
- };
134
-
135
- /** @param {'en'|'zh'} [locale] */
136
- export function migrateHelp(locale = 'en') {
137
- return MIGRATE_HELP[locale === 'zh' ? 'zh' : 'en'];
138
- }
1
+ const EXIT_CODES = `Exit codes:
2
+ 0 success
3
+ 2 usage or argument error
4
+ 3 document compile, render, React or build-artifact error
5
+ 4 input or output file I/O error
6
+ 5 asset or security policy error`;
7
+
8
+ /** @param {string} version */
9
+ export function mainHelp(version) {
10
+ return `reactive-md ${version}
11
+
12
+ Usage:
13
+ reactive-md build <doc.reactive.md> -o <doc.html> [options]
14
+ reactive-md lint [--json] [--warnings-as-errors] [--locale en|zh] <file... | ->
15
+ reactive-md migrate <file | -> [options]
16
+ reactive-md build --help
17
+ reactive-md lint --help
18
+ reactive-md migrate --help
19
+ reactive-md --version
20
+
21
+ Commands:
22
+ build Compile one local document into a single, self-contained HTML file.
23
+ lint Compile documents and report diagnostics.
24
+ migrate Migrate a document's syntax revision metadata.
25
+
26
+ Run "reactive-md build --help", "reactive-md lint --help" or
27
+ "reactive-md migrate --help" for the options and the document diagnostic
28
+ format. "format" is not part of this release.
29
+
30
+ Build ${EXIT_CODES.toLowerCase()}
31
+ Lint exit codes: 0 clean, 1 diagnostics, 2 usage or file-read error.
32
+ Migrate exit codes: 0 success, 1 migration needed or blocked, 2 usage or I/O error.
33
+ `;
34
+ }
35
+
36
+ export function buildHelp() {
37
+ return `Usage: reactive-md build <doc.reactive.md> -o <doc.html> [options]
38
+
39
+ Compile one document with the packaged core, optionally validate a parameter
40
+ state file, verify and inline local images, server-render the document with
41
+ React 19, and write one UTF-8 HTML file. The output is assembled through the
42
+ same shareable-HTML shell used by the interactive runtime (CSP, escaped JSON,
43
+ notices and print styles included).
44
+
45
+ Options:
46
+ -o, --output <file> Output HTML path (required). The parent
47
+ directory must already exist.
48
+ --mode <interactive|static> Output mode (default interactive). Static
49
+ output has no runtime script and no
50
+ auto-mount payload.
51
+ --state-file <file.json> Export this validated state as the baseline
52
+ instead of the document's initial values.
53
+ --assets <inline|omit> Image handling (default inline). "omit"
54
+ skips all image reads and leaves the
55
+ renderer's normal alt fallback.
56
+ --asset-root <dir> Extra local directory that relative image
57
+ URLs may resolve inside. URLs and remote
58
+ image roots are not supported.
59
+ --locale <en|zh> UI locale (default en).
60
+ --color-scheme <auto|light|dark>
61
+ Document color scheme (default auto).
62
+ --title <text> Override the document title. By default the
63
+ first heading is rendered as plain text, or
64
+ the input file name is used.
65
+ --strict Treat compile warnings as errors. With
66
+ --assets omit, omitted images also fail.
67
+ -h, --help Show this help.
68
+
69
+ Interactive HTML requires React 19 and react-dom, plus the prebuilt
70
+ dist-standalone IIFE. Every build requires the prebuilt dist-library artifacts.
71
+ From a source checkout, run "npm run build" before building documents.
72
+
73
+ ${EXIT_CODES}
74
+ `;
75
+ }
76
+
77
+ const MIGRATE_HELP = {
78
+ en: `Usage: reactive-md migrate <file | -> [options]
79
+
80
+ Migrate a document's syntax revision metadata. By default the migrated source
81
+ is written to stdout and the input file is left unchanged. Use - for stdin.
82
+
83
+ Options:
84
+ --from <local-draft-1|local-draft-2>
85
+ Source revision to migrate from (default: the
86
+ declared revision, or the current revision
87
+ when none is declared). Unversioned
88
+ historical documents require --from
89
+ local-draft-1.
90
+ --check Report whether migration is needed or
91
+ blocked, without writing output.
92
+ --json Print one structured JSON report. The
93
+ migrated source appears only as a JSON field.
94
+ -o, --output <file> Write the migrated source to a new file.
95
+ Existing files, including the input, are
96
+ refused.
97
+ --accept-semantic-changes Allow migrations that change reader
98
+ semantics, and report a warning.
99
+ --locale <en|zh> Message language (default en).
100
+ -h, --help Show this help.
101
+
102
+ Migration replaces only the metadata comment. It preserves the body, BOM and
103
+ line endings and is idempotent. A blocked migration leaves the source
104
+ unchanged. Migration never rewrites state files; export fresh state after a
105
+ source digest change.
106
+
107
+ Exit codes: 0 success, 1 migration needed or blocked, 2 usage or I/O error.
108
+ `,
109
+ zh: `用法:reactive-md migrate <文件 | -> [选项]
110
+
111
+ 迁移文档的语法修订版本元数据。默认将迁移后的源文本写到标准输出,不修改输入
112
+ 文件。用 - 读取标准输入。
113
+
114
+ 选项:
115
+ --from <local-draft-1|local-draft-2>
116
+ 迁移的起始修订版本(默认取文档声明的版本;
117
+ 未声明时取当前版本)。未声明的历史文档必须
118
+ 指定 --from local-draft-1。
119
+ --check 只报告是否需要迁移或被阻止,不写输出。
120
+ --json 输出一个结构化 JSON 报告。迁移后的源文本
121
+ 只作为 JSON 字段出现。
122
+ -o, --output <文件> 将迁移后的源文本写入新文件。已存在的文件
123
+ (包括输入文件)一律拒绝。
124
+ --accept-semantic-changes 允许会改变读者语义的迁移,并给出警告。
125
+ --locale <en|zh> 消息语言(默认 en)。
126
+ -h, --help 显示此帮助。
127
+
128
+ 迁移只替换元数据注释,保留正文、BOM 和换行符,并且幂等。迁移被阻止时源文本
129
+ 保持不变。迁移不改写状态文件;源摘要变化后请重新导出状态。
130
+
131
+ 退出码:0 成功,1 需要迁移或被阻止,2 用法或 I/O 错误。
132
+ `,
133
+ };
134
+
135
+ /** @param {'en'|'zh'} [locale] */
136
+ export function migrateHelp(locale = 'en') {
137
+ return MIGRATE_HELP[locale === 'zh' ? 'zh' : 'en'];
138
+ }
package/cli/lint.mjs CHANGED
@@ -1,177 +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
- }
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
+ }