dsh-crate 0.0.0-stage → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (132) hide show
  1. package/LICENSE +27 -0
  2. package/README.md +288 -2
  3. package/README.zh.md +263 -0
  4. package/UPDATE-API-V1.md +207 -0
  5. package/assets/logo.svg +37 -0
  6. package/client/client.js +18964 -0
  7. package/cordis.patch.yml +4 -0
  8. package/lib/accelerate.js +194 -0
  9. package/lib/agents.js +67 -0
  10. package/lib/backup.js +688 -0
  11. package/lib/body-progress.js +173 -0
  12. package/lib/catalog-local-match.js +160 -0
  13. package/lib/catalog-npm.js +180 -0
  14. package/lib/changelog.js +462 -0
  15. package/lib/channels.js +64 -0
  16. package/lib/check.js +1557 -0
  17. package/lib/compatibility.js +243 -0
  18. package/lib/crate-catalog.js +179 -0
  19. package/lib/diagnostics.js +49 -0
  20. package/lib/discovery-compatibility.js +447 -0
  21. package/lib/drain-journal.js +164 -0
  22. package/lib/drain.js +1043 -0
  23. package/lib/dsh-cli.js +1373 -0
  24. package/lib/dsh-install.js +259 -0
  25. package/lib/entry-identity.js +85 -0
  26. package/lib/gist.js +369 -0
  27. package/lib/groups.js +108 -0
  28. package/lib/home-paths.js +29 -0
  29. package/lib/host-recovery.js +187 -0
  30. package/lib/hot.js +871 -0
  31. package/lib/http.js +252 -0
  32. package/lib/index.js +394 -0
  33. package/lib/install.js +1147 -0
  34. package/lib/lifecycle.js +37 -0
  35. package/lib/log-redaction.js +24 -0
  36. package/lib/log.js +204 -0
  37. package/lib/ndjson.js +154 -0
  38. package/lib/net.js +174 -0
  39. package/lib/official-desktop.js +619 -0
  40. package/lib/order.js +284 -0
  41. package/lib/patch.js +943 -0
  42. package/lib/pending-rows.js +142 -0
  43. package/lib/pending-updates.js +346 -0
  44. package/lib/pnpm-compat.js +972 -0
  45. package/lib/presets.js +282 -0
  46. package/lib/probe-context.js +20 -0
  47. package/lib/proc-text.js +69 -0
  48. package/lib/profile.js +1978 -0
  49. package/lib/recovery.js +1059 -0
  50. package/lib/region-probe.js +93 -0
  51. package/lib/regions.js +283 -0
  52. package/lib/registry.js +308 -0
  53. package/lib/release-candidates.js +115 -0
  54. package/lib/release-updates.js +70 -0
  55. package/lib/restart.js +688 -0
  56. package/lib/routes.js +7960 -0
  57. package/lib/settings.js +164 -0
  58. package/lib/shelfry-catalog.js +179 -0
  59. package/lib/snapshot.js +506 -0
  60. package/lib/source-migration.js +164 -0
  61. package/lib/sources.js +1005 -0
  62. package/lib/state.js +38 -0
  63. package/lib/store.js +163 -0
  64. package/lib/themes.js +350 -0
  65. package/lib/trial.js +125 -0
  66. package/lib/types/accelerate.d.ts +85 -0
  67. package/lib/types/agents.d.ts +52 -0
  68. package/lib/types/backup.d.ts +171 -0
  69. package/lib/types/body-progress.d.ts +94 -0
  70. package/lib/types/catalog-local-match.d.ts +39 -0
  71. package/lib/types/catalog-npm.d.ts +77 -0
  72. package/lib/types/changelog.d.ts +131 -0
  73. package/lib/types/channels.d.ts +56 -0
  74. package/lib/types/check.d.ts +353 -0
  75. package/lib/types/compatibility.d.ts +83 -0
  76. package/lib/types/crate-catalog.d.ts +48 -0
  77. package/lib/types/diagnostics.d.ts +29 -0
  78. package/lib/types/discovery-compatibility.d.ts +145 -0
  79. package/lib/types/drain-journal.d.ts +25 -0
  80. package/lib/types/drain.d.ts +306 -0
  81. package/lib/types/dsh-cli.d.ts +481 -0
  82. package/lib/types/dsh-install.d.ts +106 -0
  83. package/lib/types/entry-identity.d.ts +68 -0
  84. package/lib/types/gist.d.ts +79 -0
  85. package/lib/types/groups.d.ts +34 -0
  86. package/lib/types/home-paths.d.ts +13 -0
  87. package/lib/types/host-recovery.d.ts +95 -0
  88. package/lib/types/hot.d.ts +405 -0
  89. package/lib/types/http.d.ts +114 -0
  90. package/lib/types/index.d.ts +52 -0
  91. package/lib/types/install.d.ts +463 -0
  92. package/lib/types/lifecycle.d.ts +14 -0
  93. package/lib/types/log-redaction.d.ts +2 -0
  94. package/lib/types/log.d.ts +43 -0
  95. package/lib/types/ndjson.d.ts +52 -0
  96. package/lib/types/net.d.ts +94 -0
  97. package/lib/types/official-desktop.d.ts +59 -0
  98. package/lib/types/order.d.ts +100 -0
  99. package/lib/types/patch.d.ts +218 -0
  100. package/lib/types/pending-rows.d.ts +81 -0
  101. package/lib/types/pending-updates.d.ts +161 -0
  102. package/lib/types/pnpm-compat.d.ts +102 -0
  103. package/lib/types/presets.d.ts +94 -0
  104. package/lib/types/probe-context.d.ts +14 -0
  105. package/lib/types/proc-text.d.ts +29 -0
  106. package/lib/types/profile.d.ts +551 -0
  107. package/lib/types/recovery.d.ts +342 -0
  108. package/lib/types/region-probe.d.ts +50 -0
  109. package/lib/types/regions.d.ts +134 -0
  110. package/lib/types/registry.d.ts +160 -0
  111. package/lib/types/release-candidates.d.ts +42 -0
  112. package/lib/types/release-updates.d.ts +15 -0
  113. package/lib/types/restart.d.ts +279 -0
  114. package/lib/types/routes.d.ts +130 -0
  115. package/lib/types/settings.d.ts +112 -0
  116. package/lib/types/shelfry-catalog.d.ts +48 -0
  117. package/lib/types/snapshot.d.ts +93 -0
  118. package/lib/types/source-migration.d.ts +100 -0
  119. package/lib/types/sources.d.ts +391 -0
  120. package/lib/types/state.d.ts +20 -0
  121. package/lib/types/store.d.ts +47 -0
  122. package/lib/types/themes.d.ts +46 -0
  123. package/lib/types/trial.d.ts +61 -0
  124. package/lib/types/update-api-v1.d.ts +83 -0
  125. package/lib/types/updates.d.ts +273 -0
  126. package/lib/types/verify.d.ts +277 -0
  127. package/lib/update-api-v1.js +273 -0
  128. package/lib/updates.js +981 -0
  129. package/lib/verify.js +904 -0
  130. package/locale/en.json +5 -0
  131. package/locale/zh.json +6 -0
  132. package/package.json +113 -4
package/lib/patch.js ADDED
@@ -0,0 +1,943 @@
1
+ /**
2
+ * Patch-layer plugin toggles — hot disable/enable through the profile's
3
+ * user patch layer (cordis.patch.yml), the mechanism ported from
4
+ * Noob-stupid/dsh-plugin-hub's plugin console.
5
+ *
6
+ * DSH composes a web profile from the bundle layers + the user patch layer
7
+ * (`$DSH_HOME/profiles/<name>/cordis.patch.yml`), with per-key override
8
+ * semantics: a patch row `- id: X` + `disabled: true` stops that loader
9
+ * entry, and `disabled: false` force-enables one a lower layer disabled.
10
+ * The profile's config-file watcher (HMR) re-composes within ~1s of the
11
+ * save — no restart — and the loader re-applies the same file on every
12
+ * boot, so the choice survives restarts through the official mechanism.
13
+ *
14
+ * The market ALSO keeps its own in-memory/state.json bookkeeping (hot-mount
15
+ * shims have no bundle row to patch, and the client's disable list drives
16
+ * the switches); this module is the durable, HMR-driven layer on top.
17
+ *
18
+ * Safety (borrowed from the plugin-hub implementation):
19
+ * - writes are serialized so concurrent toggles cannot interleave a
20
+ * read-modify-write;
21
+ * - an append is REFUSED when the patch file is not a valid entry list —
22
+ * a malformed file (e.g. a stray `[]` followed by items) is never made
23
+ * worse, the market reports it instead;
24
+ * - host infrastructure rows (transport / hot-reload / storage / settings
25
+ * chains) are protected and refuse to toggle.
26
+ */
27
+ import { readFileSync, writeFileSync } from 'node:fs';
28
+ import { join } from 'node:path';
29
+ import { fileURLToPath } from 'node:url';
30
+ import { logEvent } from './log.js';
31
+ import { parsePatchFile, parsePatchText } from './check.js';
32
+ import { bundleOptOutRowIds, bundlePatchInsertedIds, declaredBundlePatchFiles, parsePatchRows } from './profile.js';
33
+ /**
34
+ * Host infrastructure rows: disabling any of these breaks the very chain
35
+ * the patch layer runs on (e.g. timer → HMR, webserver → the page itself),
36
+ * so they refuse to toggle. Same list the plugin-hub console uses — the
37
+ * target host is the same DSH.
38
+ */
39
+ const PROTECTED_MODULE_PATTERNS = [
40
+ /^cordis:/u,
41
+ /^@deepseek-ai\/cordis-plugin-/u,
42
+ /^@deepseek-ai\/dsh-host-/u,
43
+ /^@deepseek-ai\/dsh-client-modules$/u,
44
+ /^@deepseek-ai\/dsh-client-connection$/u,
45
+ /^@deepseek-ai\/dsh-client-hmr$/u,
46
+ /^@deepseek-ai\/dsh-client-runtime$/u,
47
+ /^@deepseek-ai\/dsh-client-locale$/u,
48
+ /^@deepseek-ai\/dsh-client-web/u,
49
+ /^@deepseek-ai\/dsh-web-frontend$/u,
50
+ /^@deepseek-ai\/dsh-web-app$/u,
51
+ /^@deepseek-ai\/dsh-settings/u,
52
+ /^@deepseek-ai\/dsh-credentials/u,
53
+ /^@deepseek-ai\/dsh-session/u,
54
+ /^@deepseek-ai\/dsh-storage/u,
55
+ /^@deepseek-ai\/dsh-typert/u,
56
+ /^@deepseek-ai\/dsh-api-remotes$/u,
57
+ /^@deepseek-ai\/dsh-tools$/u,
58
+ /^@deepseek-ai\/dsh-system-prompt$/u,
59
+ /^@deepseek-ai\/dsh-agent/u,
60
+ /^@deepseek-ai\/dsh-llm/u,
61
+ /^@deepseek-ai\/dsh-persona$/u,
62
+ /^@deepseek-ai\/dsh-scope$/u,
63
+ /^@deepseek-ai\/dsh-launch-environment$/u,
64
+ /^@deepseek-ai\/dsh-shell$/u,
65
+ /^@deepseek-ai\/dsh-subprocess/u,
66
+ /^@deepseek-ai\/dsh-fs/u,
67
+ /^@deepseek-ai\/dsh-sandbox/u,
68
+ /^@deepseek-ai\/dsh-jobs/u,
69
+ /^@deepseek-ai\/dsh-skill/u,
70
+ /^@deepseek-ai\/dsh-goal/u,
71
+ /^@deepseek-ai\/dsh-workflow/u,
72
+ /^@deepseek-ai\/dsh-subagent/u,
73
+ /^@deepseek-ai\/dsh-web$/u,
74
+ /^@deepseek-ai\/dsh-workspace/u,
75
+ /^@deepseek-ai\/dsh-user-approval$/u,
76
+ /^@deepseek-ai\/dsh-user-questions$/u,
77
+ /^@deepseek-ai\/dsh-commands$/u,
78
+ /^@deepseek-ai\/dsh-hook/u,
79
+ /^@deepseek-ai\/dsh-spill/u,
80
+ /^@deepseek-ai\/dsh-guard/u,
81
+ /^@deepseek-ai\/dsh-tool-call-timeout-policy$/u,
82
+ /^@deepseek-ai\/dsh-repeat-tool-reminder$/u,
83
+ ];
84
+ /** True when the module name sits on the host infrastructure chain. */
85
+ export function isProtectedModule(moduleName) {
86
+ return typeof moduleName === 'string' && PROTECTED_MODULE_PATTERNS.some(pattern => pattern.test(moduleName));
87
+ }
88
+ /**
89
+ * Resolve the profile's user patch layer. Prefers the path the loader's
90
+ * cordis:include entry actually read (authoritative under hosts that own
91
+ * the profile directory, like DSH Desktop); falls back to the conventional
92
+ * `<profile>/cordis.patch.yml`.
93
+ */
94
+ export function findUserPatchPath(host, profileDir) {
95
+ for (const entry of host.loader.entries()) {
96
+ const cfg = entry.options?.config;
97
+ if (entry.options?.name !== 'cordis:include' || cfg == null || typeof cfg.path !== 'string')
98
+ continue;
99
+ if (!cfg.path.includes('cordis.yml'))
100
+ continue;
101
+ let includePath = cfg.path;
102
+ if (includePath.startsWith('file://')) {
103
+ try {
104
+ includePath = fileURLToPath(includePath);
105
+ }
106
+ catch {
107
+ // fileURLToPath rejects POSIX-style URLs on Windows; the scheme is
108
+ // all we need to strip for the path to be usable.
109
+ includePath = includePath.replace(/^file:\/\//u, '');
110
+ }
111
+ }
112
+ return includePath.replace(/cordis\.yml$/u, 'cordis.patch.yml');
113
+ }
114
+ return join(profileDir, 'cordis.patch.yml');
115
+ }
116
+ /** Row ids the market is allowed to write: plain unquoted YAML scalars. */
117
+ const ROW_ID_RE = /^[A-Za-z0-9_.-]+$/u;
118
+ function nextPatchContentLine(lines, from) {
119
+ let index = from;
120
+ while (index < lines.length) {
121
+ const line = (lines[index] ?? '').trim();
122
+ if (line !== '' && !line.startsWith('#'))
123
+ break;
124
+ index += 1;
125
+ }
126
+ return index;
127
+ }
128
+ /**
129
+ * Line-wise scan of one patch file — the plugin-hub shapes. Deliberately
130
+ * not a YAML parse: the file may hold structures the market's dialect
131
+ * rejects, but a plain `- id: X` + `disabled: true|false` pair is enough
132
+ * to know what the user patch layer says.
133
+ */
134
+ /**
135
+ * The value of a top-level key in a patch entry that starts after `start`.
136
+ *
137
+ * An entry runs until the next `- ` at column 0, and its keys sit at exactly
138
+ * two spaces; anything deeper belongs to `config:` and says nothing about the
139
+ * row itself. Reading only the line AFTER `- id:` missed `disabled: true`
140
+ * whenever `name`, `inject` or a config block came first — the row then read
141
+ * as enabled, so a plugin the user had switched off was reported "restart to
142
+ * apply" forever, every boot (#1099).
143
+ *
144
+ * @returns the scalar as written (comments stripped), or null when the entry
145
+ * does not carry the key at all.
146
+ */
147
+ function entryKeyValue(lines, start, key) {
148
+ const pattern = new RegExp(`^ {2}${key}:[ \\t]*(.*?)[ \\t]*$`, 'u');
149
+ for (let index = start; index < lines.length; index += 1) {
150
+ const line = lines[index] ?? '';
151
+ if (/^- /u.test(line))
152
+ return null;
153
+ const match = pattern.exec(line);
154
+ // A `#` starts a comment only after whitespace; `#` inside a bare scalar
155
+ // is data, and YAML would keep it.
156
+ if (match !== null)
157
+ return (match[1] ?? '').replace(/[ \t]+#.*$/u, '').trim();
158
+ }
159
+ return null;
160
+ }
161
+ /**
162
+ * Whether a patch entry speaks for the row it names.
163
+ *
164
+ * The host skips an entry whose `name` is not the name that row's id composes
165
+ * to — `applyPatches` in dsh-app-boot, `if (name && name !== target.name)`,
166
+ * the same line in every published version. A row left behind by a package
167
+ * rename therefore never takes effect, while anything that counts the flag
168
+ * alone reports the plugin as off (#1113). Only a row that CARRIES a name is
169
+ * compared, and only when the composed name is known: an id that is not in
170
+ * the loader has nothing to compare against, and its flag stands.
171
+ *
172
+ * @param name - the `name` the entry carries, if any.
173
+ * @param expected - the composed entry's own name, or null when unknown.
174
+ */
175
+ function rowApplies(name, expected) {
176
+ if (typeof name !== 'string' || name === '')
177
+ return true;
178
+ return expected === null || name === expected;
179
+ }
180
+ /**
181
+ * The name the loader composed for a row, or null when the id is not there.
182
+ *
183
+ * This is the comparison the host makes, against the composed entry's own
184
+ * `name` — NOT `nameMatchesPackage()`, which judges package ownership and
185
+ * treats a subpath name and a foreign package name the same way (#1113).
186
+ */
187
+ export function composedRowName(host, rowId) {
188
+ for (const entry of host.loader.entries()) {
189
+ if (loaderEntryId(entry) !== rowId)
190
+ continue;
191
+ const name = entry.options?.name;
192
+ return typeof name === 'string' && name !== '' ? name : null;
193
+ }
194
+ return null;
195
+ }
196
+ /**
197
+ * Whether the user layer's flag for this row is a decision the host applies.
198
+ *
199
+ * @param state - the user patch state.
200
+ * @param rowId - the row being asked about.
201
+ * @param expected - the composed entry's name, or null when the id is not in
202
+ * the loader.
203
+ */
204
+ export function rowFlagApplies(state, rowId, expected) {
205
+ const carried = state.names?.[rowId];
206
+ return carried === undefined || rowApplies(carried, expected);
207
+ }
208
+ /** The state with one row's flags dropped when its `name` does not apply. */
209
+ function withoutMismatchedRow(state, rowId, expected) {
210
+ if (rowFlagApplies(state, rowId, expected))
211
+ return state;
212
+ return {
213
+ disables: state.disables.filter(id => id !== rowId),
214
+ forced: state.forced.filter(id => id !== rowId),
215
+ inserts: state.inserts,
216
+ ...(state.names !== undefined ? { names: state.names } : {}),
217
+ };
218
+ }
219
+ export function readUserPatchState(patchPath) {
220
+ // The host composes the file in order, later entries override earlier ones,
221
+ // so a row has one final flag: listing it as both disabled and forced showed
222
+ // a plugin as off while the file had it on (#1099).
223
+ const flags = new Map();
224
+ const names = new Map();
225
+ const inserts = [];
226
+ let text = '';
227
+ try {
228
+ text = readPatchText(patchPath);
229
+ }
230
+ catch { /* no patch file — empty state */ }
231
+ const lines = text.split(/\r?\n/u);
232
+ let inInsert = false;
233
+ for (let index = 0; index < lines.length; index += 1) {
234
+ const line = lines[index] ?? '';
235
+ if (/^- insert:\s*$/u.test(line)) {
236
+ inInsert = true;
237
+ continue;
238
+ }
239
+ if (/^- /u.test(line))
240
+ inInsert = false;
241
+ if (inInsert) {
242
+ const insertRow = /^ {4}- id: ([A-Za-z0-9_.-]+)/u.exec(line);
243
+ if (insertRow !== null)
244
+ inserts.push(insertRow[1]);
245
+ continue;
246
+ }
247
+ const disableRow = /^- id: (?:([A-Za-z0-9_.-]+)|'([A-Za-z0-9_.-]+)'|"([A-Za-z0-9_.-]+)")[ \t]*$/u.exec(line);
248
+ if (disableRow === null)
249
+ continue;
250
+ const id = (disableRow[1] ?? disableRow[2] ?? disableRow[3]);
251
+ const value = entryKeyValue(lines, index + 1, 'disabled');
252
+ if (value !== 'true' && value !== 'false')
253
+ continue;
254
+ flags.set(id, value);
255
+ // A row that names a module is only applied by the host when that name is
256
+ // the one the row's id composes to; the flag stays here so the caller can
257
+ // make that comparison (#1113).
258
+ const named = entryKeyValue(lines, index + 1, 'name');
259
+ const unwrapped = named === null ? null : named.replace(/^(['"])(.*)\1$/u, '$2');
260
+ if (unwrapped !== null && unwrapped !== '')
261
+ names.set(id, unwrapped);
262
+ else
263
+ names.delete(id);
264
+ }
265
+ const withFlag = (flag) => [...flags.keys()].filter(id => flags.get(id) === flag);
266
+ return {
267
+ disables: withFlag('true'),
268
+ forced: withFlag('false'),
269
+ inserts,
270
+ ...(names.size > 0 ? { names: Object.fromEntries(names) } : {}),
271
+ };
272
+ }
273
+ /**
274
+ * User-authored insert rows that still load `packageName` (or one of its
275
+ * exported subpaths). This evidence deliberately stays separate from the
276
+ * package's own bundle declaration: uninstall may clean market-owned rows,
277
+ * but it must never rewrite an insert the user owns.
278
+ *
279
+ * A missing patch is the ordinary empty-profile shape. `null` means the
280
+ * existing file could not be read as DSH's patch dialect; callers must treat
281
+ * that as indeterminate and refuse the destructive step.
282
+ */
283
+ export function userPatchPackageReferences(patchPath, packageName) {
284
+ let source;
285
+ try {
286
+ source = readFileSync(patchPath, 'utf8');
287
+ }
288
+ catch (error) {
289
+ const code = error !== null && typeof error === 'object' && 'code' in error
290
+ ? error.code
291
+ : undefined;
292
+ if (code === 'ENOENT')
293
+ return [];
294
+ return null;
295
+ }
296
+ // Use the same schema as profile composition, including !!js scalars. A
297
+ // line scanner cannot distinguish flow-style entries or nested loader
298
+ // groups from arbitrary config keys in a hand-written user patch.
299
+ const rows = parsePatchText(source);
300
+ if (rows === null)
301
+ return null;
302
+ const insertedNames = new Set();
303
+ const visiting = new Set();
304
+ const visited = new Set();
305
+ const collect = (entries) => {
306
+ if (visited.has(entries))
307
+ return true;
308
+ if (visiting.has(entries))
309
+ return false;
310
+ visiting.add(entries);
311
+ for (const entry of entries) {
312
+ if (entry === null || typeof entry !== 'object' || Array.isArray(entry)) {
313
+ visiting.delete(entries);
314
+ return false;
315
+ }
316
+ const row = entry;
317
+ if ('name' in row && typeof row.name !== 'string') {
318
+ visiting.delete(entries);
319
+ return false;
320
+ }
321
+ if (typeof row.name === 'string')
322
+ insertedNames.add(row.name);
323
+ // Only group rows treat an array-valued config as child loader rows.
324
+ // Other plugins may use arrays of `{ name: ... }` as ordinary options,
325
+ // and those must not become false package references.
326
+ if (row.group === true && Array.isArray(row.config)) {
327
+ if (!collect(row.config)) {
328
+ visiting.delete(entries);
329
+ return false;
330
+ }
331
+ }
332
+ }
333
+ visiting.delete(entries);
334
+ visited.add(entries);
335
+ return true;
336
+ };
337
+ for (const patch of rows) {
338
+ if (patch === null || typeof patch !== 'object' || Array.isArray(patch))
339
+ return null;
340
+ const patchRow = patch;
341
+ if (!('insert' in patchRow))
342
+ continue;
343
+ if (!Array.isArray(patchRow.insert) || !collect(patchRow.insert))
344
+ return null;
345
+ }
346
+ return [...insertedNames].filter(reference => reference === packageName || reference.startsWith(`${packageName}/`));
347
+ }
348
+ /**
349
+ * A loader entry's id as a string, or '' when it has none.
350
+ *
351
+ * `EntryOptions.id` is a TypeScript interface, not a runtime check: an
352
+ * unquoted `- id: 1` in `cordis.patch.yml` is parsed by YAML as the NUMBER 1,
353
+ * the host's loader accepts it, and every `.split(':')` on it then throws —
354
+ * `/dsh-crate/installed` answered 400 with an empty body and the UI showed
355
+ * "no community plugins installed" (#1071). The market's own regex parser
356
+ * only ever produces strings, so this is reachable only through the loader.
357
+ *
358
+ * Numbers are stringified rather than dropped: `id: 1` names the same entry
359
+ * the user wrote, and the market's own row comparisons are string-keyed.
360
+ *
361
+ * @param entry - a host loader entry.
362
+ * @returns the id as a string, '' when absent or not a string/number.
363
+ */
364
+ export function loaderEntryId(entry) {
365
+ const id = entry?.options?.id;
366
+ if (typeof id === 'string')
367
+ return id;
368
+ if (typeof id === 'number' && Number.isFinite(id))
369
+ return String(id);
370
+ return '';
371
+ }
372
+ /** The include entry's id prefix (loader entry ids look like `include:X`). */
373
+ function includePrefix(host) {
374
+ for (const entry of host.loader.entries()) {
375
+ if (entry.options?.name === 'cordis:include' && typeof entry.options.id === 'string') {
376
+ return `${entry.options.id}:`;
377
+ }
378
+ }
379
+ return '';
380
+ }
381
+ /**
382
+ * The user-patch row ids one installed package owns: its bundle patch's
383
+ * insert rows, plus the loader entries currently carrying its name.
384
+ * Empty for client-only packages (no bundle rows) — the market's own
385
+ * state.json mechanism covers those, and there is nothing to patch.
386
+ * Market-owned namespaces (hot-mount `mkt-*`, shim `client-*`) are
387
+ * excluded: their rows live in the market's own include subtree, and a
388
+ * permanent patch row targeting them would be a boot-time orphan.
389
+ */
390
+ export function rowIdsForPackage(host, profileDirectory, packageName) {
391
+ const ids = new Set();
392
+ const packageDir = join(profileDirectory, 'node_modules', packageName);
393
+ // ONLY the rows this package inserts (#147). A bundle patch also carries
394
+ // rows that merely reconfigure OTHER plugins — dsh-vision-router tunes the
395
+ // official `attachment-local` row — and writing `disabled: true` onto
396
+ // those took down attachments and the DeepSeek model along with it.
397
+ try {
398
+ for (const id of bundlePatchInsertedIds(packageDir))
399
+ ids.add(id);
400
+ }
401
+ catch { /* package not installed — loader side may still know it */ }
402
+ // The conventional location too: a package may ship cordis.patch.yml at
403
+ // its root without declaring dsh.bundle.patch (the loader probes it too).
404
+ // Same parser, deliberately: this used to be a second hand-rolled scan
405
+ // that closed the insert block only on `id:` lines, so `- disable:` with
406
+ // nested ids under it claimed the neighbour's rows — #147 all over again
407
+ // on the path #147 did not touch.
408
+ try {
409
+ for (const id of parsePatchRows(readFileSync(join(packageDir, 'cordis.patch.yml'), 'utf8')).insertedIds) {
410
+ ids.add(id);
411
+ }
412
+ }
413
+ catch { /* no conventional patch — nothing more to add */ }
414
+ const prefix = includePrefix(host);
415
+ for (const entry of host.loader.entries()) {
416
+ if (entry.options?.name !== packageName)
417
+ continue;
418
+ let id = loaderEntryId(entry);
419
+ if (id === '')
420
+ continue;
421
+ if (prefix !== '' && id.startsWith(prefix))
422
+ id = id.slice(prefix.length);
423
+ if (/^(?:mkt-|client-)/u.test(id))
424
+ continue;
425
+ ids.add(id);
426
+ }
427
+ return [...ids];
428
+ }
429
+ /**
430
+ * Top-level patch rows that DISABLE another plugin: a row carrying both an
431
+ * `id` and `disabled: true`. Rows nested under an `insert:` block are separate
432
+ * array elements shaped `{ insert: [...] }`, so anything here is by definition
433
+ * a sibling row targeting a plugin this package does not own.
434
+ */
435
+ function foreignDisableIds(rows) {
436
+ const ids = [];
437
+ for (const row of rows) {
438
+ if (row === null || typeof row !== 'object' || Array.isArray(row))
439
+ continue;
440
+ const record = row;
441
+ const id = record.id;
442
+ if (typeof id === 'string' && record.disabled === true && !ids.includes(id))
443
+ ids.push(id);
444
+ }
445
+ return ids;
446
+ }
447
+ /**
448
+ * Top-level patch rows that add an `inject:` requirement to another plugin.
449
+ *
450
+ * Same shape rule as foreignDisableIds: anything at the top level with an id
451
+ * is a statement about a plugin this package does not own. An `inject` there
452
+ * makes that foreign row depend on a service — usually one this bundle
453
+ * provides — so switching this package off while leaving its patch in the
454
+ * stack strands the row: #938's billion-context adds
455
+ * `inject: [biliBasicCompactionPolicy]` to the four official agent presets,
456
+ * and a row-level disable left them unable to activate.
457
+ */
458
+ function foreignInjectIds(rows) {
459
+ const ids = [];
460
+ for (const row of rows) {
461
+ if (row === null || typeof row !== 'object' || Array.isArray(row))
462
+ continue;
463
+ const record = row;
464
+ const id = record.id;
465
+ if (typeof id === 'string' && record.inject !== undefined && !ids.includes(id))
466
+ ids.push(id);
467
+ }
468
+ return ids;
469
+ }
470
+ /**
471
+ * The ids of OTHER plugins a package's bundle patch rewires — top-level rows
472
+ * that either `disabled: true` a plugin it does not own, or add an `inject:`
473
+ * requirement to one.
474
+ *
475
+ * Both are the marker of a bundle whose toggle-off can brick the boot while
476
+ * its patch keeps applying (#224, #938):
477
+ * - dsh-postgres-backends disables session-persistence-jsonl, so once the
478
+ * market also disables the postgres backends nothing provides
479
+ * sessionPersistence;
480
+ * - billion-context adds `inject: [biliBasicCompactionPolicy]` to the four
481
+ * official agent presets, so disabling only its own row leaves the presets
482
+ * waiting for a service that no longer exists — every preset disappears.
483
+ *
484
+ * A bundle that merely RECONFIGURES a neighbour is deliberately NOT counted:
485
+ * the e2e fixture-cross tweaks dshm-fixture-b's config, and #147 requires
486
+ * disabling it to leave that neighbour live — dropping such a bundle from the
487
+ * stack broke its re-enable. Config-only side effects stay on the normal #147
488
+ * path. Removing the bundle still neutralizes any config side effects it
489
+ * carries, since its whole patch stops applying.
490
+ *
491
+ * Reads both patch sources like rowIdsForPackage — the declared
492
+ * dsh.bundle.patch (one file or a LIST of them, #792) and the conventional
493
+ * root cordis.patch.yml — so either form is detected, and every declared file
494
+ * is attributed.
495
+ */
496
+ export function carrierRowIds(profileDirectory, packageName) {
497
+ const packageDir = join(profileDirectory, 'node_modules', packageName);
498
+ const rows = new Set();
499
+ const collectFromFile = (patchPath) => {
500
+ const parsed = parsePatchFile(patchPath);
501
+ if (parsed === null)
502
+ return;
503
+ for (const id of foreignDisableIds(parsed))
504
+ rows.add(id);
505
+ for (const id of foreignInjectIds(parsed))
506
+ rows.add(id);
507
+ };
508
+ for (const file of declaredBundlePatchFiles(packageDir))
509
+ collectFromFile(file);
510
+ collectFromFile(join(packageDir, 'cordis.patch.yml'));
511
+ return [...rows];
512
+ }
513
+ /**
514
+ * The ids a package's bundle patch touches WITHOUT inserting them itself.
515
+ *
516
+ * `insert:` rows are the package's own — that split is what `rowIdsForPackage`
517
+ * relies on (#147: a bundle patch also carries rows that merely reconfigure
518
+ * other plugins, and writing `disabled: true` onto those took down the
519
+ * neighbour). Every other row is a statement about a DIFFERENT plugin.
520
+ *
521
+ * It answers one question for the toggle route (#696 B): may this bundle leave
522
+ * `dsh.profile.bundles` when the user turns it off? Leaving takes its whole
523
+ * patch with it, which is exactly right when the patch speaks only for itself
524
+ * and wrong when it configures a neighbour — the shape #147 and the
525
+ * fixture-cross e2e exist to protect, where the neighbour must keep running
526
+ * and the bundle must keep re-enabling.
527
+ *
528
+ * Reads both patch sources like carrierRowIds: the declared
529
+ * `dsh.bundle.patch` (one file or a LIST, #792) and the conventional root
530
+ * cordis.patch.yml. Ownership is judged per file, because a package may ship
531
+ * both and only the file's own `insert:` block says which ids it brings in.
532
+ */
533
+ export function foreignRowIds(profileDirectory, packageName) {
534
+ const packageDir = join(profileDirectory, 'node_modules', packageName);
535
+ const foreign = new Set();
536
+ const collect = (text) => {
537
+ const rows = parsePatchText(text);
538
+ if (rows === null)
539
+ return;
540
+ const own = new Set(parsePatchRows(text).insertedIds);
541
+ for (const row of rows) {
542
+ if (row === null || typeof row !== 'object' || Array.isArray(row))
543
+ continue;
544
+ const id = row.id;
545
+ if (typeof id === 'string' && id !== '' && !own.has(id))
546
+ foreign.add(id);
547
+ }
548
+ };
549
+ const readPatch = (patchPath) => {
550
+ try {
551
+ collect(readFileSync(patchPath, 'utf8'));
552
+ }
553
+ catch { /* no such patch — nothing attributed to it */ }
554
+ };
555
+ for (const file of declaredBundlePatchFiles(packageDir))
556
+ readPatch(file);
557
+ readPatch(join(packageDir, 'cordis.patch.yml'));
558
+ return [...foreign];
559
+ }
560
+ /**
561
+ * Per-package patch-layer flags for the installed list: names whose rows the
562
+ * user patch layer disables / force-enables. These cover toggles made
563
+ * OUTSIDE the market (hand-edited cordis.patch.yml, dsh-web-plugin-manager,
564
+ * the dsh CLI), which the market's own state.json never sees.
565
+ */
566
+ export function packagePatchFlags(host, profileDirectory, names, state) {
567
+ const disabled = [];
568
+ const forced = [];
569
+ for (const name of names) {
570
+ const rows = rowIdsForPackage(host, profileDirectory, name);
571
+ // Rows the package's own layer already ships off say nothing about what
572
+ // the user decided (#876): `dsh-mnemon` ships four strategy rows as
573
+ // opt-in, its user patch layer repeats one of them, and the package was
574
+ // reported as 「已停用 / 重启后保持关闭」 while it was running. Only the
575
+ // user's decisions ABOVE the bundle's own default count.
576
+ const optOut = new Set(bundleOptOutRowIds(join(profileDirectory, 'node_modules', name)));
577
+ const decidedByUser = (id) => !optOut.has(id);
578
+ // A row that names a module other than this id's does nothing in the
579
+ // host, so it is not a decision about this package (#1113): the shape a
580
+ // package rename leaves behind.
581
+ const applies = (id) => rowFlagApplies(state, id, composedRowName(host, id));
582
+ if (rows.some(id => decidedByUser(id) && applies(id) && state.disables.includes(id)))
583
+ disabled.push(name);
584
+ if (rows.some(id => decidedByUser(id) && applies(id) && state.forced.includes(id)))
585
+ forced.push(name);
586
+ }
587
+ return { disabled, forced };
588
+ }
589
+ /** Serialize patch-file writes: concurrent toggles must not interleave. */
590
+ let writeQueue = Promise.resolve();
591
+ function queuedWrite(fn) {
592
+ const run = writeQueue.then(fn, fn);
593
+ writeQueue = run.then(() => undefined, () => undefined);
594
+ return run;
595
+ }
596
+ function escapeRegExp(value) {
597
+ return value.replace(/[.*+?^${}()|[\]\\]/gu, '\\$&');
598
+ }
599
+ function rowBlock(rowId, disabled) {
600
+ return `- id: ${rowId}\n disabled: ${disabled ? 'true' : 'false'}\n`;
601
+ }
602
+ /**
603
+ * Rewrite standalone id/flag rows while preserving the surrounding file.
604
+ * Comments and blank lines may separate the fields (#930). Look beyond them
605
+ * after the flag too: an indented config/name/key makes this a longer entry,
606
+ * whose first lines must never be removed (#821). Trailing comments stay put.
607
+ */
608
+ function rewriteRowBlocks(text, rowId, disabled, replace, expected = null) {
609
+ const id = escapeRegExp(rowId);
610
+ const idLine = new RegExp(`^- id: (?:${id}|'${id}'|"${id}")[ \t]*$`, 'u');
611
+ const lines = text.match(/[^\n]*(?:\n|$)/gu)?.filter(Boolean) ?? [];
612
+ const offsets = [0];
613
+ for (const line of lines)
614
+ offsets.push(offsets[offsets.length - 1] + line.length);
615
+ let result = '', copied = 0;
616
+ for (let index = 0; index < lines.length; index += 1) {
617
+ if (!idLine.test(lines[index].replace(/\r?\n$/u, '')))
618
+ continue;
619
+ // A row that names another module is skipped by the host, so rewriting it
620
+ // would report a change that never happens (#1113).
621
+ const named = entryKeyValue(lines, index + 1, 'name');
622
+ if (!rowApplies(named === null ? null : named.replace(/^(['"])(.*)\1$/u, '$2'), expected))
623
+ continue;
624
+ const flagIndex = nextPatchContentLine(lines, index + 1);
625
+ const flag = /^ {2}disabled: (true|false)[ \t]*(?:\r?\n)?$/u.exec(lines[flagIndex] ?? '');
626
+ if (flag === null || (disabled !== 'any' && flag[1] !== disabled))
627
+ continue;
628
+ const following = nextPatchContentLine(lines, flagIndex + 1);
629
+ if (/^[ \t]/u.test(lines[following] ?? ''))
630
+ continue;
631
+ const start = offsets[index], end = offsets[flagIndex + 1];
632
+ result += text.slice(copied, start) + replace(text.slice(start, end));
633
+ copied = end;
634
+ index = flagIndex;
635
+ }
636
+ return result + text.slice(copied);
637
+ }
638
+ /**
639
+ * What the patch file finally says about one row: the flag of its last
640
+ * `- id: X` entry that carries one, rows with more keys included. Later
641
+ * entries override earlier ones.
642
+ */
643
+ /**
644
+ * The row's own flag as the HOST will compose it, from a real YAML parse.
645
+ *
646
+ * The line scanner is deliberately conservative, so it is blind to spellings
647
+ * it was not written for — flow style `- { id: x, disabled: true }`, `disabled`
648
+ * above `id`, `True`, a comment on the id line (#1112). The host parses the
649
+ * file and applies entries in order, the last one winning, so this is both the
650
+ * reading the user means and the one that decides.
651
+ *
652
+ * @returns 'true'/'false' from the last entry naming the row, or null when the
653
+ * text cannot be read as DSH's patch dialect — the caller then keeps the line
654
+ * scanner's answer rather than guessing.
655
+ */
656
+ function composedRowFlag(text, rowId, expected = null) {
657
+ let rows;
658
+ try {
659
+ rows = parsePatchText(text);
660
+ }
661
+ catch {
662
+ return null;
663
+ }
664
+ if (rows === null)
665
+ return null;
666
+ let flag = null;
667
+ for (const row of rows) {
668
+ if (row === null || typeof row !== 'object' || Array.isArray(row))
669
+ continue;
670
+ const entry = row;
671
+ if (entry.id !== rowId)
672
+ continue;
673
+ // A row naming another module never reaches this id's entry (#1113).
674
+ if (!rowApplies(entry.name, expected))
675
+ continue;
676
+ // An `!!js` expression arrives as a function (or a tag object): it decides
677
+ // by itself, and flattening it here would freeze one host's answer.
678
+ if (entry.disabled === true)
679
+ flag = 'true';
680
+ else if (entry.disabled === false)
681
+ flag = 'false';
682
+ }
683
+ return flag;
684
+ }
685
+ function lastRowFlag(text, rowId, expected = null) {
686
+ const id = escapeRegExp(rowId);
687
+ const idLine = new RegExp(`^- id: (?:${id}|'${id}'|"${id}")\\s*$`, 'u');
688
+ const lines = text.split(/\r?\n/u);
689
+ let flag = null;
690
+ for (let index = 0; index < lines.length; index += 1) {
691
+ if (!idLine.test(lines[index] ?? ''))
692
+ continue;
693
+ const named = entryKeyValue(lines, index + 1, 'name');
694
+ const name = named === null ? null : named.replace(/^(['"])(.*)\1$/u, '$2');
695
+ if (!rowApplies(name, expected))
696
+ continue;
697
+ const value = entryKeyValue(lines, index + 1, 'disabled');
698
+ if (value === 'true' || value === 'false')
699
+ flag = value;
700
+ }
701
+ return flag;
702
+ }
703
+ /**
704
+ * Append one top-level patch entry, refusing when the file is not a valid
705
+ * entry list. The refusal is the point: a malformed patch layer (the
706
+ * `[]` + items mistake, or any broken YAML) must never be made worse —
707
+ * the market reports it and keeps its own live/state.json toggle instead.
708
+ */
709
+ /**
710
+ * Write the patch file, or say in the user's words why it could not be
711
+ * written (kettly1260's family of reports, and #582's read-only case): a bare
712
+ * `EACCES: permission denied, open '…'` reaching the UI tells a user nothing
713
+ * they can act on, while the plugin's actual state has already changed.
714
+ */
715
+ /**
716
+ * The user patch as text, without a leading UTF-8 BOM.
717
+ *
718
+ * Windows Notepad saves UTF-8 with one, and `readFileSync` keeps it. js-yaml
719
+ * and the host strip it, so the host saw the first row while every
720
+ * `^`-anchored scan here missed it: a first `- id:` read as absent, and a
721
+ * first `[]` was not recognised as the placeholder, so a toggle appended
722
+ * after it and wrote a second top-level node. The market's own writes drop
723
+ * the BOM from then on. Throws like `readFileSync` when the file is missing.
724
+ */
725
+ function readPatchText(patchPath) {
726
+ const text = readFileSync(patchPath, 'utf8');
727
+ return text.startsWith('') ? text.slice(1) : text;
728
+ }
729
+ function writePatchFile(patchPath, contents) {
730
+ try {
731
+ writeFileSync(patchPath, contents);
732
+ return { ok: true, reason: null };
733
+ }
734
+ catch (error) {
735
+ const code = error !== null && typeof error === 'object' && 'code' in error ? String(error.code) : '';
736
+ const detail = code === 'EACCES' || code === 'EPERM' || code === 'EROFS'
737
+ ? '文件不可写(只读或被系统保护)'
738
+ : code === 'ENOSPC'
739
+ ? '磁盘空间不足'
740
+ : error instanceof Error ? error.message : String(error);
741
+ return {
742
+ ok: false,
743
+ reason: `补丁层文件写不进去:${detail} / the patch file could not be written: ${code === 'EACCES' || code === 'EPERM' || code === 'EROFS' ? 'it is read-only' : detail}`,
744
+ };
745
+ }
746
+ }
747
+ function appendPatchEntry(patchPath, block) {
748
+ let text = '';
749
+ try {
750
+ text = readPatchText(patchPath);
751
+ }
752
+ catch { /* created below */ }
753
+ const core = text.trim();
754
+ if (core === '') {
755
+ return writePatchFile(patchPath, block);
756
+ }
757
+ // The dsh profile template ships an empty `[]` placeholder (a valid
758
+ // empty list). Appending after it would create TWO top-level elements in
759
+ // one document — the exact YAML error a hand-edit runs into. Comment the
760
+ // placeholder out (keeping the template header) and append the entry.
761
+ const withoutComments = text.replace(/^[ \t]*#.*$/gmu, '').trim();
762
+ // Comments only (the user dropped the placeholder): append after them.
763
+ if (withoutComments === '') {
764
+ const next = text.endsWith('\n') ? text : `${text}\n`;
765
+ return writePatchFile(patchPath, `${next}${block}`);
766
+ }
767
+ if (withoutComments === '[]' || withoutComments === '[ ]') {
768
+ const commented = text.replace(/^[ \t]*\[[ \t]*\][ \t]*(?:#.*)?(?:\r?\n|$)/mu, '# []\n');
769
+ const next = commented.endsWith('\n') ? commented : `${commented}\n`;
770
+ return writePatchFile(patchPath, `${next}${block}`);
771
+ }
772
+ // A top-level flow LIST (other than the placeholder above) cannot be
773
+ // appended to: `- id: X` after `[1, 2]` would create two top-level
774
+ // elements in one document. Block items whose VALUE is flow style (e.g.
775
+ // `- config: [1, 2]`) are fine — their last line starts with `- `.
776
+ const lastContentLine = text.split(/\r?\n/u)
777
+ .map(line => line.trim())
778
+ .filter(line => line !== '' && !line.startsWith('#'))
779
+ .pop() ?? '';
780
+ if (/^[[{]/u.test(lastContentLine)) {
781
+ return {
782
+ ok: false,
783
+ reason: '补丁层以顶层流式结构结尾,不支持自动追加;请先整理为条目列表 / the patch layer ends in a top-level flow structure; refusing to append — tidy the file into an entry list first',
784
+ };
785
+ }
786
+ // The dsh entry-list dialect decides: anything that does not parse as a
787
+ // top-level array is left untouched (appending would deepen the break).
788
+ if (parsePatchFile(patchPath) === null) {
789
+ return {
790
+ ok: false,
791
+ reason: '补丁层不是合法的条目数组,已拒绝追加以免破坏;请先修正 YAML / the patch layer is not a valid entry list; refused to append — fix the YAML first',
792
+ };
793
+ }
794
+ const next = text.endsWith('\n') ? text : `${text}\n`;
795
+ return writePatchFile(patchPath, `${next}${block}`);
796
+ }
797
+ /**
798
+ * Disable one row: `- id: X` + `disabled: true` (idempotent).
799
+ *
800
+ * A force-enable block already there is flipped in place rather than
801
+ * followed by a second block (#821): the pair cancelled out by order alone,
802
+ * and an uninstall that cleared one of them left the other behind to switch
803
+ * a later reinstall off. Duplicates an older version left are folded into
804
+ * the one block at the same time.
805
+ */
806
+ export function disableRow(patchPath, rowId, options = {}) {
807
+ return queuedWrite(async () => {
808
+ if (!ROW_ID_RE.test(rowId)) {
809
+ return { ok: false, reason: `行 id 含特殊字符,不支持写入补丁层 / row id ${rowId} cannot be written to the patch layer` };
810
+ }
811
+ const text = (() => {
812
+ try {
813
+ return readPatchText(patchPath);
814
+ }
815
+ catch {
816
+ return '';
817
+ }
818
+ })();
819
+ let kept = false;
820
+ const next = rewriteRowBlocks(text, rowId, 'any', block => {
821
+ if (kept)
822
+ return '';
823
+ kept = true;
824
+ return block.replace(/^ {2}disabled: false(?=[ \t]*(?:\r?\n|$))/mu, ' disabled: true');
825
+ }, options.expectedName ?? null);
826
+ if (next !== text) {
827
+ const flipped = writePatchFile(patchPath, next);
828
+ if (!flipped.ok)
829
+ return flipped;
830
+ // A longer entry for the row further down still has the last word.
831
+ if (lastRowFlag(next, rowId, options.expectedName ?? null) !== 'true') {
832
+ const result = appendPatchEntry(patchPath, rowBlock(rowId, true));
833
+ if (!result.ok)
834
+ return result;
835
+ }
836
+ logEvent('info', 'patch', `disabled row ${rowId} in ${patchPath}`);
837
+ return { ok: true, reason: null };
838
+ }
839
+ // A row whose `name` is not this entry's owns nothing here: counting it
840
+ // as already-disabled would answer "off" and change nothing, leaving the
841
+ // plugin running (#1113).
842
+ const state = withoutMismatchedRow(readUserPatchState(patchPath), rowId, options.expectedName ?? null);
843
+ if (state.disables.includes(rowId))
844
+ return { ok: true, reason: null };
845
+ const result = appendPatchEntry(patchPath, rowBlock(rowId, true));
846
+ if (result.ok)
847
+ logEvent('info', 'patch', `disabled row ${rowId} in ${patchPath}`);
848
+ return result;
849
+ });
850
+ }
851
+ /** Enable one row: remove its `disabled: true` blocks; force-enable with
852
+ * `disabled: false` when a lower layer (bundle/home patch) holds it down, or
853
+ * when a longer entry of the row still says `disabled: true` (#1099): that
854
+ * entry is never cut up (#821), so it can only be overridden from below.
855
+ *
856
+ * `cleanOnly` is that cleanup and nothing else: remove a block the market
857
+ * itself left on a row, never write a new one (#1110). An opt-in row of a
858
+ * bundle and a row whose `disabled` is an expression are off by design, and
859
+ * appending `disabled: false` above them force-opens a row that should stay
860
+ * closed — the host composes later entries last, so the append wins. */
861
+ export function enableRow(patchPath, rowId, options = {}) {
862
+ const cleanOnly = options.cleanOnly === true;
863
+ const expected = options.expectedName ?? null;
864
+ return queuedWrite(async () => {
865
+ if (!ROW_ID_RE.test(rowId)) {
866
+ return { ok: false, reason: `行 id 含特殊字符,不支持写入补丁层 / row id ${rowId} cannot be written to the patch layer` };
867
+ }
868
+ const state = withoutMismatchedRow(readUserPatchState(patchPath), rowId, expected);
869
+ const text = (() => {
870
+ try {
871
+ return readPatchText(patchPath);
872
+ }
873
+ catch {
874
+ return '';
875
+ }
876
+ })();
877
+ const next = rewriteRowBlocks(text, rowId, 'true', () => '', expected);
878
+ if (next !== text) {
879
+ const written = writePatchFile(patchPath, withPlaceholderRestored(next));
880
+ if (!written.ok)
881
+ return written;
882
+ // A longer entry for the row may still have the last word — and so may a
883
+ // spelling the line scanner cannot see (#1112). Ask the parser the host
884
+ // uses; when the file is not readable as its dialect, fall back to the
885
+ // scanner.
886
+ const stillOff = composedRowFlag(next, rowId, expected) ?? lastRowFlag(next, rowId, expected);
887
+ if (!cleanOnly && stillOff === 'true') {
888
+ const result = appendPatchEntry(patchPath, rowBlock(rowId, false));
889
+ if (!result.ok)
890
+ return result;
891
+ }
892
+ logEvent('info', 'patch', `${cleanOnly ? 'cleared the block on' : 'enabled'} row ${rowId} in ${patchPath}`);
893
+ return { ok: true, reason: null };
894
+ }
895
+ // Nothing of the market's own to clean: the row's default stands.
896
+ if (cleanOnly)
897
+ return { ok: true, reason: null };
898
+ if (state.forced.includes(rowId))
899
+ return { ok: true, reason: null };
900
+ const result = appendPatchEntry(patchPath, rowBlock(rowId, false));
901
+ if (result.ok)
902
+ logEvent('info', 'patch', `force-enabled row ${rowId} in ${patchPath}`);
903
+ return result;
904
+ });
905
+ }
906
+ /**
907
+ * Put the empty-list placeholder back when nothing else is left.
908
+ *
909
+ * Appending the first row comments the template's `[]` out (see
910
+ * appendPatchEntry), so removing the LAST row leaves a file of pure
911
+ * comments. That is not a top-level array, and dsh refuses to boot the
912
+ * profile at all — "must be a top-level YAML array of loader patch
913
+ * entries". Disable a plugin, enable it again, and the profile is bricked.
914
+ */
915
+ function withPlaceholderRestored(text) {
916
+ if (text.replace(/^[ \t]*#.*$/gmu, '').trim() !== '')
917
+ return text;
918
+ const uncommented = text.replace(/^[ \t]*#[ \t]*\[[ \t]*\][ \t]*(?:\r?\n|$)/mu, '[]\n');
919
+ if (uncommented !== text)
920
+ return uncommented;
921
+ // No commented placeholder to revive (hand-written file): add one.
922
+ return text === '' || text.endsWith('\n') ? `${text}[]\n` : `${text}\n[]\n`;
923
+ }
924
+ /** Remove every disable/force block the market (or the user) wrote for a
925
+ * row — the uninstall cleanup, so a removed plugin leaves no orphan rows. */
926
+ export function removeRowBlocks(patchPath, rowIds) {
927
+ let text = '';
928
+ try {
929
+ text = readPatchText(patchPath);
930
+ }
931
+ catch {
932
+ return { ok: true, reason: null };
933
+ } // no file, nothing to remove
934
+ let next = text;
935
+ for (const rowId of rowIds)
936
+ next = rewriteRowBlocks(next, rowId, 'any', () => '');
937
+ if (next === text)
938
+ return { ok: true, reason: null };
939
+ const written = writePatchFile(patchPath, withPlaceholderRestored(next));
940
+ if (written.ok)
941
+ logEvent('info', 'patch', `removed patch rows for ${rowIds.join(', ')}`);
942
+ return written;
943
+ }