dsh-modpack-kit 0.0.0-stage → 0.1.3
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/LICENSE +75 -0
- package/README.md +224 -2
- package/assets/icon-180.png +0 -0
- package/assets/install-stub.cmd +15 -0
- package/assets/install-stub.mjs +259 -0
- package/assets/install-stub.sh +9 -0
- package/client.js +1275 -0
- package/cordis.patch.yml +3 -0
- package/docs/DETAIL.md +97 -0
- package/icon.svg +14 -0
- package/index.js +820 -0
- package/lib/classify.mjs +105 -0
- package/lib/compat.mjs +112 -0
- package/lib/install.mjs +349 -0
- package/lib/manifest.mjs +197 -0
- package/lib/market-catalog.mjs +419 -0
- package/lib/pack.mjs +460 -0
- package/lib/profile.mjs +274 -0
- package/lib/registry.mjs +223 -0
- package/lib/scan.mjs +325 -0
- package/lib/semver.mjs +143 -0
- package/lib/store.mjs +183 -0
- package/lib/tar.mjs +107 -0
- package/lib/yamlish.mjs +385 -0
- package/lib/zip.mjs +232 -0
- package/locale/en.json +7 -0
- package/locale/zh.json +7 -0
- package/package.json +54 -3
package/lib/tar.mjs
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-modpack —— 最小 tgz 读取(npm 包用)。
|
|
3
|
+
*
|
|
4
|
+
* 只做一件事:把 `.tgz` 里的普通文件取出来。目录条目、pax 扩展头按规范跳过
|
|
5
|
+
* 或解析名字;符号链接、硬链接、设备节点一律拒绝——整合包里不需要它们,
|
|
6
|
+
* 而它们正是「解包时写到包外」最常见的载体。
|
|
7
|
+
*/
|
|
8
|
+
import { gunzipSync } from 'node:zlib'
|
|
9
|
+
import { safeEntryName } from './zip.mjs'
|
|
10
|
+
|
|
11
|
+
const BLOCK = 512
|
|
12
|
+
const LIMITS = { entries: 20000, entryBytes: 64 * 1024 * 1024, totalBytes: 512 * 1024 * 1024 }
|
|
13
|
+
|
|
14
|
+
function readString(buf, start, len) {
|
|
15
|
+
const slice = buf.subarray(start, start + len)
|
|
16
|
+
const zero = slice.indexOf(0)
|
|
17
|
+
return slice.toString('utf8', 0, zero === -1 ? slice.length : zero)
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function readOctal(buf, start, len) {
|
|
21
|
+
const text = readString(buf, start, len).trim()
|
|
22
|
+
if (text === '') return 0
|
|
23
|
+
const value = Number.parseInt(text, 8)
|
|
24
|
+
return Number.isFinite(value) && value >= 0 ? value : 0
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function parsePax(data) {
|
|
28
|
+
const out = {}
|
|
29
|
+
let offset = 0
|
|
30
|
+
while (offset < data.length) {
|
|
31
|
+
const space = data.indexOf(0x20, offset)
|
|
32
|
+
if (space === -1) break
|
|
33
|
+
const len = Number.parseInt(data.toString('utf8', offset, space), 10)
|
|
34
|
+
if (!Number.isFinite(len) || len <= 0) break
|
|
35
|
+
const record = data.toString('utf8', space + 1, offset + len - 1)
|
|
36
|
+
const eq = record.indexOf('=')
|
|
37
|
+
if (eq > 0) out[record.slice(0, eq)] = record.slice(eq + 1)
|
|
38
|
+
offset += len
|
|
39
|
+
}
|
|
40
|
+
return out
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* 解 gzip tar。
|
|
45
|
+
* @param {Buffer} gz
|
|
46
|
+
* @returns {{name: string, data: Buffer, mode: number, mtime: Date}[]}
|
|
47
|
+
*/
|
|
48
|
+
export function readTarball(gz, options = {}) {
|
|
49
|
+
let buf
|
|
50
|
+
try {
|
|
51
|
+
buf = gunzipSync(gz, { maxOutputLength: options.maxBytes ?? LIMITS.totalBytes })
|
|
52
|
+
} catch (error) {
|
|
53
|
+
throw new Error('tgz: 解压失败(' + String(error?.message || error) + ')')
|
|
54
|
+
}
|
|
55
|
+
const entries = []
|
|
56
|
+
let total = 0
|
|
57
|
+
let offset = 0
|
|
58
|
+
let pendingName = null
|
|
59
|
+
let pendingPax = {}
|
|
60
|
+
while (offset + BLOCK <= buf.length) {
|
|
61
|
+
const header = buf.subarray(offset, offset + BLOCK)
|
|
62
|
+
if (header.every((b) => b === 0)) break
|
|
63
|
+
let name = readString(header, 0, 100)
|
|
64
|
+
const size = readOctal(header, 124, 12)
|
|
65
|
+
const mode = readOctal(header, 100, 8)
|
|
66
|
+
const mtimeSec = readOctal(header, 136, 12)
|
|
67
|
+
const type = String.fromCharCode(header[156] || 0x30)
|
|
68
|
+
const prefix = readString(header, 345, 155)
|
|
69
|
+
if (prefix) name = prefix + '/' + name
|
|
70
|
+
const bodyStart = offset + BLOCK
|
|
71
|
+
if (entries.length >= (options.maxEntries ?? LIMITS.entries)) throw new Error('tgz: 条目数超过上限(疑似构造包)')
|
|
72
|
+
if (size > (options.maxEntryBytes ?? LIMITS.entryBytes)) throw new Error('tgz: 条目过大 ' + name)
|
|
73
|
+
if (bodyStart + size > buf.length) throw new Error('tgz: 条目数据越界 ' + name)
|
|
74
|
+
const body = buf.subarray(bodyStart, bodyStart + size)
|
|
75
|
+
offset = bodyStart + Math.ceil(size / BLOCK) * BLOCK
|
|
76
|
+
|
|
77
|
+
if (type === 'x') { pendingPax = parsePax(body); continue }
|
|
78
|
+
if (type === 'g') continue
|
|
79
|
+
if (type === 'L') { pendingName = readString(body, 0, body.length).replace(/\0.*$/s, ''); continue }
|
|
80
|
+
if (type === 'K') continue
|
|
81
|
+
|
|
82
|
+
if (pendingPax.path) name = pendingPax.path
|
|
83
|
+
if (pendingName) { name = pendingName; pendingName = null }
|
|
84
|
+
const mtime = mtimeSec > 0 ? new Date(mtimeSec * 1000) : new Date(0)
|
|
85
|
+
pendingPax = {}
|
|
86
|
+
|
|
87
|
+
if (type === '5') continue
|
|
88
|
+
if (type === '2' || type === '1') throw new Error('tgz: 拒绝链接条目 ' + name)
|
|
89
|
+
if (type !== '0' && type !== '\0') throw new Error('tgz: 不支持的条目类型 ' + type + ' ' + name)
|
|
90
|
+
total += size
|
|
91
|
+
if (total > (options.maxTotalBytes ?? LIMITS.totalBytes)) throw new Error('tgz: 解压总量超过上限')
|
|
92
|
+
entries.push({ name: safeEntryName(name), data: Buffer.from(body), mode, mtime })
|
|
93
|
+
}
|
|
94
|
+
return entries
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** 去掉 npm 包统一的一层前缀(通常是 `package/`)。 */
|
|
98
|
+
export function stripPackagePrefix(entries) {
|
|
99
|
+
if (entries.length === 0) return entries
|
|
100
|
+
const firstSegments = new Set(entries.map((e) => e.name.split('/')[0]))
|
|
101
|
+
if (firstSegments.size !== 1) return entries
|
|
102
|
+
const [prefix] = firstSegments
|
|
103
|
+
if (!prefix || entries.some((e) => !e.name.startsWith(prefix + '/'))) return entries
|
|
104
|
+
return entries.map((e) => ({ ...e, name: e.name.slice(prefix.length + 1) })).filter((e) => e.name !== '')
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
export const tarLimits = LIMITS
|
package/lib/yamlish.mjs
ADDED
|
@@ -0,0 +1,385 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-modpack —— 够用的 YAML 子集(只服务 profile 的 cordis.patch.yml)。
|
|
3
|
+
*
|
|
4
|
+
* 为什么不用 js-yaml:插件不该为了读一个补丁文件多背一个依赖;而这个文件
|
|
5
|
+
* 的形状是固定的(顶层列表,元素里是 id/name/disabled/config,值是标量、
|
|
6
|
+
* 嵌套映射、字符串列表和块标量)。
|
|
7
|
+
*
|
|
8
|
+
* 边界:支持块状映射/序列、单双引号、块标量 `|` `>`、flow 的 `[]` `{}`、
|
|
9
|
+
* 注释、布尔/null/数字。不支持锚点、多文档、tag、复杂键。解析失败会抛错,
|
|
10
|
+
* 调用方必须回退到「只报告、不自动改」——猜错的 YAML 比不改更危险。
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
class YamlError extends Error {}
|
|
14
|
+
|
|
15
|
+
function stripComment(line) {
|
|
16
|
+
let inSingle = false
|
|
17
|
+
let inDouble = false
|
|
18
|
+
for (let i = 0; i < line.length; i += 1) {
|
|
19
|
+
const ch = line[i]
|
|
20
|
+
if (ch === "'" && !inDouble) inSingle = !inSingle
|
|
21
|
+
else if (ch === '"' && !inSingle && line[i - 1] !== '\\') inDouble = !inDouble
|
|
22
|
+
else if (ch === '#' && !inSingle && !inDouble && (i === 0 || /\s/u.test(line[i - 1]))) return line.slice(0, i)
|
|
23
|
+
}
|
|
24
|
+
return line
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const indentOf = (line) => line.length - line.trimStart().length
|
|
28
|
+
|
|
29
|
+
function parseDoubleQuoted(text) {
|
|
30
|
+
const body = text.slice(1, -1)
|
|
31
|
+
let out = ''
|
|
32
|
+
for (let i = 0; i < body.length; i += 1) {
|
|
33
|
+
const ch = body[i]
|
|
34
|
+
if (ch !== '\\') { out += ch; continue }
|
|
35
|
+
const next = body[i + 1]
|
|
36
|
+
i += 1
|
|
37
|
+
switch (next) {
|
|
38
|
+
case 'n': out += '\n'; break
|
|
39
|
+
case 't': out += '\t'; break
|
|
40
|
+
case 'r': out += '\r'; break
|
|
41
|
+
case '"': out += '"'; break
|
|
42
|
+
case '\\': out += '\\'; break
|
|
43
|
+
case '0': out += '\0'; break
|
|
44
|
+
case 'u': {
|
|
45
|
+
out += String.fromCharCode(Number.parseInt(body.slice(i + 1, i + 5), 16))
|
|
46
|
+
i += 4
|
|
47
|
+
break
|
|
48
|
+
}
|
|
49
|
+
default: out += '\\' + (next ?? '')
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
return out
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function parseSingleQuoted(text) {
|
|
56
|
+
return text.slice(1, -1).replace(/''/gu, "'")
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** flow 序列/映射(只用于 `[a, b]` / `{a: b}` 这种一行写完的值)。 */
|
|
60
|
+
function parseFlow(text) {
|
|
61
|
+
let i = 0
|
|
62
|
+
const ws = () => { while (i < text.length && /\s/u.test(text[i])) i += 1 }
|
|
63
|
+
const scalar = () => {
|
|
64
|
+
ws()
|
|
65
|
+
if (text[i] === '"') {
|
|
66
|
+
const start = i
|
|
67
|
+
i += 1
|
|
68
|
+
while (i < text.length && !(text[i] === '"' && text[i - 1] !== '\\')) i += 1
|
|
69
|
+
i += 1
|
|
70
|
+
return parseDoubleQuoted(text.slice(start, i))
|
|
71
|
+
}
|
|
72
|
+
if (text[i] === "'") {
|
|
73
|
+
const start = i
|
|
74
|
+
i += 1
|
|
75
|
+
while (i < text.length && text[i] !== "'") i += 1
|
|
76
|
+
i += 1
|
|
77
|
+
return parseSingleQuoted(text.slice(start, i))
|
|
78
|
+
}
|
|
79
|
+
if (text[i] === '[') return list()
|
|
80
|
+
if (text[i] === '{') return map()
|
|
81
|
+
const start = i
|
|
82
|
+
while (i < text.length && !/[,\]}:]/u.test(text[i])) i += 1
|
|
83
|
+
return parseScalar(text.slice(start, i).trim())
|
|
84
|
+
}
|
|
85
|
+
const list = () => {
|
|
86
|
+
i += 1
|
|
87
|
+
const out = []
|
|
88
|
+
ws()
|
|
89
|
+
if (text[i] === ']') { i += 1; return out }
|
|
90
|
+
for (;;) {
|
|
91
|
+
out.push(scalar())
|
|
92
|
+
ws()
|
|
93
|
+
if (text[i] === ',') { i += 1; continue }
|
|
94
|
+
if (text[i] === ']') { i += 1; break }
|
|
95
|
+
throw new YamlError('flow 序列语法错误:' + text)
|
|
96
|
+
}
|
|
97
|
+
return out
|
|
98
|
+
}
|
|
99
|
+
const map = () => {
|
|
100
|
+
i += 1
|
|
101
|
+
const out = {}
|
|
102
|
+
ws()
|
|
103
|
+
if (text[i] === '}') { i += 1; return out }
|
|
104
|
+
for (;;) {
|
|
105
|
+
ws()
|
|
106
|
+
const keyStart = i
|
|
107
|
+
while (i < text.length && text[i] !== ':') i += 1
|
|
108
|
+
const key = text.slice(keyStart, i).trim()
|
|
109
|
+
i += 1
|
|
110
|
+
out[key] = scalar()
|
|
111
|
+
ws()
|
|
112
|
+
if (text[i] === ',') { i += 1; continue }
|
|
113
|
+
if (text[i] === '}') { i += 1; break }
|
|
114
|
+
throw new YamlError('flow 映射语法错误:' + text)
|
|
115
|
+
}
|
|
116
|
+
return out
|
|
117
|
+
}
|
|
118
|
+
const value = scalar()
|
|
119
|
+
ws()
|
|
120
|
+
if (i !== text.length) throw new YamlError('flow 值后有多余内容:' + text)
|
|
121
|
+
return value
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function parseScalar(raw) {
|
|
125
|
+
const text = raw.trim()
|
|
126
|
+
if (text === '') return ''
|
|
127
|
+
if (text === '~' || text === 'null' || text === 'Null' || text === 'NULL') return null
|
|
128
|
+
if (/^(?:true|True|TRUE)$/u.test(text)) return true
|
|
129
|
+
if (/^(?:false|False|FALSE)$/u.test(text)) return false
|
|
130
|
+
if (/^[+-]?(?:\d+|\d*\.\d+)(?:[eE][+-]?\d+)?$/u.test(text)) return Number(text)
|
|
131
|
+
if (text.startsWith('"') && text.endsWith('"') && text.length >= 2) return parseDoubleQuoted(text)
|
|
132
|
+
if (text.startsWith("'") && text.endsWith("'") && text.length >= 2) return parseSingleQuoted(text)
|
|
133
|
+
if (text.startsWith('[') || text.startsWith('{')) return parseFlow(text)
|
|
134
|
+
return text
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
class Parser {
|
|
138
|
+
constructor(text) {
|
|
139
|
+
this.raw = text
|
|
140
|
+
this.lines = text.split(/\r?\n/u)
|
|
141
|
+
this.i = 0
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
skipBlank() {
|
|
145
|
+
while (this.i < this.lines.length) {
|
|
146
|
+
const line = stripComment(this.lines[this.i])
|
|
147
|
+
if (line.trim() !== '') return
|
|
148
|
+
this.i += 1
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** 解析从当前行开始、缩进 >= indent 的块。 */
|
|
153
|
+
parseBlock(indent) {
|
|
154
|
+
this.skipBlank()
|
|
155
|
+
if (this.i >= this.lines.length) return null
|
|
156
|
+
const line = stripComment(this.lines[this.i])
|
|
157
|
+
if (indentOf(line) < indent) return null
|
|
158
|
+
if (/^\s*- /u.test(line) || /^\s*-$/u.test(line)) return this.parseSequence(indent)
|
|
159
|
+
return this.parseMapping(indent)
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
parseSequence(indent) {
|
|
163
|
+
const out = []
|
|
164
|
+
for (;;) {
|
|
165
|
+
this.skipBlank()
|
|
166
|
+
if (this.i >= this.lines.length) break
|
|
167
|
+
const rawLine = stripComment(this.lines[this.i])
|
|
168
|
+
if (indentOf(rawLine) !== indent) break
|
|
169
|
+
if (!/^-(\s|$)/u.test(rawLine.trimStart())) break
|
|
170
|
+
const rest = rawLine.trimStart().slice(1)
|
|
171
|
+
if (rest.trim() === '') {
|
|
172
|
+
this.i += 1
|
|
173
|
+
out.push(this.parseBlock(indent + 2))
|
|
174
|
+
continue
|
|
175
|
+
}
|
|
176
|
+
if (/^\s+\S/u.test(rest) && /^[^\s]['"]?.*?:\s/u.test(rest.trim())) {
|
|
177
|
+
// `- id: x` —— 把这一行改写成更深缩进的映射首行
|
|
178
|
+
const innerIndent = indent + 2
|
|
179
|
+
this.lines[this.i] = ' '.repeat(innerIndent) + rest.trimStart()
|
|
180
|
+
out.push(this.parseMapping(innerIndent))
|
|
181
|
+
continue
|
|
182
|
+
}
|
|
183
|
+
this.i += 1
|
|
184
|
+
out.push(this.parseInlineValue(rest.trim(), indent))
|
|
185
|
+
}
|
|
186
|
+
return out
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
parseInlineValue(text, indent) {
|
|
190
|
+
if (/^[|>][+-]?$/u.test(text) || /^[|>][+-]?\s/u.test(text)) return this.parseBlockScalar(text, indent)
|
|
191
|
+
return parseScalar(text)
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
parseBlockScalar(header, indent) {
|
|
195
|
+
const style = header[0]
|
|
196
|
+
const chomp = header.slice(1).trim()
|
|
197
|
+
const collected = []
|
|
198
|
+
let blockIndent = -1
|
|
199
|
+
while (this.i < this.lines.length) {
|
|
200
|
+
const line = this.lines[this.i]
|
|
201
|
+
if (line.trim() === '') { collected.push(''); this.i += 1; continue }
|
|
202
|
+
const ind = indentOf(line)
|
|
203
|
+
if (ind <= indent) break
|
|
204
|
+
if (blockIndent === -1) blockIndent = ind
|
|
205
|
+
if (ind < blockIndent) break
|
|
206
|
+
collected.push(line.slice(blockIndent))
|
|
207
|
+
this.i += 1
|
|
208
|
+
}
|
|
209
|
+
while (collected.length > 0 && collected[collected.length - 1] === '') collected.pop()
|
|
210
|
+
const text = style === '|' ? collected.join('\n') : collected.join(' ').replace(/\s+/gu, ' ').trim()
|
|
211
|
+
if (chomp === '-') return text
|
|
212
|
+
return text + '\n'
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
parseMapping(indent) {
|
|
216
|
+
const out = {}
|
|
217
|
+
for (;;) {
|
|
218
|
+
this.skipBlank()
|
|
219
|
+
if (this.i >= this.lines.length) break
|
|
220
|
+
const rawLine = stripComment(this.lines[this.i])
|
|
221
|
+
if (indentOf(rawLine) !== indent) break
|
|
222
|
+
if (/^-(\s|$)/u.test(rawLine.trimStart())) break
|
|
223
|
+
const m = /^([^:]+?):(?:\s+(.*))?$/u.exec(rawLine.trim())
|
|
224
|
+
if (!m) throw new YamlError('无法解析第 ' + (this.i + 1) + ' 行:' + this.lines[this.i])
|
|
225
|
+
const key = parseScalar(m[1].trim())
|
|
226
|
+
const rest = (m[2] ?? '').trim()
|
|
227
|
+
this.i += 1
|
|
228
|
+
if (rest === '') {
|
|
229
|
+
const next = this.peekMeaningful()
|
|
230
|
+
if (next && next.indent > indent) out[key] = this.parseBlock(next.indent)
|
|
231
|
+
else if (next && next.indent === indent && /^-(\s|$)/u.test(next.text.trimStart())) out[key] = this.parseSequence(indent)
|
|
232
|
+
else out[key] = null
|
|
233
|
+
} else if (/^[|>][+-]?$/u.test(rest)) {
|
|
234
|
+
out[key] = this.parseBlockScalar(rest, indent)
|
|
235
|
+
} else {
|
|
236
|
+
out[key] = parseScalar(rest)
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
return out
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
peekMeaningful() {
|
|
243
|
+
let j = this.i
|
|
244
|
+
while (j < this.lines.length) {
|
|
245
|
+
const line = stripComment(this.lines[j])
|
|
246
|
+
if (line.trim() !== '') return { indent: indentOf(line), text: line, line: j }
|
|
247
|
+
j += 1
|
|
248
|
+
}
|
|
249
|
+
return null
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/** 解析整份 YAML 文档;顶层可以是列表或映射。 */
|
|
254
|
+
export function parseYaml(text) {
|
|
255
|
+
const parser = new Parser(String(text ?? ''))
|
|
256
|
+
parser.skipBlank()
|
|
257
|
+
if (parser.i >= parser.lines.length) return []
|
|
258
|
+
const first = stripComment(parser.lines[parser.i])
|
|
259
|
+
if (indentOf(first) !== 0) throw new YamlError('顶层缩进不为 0')
|
|
260
|
+
const result = /^-(\s|$)/u.test(first.trimStart()) ? parser.parseSequence(0) : parser.parseMapping(0)
|
|
261
|
+
parser.skipBlank()
|
|
262
|
+
if (parser.i < parser.lines.length) throw new YamlError('第 ' + (parser.i + 1) + ' 行之后有无法解析的内容')
|
|
263
|
+
return result
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
const PLAIN_SAFE = /^[A-Za-z0-9_./@+-]+$/u
|
|
267
|
+
|
|
268
|
+
export function emitScalar(value) {
|
|
269
|
+
if (value === null || value === undefined) return 'null'
|
|
270
|
+
if (typeof value === 'boolean') return value ? 'true' : 'false'
|
|
271
|
+
if (typeof value === 'number') return Number.isFinite(value) ? String(value) : 'null'
|
|
272
|
+
const text = String(value)
|
|
273
|
+
if (text === '') return '""'
|
|
274
|
+
if (PLAIN_SAFE.test(text) && !/^(?:true|false|null|~|\d+)$/iu.test(text)) return text
|
|
275
|
+
return JSON.stringify(text)
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
/** 把 JSON 安全值写成 YAML 行(不含结尾换行)。 */
|
|
279
|
+
export function emitYaml(value, indent = 0) {
|
|
280
|
+
const pad = ' '.repeat(indent)
|
|
281
|
+
const lines = []
|
|
282
|
+
if (Array.isArray(value)) {
|
|
283
|
+
if (value.length === 0) return pad + '[]'
|
|
284
|
+
for (const item of value) {
|
|
285
|
+
if (item !== null && typeof item === 'object' && !Array.isArray(item)) {
|
|
286
|
+
const nested = emitYaml(item, indent + 2).split('\n')
|
|
287
|
+
lines.push(pad + '- ' + nested[0].trimStart())
|
|
288
|
+
lines.push(...nested.slice(1))
|
|
289
|
+
} else if (Array.isArray(item)) {
|
|
290
|
+
lines.push(pad + '- ' + emitYaml(item, indent + 2).trimStart())
|
|
291
|
+
} else {
|
|
292
|
+
lines.push(pad + '- ' + emitScalar(item))
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
return lines.join('\n')
|
|
296
|
+
}
|
|
297
|
+
if (value !== null && typeof value === 'object') {
|
|
298
|
+
const keys = Object.keys(value)
|
|
299
|
+
if (keys.length === 0) return pad + '{}'
|
|
300
|
+
for (const key of keys) {
|
|
301
|
+
const v = value[key]
|
|
302
|
+
if (v !== null && typeof v === 'object') {
|
|
303
|
+
const nested = emitYaml(v, indent + 2).split('\n')
|
|
304
|
+
if (Array.isArray(v) || Object.keys(v).length > 0) {
|
|
305
|
+
lines.push(pad + emitScalar(key) + ':')
|
|
306
|
+
lines.push(...nested)
|
|
307
|
+
} else {
|
|
308
|
+
lines.push(pad + emitScalar(key) + ': ' + (Array.isArray(v) ? '[]' : '{}'))
|
|
309
|
+
}
|
|
310
|
+
} else {
|
|
311
|
+
lines.push(pad + emitScalar(key) + ': ' + emitScalar(v))
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
return lines.join('\n')
|
|
315
|
+
}
|
|
316
|
+
return pad + emitScalar(value)
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
/**
|
|
320
|
+
* 把 patch 文件切成顶层条目,保留每条原文与行范围。
|
|
321
|
+
* 注释和空行归到「它前面那条」的尾巴里,这样替换一条不会吃掉相邻注释。
|
|
322
|
+
* @returns {{items: {start: number, end: number, raw: string, value: any}[], preamble: string, postamble: string, lines: string[]}}
|
|
323
|
+
*/
|
|
324
|
+
export function splitTopLevelItems(text) {
|
|
325
|
+
const lines = String(text ?? '').split(/\r?\n/u)
|
|
326
|
+
const starts = []
|
|
327
|
+
for (let i = 0; i < lines.length; i += 1) {
|
|
328
|
+
if (/^-(\s|$)/u.test(lines[i])) starts.push(i)
|
|
329
|
+
}
|
|
330
|
+
const preamble = starts.length === 0 ? lines.join('\n') : lines.slice(0, starts[0]).join('\n')
|
|
331
|
+
const items = []
|
|
332
|
+
for (let k = 0; k < starts.length; k += 1) {
|
|
333
|
+
const start = starts[k]
|
|
334
|
+
const endExclusive = k + 1 < starts.length ? starts[k + 1] : lines.length
|
|
335
|
+
// 尾部注释/空行留给下一条,避免把「下一条的说明」并进本条
|
|
336
|
+
let cut = endExclusive
|
|
337
|
+
while (cut > start + 1 && /^\s*(?:#.*)?$/u.test(lines[cut - 1])) cut -= 1
|
|
338
|
+
const chunk = lines.slice(start, cut)
|
|
339
|
+
let value = null
|
|
340
|
+
try {
|
|
341
|
+
value = parseYaml(chunk.join('\n'))[0]
|
|
342
|
+
} catch {
|
|
343
|
+
value = null
|
|
344
|
+
}
|
|
345
|
+
items.push({ start, end: cut, raw: chunk.join('\n'), value })
|
|
346
|
+
}
|
|
347
|
+
const lastEnd = items.length > 0 ? items[items.length - 1].end : lines.length
|
|
348
|
+
const postamble = lines.slice(lastEnd).join('\n')
|
|
349
|
+
return { items, preamble, postamble, lines }
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
/**
|
|
353
|
+
* 在 patch 文本里按 id 替换一条,或追加一条。其他条目逐字节保留。
|
|
354
|
+
* @param {string} text 原 patch 文本
|
|
355
|
+
* @param {{id: string, name?: string, config?: any, disabled?: boolean}} value
|
|
356
|
+
* @returns {{text: string, action: 'replaced'|'inserted'}}
|
|
357
|
+
*/
|
|
358
|
+
export function upsertPatchItem(text, value) {
|
|
359
|
+
const { items, preamble, postamble, lines } = splitTopLevelItems(text)
|
|
360
|
+
const emitted = emitYaml([{ ...value, config: value.config ?? {} }], 0)
|
|
361
|
+
const index = items.findIndex((it) => it.value && it.value.id === value.id)
|
|
362
|
+
if (index === -1) {
|
|
363
|
+
const base = String(text ?? '')
|
|
364
|
+
const trimmed = base.replace(/\s*$/u, '')
|
|
365
|
+
return { text: (trimmed === '' ? '' : trimmed + '\n') + emitted + '\n', action: 'inserted' }
|
|
366
|
+
}
|
|
367
|
+
const target = items[index]
|
|
368
|
+
const trailingNewline = String(text ?? '').endsWith('\n')
|
|
369
|
+
const rebuilt = [...lines.slice(0, target.start), ...emitted.split('\n'), ...lines.slice(target.end)].join('\n')
|
|
370
|
+
const out = trailingNewline && !rebuilt.endsWith('\n') ? rebuilt + '\n' : rebuilt
|
|
371
|
+
return { text: out, action: 'replaced' }
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
/** 取某个 id 的条目值。 */
|
|
375
|
+
export function findPatchItem(text, id) {
|
|
376
|
+
try {
|
|
377
|
+
const list = parseYaml(text)
|
|
378
|
+
if (!Array.isArray(list)) return null
|
|
379
|
+
return list.find((it) => it && typeof it === 'object' && it.id === id) ?? null
|
|
380
|
+
} catch {
|
|
381
|
+
return null
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
export { YamlError }
|