dsh-crate 0.5.2 → 0.5.4

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 (46) hide show
  1. package/assets/logo.svg +11 -33
  2. package/client/client.js +2271 -561
  3. package/lib/body-progress.js +4 -3
  4. package/lib/changelog.js +15 -2
  5. package/lib/discovery-cache.js +210 -0
  6. package/lib/discovery-compatibility.js +135 -90
  7. package/lib/drain.js +28 -9
  8. package/lib/dsh-cli.js +36 -6
  9. package/lib/github-install-target.js +53 -0
  10. package/lib/hot.js +400 -33
  11. package/lib/index.js +23 -9
  12. package/lib/install.js +37 -0
  13. package/lib/patch.js +123 -73
  14. package/lib/pending-rows.js +3 -4
  15. package/lib/pnpm-compat.js +234 -2
  16. package/lib/proc-text.js +16 -1
  17. package/lib/profile.js +17 -1
  18. package/lib/recovery.js +2 -1
  19. package/lib/registry.js +24 -16
  20. package/lib/release-candidates.js +4 -0
  21. package/lib/release-updates.js +9 -2
  22. package/lib/routes.js +459 -134
  23. package/lib/themes.js +42 -9
  24. package/lib/types/body-progress.d.ts +2 -1
  25. package/lib/types/changelog.d.ts +10 -1
  26. package/lib/types/discovery-cache.d.ts +38 -0
  27. package/lib/types/discovery-compatibility.d.ts +24 -14
  28. package/lib/types/dsh-cli.d.ts +19 -2
  29. package/lib/types/github-install-target.d.ts +11 -0
  30. package/lib/types/hot.d.ts +91 -7
  31. package/lib/types/index.d.ts +17 -0
  32. package/lib/types/install.d.ts +19 -0
  33. package/lib/types/patch.d.ts +6 -2
  34. package/lib/types/profile.d.ts +4 -1
  35. package/lib/types/registry.d.ts +9 -8
  36. package/lib/types/release-candidates.d.ts +2 -0
  37. package/lib/types/routes.d.ts +2 -2
  38. package/lib/types/themes.d.ts +7 -1
  39. package/lib/types/update-notification-settings.d.ts +5 -0
  40. package/lib/types/update-notifications.d.ts +51 -0
  41. package/lib/types/updates.d.ts +5 -1
  42. package/lib/update-notification-settings.js +6 -0
  43. package/lib/update-notifications.js +166 -0
  44. package/lib/updates.js +41 -11
  45. package/lib/verify.js +24 -2
  46. package/package.json +1 -1
package/lib/index.js CHANGED
@@ -2,6 +2,7 @@
2
2
  * dsh-crate host entry: mounts the market's HTTP routes once the profile
3
3
  * composes the webServer and shell services.
4
4
  */
5
+ import z from '@deepseek-ai/schemastery';
5
6
  import { dirname, isAbsolute } from 'node:path';
6
7
  import { createDesktopPluginRuntime, setHostPackageManager } from './dsh-cli.js';
7
8
  import { createOfficialDesktopRuntime } from './official-desktop.js';
@@ -22,6 +23,18 @@ export const name = 'dsh-crate';
22
23
  * (#928). Nothing happens when the journal is empty, which is the normal case.
23
24
  */
24
25
  const PENDING_UPDATE_REPAIR_DELAY_MS = 8_000;
26
+ /** A field the form may edit; newer hosts hand one back as a live reference (#1144). */
27
+ const editable = (schema) => schema.extra('volatile', true);
28
+ const valueOf = (field) => typeof field?.get === 'function' ? field.get() : field;
29
+ /** dsh 0.1.7+ builds its form from `plugin.Config` and writes `simplify(config)` back, so every field the market reads is named here or the first form save deletes it. Each is loose: an older composition still boots, a mistyped value is dropped, and neither editable field takes a default, so "unconfigured" stays distinguishable (#1144, #229). */
30
+ export const Config = z.object({
31
+ profile: z.string().loose(),
32
+ channel: z.string().loose(),
33
+ region: z.string().loose(),
34
+ allowRestart: editable(z.boolean().loose()),
35
+ maxSnapshots: editable(z.number().loose()),
36
+ buildEnv: z.dict(z.any()).loose().extra('default', undefined),
37
+ }).loose();
25
38
  /**
26
39
  * Register the market against the host context.
27
40
  * @param ctx - Host context that may acquire webServer and shell services.
@@ -289,7 +302,7 @@ export function apply(ctx, config) {
289
302
  },
290
303
  desktopHost: true,
291
304
  allowRestart: false,
292
- maxSnapshots: config?.maxSnapshots,
305
+ maxSnapshots: valueOf(config?.maxSnapshots),
293
306
  // The third construction site, and the one #527's review caught
294
307
  // missing: a `buildEnv` configured in cordis.yml was silently
295
308
  // dropped on the official desktop host — the very host the feature
@@ -315,9 +328,9 @@ export function apply(ctx, config) {
315
328
  repairTimer.unref?.();
316
329
  return async () => {
317
330
  clearTimeout(repairTimer);
318
- disposeRoutes();
331
+ const routesDisposed = disposeRoutes();
319
332
  restoreTrustedHosts();
320
- await runtime.dispose();
333
+ await Promise.all([routesDisposed, runtime.dispose()]);
321
334
  };
322
335
  }, 'dsh-crate: official Desktop routes and package operations');
323
336
  return;
@@ -342,8 +355,8 @@ export function apply(ctx, config) {
342
355
  // would turn "the operator said nothing" into "the operator said
343
356
  // yes", and restartAllowed() could no longer tell them apart — which
344
357
  // is exactly the distinction supervisor detection needs (#229).
345
- allowRestart: config?.allowRestart,
346
- maxSnapshots: config?.maxSnapshots,
358
+ allowRestart: valueOf(config?.allowRestart),
359
+ maxSnapshots: valueOf(config?.maxSnapshots),
347
360
  // Build-time environment (#336); undefined means "inherit", and the
348
361
  // settings wiring below is what makes it editable at runtime.
349
362
  buildEnv: config?.buildEnv,
@@ -355,8 +368,9 @@ export function apply(ctx, config) {
355
368
  const restoreTrustedHosts = useTrustedHosts(ctx);
356
369
  const disposeRoutes = mountMarketRoutes(host, resolved, undefined, agentsLookupOf(ctx));
357
370
  return () => {
358
- disposeRoutes();
371
+ const routesDisposed = disposeRoutes();
359
372
  restoreTrustedHosts();
373
+ return routesDisposed;
360
374
  };
361
375
  }, 'dsh-crate: http routes');
362
376
  return;
@@ -388,7 +402,7 @@ export function apply(ctx, config) {
388
402
  // Relaunching a raw Electron process would bypass Desktop's launcher
389
403
  // lifecycle. The shell remains responsible for restart in this mode.
390
404
  allowRestart: false,
391
- maxSnapshots: config?.maxSnapshots,
405
+ maxSnapshots: valueOf(config?.maxSnapshots),
392
406
  // The operator's pinned build environment applies in Desktop mode
393
407
  // too: Desktop's packaged pnpm still runs plugin build scripts.
394
408
  buildEnv: config?.buildEnv,
@@ -407,9 +421,9 @@ export function apply(ctx, config) {
407
421
  // market can ask for a replay instead of mounting a second entry.
408
422
  const disposeRoutes = mountMarketRoutes(host, resolved, runtime, agentsLookupOf(ctx), desktopProfiles.pluginActivation);
409
423
  return async () => {
410
- disposeRoutes();
424
+ const routesDisposed = disposeRoutes();
411
425
  restoreTrustedHosts();
412
- await runtime.dispose();
426
+ await Promise.all([routesDisposed, runtime.dispose()]);
413
427
  };
414
428
  }, 'dsh-crate: Desktop http routes and package operations');
415
429
  });
package/lib/install.js CHANGED
@@ -1004,6 +1004,43 @@ export function removeDanglingHostBridge(name, profileDirectory, hostDirectory)
1004
1004
  logEvent('info', 'uninstall', `${name}: removed the dangling host bridge the boot projection left at ${bridge}`);
1005
1005
  return true;
1006
1006
  }
1007
+ /**
1008
+ * Remove the link a confirmed uninstall left at `node_modules/<name>` (#1191).
1009
+ *
1010
+ * A plugin installed from a local checkout (`link:`) is a junction or
1011
+ * directory symlink into that checkout. The uninstall has removed the
1012
+ * dependency from package.json and the lockfile, but on Windows the link was
1013
+ * reported still there, and the next install of the same name (the online
1014
+ * release) makes pnpm rename `<name>_tmp_*` over it, which Windows refuses
1015
+ * with EPERM.
1016
+ *
1017
+ * Only a link is ever touched, and only when the manifest no longer lists
1018
+ * `name` — a link the profile still owns must survive. `rmSync` without
1019
+ * `recursive` unlinks the link itself and never reaches the checkout it points
1020
+ * at (the same measurement the host-bridge cleanup above relies on).
1021
+ *
1022
+ * @returns the checkout path the removed link pointed at, or null when there
1023
+ * was nothing to remove. Never throws: the uninstall already succeeded.
1024
+ */
1025
+ export function removeLeftoverProfileLink(profile, name, profileDirectory) {
1026
+ const path = join(profileDirectory, 'node_modules', name);
1027
+ try {
1028
+ if (!lstatSync(path).isSymbolicLink())
1029
+ return null;
1030
+ if (readInstalled(profile, profileDirectory)[name] !== undefined)
1031
+ return null;
1032
+ const target = readlinkSync(path);
1033
+ rmSync(path, { force: true });
1034
+ logEvent('info', 'uninstall', `${name}: removed the leftover link at node_modules/${name} (it pointed at ${target}); the checkout itself was not touched (#1191)`);
1035
+ return target;
1036
+ }
1037
+ catch (error) {
1038
+ if (error.code !== 'ENOENT') {
1039
+ logEvent('warn', 'uninstall', `${name}: could not remove the leftover link at node_modules/${name} — ${error instanceof Error ? error.message : String(error)}`);
1040
+ }
1041
+ return null;
1042
+ }
1043
+ }
1007
1044
  /**
1008
1045
  * Group flat `{id, owner}` conflict hits by the installed plugin that owns
1009
1046
  * them. What the user has to decide is which PLUGINS to uninstall, not which
package/lib/patch.js CHANGED
@@ -30,6 +30,7 @@ import { fileURLToPath } from 'node:url';
30
30
  import { logEvent } from './log.js';
31
31
  import { parsePatchFile, parsePatchText } from './check.js';
32
32
  import { bundleOptOutRowIds, bundlePatchInsertedIds, declaredBundlePatchFiles, parsePatchRows } from './profile.js';
33
+ import { NPM_NAME_RE } from './sources.js';
33
34
  /**
34
35
  * Host infrastructure rows: disabling any of these breaks the very chain
35
36
  * the patch layer runs on (e.g. timer → HMR, webserver → the page itself),
@@ -145,10 +146,29 @@ function nextPatchContentLine(lines, from) {
145
146
  * does not carry the key at all.
146
147
  */
147
148
  function entryKeyValue(lines, start, key) {
148
- const pattern = new RegExp(`^ {2}${key}:[ \\t]*(.*?)[ \\t]*$`, 'u');
149
+ return fieldValue(lines, start, 0, key);
150
+ }
151
+ /**
152
+ * The value of one field inside a row that starts before `start`.
153
+ *
154
+ * The field sits two spaces deeper than the `- id:` marker that opens the row.
155
+ * A top-level row is therefore written at two spaces and an inserted row — one
156
+ * nested under `- insert:` — at six, because the row itself sits at four. The
157
+ * block ends at the next line indented no deeper than the id; a comment at
158
+ * that depth is not structural and does not end it.
159
+ *
160
+ * @param indent - the column of the row's own `- id:` marker.
161
+ * @returns the scalar as written (comments stripped), or null when absent.
162
+ */
163
+ function fieldValue(lines, start, indent, key) {
164
+ const fieldIndent = indent + 2;
165
+ const pattern = new RegExp(`^ {${String(fieldIndent)}}${key}:[ \\t]*(.*?)[ \\t]*$`, 'u');
149
166
  for (let index = start; index < lines.length; index += 1) {
150
167
  const line = lines[index] ?? '';
151
- if (/^- /u.test(line))
168
+ const body = line.trimStart();
169
+ if (body === '')
170
+ continue;
171
+ if (line.length - body.length < fieldIndent && !body.startsWith('#'))
152
172
  return null;
153
173
  const match = pattern.exec(line);
154
174
  // A `#` starts a comment only after whitespace; `#` inside a bare scalar
@@ -185,13 +205,18 @@ function rowApplies(name, expected) {
185
205
  * treats a subpath name and a foreign package name the same way (#1113).
186
206
  */
187
207
  export function composedRowName(host, rowId) {
208
+ const prefix = includePrefix(host);
209
+ const profileId = prefix === '' ? rowId : prefix + rowId;
210
+ let directName = null;
188
211
  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;
212
+ const id = loaderEntryId(entry);
213
+ const candidate = entry.options?.name;
214
+ if (id === profileId && candidate)
215
+ return candidate;
216
+ if (id === rowId && candidate)
217
+ directName = candidate;
193
218
  }
194
- return null;
219
+ return directName;
195
220
  }
196
221
  /**
197
222
  * Whether the user layer's flag for this row is a decision the host applies.
@@ -205,18 +230,7 @@ export function rowFlagApplies(state, rowId, expected) {
205
230
  const carried = state.names?.[rowId];
206
231
  return carried === undefined || rowApplies(carried, expected);
207
232
  }
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) {
233
+ export function readUserPatchState(patchPath, expectedNameFor) {
220
234
  // The host composes the file in order, later entries override earlier ones,
221
235
  // so a row has one final flag: listing it as both disabled and forced showed
222
236
  // a plugin as off while the file had it on (#1099).
@@ -240,8 +254,24 @@ export function readUserPatchState(patchPath) {
240
254
  inInsert = false;
241
255
  if (inInsert) {
242
256
  const insertRow = /^ {4}- id: ([A-Za-z0-9_.-]+)/u.exec(line);
243
- if (insertRow !== null)
244
- inserts.push(insertRow[1]);
257
+ if (insertRow !== null) {
258
+ const inserted = insertRow[1];
259
+ inserts.push(inserted);
260
+ // An inserted row's own fields sit at six spaces, and the include
261
+ // composition applies `disabled` from either indent. Stopping at the id
262
+ // left every inserted row out of the flag map, so the market showed a
263
+ // plugin as on — with a toggle that could not be answered — while the
264
+ // loader had the row off.
265
+ const insertFlag = fieldValue(lines, index + 1, 4, 'disabled');
266
+ if (insertFlag === 'true' || insertFlag === 'false')
267
+ flags.set(inserted, insertFlag);
268
+ const insertNamed = fieldValue(lines, index + 1, 4, 'name');
269
+ const insertName = insertNamed === null ? null : insertNamed.replace(/^(['"])(.*)\1$/u, '$2');
270
+ if (insertName !== null && insertName !== '')
271
+ names.set(inserted, insertName);
272
+ else
273
+ names.delete(inserted);
274
+ }
245
275
  continue;
246
276
  }
247
277
  const disableRow = /^- id: (?:([A-Za-z0-9_.-]+)|'([A-Za-z0-9_.-]+)'|"([A-Za-z0-9_.-]+)")[ \t]*$/u.exec(line);
@@ -251,12 +281,14 @@ export function readUserPatchState(patchPath) {
251
281
  const value = entryKeyValue(lines, index + 1, 'disabled');
252
282
  if (value !== 'true' && value !== 'false')
253
283
  continue;
254
- flags.set(id, value);
255
284
  // A row that names a module is only applied by the host when that name is
256
285
  // the one the row's id composes to; the flag stays here so the caller can
257
286
  // make that comparison (#1113).
258
287
  const named = entryKeyValue(lines, index + 1, 'name');
259
288
  const unwrapped = named === null ? null : named.replace(/^(['"])(.*)\1$/u, '$2');
289
+ if (expectedNameFor !== undefined && !rowApplies(unwrapped, expectedNameFor(id)))
290
+ continue;
291
+ flags.set(id, value);
260
292
  if (unwrapped !== null && unwrapped !== '')
261
293
  names.set(id, unwrapped);
262
294
  else
@@ -579,7 +611,13 @@ export function packagePatchFlags(host, profileDirectory, names, state) {
579
611
  // host, so it is not a decision about this package (#1113): the shape a
580
612
  // package rename leaves behind.
581
613
  const applies = (id) => rowFlagApplies(state, id, composedRowName(host, id));
582
- if (rows.some(id => decidedByUser(id) && applies(id) && state.disables.includes(id)))
614
+ // A package counts as off only when nothing of it is left running: a
615
+ // multi-component plugin with some components switched off is still on
616
+ // (#1150). One disabled row used to flip the whole package, which kept
617
+ // it out of 「全部更新」.
618
+ // Rows that name another module do not count either way (#1113).
619
+ const decidedRows = rows.filter(id => decidedByUser(id) && applies(id));
620
+ if (decidedRows.length > 0 && decidedRows.every(id => state.disables.includes(id)))
583
621
  disabled.push(name);
584
622
  if (rows.some(id => decidedByUser(id) && applies(id) && state.forced.includes(id)))
585
623
  forced.push(name);
@@ -596,16 +634,20 @@ function queuedWrite(fn) {
596
634
  function escapeRegExp(value) {
597
635
  return value.replace(/[.*+?^${}()|[\]\\]/gu, '\\$&');
598
636
  }
599
- function rowBlock(rowId, disabled) {
600
- return `- id: ${rowId}\n disabled: ${disabled ? 'true' : 'false'}\n`;
637
+ const MARKET_ROW_MARKER = '# dsh-crate';
638
+ function moduleNameLine(name) {
639
+ return ` name: '${name}' ${MARKET_ROW_MARKER}`;
640
+ }
641
+ function rowBlock(rowId, disabled, name = null) {
642
+ const block = `- id: ${rowId}\n disabled: ${disabled ? 'true' : 'false'}\n`;
643
+ return name === null ? block : block + moduleNameLine(name) + '\n';
601
644
  }
602
645
  /**
603
646
  * 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.
647
+ * Also accept the module name market adds to its own rows (#1196). Any
648
+ * other key makes the entry a user configuration to preserve (#821).
607
649
  */
608
- function rewriteRowBlocks(text, rowId, disabled, replace, expected = null) {
650
+ function rewriteRowBlocks(text, rowId, disabled, replace, expected = null, owner = expected) {
609
651
  const id = escapeRegExp(rowId);
610
652
  const idLine = new RegExp(`^- id: (?:${id}|'${id}'|"${id}")[ \t]*$`, 'u');
611
653
  const lines = text.match(/[^\n]*(?:\n|$)/gu)?.filter(Boolean) ?? [];
@@ -616,22 +658,27 @@ function rewriteRowBlocks(text, rowId, disabled, replace, expected = null) {
616
658
  for (let index = 0; index < lines.length; index += 1) {
617
659
  if (!idLine.test(lines[index].replace(/\r?\n$/u, '')))
618
660
  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
661
  const flagIndex = nextPatchContentLine(lines, index + 1);
625
662
  const flag = /^ {2}disabled: (true|false)[ \t]*(?:\r?\n)?$/u.exec(lines[flagIndex] ?? '');
626
663
  if (flag === null || (disabled !== 'any' && flag[1] !== disabled))
627
664
  continue;
628
- const following = nextPatchContentLine(lines, flagIndex + 1);
665
+ let lastKey = flagIndex;
666
+ let name = null;
667
+ let following = nextPatchContentLine(lines, lastKey + 1);
668
+ const marker = /^ {2}name: (['"])([^'"]+)\1[ \t]+# dsh-crate[ \t]*(?:\r?\n)?$/u.exec(lines[following] ?? '');
669
+ if (marker !== null) {
670
+ name = marker[2];
671
+ if (!NPM_NAME_RE.test(name) || !rowApplies(name, expected) || !rowApplies(name, owner))
672
+ continue;
673
+ lastKey = following;
674
+ following = nextPatchContentLine(lines, lastKey + 1);
675
+ }
629
676
  if (/^[ \t]/u.test(lines[following] ?? ''))
630
677
  continue;
631
- const start = offsets[index], end = offsets[flagIndex + 1];
632
- result += text.slice(copied, start) + replace(text.slice(start, end));
678
+ const start = offsets[index], end = offsets[lastKey + 1];
679
+ result += text.slice(copied, start) + replace(text.slice(start, end), name);
633
680
  copied = end;
634
- index = flagIndex;
681
+ index = lastKey;
635
682
  }
636
683
  return result + text.slice(copied);
637
684
  }
@@ -744,12 +791,7 @@ function writePatchFile(patchPath, contents) {
744
791
  };
745
792
  }
746
793
  }
747
- function appendPatchEntry(patchPath, block) {
748
- let text = '';
749
- try {
750
- text = readPatchText(patchPath);
751
- }
752
- catch { /* created below */ }
794
+ function appendPatchEntry(patchPath, block, text) {
753
795
  const core = text.trim();
754
796
  if (core === '') {
755
797
  return writePatchFile(patchPath, block);
@@ -785,7 +827,7 @@ function appendPatchEntry(patchPath, block) {
785
827
  }
786
828
  // The dsh entry-list dialect decides: anything that does not parse as a
787
829
  // top-level array is left untouched (appending would deepen the break).
788
- if (parsePatchFile(patchPath) === null) {
830
+ if (parsePatchText(text) === null) {
789
831
  return {
790
832
  ok: false,
791
833
  reason: '补丁层不是合法的条目数组,已拒绝追加以免破坏;请先修正 YAML / the patch layer is not a valid entry list; refused to append — fix the YAML first',
@@ -804,6 +846,8 @@ function appendPatchEntry(patchPath, block) {
804
846
  * the one block at the same time.
805
847
  */
806
848
  export function disableRow(patchPath, rowId, options = {}) {
849
+ const expected = options.expectedName ?? null;
850
+ const name = options.recordModuleName === true && expected !== null && NPM_NAME_RE.test(expected) ? expected : null;
807
851
  return queuedWrite(async () => {
808
852
  if (!ROW_ID_RE.test(rowId)) {
809
853
  return { ok: false, reason: `行 id 含特殊字符,不支持写入补丁层 / row id ${rowId} cannot be written to the patch layer` };
@@ -817,32 +861,33 @@ export function disableRow(patchPath, rowId, options = {}) {
817
861
  }
818
862
  })();
819
863
  let kept = false;
820
- const next = rewriteRowBlocks(text, rowId, 'any', block => {
864
+ const next = rewriteRowBlocks(text, rowId, 'any', (block, recordedName) => {
821
865
  if (kept)
822
866
  return '';
823
867
  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)
868
+ const flipped = block.replace(/^ {2}disabled: false(?=[ \t]*(?:\r?\n|$))/mu, ' disabled: true');
869
+ if (recordedName !== null || name === null)
829
870
  return flipped;
871
+ const eol = block.includes('\r\n') ? '\r\n' : '\n';
872
+ return (flipped.endsWith('\n') ? flipped : flipped + eol) + moduleNameLine(name) + eol;
873
+ }, expected, options.packageName ?? expected);
874
+ if (next !== text) {
830
875
  // 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
- }
876
+ const result = lastRowFlag(next, rowId, expected) === 'true'
877
+ ? writePatchFile(patchPath, next)
878
+ : appendPatchEntry(patchPath, rowBlock(rowId, true, name), next);
879
+ if (!result.ok)
880
+ return result;
836
881
  logEvent('info', 'patch', `disabled row ${rowId} in ${patchPath}`);
837
882
  return { ok: true, reason: null };
838
883
  }
839
884
  // A row whose `name` is not this entry's owns nothing here: counting it
840
885
  // as already-disabled would answer "off" and change nothing, leaving the
841
886
  // plugin running (#1113).
842
- const state = withoutMismatchedRow(readUserPatchState(patchPath), rowId, options.expectedName ?? null);
887
+ const state = readUserPatchState(patchPath, id => id === rowId ? expected ?? options.packageName ?? null : null);
843
888
  if (state.disables.includes(rowId))
844
889
  return { ok: true, reason: null };
845
- const result = appendPatchEntry(patchPath, rowBlock(rowId, true));
890
+ const result = appendPatchEntry(patchPath, rowBlock(rowId, true, name), text);
846
891
  if (result.ok)
847
892
  logEvent('info', 'patch', `disabled row ${rowId} in ${patchPath}`);
848
893
  return result;
@@ -865,7 +910,7 @@ export function enableRow(patchPath, rowId, options = {}) {
865
910
  if (!ROW_ID_RE.test(rowId)) {
866
911
  return { ok: false, reason: `行 id 含特殊字符,不支持写入补丁层 / row id ${rowId} cannot be written to the patch layer` };
867
912
  }
868
- const state = withoutMismatchedRow(readUserPatchState(patchPath), rowId, expected);
913
+ const state = readUserPatchState(patchPath, id => id === rowId ? expected ?? options.packageName ?? null : null);
869
914
  const text = (() => {
870
915
  try {
871
916
  return readPatchText(patchPath);
@@ -874,30 +919,35 @@ export function enableRow(patchPath, rowId, options = {}) {
874
919
  return '';
875
920
  }
876
921
  })();
877
- const next = rewriteRowBlocks(text, rowId, 'true', () => '', expected);
922
+ let removedMarketName;
923
+ const next = rewriteRowBlocks(text, rowId, 'true', (_block, name) => {
924
+ if (name !== null)
925
+ removedMarketName = name;
926
+ return '';
927
+ }, expected, options.packageName ?? expected);
878
928
  if (next !== text) {
879
- const written = writePatchFile(patchPath, withPlaceholderRestored(next));
880
- if (!written.ok)
881
- return written;
882
929
  // A longer entry for the row may still have the last word — and so may a
883
930
  // spelling the line scanner cannot see (#1112). Ask the parser the host
884
931
  // uses; when the file is not readable as its dialect, fall back to the
885
932
  // 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
- }
933
+ const target = expected ?? removedMarketName ?? options.packageName ?? null;
934
+ const stillOff = composedRowFlag(next, rowId, target) ?? lastRowFlag(next, rowId, target);
935
+ const written = !cleanOnly && stillOff === 'true'
936
+ ? appendPatchEntry(patchPath, rowBlock(rowId, false, removedMarketName ?? null), next)
937
+ : writePatchFile(patchPath, withPlaceholderRestored(next));
938
+ if (!written.ok)
939
+ return written;
892
940
  logEvent('info', 'patch', `${cleanOnly ? 'cleared the block on' : 'enabled'} row ${rowId} in ${patchPath}`);
893
- return { ok: true, reason: null };
941
+ return removedMarketName === undefined
942
+ ? { ok: true, reason: null }
943
+ : { ok: true, reason: null, removedMarketName };
894
944
  }
895
945
  // Nothing of the market's own to clean: the row's default stands.
896
946
  if (cleanOnly)
897
947
  return { ok: true, reason: null };
898
948
  if (state.forced.includes(rowId))
899
949
  return { ok: true, reason: null };
900
- const result = appendPatchEntry(patchPath, rowBlock(rowId, false));
950
+ const result = appendPatchEntry(patchPath, rowBlock(rowId, false), text);
901
951
  if (result.ok)
902
952
  logEvent('info', 'patch', `force-enabled row ${rowId} in ${patchPath}`);
903
953
  return result;
@@ -923,7 +973,7 @@ function withPlaceholderRestored(text) {
923
973
  }
924
974
  /** Remove every disable/force block the market (or the user) wrote for a
925
975
  * row — the uninstall cleanup, so a removed plugin leaves no orphan rows. */
926
- export function removeRowBlocks(patchPath, rowIds) {
976
+ export function removeRowBlocks(patchPath, rowIds, packageName = null) {
927
977
  let text = '';
928
978
  try {
929
979
  text = readPatchText(patchPath);
@@ -933,7 +983,7 @@ export function removeRowBlocks(patchPath, rowIds) {
933
983
  } // no file, nothing to remove
934
984
  let next = text;
935
985
  for (const rowId of rowIds)
936
- next = rewriteRowBlocks(next, rowId, 'any', () => '');
986
+ next = rewriteRowBlocks(next, rowId, 'any', () => '', packageName);
937
987
  if (next === text)
938
988
  return { ok: true, reason: null };
939
989
  const written = writePatchFile(patchPath, withPlaceholderRestored(next));
@@ -30,14 +30,13 @@
30
30
  * ordinary start after a restart.
31
31
  */
32
32
  import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
33
- import { dirname } from 'node:path';
33
+ import { dirname, join } from 'node:path';
34
34
  import { removeRowBlocks } from './patch.js';
35
35
  import { readInstalled } from './profile.js';
36
- import { statePath } from './state.js';
37
36
  const STATE_VERSION = 1;
38
37
  /** Same directory as the other durable per-profile state (see pending-updates.ts). */
39
38
  export function pendingRowsFile(profileDirectory) {
40
- return statePath(profileDirectory, 'pending-rows.json');
39
+ return join(profileDirectory, '.dsh-crate', 'pending-rows.json');
41
40
  }
42
41
  export class PendingRowJournal {
43
42
  file;
@@ -130,7 +129,7 @@ export function repairOrphanedRows(options) {
130
129
  report.kept.push(record.name);
131
130
  continue;
132
131
  }
133
- const cleaned = removeRowBlocks(record.patchPath, record.rows);
132
+ const cleaned = removeRowBlocks(record.patchPath, record.rows, record.name);
134
133
  if (!cleaned.ok) {
135
134
  report.failed.push(record.name);
136
135
  continue;