@befe/demo-lino 0.0.0-stage → 0.0.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.
- package/README.md +120 -2
- package/bin/lino.ts +224 -0
- package/package.json +40 -4
- package/src/compare.ts +62 -0
- package/src/index.ts +7 -0
- package/src/parse.ts +305 -0
- package/src/stringify.ts +250 -0
- package/src/types.ts +20 -0
package/README.md
CHANGED
|
@@ -1,3 +1,121 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @befe/demo-lino
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
lino 配置格式的原型包:lino 文本与 JSON 互转的解析器、生成器,外加一个 `lino` 命令。
|
|
4
|
+
|
|
5
|
+
- `demo-` 前缀表示原型,语法还在对齐中
|
|
6
|
+
- 语法口径不在本 README,以话题文档为准:ref#file_配置格式设计.261122_zeh7jc5k_ctag.
|
|
7
|
+
|
|
8
|
+
## 安装
|
|
9
|
+
|
|
10
|
+
- 只发在内网 registry,运行要求 bun(>= 1.4.2),包里直接是 `.ts` 源码,没有给 node 用的构建产物
|
|
11
|
+
- 安装
|
|
12
|
+
|
|
13
|
+
```sh
|
|
14
|
+
bun add @befe/demo-lino --registry http://registry.npm.baidu-int.com
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
- 版本口径:`0.0.x` 不承诺兼容
|
|
18
|
+
- 按 semver,`^0.0.1` 只匹配 `0.0.1`,升级要手动改版本号
|
|
19
|
+
- 每次升级都先看发版记录里的语法变化
|
|
20
|
+
- 使用方是 TypeScript 项目时,`tsconfig.json` 要用 `"moduleResolution": "Bundler"`
|
|
21
|
+
- 包里发的是 `.ts` 源码,包内相对 import 不带后缀(如 `./parse`)
|
|
22
|
+
- 用 `NodeNext` / `Node16` 会对这些 import 报 TS2835(要求写明 `.js` 后缀)
|
|
23
|
+
|
|
24
|
+
## 已知限制(0.0.1)
|
|
25
|
+
|
|
26
|
+
- 不接受 CRLF 换行:`parse` 只按 `\n` 分行,带 `\r` 的行会报「认不出这一行」,读之前先把 `\r\n` 换成 `\n`
|
|
27
|
+
- 同理,`stringify` 遇到字符串值或键名里有 `\r`、`\u2028`、`\u2029` 时抛 `TypeError`,因为写出去读不回来
|
|
28
|
+
- 多行文本里 `- ` 行的缩进不规整(奇数格、首个 `- ` 行比后面深)时,`stringify` 可能写出读不回的文本,而且不一定告警
|
|
29
|
+
- 写文件前用 `lino check --from-json <x.json>` 自检,FAIL 就说明这份数据踩到了
|
|
30
|
+
|
|
31
|
+
## API
|
|
32
|
+
|
|
33
|
+
- 对外只有一个入口 `@befe/demo-lino`,不支持深层 import 内部文件
|
|
34
|
+
- 函数:`parse`、`stringify`
|
|
35
|
+
- 错误类:`ParseError`
|
|
36
|
+
- 类型:`LinoConf`(顶层对象)、`LinoValue`(任意值,与 JSON 值对应)、`StringifyOptions`、`LinoWarning`
|
|
37
|
+
|
|
38
|
+
```ts
|
|
39
|
+
import { parse, stringify, ParseError, type LinoConf, type LinoWarning } from '@befe/demo-lino'
|
|
40
|
+
|
|
41
|
+
const conf: LinoConf = parse('* name: Mary\n* age = 12\n')
|
|
42
|
+
// → { name: 'Mary', age: 12 }
|
|
43
|
+
|
|
44
|
+
const warnings: LinoWarning[] = []
|
|
45
|
+
const text = stringify({ name: 'Mary', note: '' }, { onWarning: (w) => warnings.push(w) })
|
|
46
|
+
// text → '* name: Mary\n* note:\n'
|
|
47
|
+
// warnings → [{ path: '$.note', message: '空字符串,写成「键:」不带值,待口径确认' }]
|
|
48
|
+
|
|
49
|
+
try {
|
|
50
|
+
parse('* a:\n * b: 1\n')
|
|
51
|
+
} catch (error) {
|
|
52
|
+
if (error instanceof ParseError) console.error(error.message) // 第 2 行:缩进必须是偶数个空格,这里是 3 个
|
|
53
|
+
}
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
- `parse(text: string): LinoConf`
|
|
57
|
+
- 文本不合语法时抛 `ParseError`,`message` 以「第 N 行:」开头
|
|
58
|
+
- 返回普通对象;`__proto__` 这类键写成可枚举的自有属性,`Object.keys` 能看到,不改原型
|
|
59
|
+
- `stringify(value: LinoConf, options?: StringifyOptions): string`
|
|
60
|
+
- 输出末尾带一个换行;空对象得到 `"\n"`
|
|
61
|
+
- 下面几种情况抛 `TypeError`,`message` 以路径开头(如 `$.a.b:…`)
|
|
62
|
+
- 顶层不是普通对象(数组、null、字符串、`Date` 等)
|
|
63
|
+
- 任意位置出现 `undefined`、函数、symbol、bigint、`NaN`、`Infinity`、稀疏数组的空位、非普通对象、循环引用
|
|
64
|
+
- 字符串值或键名里有 `\r`、`\u2028`、`\u2029`
|
|
65
|
+
- 校验先于生成:抛错时不会已经交出告警
|
|
66
|
+
- 告警:`options.onWarning?: (w: { path: string; message: string }) => void`
|
|
67
|
+
- 输出走了未定口径时(空字符串、数组项里有换行、键名需要引号、多行文本的续行缩进读不回原样等)每条调用一次
|
|
68
|
+
- `path` 写法:`$` 是顶层,`.key` 是对象键,`[0]` 是数组下标,如 `$.upstream[0].name`
|
|
69
|
+
- 不传 `onWarning` 就静默;库函数不写 stderr,每次调用的告警互不串
|
|
70
|
+
|
|
71
|
+
## CLI
|
|
72
|
+
|
|
73
|
+
- 装包后得到命令 `lino`;方向用子命令名区分
|
|
74
|
+
|
|
75
|
+
| 命令 | 方向 | 输出 |
|
|
76
|
+
| --- | --- | --- |
|
|
77
|
+
| `lino to-json <x.lino> [--out f]` | lino → JSON | JSON(2 空格缩进,末尾换行) |
|
|
78
|
+
| `lino from-json <x.json> [--out f]` | JSON → lino | lino 文本;告警逐条写 stderr |
|
|
79
|
+
| `lino check <x.lino>` | lino → 对象 → lino → 对象 | 两次解析结果深比对 |
|
|
80
|
+
| `lino check --from-json <x.json>` | JSON → lino → 对象 | 与原 JSON 严格深比对 |
|
|
81
|
+
| `lino --help` / `-h` | | 帮助;子命令后面加 `-h` / `--help` 也打同一份帮助 |
|
|
82
|
+
| `lino --version` / `-v` | | 版本号(取自 package.json);只认第一个位置,子命令后面的 `-v` 算未知选项 |
|
|
83
|
+
|
|
84
|
+
- 输出分流
|
|
85
|
+
- stdout:转换出的数据;`check` 的 `PASS` / `FAIL` 行与差异明细;`--help`、`--version` 的内容
|
|
86
|
+
- stderr:告警(`告警 $.path:…`)、`--out` 的「已写入」提示、错误信息、用法错误时的帮助
|
|
87
|
+
- `--out f`:把数据写进文件 `f`,stdout 不再输出数据;只有 `to-json`、`from-json` 收这个选项
|
|
88
|
+
- `check` 的差异最多列 20 条,超出的只给条数
|
|
89
|
+
- 示例
|
|
90
|
+
|
|
91
|
+
```sh
|
|
92
|
+
lino from-json conf.json --out conf.lino
|
|
93
|
+
lino to-json conf.lino > conf.json
|
|
94
|
+
lino check conf.lino
|
|
95
|
+
lino check --from-json conf.json
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
## 退出码
|
|
99
|
+
|
|
100
|
+
- `0`:成功;`check` 为 PASS
|
|
101
|
+
- `1`:数据或解析错误
|
|
102
|
+
- 输入文件读不到、JSON 不合法、lino 解析失败、`stringify` 抛 `TypeError`、`--out` 写不了
|
|
103
|
+
- `check` 为 FAIL
|
|
104
|
+
- `2`:用法错误
|
|
105
|
+
- 没有子命令、未知子命令、缺输入文件、多给了输入文件、未知选项、`--out` 后面没给路径
|
|
106
|
+
|
|
107
|
+
## 开发
|
|
108
|
+
|
|
109
|
+
- 目录:`src/` 是库,`bin/lino.ts` 是 CLI,`test/` 是测试与夹具,`bench/` 是基准;发包只带 `src/`、`bin/`、`README.md`
|
|
110
|
+
- 常用命令
|
|
111
|
+
|
|
112
|
+
```sh
|
|
113
|
+
bun install
|
|
114
|
+
bun run typecheck
|
|
115
|
+
bun test
|
|
116
|
+
UPDATE=1 bun test test/fixtures.test.ts # 用当前 stringify 重写夹具的 expected.lino,重写后要人工核对 diff
|
|
117
|
+
bun run bench
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
- 夹具:`test/fixtures/cases/<NN-名字>/` 下一份 `input.json` + 一份 `expected.lino`
|
|
121
|
+
- 断言 `stringify(input)` 与 `expected.lino` 逐字相等、`parse(expected.lino)` 与 `input` 深等
|
package/bin/lino.ts
ADDED
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
#!/usr/bin/env bun
|
|
2
|
+
/**
|
|
3
|
+
* lino 命令行(子命令迁自 demo v1 的转换脚本与 round-trip)
|
|
4
|
+
*
|
|
5
|
+
* 约定:数据只写 stdout;提示、告警、错误写 stderr
|
|
6
|
+
* 退出码:0 成功;1 数据或解析错误(含 check FAIL);2 用法错误
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { readFileSync, writeFileSync } from 'node:fs'
|
|
10
|
+
|
|
11
|
+
import pkg from '../package.json'
|
|
12
|
+
import { compare, type Diff } from '../src/compare'
|
|
13
|
+
import { parse, stringify, type LinoConf, type LinoValue, type LinoWarning } from '../src/index'
|
|
14
|
+
|
|
15
|
+
const HELP = `lino ${pkg.version}:lino 配置文本与 JSON 互转、自检
|
|
16
|
+
|
|
17
|
+
用法:
|
|
18
|
+
lino to-json <x.lino> [--out f] lino → JSON(2 空格缩进,末尾换行)
|
|
19
|
+
lino from-json <x.json> [--out f] JSON → lino;告警逐条写 stderr
|
|
20
|
+
lino check <x.lino> parse → stringify → parse,两次结果深比对
|
|
21
|
+
lino check --from-json <x.json> stringify → parse,与原 JSON 严格深比对
|
|
22
|
+
lino --help | -h 显示本帮助(子命令后面加 -h / --help 也显示本帮助)
|
|
23
|
+
lino --version | -v 显示版本(只认第一个位置)
|
|
24
|
+
|
|
25
|
+
输出:数据写 stdout;check 的 PASS/FAIL 与差异写 stdout;提示、告警、错误写 stderr
|
|
26
|
+
退出码:0 成功;1 数据或解析错误(含 check FAIL);2 用法错误
|
|
27
|
+
`
|
|
28
|
+
|
|
29
|
+
const MAX_DIFFS = 20
|
|
30
|
+
|
|
31
|
+
class UsageError extends Error {}
|
|
32
|
+
|
|
33
|
+
/** 数据或解析错误,对应退出码 1 */
|
|
34
|
+
class DataError extends Error {}
|
|
35
|
+
|
|
36
|
+
interface Io {
|
|
37
|
+
out: (text: string) => void
|
|
38
|
+
err: (text: string) => void
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
interface CommandArgs {
|
|
42
|
+
input: string
|
|
43
|
+
out?: string
|
|
44
|
+
fromJson: boolean
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function parseCommandArgs(command: string, argv: string[]): CommandArgs {
|
|
48
|
+
const allowOut = command !== 'check'
|
|
49
|
+
const allowFromJson = command === 'check'
|
|
50
|
+
let input: string | undefined
|
|
51
|
+
let out: string | undefined
|
|
52
|
+
let fromJson = false
|
|
53
|
+
|
|
54
|
+
for (let index = 0; index < argv.length; index += 1) {
|
|
55
|
+
const arg = argv[index]!
|
|
56
|
+
if (arg === '--out' && allowOut) {
|
|
57
|
+
const value = argv[index + 1]
|
|
58
|
+
if (!value || value.startsWith('-')) throw new UsageError('--out 后面要给一个路径')
|
|
59
|
+
out = value
|
|
60
|
+
index += 1
|
|
61
|
+
continue
|
|
62
|
+
}
|
|
63
|
+
if (arg === '--from-json' && allowFromJson) {
|
|
64
|
+
fromJson = true
|
|
65
|
+
continue
|
|
66
|
+
}
|
|
67
|
+
if (arg.startsWith('-')) throw new UsageError(`${command} 不认识的选项:${arg}`)
|
|
68
|
+
if (input !== undefined) throw new UsageError(`只能给一个输入文件,这里是「${input}」和「${arg}」`)
|
|
69
|
+
input = arg
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
if (input === undefined) throw new UsageError(`${command} 缺少输入文件`)
|
|
73
|
+
return { input, out, fromJson }
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function readInput(path: string): string {
|
|
77
|
+
try {
|
|
78
|
+
return readFileSync(path, 'utf8')
|
|
79
|
+
} catch (error) {
|
|
80
|
+
throw new DataError(`读不到输入文件:${(error as Error).message}`)
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function readJson(path: string): unknown {
|
|
85
|
+
const text = readInput(path)
|
|
86
|
+
try {
|
|
87
|
+
return JSON.parse(text)
|
|
88
|
+
} catch (error) {
|
|
89
|
+
throw new DataError(`读不懂输入的 JSON:${(error as Error).message}`)
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function parseLino(text: string, label: string): LinoConf {
|
|
94
|
+
try {
|
|
95
|
+
return parse(text)
|
|
96
|
+
} catch (error) {
|
|
97
|
+
throw new DataError(`${label}:${(error as Error).message}`)
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function stringifyLino(value: unknown, io: Io): string {
|
|
102
|
+
try {
|
|
103
|
+
return stringify(value as LinoConf, { onWarning: (warning) => printWarning(warning, io) })
|
|
104
|
+
} catch (error) {
|
|
105
|
+
throw new DataError(`转换失败:${(error as Error).message}`)
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function printWarning(warning: LinoWarning, io: Io): void {
|
|
110
|
+
io.err(`告警 ${warning.path}:${warning.message}\n`)
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function emit(text: string, outPath: string | undefined, io: Io): void {
|
|
114
|
+
if (!outPath) {
|
|
115
|
+
io.out(text)
|
|
116
|
+
return
|
|
117
|
+
}
|
|
118
|
+
try {
|
|
119
|
+
writeFileSync(outPath, text)
|
|
120
|
+
} catch (error) {
|
|
121
|
+
throw new DataError(`写不了 ${outPath}:${(error as Error).message}`)
|
|
122
|
+
}
|
|
123
|
+
io.err(`已写入 ${outPath}\n`)
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
function reportDiffs(diffs: Diff[], io: Io): void {
|
|
127
|
+
io.out(`FAIL ${diffs.length} 处不一致:\n`)
|
|
128
|
+
for (const diff of diffs.slice(0, MAX_DIFFS)) {
|
|
129
|
+
io.out(`- ${diff.path}:期望 ${diff.expected},实际 ${diff.actual}\n`)
|
|
130
|
+
}
|
|
131
|
+
if (diffs.length > MAX_DIFFS) io.out(`- …还有 ${diffs.length - MAX_DIFFS} 处\n`)
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
function runToJson(args: CommandArgs, io: Io): number {
|
|
135
|
+
const value = parseLino(readInput(args.input), '解析失败')
|
|
136
|
+
emit(`${JSON.stringify(value, null, 2)}\n`, args.out, io)
|
|
137
|
+
return 0
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
function runFromJson(args: CommandArgs, io: Io): number {
|
|
141
|
+
const text = stringifyLino(readJson(args.input), io)
|
|
142
|
+
emit(text, args.out, io)
|
|
143
|
+
return 0
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
function runCheck(args: CommandArgs, io: Io): number {
|
|
147
|
+
let expected: LinoValue
|
|
148
|
+
let text: string
|
|
149
|
+
if (args.fromJson) {
|
|
150
|
+
// 等价 v1 round-trip:JSON → lino → 再解析,与原 JSON 严格深比对
|
|
151
|
+
const source = readJson(args.input)
|
|
152
|
+
text = stringifyLino(source, io)
|
|
153
|
+
expected = source as LinoValue
|
|
154
|
+
} else {
|
|
155
|
+
// lino → 对象 → lino → 再解析,比两次解析结果
|
|
156
|
+
expected = parseLino(readInput(args.input), '解析失败')
|
|
157
|
+
text = stringifyLino(expected, io)
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
let actual: LinoConf
|
|
161
|
+
try {
|
|
162
|
+
actual = parse(text)
|
|
163
|
+
} catch (error) {
|
|
164
|
+
io.out(`FAIL 生成的文本读不回来:${(error as Error).message}\n`)
|
|
165
|
+
return 1
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
const diffs = compare(expected, actual)
|
|
169
|
+
if (diffs.length === 0) {
|
|
170
|
+
io.out('PASS roundtrip 一致\n')
|
|
171
|
+
return 0
|
|
172
|
+
}
|
|
173
|
+
reportDiffs(diffs, io)
|
|
174
|
+
return 1
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
const COMMANDS: { [name: string]: (args: CommandArgs, io: Io) => number } = {
|
|
178
|
+
'to-json': runToJson,
|
|
179
|
+
'from-json': runFromJson,
|
|
180
|
+
check: runCheck,
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
function main(argv: string[], io: Io): number {
|
|
184
|
+
const [command, ...rest] = argv
|
|
185
|
+
// 全局的 --help / --version 只在第一个位置认
|
|
186
|
+
if (command === '--help' || command === '-h') {
|
|
187
|
+
io.out(HELP)
|
|
188
|
+
return 0
|
|
189
|
+
}
|
|
190
|
+
if (command === '--version' || command === '-v') {
|
|
191
|
+
io.out(`${pkg.version}\n`)
|
|
192
|
+
return 0
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
try {
|
|
196
|
+
if (command === undefined) throw new UsageError('缺少子命令')
|
|
197
|
+
const run = Object.hasOwn(COMMANDS, command) ? COMMANDS[command] : undefined
|
|
198
|
+
if (!run) throw new UsageError(`不认识的子命令:${command}`)
|
|
199
|
+
// 子命令后面的 -h / --help 打总帮助;-v / --version 在这里不认,交给参数解析报未知选项
|
|
200
|
+
if (rest.includes('--help') || rest.includes('-h')) {
|
|
201
|
+
io.out(HELP)
|
|
202
|
+
return 0
|
|
203
|
+
}
|
|
204
|
+
return run(parseCommandArgs(command, rest), io)
|
|
205
|
+
} catch (error) {
|
|
206
|
+
if (error instanceof UsageError) {
|
|
207
|
+
io.err(`${error.message}\n\n${HELP}`)
|
|
208
|
+
return 2
|
|
209
|
+
}
|
|
210
|
+
if (error instanceof DataError) {
|
|
211
|
+
io.err(`${error.message}\n`)
|
|
212
|
+
return 1
|
|
213
|
+
}
|
|
214
|
+
io.err(`出错了:${(error as Error).message}\n`)
|
|
215
|
+
return 1
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
if (import.meta.main) {
|
|
220
|
+
process.exitCode = main(process.argv.slice(2), {
|
|
221
|
+
out: (text) => process.stdout.write(text),
|
|
222
|
+
err: (text) => process.stderr.write(text),
|
|
223
|
+
})
|
|
224
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,42 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@befe/demo-lino",
|
|
3
|
-
"version": "0.0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.0.1",
|
|
4
|
+
"description": "lino 配置格式原型:lino 文本与 JSON 互转的解析器、生成器和 lino 命令行",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"exports": {
|
|
7
|
+
".": "./src/index.ts",
|
|
8
|
+
"./package.json": "./package.json"
|
|
9
|
+
},
|
|
10
|
+
"main": "./src/index.ts",
|
|
11
|
+
"types": "./src/index.ts",
|
|
12
|
+
"bin": {
|
|
13
|
+
"lino": "./bin/lino.ts"
|
|
14
|
+
},
|
|
15
|
+
"files": [
|
|
16
|
+
"src",
|
|
17
|
+
"bin",
|
|
18
|
+
"README.md"
|
|
19
|
+
],
|
|
20
|
+
"scripts": {
|
|
21
|
+
"typecheck": "tsc --noEmit",
|
|
22
|
+
"test": "bun test test/",
|
|
23
|
+
"bench": "bun bench/bench.ts",
|
|
24
|
+
"prepack": "bun run typecheck && bun run test"
|
|
25
|
+
},
|
|
26
|
+
"engines": {
|
|
27
|
+
"bun": ">=1.4.2"
|
|
28
|
+
},
|
|
29
|
+
"publishConfig": {
|
|
30
|
+
"registry": "http://registry.npm.baidu-int.com"
|
|
31
|
+
},
|
|
32
|
+
"repository": {
|
|
33
|
+
"type": "git",
|
|
34
|
+
"url": "ssh://git@icode.baidu.com:8235/baidu/erp/fin-dev-agent",
|
|
35
|
+
"directory": "projects/工作区迭代优化/工作区迭代优化-vaults/2611/demo_lino包.261122_hsrwjncm_ctag/demo-lino"
|
|
36
|
+
},
|
|
37
|
+
"license": "UNLICENSED",
|
|
38
|
+
"devDependencies": {
|
|
39
|
+
"@types/bun": "^1.4.5",
|
|
40
|
+
"typescript": "^5.9.3"
|
|
41
|
+
}
|
|
42
|
+
}
|
package/src/compare.ts
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 深比对(迁自 demo v1 的 compare-json.ts):按路径报差异,类型不同也算不一致
|
|
3
|
+
* 只返回差异数据、不打印;包内部用(lino check),不从 index 导出
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import type { LinoValue } from './types'
|
|
7
|
+
|
|
8
|
+
export interface Diff {
|
|
9
|
+
path: string
|
|
10
|
+
expected: string
|
|
11
|
+
actual: string
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
const MISSING = '(没有这个键)'
|
|
15
|
+
|
|
16
|
+
export function show(value: LinoValue | undefined): string {
|
|
17
|
+
if (value === undefined) return MISSING
|
|
18
|
+
return JSON.stringify(value)
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function compare(expected: LinoValue, actual: LinoValue, path = '$', diffs: Diff[] = []): Diff[] {
|
|
22
|
+
if (Array.isArray(expected) || Array.isArray(actual)) {
|
|
23
|
+
if (!Array.isArray(expected) || !Array.isArray(actual)) {
|
|
24
|
+
diffs.push({ path, expected: show(expected), actual: show(actual) })
|
|
25
|
+
return diffs
|
|
26
|
+
}
|
|
27
|
+
if (expected.length !== actual.length) {
|
|
28
|
+
diffs.push({ path: `${path}.length`, expected: `${expected.length}`, actual: `${actual.length}` })
|
|
29
|
+
}
|
|
30
|
+
const length = Math.min(expected.length, actual.length)
|
|
31
|
+
for (let index = 0; index < length; index += 1) {
|
|
32
|
+
compare(expected[index]!, actual[index]!, `${path}[${index}]`, diffs)
|
|
33
|
+
}
|
|
34
|
+
return diffs
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
if (typeof expected === 'object' && expected !== null && typeof actual === 'object' && actual !== null) {
|
|
38
|
+
const expectedKeys = Object.keys(expected)
|
|
39
|
+
const actualKeys = Object.keys(actual)
|
|
40
|
+
|
|
41
|
+
for (const key of expectedKeys) {
|
|
42
|
+
if (!actualKeys.includes(key)) {
|
|
43
|
+
diffs.push({ path: `${path}.${key}`, expected: show(expected[key]), actual: MISSING })
|
|
44
|
+
continue
|
|
45
|
+
}
|
|
46
|
+
compare(expected[key]!, actual[key]!, `${path}.${key}`, diffs)
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
for (const key of actualKeys) {
|
|
50
|
+
if (!expectedKeys.includes(key)) {
|
|
51
|
+
diffs.push({ path: `${path}.${key}`, expected: MISSING, actual: show(actual[key]) })
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
return diffs
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
if (expected !== actual || typeof expected !== typeof actual) {
|
|
58
|
+
diffs.push({ path, expected: show(expected), actual: show(actual) })
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
return diffs
|
|
62
|
+
}
|
package/src/index.ts
ADDED
package/src/parse.ts
ADDED
|
@@ -0,0 +1,305 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* lino 文本 → 对象(迁自 demo v1 的解析器,语法行为不变)
|
|
3
|
+
*
|
|
4
|
+
* 认的写法:
|
|
5
|
+
* * 键: 值 → 字符串
|
|
6
|
+
* * 键 = 12 → 数字 / true / false / null / 带引号的字符串
|
|
7
|
+
* * 键 = [] → 数组,子项 * : 值 / * = 值 / * = [] / * : 对象 / * = {}
|
|
8
|
+
* * 键 = {} → 空对象
|
|
9
|
+
* * 键: → 对象(下面挂 * 子键)或多行文本(下面挂 - / +)
|
|
10
|
+
* * : 值 → 数组项字符串;* : 起对象项;* = [] / * = {} 起容器项
|
|
11
|
+
* * // … → 注释(// 后须是空格或行尾),跳过
|
|
12
|
+
* * $$xxx → 预设字段,跳过(不校验位置)
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import type { LinoConf, LinoValue } from './types'
|
|
16
|
+
|
|
17
|
+
const INDENT = ' '
|
|
18
|
+
const NUMBER_PATTERN = /^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?$/
|
|
19
|
+
|
|
20
|
+
interface Line {
|
|
21
|
+
indent: number
|
|
22
|
+
marker: '*' | '-' | '+'
|
|
23
|
+
text: string
|
|
24
|
+
lineNo: number
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
interface Node extends Line {
|
|
28
|
+
children: Node[]
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** 文本不合语法时抛出;message 形如 `第 3 行:…` */
|
|
32
|
+
export class ParseError extends Error {
|
|
33
|
+
constructor(message: string) {
|
|
34
|
+
super(message)
|
|
35
|
+
this.name = 'ParseError'
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function fail(lineNo: number, message: string): ParseError {
|
|
40
|
+
return new ParseError(`第 ${lineNo} 行:${message}`)
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function isComment(text: string): boolean {
|
|
44
|
+
// `//` 后面必须是空格或行尾,这样 `//x: 1` 这种键名还能用
|
|
45
|
+
return /^\/\/(\s|$)/.test(text)
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* 写成可枚举的自有属性:普通对象上直接赋 `__proto__` 会走 setter 改原型,
|
|
50
|
+
* 用 defineProperty 才能让它出现在 Object.keys 里且不污染原型
|
|
51
|
+
*/
|
|
52
|
+
function setKey(target: LinoConf, key: string, value: LinoValue): void {
|
|
53
|
+
if (key === '__proto__') {
|
|
54
|
+
Object.defineProperty(target, key, { value, enumerable: true, writable: true, configurable: true })
|
|
55
|
+
return
|
|
56
|
+
}
|
|
57
|
+
target[key] = value
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function toLines(text: string): Line[] {
|
|
61
|
+
const lines: Line[] = []
|
|
62
|
+
|
|
63
|
+
text.split('\n').forEach((raw, index) => {
|
|
64
|
+
// 只把行首的 tab 展开成两格,行内的 tab 属于文本,原样保留
|
|
65
|
+
const leadingMatch = /^[ \t]*/.exec(raw)!
|
|
66
|
+
const indentRaw = leadingMatch[0]
|
|
67
|
+
const indent = indentRaw.replace(/\t/g, ' ').length
|
|
68
|
+
const rest = raw.slice(indentRaw.length)
|
|
69
|
+
|
|
70
|
+
if (rest.trim() === '') return
|
|
71
|
+
if (indent % 2 !== 0) {
|
|
72
|
+
throw fail(index + 1, `缩进必须是偶数个空格,这里是 ${indent} 个`)
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
const match = /^([*+-])(?:\s(.*))?$/.exec(rest)
|
|
76
|
+
if (!match) {
|
|
77
|
+
throw fail(index + 1, `认不出这一行:${raw}`)
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
lines.push({
|
|
81
|
+
indent,
|
|
82
|
+
marker: match[1] as '*' | '-' | '+',
|
|
83
|
+
text: match[2] ?? '',
|
|
84
|
+
lineNo: index + 1,
|
|
85
|
+
})
|
|
86
|
+
})
|
|
87
|
+
|
|
88
|
+
return lines
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function buildTree(lines: Line[]): Node[] {
|
|
92
|
+
const root: Node = { indent: -1, marker: '*', text: '', lineNo: 0, children: [] }
|
|
93
|
+
const stack: Node[] = [root]
|
|
94
|
+
|
|
95
|
+
for (const line of lines) {
|
|
96
|
+
while (stack.length > 1 && line.indent <= stack[stack.length - 1]!.indent) stack.pop()
|
|
97
|
+
const node: Node = { ...line, children: [] }
|
|
98
|
+
stack[stack.length - 1]!.children.push(node)
|
|
99
|
+
stack.push(node)
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
const check = (node: Node): void => {
|
|
103
|
+
const first = node.children[0]
|
|
104
|
+
if (first) {
|
|
105
|
+
for (const child of node.children) {
|
|
106
|
+
if (child.indent !== first.indent) {
|
|
107
|
+
throw fail(child.lineNo, `同一层的缩进必须一致:这里 ${child.indent} 格,同层首个是 ${first.indent} 格`)
|
|
108
|
+
}
|
|
109
|
+
if (child.indent <= node.indent) {
|
|
110
|
+
throw fail(child.lineNo, `子项的缩进必须比上一级更深:${child.indent} 格`)
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
node.children.forEach(check)
|
|
115
|
+
}
|
|
116
|
+
check(root)
|
|
117
|
+
|
|
118
|
+
return root.children
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function splitField(node: Node): { key: string; separator: ':' | '='; value: string } {
|
|
122
|
+
const colon = node.text.indexOf(':')
|
|
123
|
+
const equal = node.text.indexOf('=')
|
|
124
|
+
let index = -1
|
|
125
|
+
let separator: ':' | '=' = ':'
|
|
126
|
+
|
|
127
|
+
if (colon >= 0 && equal >= 0) {
|
|
128
|
+
if (colon < equal) {
|
|
129
|
+
index = colon
|
|
130
|
+
separator = ':'
|
|
131
|
+
} else {
|
|
132
|
+
index = equal
|
|
133
|
+
separator = '='
|
|
134
|
+
}
|
|
135
|
+
} else if (colon >= 0) {
|
|
136
|
+
index = colon
|
|
137
|
+
} else if (equal >= 0) {
|
|
138
|
+
index = equal
|
|
139
|
+
separator = '='
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
if (index < 0) throw fail(node.lineNo, `没有 : 或 = 分隔符:${node.text}`)
|
|
143
|
+
|
|
144
|
+
const key = node.text.slice(0, index).trim()
|
|
145
|
+
const rest = node.text.slice(index + 1)
|
|
146
|
+
const value = rest.startsWith(' ') ? rest.slice(1) : rest
|
|
147
|
+
return { key, separator, value }
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* 符号后面只吃掉一个空格,这个空格在 toLines 里已经去掉,剩下的都算文本
|
|
152
|
+
* 所以这里不再做任何 trim,否则 `- item` 会被多剥一层
|
|
153
|
+
*/
|
|
154
|
+
function textOf(node: Node): string {
|
|
155
|
+
return node.text
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* 多行文本:- 与 + 都能在同一字段下出现、可以混排
|
|
160
|
+
* - 行连符号一起进值;+ 行只进文本,不带 + 号
|
|
161
|
+
* 层级都按缩进算,基准取父行下首个 item 的缩进,每两格一层
|
|
162
|
+
* 块里有 `-` 时,+ 行在层级缩进之外再补两格,文字与 `- ` 后面的内容对齐;整块都是 + 则不补
|
|
163
|
+
*/
|
|
164
|
+
function collectTextLines(hasBullet: boolean, baseIndent: number, nodes: Node[], out: string[]): void {
|
|
165
|
+
for (const node of nodes) {
|
|
166
|
+
if (node.marker !== '-' && node.marker !== '+') {
|
|
167
|
+
throw fail(node.lineNo, '多行文本下面只能是 - 或 + 行')
|
|
168
|
+
}
|
|
169
|
+
if (!hasBullet) {
|
|
170
|
+
// 纯文本块:不折层级,缩进原样留在文本里
|
|
171
|
+
out.push(textOf(node))
|
|
172
|
+
} else {
|
|
173
|
+
const level = Math.max(0, Math.round((node.indent - baseIndent) / 2))
|
|
174
|
+
const head = node.marker === '-' ? '- ' : ' '
|
|
175
|
+
out.push(`${INDENT.repeat(level)}${head}${textOf(node)}`)
|
|
176
|
+
}
|
|
177
|
+
collectTextLines(hasBullet, baseIndent, node.children, out)
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/**
|
|
182
|
+
* 带引号的字符串:首尾是同一对 `'` 或 `"` 才算,剥掉引号并解转义
|
|
183
|
+
* 不是引号包裹就返回 null,交给调用方按裸文本处理
|
|
184
|
+
*/
|
|
185
|
+
function decodeQuoted(raw: string): string | null {
|
|
186
|
+
if (raw.length < 2) return null
|
|
187
|
+
const head = raw[0]
|
|
188
|
+
if ((head !== '"' && head !== "'") || !raw.endsWith(head)) return null
|
|
189
|
+
|
|
190
|
+
const body = raw.slice(1, -1)
|
|
191
|
+
let out = ''
|
|
192
|
+
for (let index = 0; index < body.length; index += 1) {
|
|
193
|
+
const char = body[index]
|
|
194
|
+
if (char === '\\' && index + 1 < body.length) {
|
|
195
|
+
const next = body[index + 1]
|
|
196
|
+
if (next === 'n') {
|
|
197
|
+
out += '\n'
|
|
198
|
+
index += 1
|
|
199
|
+
continue
|
|
200
|
+
}
|
|
201
|
+
if (next === 't') {
|
|
202
|
+
out += '\t'
|
|
203
|
+
index += 1
|
|
204
|
+
continue
|
|
205
|
+
}
|
|
206
|
+
if (next === '"' || next === "'" || next === '\\') {
|
|
207
|
+
out += next
|
|
208
|
+
index += 1
|
|
209
|
+
continue
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
out += char
|
|
213
|
+
}
|
|
214
|
+
return out
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
function parseTypedValue(node: Node, value: string): LinoValue {
|
|
218
|
+
if (value === '[]') return node.children.map((child) => parseItem(child))
|
|
219
|
+
if (value === '{}') {
|
|
220
|
+
if (node.children.length > 0) throw fail(node.lineNo, '= {} 后面不应有子项')
|
|
221
|
+
return {}
|
|
222
|
+
}
|
|
223
|
+
if (value === 'null') return null
|
|
224
|
+
if (value === 'true') return true
|
|
225
|
+
if (value === 'false') return false
|
|
226
|
+
if (NUMBER_PATTERN.test(value)) return Number(value)
|
|
227
|
+
|
|
228
|
+
const quoted = decodeQuoted(value)
|
|
229
|
+
if (quoted !== null) return quoted
|
|
230
|
+
|
|
231
|
+
throw fail(node.lineNo, `= 后面只认数字 / true / false / null / [] / {} / 带引号的字符串:${value}`)
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
function parseItem(node: Node): LinoValue {
|
|
235
|
+
if (node.marker !== '*') throw fail(node.lineNo, '数组项必须以 * 起头')
|
|
236
|
+
const head = node.text[0]
|
|
237
|
+
const rest = node.text.slice(1)
|
|
238
|
+
const value = rest.startsWith(' ') ? rest.slice(1) : rest
|
|
239
|
+
|
|
240
|
+
// 数字 / 布尔 / 容器项写 = ,字符串项写 :;两者都能进数组
|
|
241
|
+
if (head === '=') return parseTypedValue(node, value)
|
|
242
|
+
|
|
243
|
+
if (head !== ':') throw fail(node.lineNo, `数组项要写成「* : 值」或「* = 值」:${node.text}`)
|
|
244
|
+
if (value !== '') {
|
|
245
|
+
// `* : []` 是字符串 "[]",不是容器;容器一律走 `* = []`
|
|
246
|
+
if (node.children.length > 0) {
|
|
247
|
+
throw fail(node.lineNo, `这一项已经有值「${value}」,下面不能再挂子项`)
|
|
248
|
+
}
|
|
249
|
+
// `: ` 后面的值一律原样,引号与转义都不解释;要定界就走 `* = "…"`
|
|
250
|
+
return value
|
|
251
|
+
}
|
|
252
|
+
if (node.children.length === 0) return ''
|
|
253
|
+
return parseObject(node.children)
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
function parseObject(nodes: Node[]): LinoConf {
|
|
257
|
+
const result: LinoConf = {}
|
|
258
|
+
|
|
259
|
+
for (const node of nodes) {
|
|
260
|
+
if (node.marker !== '*') throw fail(node.lineNo, '对象里只能出现 * 行')
|
|
261
|
+
if (isComment(node.text)) continue
|
|
262
|
+
if (node.text.startsWith('$$')) continue
|
|
263
|
+
|
|
264
|
+
const { key, separator, value } = splitField(node)
|
|
265
|
+
if (key === '') throw fail(node.lineNo, '对象里的键不能为空')
|
|
266
|
+
|
|
267
|
+
if (separator === '=') {
|
|
268
|
+
setKey(result, key, parseTypedValue(node, value))
|
|
269
|
+
continue
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
if (value !== '') {
|
|
273
|
+
if (node.children.length > 0) {
|
|
274
|
+
throw fail(node.lineNo, `这一项已经有值「${value}」,下面不能再挂子项`)
|
|
275
|
+
}
|
|
276
|
+
// `: ` 后面的值一律原样,引号与转义都不解释;要定界就走 `= "…"`
|
|
277
|
+
setKey(result, key, value)
|
|
278
|
+
continue
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
const firstChild = node.children[0]
|
|
282
|
+
if (!firstChild) {
|
|
283
|
+
setKey(result, key, '')
|
|
284
|
+
continue
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
const allText = node.children.every((child) => child.marker === '-' || child.marker === '+')
|
|
288
|
+
if (allText) {
|
|
289
|
+
const lines: string[] = []
|
|
290
|
+
const hasBullet = node.children.some((child) => child.marker === '-')
|
|
291
|
+
// 首个 item 的缩进当基准,整块被多缩进几格也不影响层级
|
|
292
|
+
collectTextLines(hasBullet, firstChild.indent, node.children, lines)
|
|
293
|
+
setKey(result, key, lines.join('\n'))
|
|
294
|
+
continue
|
|
295
|
+
}
|
|
296
|
+
setKey(result, key, parseObject(node.children))
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
return result
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
/** lino 文本 → 顶层对象;不合语法时抛 ParseError */
|
|
303
|
+
export function parse(text: string): LinoConf {
|
|
304
|
+
return parseObject(buildTree(toLines(text)))
|
|
305
|
+
}
|
package/src/stringify.ts
ADDED
|
@@ -0,0 +1,250 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 对象 → lino 文本(迁自 demo v1 的生成器,输出逐字不变)
|
|
3
|
+
*
|
|
4
|
+
* 与 v1 的差别只在接口:
|
|
5
|
+
* - 告警不再进模块级数组,改由 options.onWarning 逐条交出,不传就不输出
|
|
6
|
+
* - 先整体校验一遍,非法值抛 TypeError(带路径),校验通过才开始生成
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import type { LinoConf, LinoValue, StringifyOptions } from './types'
|
|
10
|
+
|
|
11
|
+
const INDENT = ' '
|
|
12
|
+
|
|
13
|
+
const RESERVED_KEYS = new Set(['__proto__', 'constructor', 'prototype'])
|
|
14
|
+
|
|
15
|
+
type Warn = (path: string, message: string) => void
|
|
16
|
+
|
|
17
|
+
function needsQuote(key: string): boolean {
|
|
18
|
+
return (
|
|
19
|
+
key === '' ||
|
|
20
|
+
/[:#=\s]/.test(key) ||
|
|
21
|
+
key.trim() !== key ||
|
|
22
|
+
key.startsWith('$') ||
|
|
23
|
+
key.startsWith('//') ||
|
|
24
|
+
RESERVED_KEYS.has(key)
|
|
25
|
+
)
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function formatKey(key: string, path: string, warn: Warn): string {
|
|
29
|
+
if (needsQuote(key)) {
|
|
30
|
+
// 不做键名引号:引号与转义都没定口径,先原样输出并提示
|
|
31
|
+
warn(path, `键名「${key}」含 : # = 空白、以 $ 或 // 开头、或是保留字,原样输出,读回来可能歧义或丢失`)
|
|
32
|
+
}
|
|
33
|
+
return key
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* 值要不要走 `= "…"`:只有首尾带空白才需要——`:` 那侧不解释引号,以引号开头没有歧义
|
|
38
|
+
* 定界写法统一双引号,反斜杠、双引号、换行、制表符转义
|
|
39
|
+
*/
|
|
40
|
+
function needsQuotedValue(value: string): boolean {
|
|
41
|
+
return value !== value.trim()
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function encodeString(value: string): string {
|
|
45
|
+
const escaped = value.replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/\n/g, '\\n').replace(/\t/g, '\\t')
|
|
46
|
+
return `"${escaped}"`
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function emitMultiLine(key: string, text: string, depth: number, path: string, warn: Warn): string[] {
|
|
50
|
+
const pad = INDENT.repeat(depth)
|
|
51
|
+
const segments = text.split('\n')
|
|
52
|
+
const lines = [`${pad}* ${key}:`]
|
|
53
|
+
// 块里有 `- ` 的话,续行的值会多两格与 `- ` 的文字对齐,这里先把那两格扣掉再折层级
|
|
54
|
+
const hasBullet = segments.some((segment) => /^ *- /.test(segment))
|
|
55
|
+
|
|
56
|
+
segments.forEach((segment, index) => {
|
|
57
|
+
if (!hasBullet) {
|
|
58
|
+
// 纯文本块:不折层级,原样写进 `+` 行,行首空格属于文本
|
|
59
|
+
lines.push(`${INDENT.repeat(depth + 1)}+ ${segment}`)
|
|
60
|
+
return
|
|
61
|
+
}
|
|
62
|
+
const outline = /^( *)- (.*)$/.exec(segment)
|
|
63
|
+
if (outline) {
|
|
64
|
+
const level = Math.floor(outline[1]!.length / 2)
|
|
65
|
+
lines.push(`${INDENT.repeat(depth + 1 + level)}- ${outline[2]}`)
|
|
66
|
+
return
|
|
67
|
+
}
|
|
68
|
+
const leading = /^ */.exec(segment)?.[0].length ?? 0
|
|
69
|
+
// 读回来的续行总是「层级 × 2 + 2」格前导空格;不是 ≥2 的偶数就还原不了
|
|
70
|
+
// 以 `-` 开头但后面不是空格的行(如 `-b`)前导是 0 格,也落在这里
|
|
71
|
+
if (leading < 2 || leading % 2 !== 0) {
|
|
72
|
+
warn(path, `多行文本第 ${index + 1} 行「${segment}」的续行缩进不是 ≥2 的偶数格,读回来会变`)
|
|
73
|
+
}
|
|
74
|
+
const level = Math.max(0, Math.floor((leading - 2) / 2))
|
|
75
|
+
lines.push(`${INDENT.repeat(depth + 1 + level)}+ ${segment.slice(leading)}`)
|
|
76
|
+
})
|
|
77
|
+
return lines
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** 数组项一行一项;v1 的 emitArray 与 emitArrayBody 逻辑相同,这里合成一个 */
|
|
81
|
+
function emitArrayBody(items: LinoValue[], depth: number, path: string, warn: Warn): string[] {
|
|
82
|
+
const inner = INDENT.repeat(depth)
|
|
83
|
+
const lines: string[] = []
|
|
84
|
+
items.forEach((item, index) => {
|
|
85
|
+
const itemPath = `${path}[${index}]`
|
|
86
|
+
if (item === null) {
|
|
87
|
+
lines.push(`${inner}* = null`)
|
|
88
|
+
return
|
|
89
|
+
}
|
|
90
|
+
if (typeof item === 'string') {
|
|
91
|
+
if (item.includes('\n')) {
|
|
92
|
+
warn(itemPath, '数组项是带换行的字符串,会压成一行')
|
|
93
|
+
}
|
|
94
|
+
const flat = item.replace(/\n/g, ' ')
|
|
95
|
+
if (needsQuotedValue(flat)) {
|
|
96
|
+
lines.push(`${inner}* = ${encodeString(flat)}`)
|
|
97
|
+
} else {
|
|
98
|
+
lines.push(`${inner}* : ${flat}`)
|
|
99
|
+
}
|
|
100
|
+
return
|
|
101
|
+
}
|
|
102
|
+
// 数字与布尔项写 = ,否则读回来会变成字符串
|
|
103
|
+
if (typeof item === 'number' || typeof item === 'boolean') {
|
|
104
|
+
lines.push(`${inner}* = ${item}`)
|
|
105
|
+
return
|
|
106
|
+
}
|
|
107
|
+
// 嵌套数组项写 * = [],与类型值的 = 分工一致
|
|
108
|
+
if (Array.isArray(item)) {
|
|
109
|
+
lines.push(`${inner}* = []`)
|
|
110
|
+
lines.push(...emitArrayBody(item, depth + 1, itemPath, warn))
|
|
111
|
+
return
|
|
112
|
+
}
|
|
113
|
+
// 对象项:有子键就写 * : 再挂子项,空对象才写 * = {}
|
|
114
|
+
if (Object.keys(item).length === 0) {
|
|
115
|
+
lines.push(`${inner}* = {}`)
|
|
116
|
+
return
|
|
117
|
+
}
|
|
118
|
+
lines.push(`${inner}* :`)
|
|
119
|
+
lines.push(...emitObjectBody(item, depth + 1, itemPath, warn))
|
|
120
|
+
})
|
|
121
|
+
return lines
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function emitObjectBody(obj: LinoConf, depth: number, path: string, warn: Warn): string[] {
|
|
125
|
+
const lines: string[] = []
|
|
126
|
+
for (const [key, value] of Object.entries(obj)) {
|
|
127
|
+
lines.push(...emitField(key, value, depth, `${path}.${key}`, warn))
|
|
128
|
+
}
|
|
129
|
+
return lines
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
function emitField(key: string, value: LinoValue, depth: number, path: string, warn: Warn): string[] {
|
|
133
|
+
const pad = INDENT.repeat(depth)
|
|
134
|
+
const name = formatKey(key, path, warn)
|
|
135
|
+
|
|
136
|
+
if (value === null) {
|
|
137
|
+
return [`${pad}* ${name} = null`]
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
if (typeof value === 'string') {
|
|
141
|
+
if (value === '') {
|
|
142
|
+
// 空字符串用「冒号后留空、下面不挂子项」表示,读回来是空字符串
|
|
143
|
+
warn(path, '空字符串,写成「键:」不带值,待口径确认')
|
|
144
|
+
return [`${pad}* ${name}:`]
|
|
145
|
+
}
|
|
146
|
+
if (value.includes('\n')) {
|
|
147
|
+
return emitMultiLine(name, value, depth, path, warn)
|
|
148
|
+
}
|
|
149
|
+
// `:` 后面照原样写;需要定界的值才改成 `= "…"`
|
|
150
|
+
if (needsQuotedValue(value)) {
|
|
151
|
+
return [`${pad}* ${name} = ${encodeString(value)}`]
|
|
152
|
+
}
|
|
153
|
+
return [`${pad}* ${name}: ${value}`]
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
if (typeof value === 'number' || typeof value === 'boolean') {
|
|
157
|
+
return [`${pad}* ${name} = ${value}`]
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
if (Array.isArray(value)) {
|
|
161
|
+
return [`${pad}* ${name} = []`, ...emitArrayBody(value, depth + 1, path, warn)]
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
// 对象默认写「冒号留空 + 子项」;只有空对象才写 = {}
|
|
165
|
+
if (Object.keys(value).length === 0) {
|
|
166
|
+
return [`${pad}* ${name} = {}`]
|
|
167
|
+
}
|
|
168
|
+
return [`${pad}* ${name}:`, ...emitObjectBody(value, depth + 1, path, warn)]
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
function isPlainObject(value: object): boolean {
|
|
172
|
+
const proto = Object.getPrototypeOf(value)
|
|
173
|
+
return proto === Object.prototype || proto === null
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
function describe(value: unknown): string {
|
|
177
|
+
if (value === undefined) return 'undefined'
|
|
178
|
+
if (typeof value === 'number') return String(value)
|
|
179
|
+
if (typeof value === 'bigint') return `bigint ${value}n`
|
|
180
|
+
if (typeof value === 'object' && value !== null) {
|
|
181
|
+
return value.constructor?.name ? `${value.constructor.name} 对象` : '非普通对象'
|
|
182
|
+
}
|
|
183
|
+
return typeof value
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/**
|
|
187
|
+
* parse 的行正则用 `.`,匹配不了 \r、\u2028、\u2029,写进去就读不回来
|
|
188
|
+
*/
|
|
189
|
+
const UNREADABLE_CHAR = /[\r\u2028\u2029]/
|
|
190
|
+
|
|
191
|
+
function checkChars(text: string, path: string, what: string): void {
|
|
192
|
+
const found = UNREADABLE_CHAR.exec(text)
|
|
193
|
+
if (found) {
|
|
194
|
+
const code = found[0].charCodeAt(0).toString(16).padStart(4, '0')
|
|
195
|
+
throw new TypeError(`${path}:${what}含 \\u${code},lino 读不回这个字符`)
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/**
|
|
200
|
+
* 生成前整体校验:只放行 LinoValue 能表达的值,其余抛 TypeError 并带路径
|
|
201
|
+
* 先校验再生成,抛错时不会已经交出半截告警
|
|
202
|
+
*/
|
|
203
|
+
function validate(value: unknown, path: string, ancestors: Set<object>): void {
|
|
204
|
+
if (typeof value === 'string') {
|
|
205
|
+
checkChars(value, path, '字符串')
|
|
206
|
+
return
|
|
207
|
+
}
|
|
208
|
+
if (value === null || typeof value === 'boolean') return
|
|
209
|
+
if (typeof value === 'number') {
|
|
210
|
+
if (!Number.isFinite(value)) throw new TypeError(`${path}:不支持 ${describe(value)}`)
|
|
211
|
+
return
|
|
212
|
+
}
|
|
213
|
+
if (typeof value !== 'object') {
|
|
214
|
+
throw new TypeError(`${path}:不支持 ${describe(value)}`)
|
|
215
|
+
}
|
|
216
|
+
if (ancestors.has(value)) throw new TypeError(`${path}:出现循环引用`)
|
|
217
|
+
|
|
218
|
+
ancestors.add(value)
|
|
219
|
+
if (Array.isArray(value)) {
|
|
220
|
+
// 用下标遍历,稀疏数组的空位会以 undefined 报出来
|
|
221
|
+
for (let index = 0; index < value.length; index += 1) {
|
|
222
|
+
validate(value[index], `${path}[${index}]`, ancestors)
|
|
223
|
+
}
|
|
224
|
+
} else {
|
|
225
|
+
if (!isPlainObject(value)) throw new TypeError(`${path}:不支持 ${describe(value)}`)
|
|
226
|
+
for (const [key, item] of Object.entries(value)) {
|
|
227
|
+
checkChars(key, `${path}.${key}`, '键名')
|
|
228
|
+
validate(item, `${path}.${key}`, ancestors)
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
ancestors.delete(value)
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/**
|
|
235
|
+
* 顶层对象 → lino 文本,末尾带一个换行;空对象得到 "\n"
|
|
236
|
+
* 顶层不是普通对象、或任意位置有 undefined / 函数 / symbol / bigint / NaN / Infinity 时抛 TypeError
|
|
237
|
+
* 字符串值或键名里有 \r、\u2028、\u2029 也抛 TypeError
|
|
238
|
+
*/
|
|
239
|
+
export function stringify(value: LinoConf, options: StringifyOptions = {}): string {
|
|
240
|
+
const input: unknown = value
|
|
241
|
+
if (input === null || typeof input !== 'object' || Array.isArray(input) || !isPlainObject(input)) {
|
|
242
|
+
throw new TypeError(`$:顶层必须是普通对象,这里是 ${Array.isArray(input) ? '数组' : input === null ? 'null' : describe(input)}`)
|
|
243
|
+
}
|
|
244
|
+
validate(input, '$', new Set())
|
|
245
|
+
|
|
246
|
+
const onWarning = options.onWarning
|
|
247
|
+
const warn: Warn = onWarning ? (path, message) => onWarning({ path, message }) : () => {}
|
|
248
|
+
const lines = emitObjectBody(value, 0, '$', warn)
|
|
249
|
+
return `${lines.join('\n')}\n`
|
|
250
|
+
}
|
package/src/types.ts
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* lino 的公共类型(迁自 demo v1 的 shared.ts)
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
/** 任意 lino 值,与 JSON 值一一对应 */
|
|
6
|
+
export type LinoValue = null | boolean | number | string | LinoValue[] | { [key: string]: LinoValue }
|
|
7
|
+
|
|
8
|
+
/** 一份 lino 文本对应的顶层对象 */
|
|
9
|
+
export type LinoConf = { [key: string]: LinoValue }
|
|
10
|
+
|
|
11
|
+
/** stringify 走了未定口径时交出的告警;path 形如 `$.a[0].b` */
|
|
12
|
+
export interface LinoWarning {
|
|
13
|
+
path: string
|
|
14
|
+
message: string
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export interface StringifyOptions {
|
|
18
|
+
/** 每条告警调用一次;不传就不输出 */
|
|
19
|
+
onWarning?: (warning: LinoWarning) => void
|
|
20
|
+
}
|