dsh-crate 0.5.7 → 0.5.8

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/lib/backup.js CHANGED
@@ -15,7 +15,7 @@ import { profileDir } from './profile.js';
15
15
  export const BACKUP_FORMAT = 'dsh-profile-backup';
16
16
  export const MAX_BACKUP_BYTES = 2 * 1024 * 1024;
17
17
  const MAX_FILES = 256;
18
- const SKIP_NAMES = new Set(['node_modules', '.dsh-crate', '.dsh-shelfry', '.git', 'pnpm-lock.yaml']);
18
+ const SKIP_NAMES = new Set(['node_modules', '.dsh-crate', '.git', 'pnpm-lock.yaml']);
19
19
  /**
20
20
  * Directories that are caches by name, wherever they sit.
21
21
  *
@@ -380,7 +380,7 @@ export async function uploadWebdav(url, username, password, backup) {
380
380
  */
381
381
  function describeUploadFailure(status) {
382
382
  if (status === 401) {
383
- return 'WebDAV 上传被拒绝(HTTP 401):服务端不认这个用户名或密码。密码不会保存到磁盘,刷新页面或重启后需要重新输入;填好后点「上传备份」重试。 / The WebDAV server rejected these credentials (HTTP 401). The password is never stored, so it has to be entered again after a reload or restart; fill it in and press Upload backup.';
383
+ return 'WebDAV 上传被拒绝(HTTP 401):服务端不认这个用户名或密码,可能是密码没填,或填错了。重新输入密码后点「上传备份」重试;密码默认不保存,勾选「记住密码」可省去重复输入。 / The WebDAV server rejected these credentials (HTTP 401): the password is missing or wrong. Enter it again and press Upload backup. The password is not saved by default; turn on Remember password to skip this next time.';
384
384
  }
385
385
  if (status === 403) {
386
386
  return 'WebDAV 上传被拒绝(HTTP 403):凭据有效,但这个账号没有写入该路径的权限。换一个可写的目录,或检查服务商的权限设置。 / The WebDAV server refused the write (HTTP 403): the credentials are valid but this account cannot write to that path. Use a writable folder, or check the provider\'s permissions.';
package/lib/check.js CHANGED
@@ -1155,7 +1155,10 @@ export function findResidualDirectories(profileDirectory, declared) {
1155
1155
  const out = [];
1156
1156
  // pnpm's staging name, from its own rename: `<name>_tmp_<pid>_<n>`.
1157
1157
  const tmpShape = /^(.+)_tmp_\d+_\w+$/;
1158
- const consider = (directory, entry, relative) => {
1158
+ // `scope` is '@x/' when `directory` is a scope root: the name a package
1159
+ // is declared under is the FULL name, so the exemption and the report both
1160
+ // need it (#1261).
1161
+ const consider = (directory, entry, relative, scope = '') => {
1159
1162
  // pnpm's own bookkeeping lives in here beside the packages: `.pnpm` (the
1160
1163
  // virtual store), `.bin`, `.modules.yaml`, `.ignored`. None of them is a
1161
1164
  // package, so none of them is a broken one.
@@ -1176,10 +1179,31 @@ export function findResidualDirectories(profileDirectory, declared) {
1176
1179
  return;
1177
1180
  const tmp = tmpShape.exec(entry);
1178
1181
  if (tmp !== null) {
1179
- out.push({ name: tmp[1], path: join(relative, entry), kind: 'tmp-directory', declared: declared.has(tmp[1]) });
1182
+ out.push({ name: scope + tmp[1], path: join(relative, entry), kind: 'tmp-directory', declared: declared.has(scope + tmp[1]) });
1180
1183
  return;
1181
1184
  }
1182
- if (declared.has(entry))
1185
+ // A scope root (`@x`) never has a package.json of its own: it only holds
1186
+ // packages. Judge each child by the same rules, and never report the
1187
+ // root while a valid package may live in it — in a hoisted layout those
1188
+ // are in-use plugins and their dependencies (#1261).
1189
+ if (scope === '' && entry.startsWith('@')) {
1190
+ let children;
1191
+ try {
1192
+ children = readdirSync(join(directory, entry));
1193
+ }
1194
+ catch {
1195
+ return;
1196
+ }
1197
+ if (children.length === 0) {
1198
+ out.push({ name: entry, path: join(relative, entry), kind: 'empty-directory', declared: false });
1199
+ return;
1200
+ }
1201
+ for (const child of children)
1202
+ consider(join(directory, entry), child, join(relative, entry), `${entry}/`);
1203
+ return;
1204
+ }
1205
+ const fullName = scope + entry;
1206
+ if (declared.has(fullName))
1183
1207
  return;
1184
1208
  let readable = false;
1185
1209
  try {
@@ -1188,7 +1212,7 @@ export function findResidualDirectories(profileDirectory, declared) {
1188
1212
  }
1189
1213
  catch { /* missing or unparseable — that is the finding */ }
1190
1214
  if (!readable)
1191
- out.push({ name: entry, path: join(relative, entry), kind: 'incomplete-package', declared: false });
1215
+ out.push({ name: fullName, path: join(relative, entry), kind: 'incomplete-package', declared: false });
1192
1216
  };
1193
1217
  const nodeModules = join(profileDirectory, 'node_modules');
1194
1218
  try {
@@ -5,6 +5,7 @@ import { classifyPnpmFailure } from './pnpm-compat.js';
5
5
  import { DeadlineExceeded, PendingUpdateJournal, repairInterruptedUpdates, withDeadline, } from './pending-updates.js';
6
6
  import { profileDir, readInstalledVersion } from './profile.js';
7
7
  import { activeRegion, DEFAULT_NPM_REGISTRY, routesFor } from './regions.js';
8
+ import { clearStartupRepairEntry } from './startup-repair-report.js';
8
9
  /**
9
10
  * How long the desktop manager gets before the market stops waiting.
10
11
  *
@@ -621,6 +622,13 @@ packageManager) {
621
622
  const message = ok ? '' : result.needsRestart === true ? RESTART_FIRST_MESSAGE : detail(result.error);
622
623
  if (!ok)
623
624
  progress.error = message;
625
+ // A later success for this package outdates what start-up repair said
626
+ // about it earlier in this process.
627
+ if (ok && directory !== undefined) {
628
+ const settledName = registryNameOf(target);
629
+ if (settledName !== undefined)
630
+ clearStartupRepairEntry(profileName, directory, settledName);
631
+ }
624
632
  // The manager never settled: the profile may be half-updated, so this
625
633
  // is neither "nothing happened" nor something the route can restore
626
634
  // through the same stuck manager (#928).
@@ -186,6 +186,14 @@ export const MAX_AUTO_REPAIR_ATTEMPTS = 3;
186
186
  function gaveUpCopy(name, attempts) {
187
187
  return `${name} 还没装回来:之前 ${String(attempts)} 次启动都没能装好,市场不再自动重试。请到「设置 → 插件」重新安装它 / ${name} is still missing: ${String(attempts)} starts could not reinstall it, so the market stopped retrying — reinstall it from Settings → Plugins`;
188
188
  }
189
+ function errorCodeOf(error) {
190
+ const code = error?.code;
191
+ return typeof code === 'string' ? code : undefined;
192
+ }
193
+ /** The manager's own code, when it named one, so a log line says why and not just "refused". */
194
+ function withCode(message, code) {
195
+ return code === undefined ? message : `${message} [${code}]`;
196
+ }
189
197
  function managerSucceeded(result) {
190
198
  return result.application === 'applied'
191
199
  || result.application === 'restart-required'
@@ -305,12 +313,38 @@ export async function repairInterruptedUpdates(options) {
305
313
  }
306
314
  const spec = entry.to === '' ? entry.spec : `${entry.name}@${entry.to}`;
307
315
  let cause = 'unknown';
316
+ let lastCode;
308
317
  try {
309
318
  // The interrupted update may have died holding the profile lock; its
310
319
  // owner is gone by now, and without this the install below waits out
311
320
  // the whole timeout on every start.
312
321
  clearStaleProfileLock(options.profileDirectory);
313
- const result = await withDeadline(options.manager.installBundle(spec, { requestId: randomUUID() }), options.timeoutMs ?? REPAIR_INSTALL_TIMEOUT_MS, `reinstall ${spec}`);
322
+ const timeoutMs = options.timeoutMs ?? REPAIR_INSTALL_TIMEOUT_MS;
323
+ const install = () => withDeadline(options.manager.installBundle(spec, { requestId: randomUUID() }), timeoutMs, `reinstall ${spec}`);
324
+ let result;
325
+ try {
326
+ result = await install();
327
+ }
328
+ catch (error) {
329
+ if (errorCodeOf(error) !== 'already-installed')
330
+ throw error;
331
+ result = { application: 'failed', error };
332
+ }
333
+ if (result.application === 'failed' && errorCodeOf(result.error) === 'already-installed'
334
+ && options.manager.removeBundle !== undefined) {
335
+ // The same two steps the normal update takes (#896): the interrupted
336
+ // update stopped before its removal landed, so the dependency is
337
+ // still declared and `add` is refused. Finish the removal, then add.
338
+ const removed = await withDeadline(options.manager.removeBundle(entry.name), timeoutMs, `remove ${entry.name}`);
339
+ if (removed.application === 'failed' || removed.application === 'cancelled') {
340
+ lastCode = errorCodeOf(removed.error);
341
+ cause = 'refused';
342
+ throw new Error(withCode(`the desktop app could not remove the old build first (${removed.application})`, lastCode));
343
+ }
344
+ journal.mark(entry.id, 'installing');
345
+ result = await install();
346
+ }
347
+ lastCode = errorCodeOf(result.error);
314
348
  if (!managerSucceeded(result)) {
315
349
  // A failed application can still be a written package: pnpm may have
316
350
  // installed the new build while only the live start failed — which is
@@ -318,8 +352,22 @@ export async function repairInterruptedUpdates(options) {
318
352
  // authority, not the application stage.
319
353
  const after = readInstalledVersion(options.profile, entry.name, options.profileDirectory);
320
354
  if (after === null || (entry.to !== '' && after !== entry.to)) {
355
+ // The update never landed but the build from before is installed and
356
+ // loaded: nothing is broken and nothing is left to repair, so this
357
+ // is neither a refusal nor a reason to count toward giving up. The
358
+ // user can run the update again from the market.
359
+ if (entry.from !== '' && after === entry.from && composed(options.profile, options.profileDirectory, entry.name)) {
360
+ journal.finish(entry.id);
361
+ report.failed.push({
362
+ name: entry.name,
363
+ cause: 'kept-old',
364
+ reason: withCode(`still on ${after}; the update to ${entry.to || spec} did not run (${result.application})`, lastCode),
365
+ });
366
+ logEvent('warn', 'update-repair', withCode(`${entry.name}: the interrupted update did not finish and ${after} is still installed and loaded; the update can be retried from the market (${result.application})`, lastCode));
367
+ continue;
368
+ }
321
369
  cause = 'refused';
322
- throw new Error(`the desktop app refused the reinstall (${result.application})`);
370
+ throw new Error(withCode(`the desktop app refused the reinstall (${result.application})`, lastCode));
323
371
  }
324
372
  // The files landing is not the same answer as the plugin loading:
325
373
  // this manager failed at the application stage, which is the step
@@ -327,7 +375,7 @@ export async function repairInterruptedUpdates(options) {
327
375
  // the record for a package the host still would not compose.
328
376
  if (!composed(options.profile, options.profileDirectory, entry.name)) {
329
377
  cause = 'not-composed';
330
- throw new Error(`the desktop app wrote ${after} but did not compose it — no dsh.profile.bundles row`);
378
+ throw new Error(withCode(`the desktop app wrote ${after} but did not compose it — no dsh.profile.bundles row`, lastCode));
331
379
  }
332
380
  journal.finish(entry.id);
333
381
  report.reinstalled.push(entry.name);
package/lib/routes.js CHANGED
@@ -59,6 +59,8 @@ import { DEFAULT_UPDATE_CHECK_INTERVAL_HOURS, isUpdateCheckIntervalHours } from
59
59
  import { createThemeManager } from './themes.js';
60
60
  import { readJsonBody, refuseUnadmitted, sameOrigin, sendJson } from './http.js';
61
61
  import { resolveDshHome } from './home-paths.js';
62
+ import { readTelemetryState, sendOpened, setTelemetryEnabled, startHeartbeat } from './telemetry.js';
63
+ import { clearWebdavSecret, readWebdavSecret, webdavSecretFor, writeWebdavSecret } from './webdav-secret.js';
62
64
  import { detectedDebugger, detectedSupervisor, restartAllowed, scheduleRestart, servingPort, trustedRestartRequest, trustedDownloadRequest, trustedSelfUninstallRequest, selfUninstallReachableFrom, restartReachableFrom } from './restart.js';
63
65
  import { activationAfterReplace, brokenClientBundles, bundlePatchIsEmpty, checkClientBundle, defaultHostRuntimeFacts, findUnservedConfigNamespaces, hasHostHalf, hostPeerGate, isDeclaredLibraryDsh, newlyBrokenBundles, peerGateRemedy, verifyActivation } from './verify.js';
64
66
  import { carrierRowIds, commitComponentSwitchPatch, composedRowName, disableRow, enableRow, findUserPatchPath, foreignRowIds, isProtectedModule, loaderEntryId, packagePatchFlags, rowFlagApplies, readComponentSwitchPatch, readUserPatchState, removeRowBlocks, rollbackComponentSwitchPatch, rowIdsForPackage, userPatchPackageReferences, writeComponentSwitchPatch, } from './patch.js';
@@ -3127,7 +3129,63 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
3127
3129
  },
3128
3130
  });
3129
3131
  };
3132
+ const telemetryOptions = {
3133
+ version: marketVersion(),
3134
+ hostVersion: () => dshHostInfo()?.version ?? null,
3135
+ kind: () => (config.desktopHost === true ? 'desktop' : 'web'),
3136
+ region: () => region,
3137
+ };
3130
3138
  const disposers = [
3139
+ // 页面打开:页面每次加载上报一次,服务端每天只保留第一次;立即返回,页面不等网络。
3140
+ registerRoute({
3141
+ kind: 'exact',
3142
+ path: '/dsh-crate/telemetry/opened',
3143
+ handler: async (request, response) => {
3144
+ if (request.method !== 'POST') {
3145
+ response.writeHead(405, { allow: 'POST' });
3146
+ response.end();
3147
+ return;
3148
+ }
3149
+ if (!sameOrigin(request)) {
3150
+ sendJson(response, 403, { error: 'untrusted origin' });
3151
+ return;
3152
+ }
3153
+ void sendOpened(telemetryOptions);
3154
+ response.writeHead(204);
3155
+ response.end();
3156
+ },
3157
+ }),
3158
+ registerRoute({
3159
+ kind: 'exact',
3160
+ path: '/dsh-crate/telemetry',
3161
+ handler: async (request, response) => {
3162
+ if (request.method === 'GET') {
3163
+ sendJson(response, 200, { enabled: readTelemetryState().enabled });
3164
+ return;
3165
+ }
3166
+ if (request.method !== 'POST') {
3167
+ response.writeHead(405, { allow: 'GET, POST' });
3168
+ response.end();
3169
+ return;
3170
+ }
3171
+ if (!sameOrigin(request)) {
3172
+ sendJson(response, 403, { error: 'untrusted origin' });
3173
+ return;
3174
+ }
3175
+ try {
3176
+ const body = await readJsonBody(request);
3177
+ if (body === null || typeof body !== 'object' || typeof body.enabled !== 'boolean') {
3178
+ sendJson(response, 400, { error: 'enabled must be a boolean' });
3179
+ return;
3180
+ }
3181
+ setTelemetryEnabled(body.enabled);
3182
+ sendJson(response, 200, { ok: true, enabled: body.enabled });
3183
+ }
3184
+ catch {
3185
+ sendJson(response, 400, { error: '没能保存这个设置,请再试一次。 / Could not save this setting. Try again.' });
3186
+ }
3187
+ },
3188
+ }),
3131
3189
  registerRoute({
3132
3190
  kind: 'exact',
3133
3191
  path: '/dsh-crate/update-notifications',
@@ -3674,8 +3732,16 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
3674
3732
  kind: 'exact',
3675
3733
  path: '/dsh-crate/webdav',
3676
3734
  handler: async (request, response) => {
3735
+ if (request.method === 'GET') {
3736
+ // #1058: whether a password is remembered, and for which address —
3737
+ // never the password itself.
3738
+ if (!sameOrigin(request))
3739
+ return sendJson(response, 403, { error: 'untrusted origin' });
3740
+ const stored = readWebdavSecret();
3741
+ return sendJson(response, 200, stored === null ? { remembered: false } : { remembered: true, url: stored.url, username: stored.username });
3742
+ }
3677
3743
  if (request.method !== 'POST') {
3678
- response.writeHead(405, { allow: 'POST' });
3744
+ response.writeHead(405, { allow: 'GET, POST' });
3679
3745
  response.end();
3680
3746
  return;
3681
3747
  }
@@ -3685,9 +3751,24 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
3685
3751
  const body = await readJsonBody(request);
3686
3752
  const url = typeof body.url === 'string' ? body.url : '';
3687
3753
  const username = typeof body.username === 'string' ? body.username : '';
3688
- const password = typeof body.password === 'string' ? body.password : '';
3754
+ const typed = typeof body.password === 'string' ? body.password : '';
3755
+ if (body.action === 'forget') {
3756
+ clearWebdavSecret();
3757
+ return sendJson(response, 200, { ok: true });
3758
+ }
3759
+ if (body.action === 'remember') {
3760
+ if (typed === '' || url === '')
3761
+ return sendJson(response, 400, { error: 'nothing to remember' });
3762
+ writeWebdavSecret({ url, username, password: typed });
3763
+ return sendJson(response, 200, { ok: true });
3764
+ }
3765
+ // An empty field falls back to the remembered password, but only for
3766
+ // the exact address and user it was saved for.
3767
+ const password = typed !== '' ? typed : (username !== '' ? webdavSecretFor(url, username) ?? '' : '');
3689
3768
  if (body.action === 'backup') {
3690
3769
  await uploadWebdav(url, username, password, createProfileBackup(config.profile, activeProfileDir));
3770
+ if (body.remember === true && typed !== '')
3771
+ writeWebdavSecret({ url, username, password: typed });
3691
3772
  sendJson(response, 200, { ok: true });
3692
3773
  }
3693
3774
  else if (body.action === 'restore') {
@@ -3696,7 +3777,10 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
3696
3777
  // posts it to /dsh-crate/restore, where downloadWebdav's strict
3697
3778
  // validation guarantees the fetch result is never blindly echoed
3698
3779
  // (review #63).
3699
- sendJson(response, 200, { ok: true, backup: await downloadWebdav(url, username, password) });
3780
+ const backup = await downloadWebdav(url, username, password);
3781
+ if (body.remember === true && typed !== '')
3782
+ writeWebdavSecret({ url, username, password: typed });
3783
+ sendJson(response, 200, { ok: true, backup });
3700
3784
  }
3701
3785
  else
3702
3786
  sendJson(response, 400, { error: 'invalid WebDAV action' });
@@ -5148,6 +5232,7 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
5148
5232
  channels: CHANNELS,
5149
5233
  region,
5150
5234
  regions: REGIONS,
5235
+ anonymousCount: readTelemetryState().enabled,
5151
5236
  // The padded/PATH- and CI-safe build environment currently pinned
5152
5237
  // (issue #336): composition plus any card-saved override. The card
5153
5238
  // edits exactly what this reports, so the form never shows a stale
@@ -8986,8 +9071,10 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
8986
9071
  })),
8987
9072
  ];
8988
9073
  startCheckoutRepair();
9074
+ const stopHeartbeat = startHeartbeat(telemetryOptions);
8989
9075
  return async () => {
8990
9076
  disposed = true;
9077
+ stopHeartbeat();
8991
9078
  checkoutRepairRound = undefined;
8992
9079
  if (checkoutRepairTimer !== undefined)
8993
9080
  clearTimeout(checkoutRepairTimer);
package/lib/snapshot.js CHANGED
@@ -22,8 +22,6 @@ import { existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, renameSync
22
22
  import { logEvent } from './log.js';
23
23
  import { stateDir } from './state.js';
24
24
  const SNAPSHOT_FORMAT = 'dsh-crate/profile-snapshot';
25
- /** 0.4.x 写下的快照格式标识,只用于读取旧快照。 */
26
- const LEGACY_SNAPSHOT_FORMAT = 'dsh-shelfry/profile-snapshot';
27
25
  const SNAPSHOT_VERSION = 2;
28
26
  /**
29
27
  * Snapshot ids are generated by nextSnapshotId and must never be attacker-
@@ -64,8 +62,7 @@ function validateSnapshotDocument(value) {
64
62
  // paths remain no-ops: older capture also omitted unreadable/invalid files,
65
63
  // so absence cannot be inferred safely after the fact.
66
64
  const legacy = !hasOwn(snap, 'format') && !hasOwn(snap, 'version');
67
- const legacyFormat = snap.format === LEGACY_SNAPSHOT_FORMAT;
68
- if (!legacy && !legacyFormat && (snap.format !== SNAPSHOT_FORMAT || snap.version !== SNAPSHOT_VERSION)) {
65
+ if (!legacy && (snap.format !== SNAPSHOT_FORMAT || snap.version !== SNAPSHOT_VERSION)) {
69
66
  return { ok: false, error: 'unsupported snapshot format or version / 不支持的快照格式或版本' };
70
67
  }
71
68
  const byPath = new Map();
@@ -74,13 +71,11 @@ function validateSnapshotDocument(value) {
74
71
  return { ok: false, error: 'corrupt snapshot file entry / 快照文件条目损坏' };
75
72
  }
76
73
  const entry = file;
77
- const rawPath = entry.path;
78
- // 0.4.x 的快照把状态文件记在旧目录名下,读取时映射到新目录。
79
- const path = rawPath === '.dsh-shelfry/state.json' ? '.dsh-crate/state.json' : rawPath;
74
+ const path = entry.path;
80
75
  if (typeof path !== 'string'
81
76
  || !SNAPSHOT_FILES.includes(path)
82
77
  || path.includes('..')) {
83
- return { ok: false, error: `unsafe snapshot path: ${String(rawPath)} / 快照路径不安全` };
78
+ return { ok: false, error: `unsafe snapshot path: ${String(path)} / 快照路径不安全` };
84
79
  }
85
80
  if (byPath.has(path)) {
86
81
  return { ok: false, error: `duplicate snapshot path: ${path} / 快照路径重复` };
@@ -95,13 +90,13 @@ function validateSnapshotDocument(value) {
95
90
  return { ok: false, error: `snapshot file ${entry.path} has invalid lines / 快照文件行无效` };
96
91
  }
97
92
  if (hasAbsent && (legacy || entry.absent !== true || path === 'package.json')) {
98
- return { ok: false, error: `snapshot file ${rawPath} has invalid absence marker / 快照文件缺失标记无效` };
93
+ return { ok: false, error: `snapshot file ${path} has invalid absence marker / 快照文件缺失标记无效` };
99
94
  }
100
95
  if ((path === 'package.json' || path === '.dsh-crate/state.json') && !hasJson && !hasAbsent) {
101
- return { ok: false, error: `snapshot file ${rawPath} has the wrong representation / 快照文件表示类型错误` };
96
+ return { ok: false, error: `snapshot file ${path} has the wrong representation / 快照文件表示类型错误` };
102
97
  }
103
98
  if (path === 'cordis.patch.yml' && !hasLines && !hasAbsent) {
104
- return { ok: false, error: `snapshot file ${rawPath} has the wrong representation / 快照文件表示类型错误` };
99
+ return { ok: false, error: `snapshot file ${path} has the wrong representation / 快照文件表示类型错误` };
105
100
  }
106
101
  byPath.set(path, { ...entry, path });
107
102
  }
@@ -13,12 +13,26 @@ function entriesOf(report) {
13
13
  ...report.abandoned.map(name => ({ name, state: 'abandoned' })),
14
14
  ].filter(({ name }) => NPM_NAME_RE.test(name));
15
15
  }
16
+ function keyOf(profile, directory) {
17
+ const absolute = resolve(directory);
18
+ return JSON.stringify([profile, process.platform === 'win32' ? absolute.toLowerCase() : absolute]);
19
+ }
20
+ /**
21
+ * A later install or update of this package settled in this process, so what
22
+ * start-up repair said about it is out of date. Drop it, or the panel keeps
23
+ * saying "still pending" until the next restart.
24
+ */
25
+ export function clearStartupRepairEntry(profile, directory, name) {
26
+ const state = globalThis[REPORTS]?.get(keyOf(profile, directory));
27
+ if (state === undefined || !state.entries.delete(name))
28
+ return;
29
+ state.revision += 1;
30
+ }
16
31
  /** Track what the existing startup repair found, without owning any package writes. */
17
32
  export function observeStartupRepair(profile, directory) {
18
33
  const global = globalThis;
19
34
  const reports = global[REPORTS] ??= new Map();
20
- const absolute = resolve(directory);
21
- const key = JSON.stringify([profile, process.platform === 'win32' ? absolute.toLowerCase() : absolute]);
35
+ const key = keyOf(profile, directory);
22
36
  const state = reports.get(key) ?? { id: randomUUID(), revision: 0, outstanding: new Set(), entries: new Map() };
23
37
  reports.set(key, state);
24
38
  const attempt = ++state.revision;
package/lib/state.js CHANGED
@@ -1,31 +1,17 @@
1
- import { existsSync, renameSync } from 'node:fs';
2
1
  import { join } from 'node:path';
3
2
  /**
4
3
  * 每个 profile 的状态目录名。
5
- * 0.5 起由 `.dsh-shelfry` 改为 `.dsh-crate`,旧目录在首次访问时就地改名。
4
+ * 0.5 起统一为 `.dsh-crate`,0.4.x 的旧目录不再读取或迁移。
6
5
  */
7
6
  export const STATE_DIR_NAME = '.dsh-crate';
8
- /** 0.4.x 使用的旧目录名,只用于迁移,不再写入。 */
9
- const LEGACY_STATE_DIR_NAME = '.dsh-shelfry';
10
7
  /**
11
- * 返回可用的状态目录。
8
+ * 返回状态目录。
12
9
  *
13
10
  * 入参:profileDir —— profile 根目录的绝对路径。
14
- * 返回:新目录路径;旧目录存在且新目录不存在时,先把旧目录改名再返回。
15
- * 改名失败时回退到旧目录,保证数据仍可读写,不影响启动。
11
+ * 返回:状态目录路径;目录本身由调用方按需创建。
16
12
  */
17
13
  export function stateDir(profileDir) {
18
- const current = join(profileDir, STATE_DIR_NAME);
19
- const legacy = join(profileDir, LEGACY_STATE_DIR_NAME);
20
- if (existsSync(current) || !existsSync(legacy))
21
- return current;
22
- try {
23
- renameSync(legacy, current);
24
- return current;
25
- }
26
- catch {
27
- return legacy;
28
- }
14
+ return join(profileDir, STATE_DIR_NAME);
29
15
  }
30
16
  /**
31
17
  * 拼出状态目录下的文件路径。
@@ -0,0 +1,125 @@
1
+ import { randomBytes } from 'node:crypto';
2
+ import { mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
3
+ import { dirname, join } from 'node:path';
4
+ import { resolveDshHome } from './home-paths.js';
5
+ import { logEvent } from './log.js';
6
+ import { marketFetch } from './net.js';
7
+ /**
8
+ * The anonymous daily count.
9
+ *
10
+ * One POST per install per UTC day, from the Node side only, carrying five
11
+ * fields (see `Ping`). On a day the user opens the plugin page, a second POST
12
+ * carries the same five plus `opened: true` — the only thing it adds is that
13
+ * the page was opened, never what was done there. It is ON by default and off
14
+ * with one switch in the settings card or with `DSH_CRATE_TELEMETRY=0` /
15
+ * `DO_NOT_TRACK=1`. Everything about it is best effort: a failure changes
16
+ * nothing for the user and is never an error.
17
+ */
18
+ export const TELEMETRY_URL = 'https://dshcrate.com/api/telemetry';
19
+ const TIMEOUT_MS = 10_000;
20
+ const START_DELAY_MS = 30_000;
21
+ const RECHECK_MS = 6 * 60 * 60 * 1000;
22
+ export function telemetryFile(home = resolveDshHome()) {
23
+ return join(home, 'dsh-crate', 'telemetry.json');
24
+ }
25
+ export function readTelemetryState(file = telemetryFile()) {
26
+ try {
27
+ const value = JSON.parse(readFileSync(file, 'utf8'));
28
+ return {
29
+ ...(typeof value.id === 'string' && /^[0-9a-f]{32}$/.test(value.id) ? { id: value.id } : {}),
30
+ ...(typeof value.lastDay === 'string' ? { lastDay: value.lastDay } : {}),
31
+ ...(typeof value.lastOpenDay === 'string' ? { lastOpenDay: value.lastOpenDay } : {}),
32
+ enabled: value.enabled !== false,
33
+ };
34
+ }
35
+ catch {
36
+ return { enabled: true };
37
+ }
38
+ }
39
+ function writeState(state, file) {
40
+ mkdirSync(dirname(file), { recursive: true });
41
+ const temp = `${file}.${process.pid}.tmp`;
42
+ writeFileSync(temp, JSON.stringify(state));
43
+ renameSync(temp, file);
44
+ }
45
+ /** Turn the count on or off. Keeps the rest of the file; deletes nothing else. */
46
+ export function setTelemetryEnabled(enabled, file = telemetryFile()) {
47
+ writeState({ ...readTelemetryState(file), enabled }, file);
48
+ }
49
+ const utcDay = (now) => new Date(now).toISOString().slice(0, 10);
50
+ /** Why nothing may be sent right now, or null. Explicit opt-outs always win. */
51
+ export function suppressedBy(env) {
52
+ if (env.DSH_CRATE_TELEMETRY === '0')
53
+ return 'DSH_CRATE_TELEMETRY=0';
54
+ if (env.DO_NOT_TRACK === '1')
55
+ return 'DO_NOT_TRACK=1';
56
+ // Tests and CI never count, unless a test points the URL at its own server.
57
+ const overridden = (env.DSH_CRATE_TELEMETRY_URL ?? '') !== '';
58
+ if (!overridden && env.CI !== undefined && env.CI !== '' && env.CI !== '0' && env.CI !== 'false')
59
+ return 'CI';
60
+ if (!overridden && (env.VITEST !== undefined || env.NODE_ENV === 'test'))
61
+ return 'test run';
62
+ return null;
63
+ }
64
+ async function send(options, opened) {
65
+ try {
66
+ const env = options.env ?? process.env;
67
+ const file = options.file ?? telemetryFile();
68
+ if (suppressedBy(env) !== null)
69
+ return 'skipped';
70
+ const state = readTelemetryState(file);
71
+ if (!state.enabled)
72
+ return 'skipped';
73
+ const day = utcDay((options.now ?? Date.now)());
74
+ if ((opened ? state.lastOpenDay : state.lastDay) === day)
75
+ return 'skipped';
76
+ const id = state.id ?? randomBytes(16).toString('hex');
77
+ const ping = {
78
+ id, v: options.version, hv: options.hostVersion(), kind: options.kind(), region: options.region(),
79
+ ...(opened ? { opened: true } : {}),
80
+ };
81
+ const response = await (options.fetch ?? marketFetch)(env.DSH_CRATE_TELEMETRY_URL || TELEMETRY_URL, {
82
+ method: 'POST',
83
+ headers: { 'content-type': 'application/json' },
84
+ body: JSON.stringify(ping),
85
+ signal: AbortSignal.timeout(TIMEOUT_MS),
86
+ });
87
+ if (response.status < 200 || response.status > 299)
88
+ return 'failed';
89
+ // Re-read: the user may have turned it off while the request was in flight.
90
+ // An open also counts as today's heartbeat: the server row is the same.
91
+ writeState({ ...readTelemetryState(file), id, lastDay: day, ...(opened ? { lastOpenDay: day } : {}) }, file);
92
+ return 'sent';
93
+ }
94
+ catch (error) {
95
+ logEvent('info', 'telemetry', `not sent: ${error instanceof Error ? error.message : 'unknown'}`);
96
+ return 'failed';
97
+ }
98
+ }
99
+ /** Send today's count if it is due. Never throws. */
100
+ export function sendHeartbeat(options) {
101
+ return send(options, false);
102
+ }
103
+ /** Note that the plugin page was opened today, if that has not been sent yet. Never throws. */
104
+ export function sendOpened(options) {
105
+ return send(options, true);
106
+ }
107
+ /** Start the schedule: first check after a short delay, then every ~6 hours. */
108
+ export function startHeartbeat(options, delayMs = START_DELAY_MS, everyMs = RECHECK_MS) {
109
+ let stopped = false;
110
+ let timer;
111
+ const tick = () => {
112
+ if (stopped)
113
+ return;
114
+ void sendHeartbeat(options).finally(() => {
115
+ if (stopped)
116
+ return;
117
+ timer = setTimeout(tick, everyMs);
118
+ timer.unref?.();
119
+ });
120
+ };
121
+ timer = setTimeout(tick, delayMs);
122
+ timer.unref?.();
123
+ return () => { stopped = true; if (timer !== undefined)
124
+ clearTimeout(timer); };
125
+ }
@@ -92,7 +92,7 @@ export interface ResidualDirectory {
92
92
  name: string;
93
93
  /** Path relative to the profile, for the diagnostics listing. */
94
94
  path: string;
95
- kind: 'incomplete-package' | 'tmp-directory';
95
+ kind: 'incomplete-package' | 'tmp-directory' | 'empty-directory';
96
96
  /**
97
97
  * The profile still declares it. Then this is not junk: composition will
98
98
  * try to load it, and the bundle layers above already report why it fails.
@@ -89,6 +89,7 @@ export declare function configuredProxy(): string | null;
89
89
  export declare function marketFetch(url: string, init?: {
90
90
  signal?: AbortSignal;
91
91
  headers?: Record<string, string>;
92
- method?: 'GET' | 'HEAD';
92
+ method?: 'GET' | 'HEAD' | 'POST';
93
+ body?: string;
93
94
  redirect?: 'follow' | 'manual';
94
95
  }): Promise<Response>;
@@ -103,6 +103,15 @@ export interface RepairManager {
103
103
  exitCode: number | null;
104
104
  };
105
105
  }>;
106
+ /**
107
+ * Optional so a minimal manager still works. Needed when the interrupted
108
+ * update died between its install being refused and its removal landing:
109
+ * the dependency line is still there, so `add` answers `already-installed`.
110
+ */
111
+ removeBundle?(name: string): Promise<{
112
+ application: string;
113
+ error?: unknown;
114
+ }>;
106
115
  }
107
116
  export interface RepairOptions {
108
117
  profile: string;
@@ -111,7 +120,9 @@ export interface RepairOptions {
111
120
  journal?: PendingUpdateJournal;
112
121
  timeoutMs?: number;
113
122
  }
114
- export type RepairFailureCause = 'version-changed' | 'refused' | 'not-composed' | 'timeout' | 'unknown' | 'abandoned';
123
+ export type RepairFailureCause = 'version-changed' | 'refused' | 'not-composed' | 'timeout' | 'unknown' | 'abandoned'
124
+ /** The reinstall did not run, but the build from before the update is installed and loaded. */
125
+ | 'kept-old';
115
126
  export interface RepairReport {
116
127
  /** Packages a previous start removed and this one put back. */
117
128
  reinstalled: string[];
@@ -13,6 +13,12 @@ export interface StartupRepairSnapshot {
13
13
  checking: boolean;
14
14
  entries: StartupRepairEntry[];
15
15
  }
16
+ /**
17
+ * A later install or update of this package settled in this process, so what
18
+ * start-up repair said about it is out of date. Drop it, or the panel keeps
19
+ * saying "still pending" until the next restart.
20
+ */
21
+ export declare function clearStartupRepairEntry(profile: string, directory: string, name: string): void;
16
22
  /** Track what the existing startup repair found, without owning any package writes. */
17
23
  export declare function observeStartupRepair(profile: string, directory: string): {
18
24
  read: () => StartupRepairSnapshot;