dsh-config-manager 0.6.0 → 0.7.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.
- package/lib/client.d.ts +5 -0
- package/lib/client.js +605 -566
- package/lib/core/local-plugin-host.d.ts +9 -0
- package/lib/core/local-plugin-host.js +174 -1
- package/lib/core/messages.d.ts +3 -0
- package/lib/core/messages.js +8 -0
- package/lib/core/run-registry.d.ts +10 -0
- package/lib/core/run-registry.js +17 -0
- package/lib/index.d.ts +3 -2
- package/lib/index.js +8 -6
- package/lib/routes/import.js +6 -1
- package/lib/routes/route-support.d.ts +2 -1
- package/lib/routes/route-support.js +8 -3
- package/lib/routes/sync.js +5 -2
- package/lib/sync/autosync-config.d.ts +9 -1
- package/lib/sync/autosync-config.js +10 -2
- package/lib/sync/autosync-scheduler.js +18 -6
- package/lib/sync/git/git-transport.d.ts +31 -1
- package/lib/sync/git/git-transport.js +119 -23
- package/lib/sync/sync-config.d.ts +34 -3
- package/lib/sync/sync-config.js +38 -5
- package/lib/ui/sync-settings-view.d.ts +4 -0
- package/lib/ui/sync-settings-view.js +3 -0
- package/package.json +1 -1
- package/src/client/run-store.test.ts +1 -1
- package/src/client/run-store.ts +5 -0
- package/src/client/sync/ChannelConfigDialog.tsx +15 -1
- package/src/client/sync/SyncPanel.tsx +6 -0
- package/src/client/sync/sync-api.ts +2 -0
- package/src/client/sync/sync-locales.ts +6 -0
- package/src/core/local-plugin-host.test.ts +31 -2
- package/src/core/local-plugin-host.ts +175 -2
- package/src/core/messages.ts +8 -0
- package/src/core/run-registry-runs.test.ts +26 -1
- package/src/core/run-registry.ts +18 -0
- package/src/index.sync.test.ts +27 -0
- package/src/index.ts +10 -8
- package/src/routes/import.ts +6 -1
- package/src/routes/route-support.ts +7 -3
- package/src/routes/sync.ts +5 -2
- package/src/sync/autosync-config.ts +10 -2
- package/src/sync/autosync-scheduler.test.ts +61 -1
- package/src/sync/autosync-scheduler.ts +17 -5
- package/src/sync/git/git-transport.test.ts +117 -0
- package/src/sync/git/git-transport.ts +131 -23
- package/src/sync/sync-config.test.ts +59 -1
- package/src/sync/sync-config.ts +51 -5
- package/src/ui/sync-settings-view.test.ts +1 -0
- package/src/ui/sync-settings-view.ts +7 -0
|
@@ -148,6 +148,8 @@ interface SyncUiState {
|
|
|
148
148
|
channel: SyncChannel
|
|
149
149
|
/** git 通道表单 */
|
|
150
150
|
repoUrl: string
|
|
151
|
+
/** 仓库内子目录前缀(空 = 仓库根;issue 131) */
|
|
152
|
+
gitSubdir: string
|
|
151
153
|
/** 仅内存:成功后清空(已写入 DSH credentials),绝不持久化 */
|
|
152
154
|
token: string
|
|
153
155
|
/** webdav 通道表单 */
|
|
@@ -232,6 +234,7 @@ const initial: SyncUiState = {
|
|
|
232
234
|
// 用户最近选择的通道优先(localStorage 记住);无则缺省 git,由 loadStatus 按配置回填
|
|
233
235
|
channel: readStoredChannel() ?? 'git',
|
|
234
236
|
repoUrl: '',
|
|
237
|
+
gitSubdir: '',
|
|
235
238
|
token: '',
|
|
236
239
|
webdavUrl: '',
|
|
237
240
|
webdavUsername: '',
|
|
@@ -291,6 +294,7 @@ function initFromStore(): SyncUiState {
|
|
|
291
294
|
// 避免升级后把用户此前记住的 webdav 通道冲掉
|
|
292
295
|
channel: resolveInitialChannel(s.channel, readStoredChannel()),
|
|
293
296
|
repoUrl: s.repoUrl,
|
|
297
|
+
gitSubdir: s.gitSubdir,
|
|
294
298
|
token: s.token,
|
|
295
299
|
webdavUrl: s.webdavUrl,
|
|
296
300
|
webdavUsername: s.webdavUsername,
|
|
@@ -491,6 +495,7 @@ export function SyncPanel({ api, t, cmT }: SyncPanelProps) {
|
|
|
491
495
|
statusInfo: info,
|
|
492
496
|
channel: remembered ?? savedChannel,
|
|
493
497
|
repoUrl: info.repoUrl ?? '',
|
|
498
|
+
gitSubdir: info.subdir ?? '',
|
|
494
499
|
webdavUrl: info.webdav?.url ?? '',
|
|
495
500
|
webdavUsername: info.webdav?.username ?? '',
|
|
496
501
|
catalog,
|
|
@@ -609,6 +614,7 @@ export function SyncPanel({ api, t, cmT }: SyncPanelProps) {
|
|
|
609
614
|
const formOf = (s: SyncUiState): SyncFormSnapshot => ({
|
|
610
615
|
channel: s.channel,
|
|
611
616
|
repoUrl: s.repoUrl,
|
|
617
|
+
gitSubdir: s.gitSubdir,
|
|
612
618
|
token: s.token,
|
|
613
619
|
webdavUrl: s.webdavUrl,
|
|
614
620
|
webdavUsername: s.webdavUsername,
|
|
@@ -68,6 +68,8 @@ export interface SyncStatusResponse {
|
|
|
68
68
|
configured: boolean;
|
|
69
69
|
/** git 通道:已配置的仓库地址(不含 token,可回显;与当前通道无关,配置过即返回) */
|
|
70
70
|
repoUrl?: string;
|
|
71
|
+
/** git 通道:仓库内子目录前缀('' / 缺省 = 仓库根;issue 131,供表单回填) */
|
|
72
|
+
subdir?: string;
|
|
71
73
|
/** git 通道:DSH credentials 中是否已存在 token(describe 只报状态,值永不返回) */
|
|
72
74
|
credentialConfigured: boolean;
|
|
73
75
|
credentialWritable: boolean;
|
|
@@ -14,6 +14,9 @@ export const zh = {
|
|
|
14
14
|
'config.title': '仓库配置',
|
|
15
15
|
'config.repoUrl': '仓库地址',
|
|
16
16
|
'config.repoUrlHint': 'Git 私有仓库地址(https / ssh / 本地路径)。认证 token 请使用下方凭据字段,不要拼入地址。',
|
|
17
|
+
'config.gitSubdir': '仓库内子目录',
|
|
18
|
+
'config.gitSubdirHint': '留空 = 直接用仓库根目录(旧行为)。填了就把同步内容放进该子目录(如「DSH备份」或「tools/dsh」):多个工具共用一个私有仓库时各自独立。切换子目录不会搬动已有快照 —— 换前缀前先重建工作副本。',
|
|
19
|
+
'config.gitSubdirPlaceholder': 'DSH备份(可选)',
|
|
17
20
|
'config.token': '认证 token',
|
|
18
21
|
'config.tokenHint': '将安全写入 DSH credentials(引用名 {ref}),不会写入同步文件或日志。留空表示沿用已保存的凭据。',
|
|
19
22
|
'config.tokenSaved': '凭据已配置',
|
|
@@ -476,6 +479,9 @@ export const en: Record<keyof typeof zh, string> = {
|
|
|
476
479
|
'config.title': 'Repository',
|
|
477
480
|
'config.repoUrl': 'Repository URL',
|
|
478
481
|
'config.repoUrlHint': 'Private Git repository URL (https / ssh / local path). Use the credential field below for the auth token; never embed it in the URL.',
|
|
482
|
+
'config.gitSubdir': 'Subdirectory in repo',
|
|
483
|
+
'config.gitSubdirHint': 'Blank = use the repository root (previous behavior). When set, sync content goes into that subdirectory (e.g. "DSH-backup" or "tools/dsh"), so several tools can share one private repo independently. Changing it does not move existing snapshots — rebuild the working copy before switching prefixes.',
|
|
484
|
+
'config.gitSubdirPlaceholder': 'DSH-backup (optional)',
|
|
479
485
|
'config.token': 'Auth token',
|
|
480
486
|
'config.tokenHint': 'Securely written into DSH credentials (ref {ref}); never written into sync files or logs. Leave blank to reuse the saved credential.',
|
|
481
487
|
'config.tokenSaved': 'Credential configured',
|
|
@@ -29,6 +29,8 @@ async function fixture(t: { after: (fn: () => Promise<void>) => void }, opts: {
|
|
|
29
29
|
tarballBytes?: number;
|
|
30
30
|
oversizeTtlMs?: number;
|
|
31
31
|
maxTarballBytes?: number;
|
|
32
|
+
/** 内容缓存上限(字节;0 = 关闭) */
|
|
33
|
+
packedCacheMaxBytes?: number;
|
|
32
34
|
} = {}): Promise<Fixture> {
|
|
33
35
|
const root = await fsp.mkdtemp(path.join(os.tmpdir(), 'dshcm-packhost-'));
|
|
34
36
|
t.after(async () => { await fsp.rm(root, { recursive: true, force: true }); });
|
|
@@ -54,6 +56,7 @@ async function fixture(t: { after: (fn: () => Promise<void>) => void }, opts: {
|
|
|
54
56
|
exec,
|
|
55
57
|
maxTarballBytes: opts.maxTarballBytes ?? 1024,
|
|
56
58
|
...(opts.oversizeTtlMs === undefined ? {} : { oversizeTtlMs: opts.oversizeTtlMs }),
|
|
59
|
+
...(opts.packedCacheMaxBytes === undefined ? {} : { packedCacheMaxBytes: opts.packedCacheMaxBytes }),
|
|
57
60
|
});
|
|
58
61
|
return {
|
|
59
62
|
hook,
|
|
@@ -115,14 +118,40 @@ test('oversizeTtlMs=0:关闭缓存,两轮都真打(测试与排障用)',
|
|
|
115
118
|
assert.equal(fx.calls(), 2);
|
|
116
119
|
});
|
|
117
120
|
|
|
118
|
-
test('未超限:正常产出 packed
|
|
121
|
+
test('未超限:正常产出 packed;源没变时第二轮走内容缓存,不再 npm pack', async (t) => {
|
|
119
122
|
const fx = await fixture(t, { tarballBytes: 256, maxTarballBytes: 1024 });
|
|
120
123
|
const first = await fx.hook(fx.plugins, ctx);
|
|
121
124
|
assert.equal(first.packed.length, 1);
|
|
122
125
|
assert.equal(first.oversize.length, 0);
|
|
123
126
|
assert.equal(first.warnings.length, 0);
|
|
127
|
+
|
|
128
|
+
// 2026-11-09:内容缓存上线后,源没变的第二轮直接复用 tarball 字节(此前是每轮都真打)。
|
|
129
|
+
const second = await fx.hook(fx.plugins, ctx);
|
|
130
|
+
assert.equal(fx.calls(), 1, '源没变 → 复用缓存,不再 spawn npm pack');
|
|
131
|
+
assert.equal(second.packed.length, 1, '缓存命中同样要产出 packed(备份缺它会把插件丢掉)');
|
|
132
|
+
assert.deepEqual(second.packed[0]?.data, first.packed[0]?.data, '复用的必须是同一份字节');
|
|
133
|
+
assert.equal(second.packed[0]?.rewrittenSpec, first.packed[0]?.rewrittenSpec);
|
|
134
|
+
});
|
|
135
|
+
|
|
136
|
+
test('内容缓存:源目录里改一个文件(lib/ 里那种不改目录 mtime 的改动)→ 必须重新打包', async (t) => {
|
|
137
|
+
const fx = await fixture(t, { tarballBytes: 256, maxTarballBytes: 1024 });
|
|
138
|
+
await fsp.mkdir(path.join(fx.sourceDir, 'lib'), { recursive: true });
|
|
139
|
+
await fsp.writeFile(path.join(fx.sourceDir, 'lib', 'index.js'), 'export const a = 1\n');
|
|
124
140
|
await fx.hook(fx.plugins, ctx);
|
|
125
|
-
assert.equal(fx.calls(),
|
|
141
|
+
assert.equal(fx.calls(), 1);
|
|
142
|
+
|
|
143
|
+
const file = path.join(fx.sourceDir, 'lib', 'index.js');
|
|
144
|
+
const future = new Date(Date.now() + 5000);
|
|
145
|
+
await fsp.utimes(file, future, future);
|
|
146
|
+
await fx.hook(fx.plugins, ctx);
|
|
147
|
+
assert.equal(fx.calls(), 2, '内容指纹按文件级 rel/size/mtime 算,改文件必须重打包(不能把旧 tarball 当当前内容)');
|
|
148
|
+
});
|
|
149
|
+
|
|
150
|
+
test('内容缓存:packedCacheMaxBytes=0 → 关闭,两轮都真打', async (t) => {
|
|
151
|
+
const fx = await fixture(t, { tarballBytes: 256, maxTarballBytes: 1024, packedCacheMaxBytes: 0 });
|
|
152
|
+
await fx.hook(fx.plugins, ctx);
|
|
153
|
+
await fx.hook(fx.plugins, ctx);
|
|
154
|
+
assert.equal(fx.calls(), 2, '关闭缓存时行为与改造前一致');
|
|
126
155
|
});
|
|
127
156
|
|
|
128
157
|
test('无本地源插件:零 spawn、零目录创建', async (t) => {
|
|
@@ -9,11 +9,12 @@
|
|
|
9
9
|
*/
|
|
10
10
|
import fsp from 'node:fs/promises';
|
|
11
11
|
import path from 'node:path';
|
|
12
|
+
import { createHash } from 'node:crypto';
|
|
12
13
|
import { spawn } from 'node:child_process';
|
|
13
14
|
|
|
14
15
|
import { packLocalPlugins, parsePackOutput, resolveLocalPluginPath } from './local-plugin-pack.ts';
|
|
15
16
|
import { quoteCmdArg } from './plugin-cli.ts';
|
|
16
|
-
import type { OversizeLocalPlugin, PackExec, PackExecResult, PackLocalPluginsResult } from './local-plugin-pack.ts';
|
|
17
|
+
import type { OversizeLocalPlugin, PackedLocalPlugin, PackExec, PackExecResult, PackLocalPluginsResult } from './local-plugin-pack.ts';
|
|
17
18
|
import type { HostContext } from './types.ts';
|
|
18
19
|
import { engineMsg } from './messages-core.ts';
|
|
19
20
|
|
|
@@ -106,6 +107,15 @@ export interface LocalPluginPackHookOptions {
|
|
|
106
107
|
sourceFingerprint?: (absPath: string) => Promise<string | null>;
|
|
107
108
|
/** tarball 体积上限(缺省 MAX_LOCAL_TARBALL_BYTES;测试用小值验证超限负缓存) */
|
|
108
109
|
maxTarballBytes?: number;
|
|
110
|
+
/**
|
|
111
|
+
* 内容缓存上限(字节;缺省 PACKED_CACHE_MAX_BYTES,**0 = 关闭**)。
|
|
112
|
+
* 命中判据 = 源目录的**内容指纹**(递归 rel/size/mtime)未变:命中即复用上次的 tarball 字节,跳过 npm pack。
|
|
113
|
+
*/
|
|
114
|
+
packedCacheMaxBytes?: number;
|
|
115
|
+
/** 内容缓存条目上限(缺省 PACKED_CACHE_MAX_ENTRIES)。 */
|
|
116
|
+
packedCacheMaxEntries?: number;
|
|
117
|
+
/** 内容指纹(测试注入;缺省 deepSourceFingerprint)。 */
|
|
118
|
+
contentFingerprint?: (absPath: string) => Promise<string | null>;
|
|
109
119
|
}
|
|
110
120
|
|
|
111
121
|
/**
|
|
@@ -140,6 +150,69 @@ async function defaultSourceFingerprint(absPath: string): Promise<string | null>
|
|
|
140
150
|
return null;
|
|
141
151
|
}
|
|
142
152
|
}
|
|
153
|
+
/** 内容缓存上限(缺省 128 MiB):只缓存真的打过的 tarball 字节。 */
|
|
154
|
+
const PACKED_CACHE_MAX_BYTES = 128 * 1024 * 1024;
|
|
155
|
+
|
|
156
|
+
/** 内容缓存条目上限(防「一堆小插件」把 Map 撑大)。 */
|
|
157
|
+
const PACKED_CACHE_MAX_ENTRIES = 64;
|
|
158
|
+
|
|
159
|
+
/** 内容指纹的遍历上限:超过就不缓存(宁可不省,也不拿可能过期的字节去备份)。 */
|
|
160
|
+
const CONTENT_FP_MAX_ENTRIES = 20_000;
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* 内容指纹(**正缓存**用):递归列出目录内每个文件的相对路径 + 字节数 + mtime。
|
|
164
|
+
*
|
|
165
|
+
* 为什么不用上面的 defaultSourceFingerprint:它只取「目录 mtime + package.json」,
|
|
166
|
+
* 在 lib/ 里改一行**不会**改目录 mtime —— 拿它做正缓存,会把旧 tarball 当成当前内容上传进备份。
|
|
167
|
+
* 负缓存能容忍这种粗糙(最坏是少备份一次、30 分钟内重试),正缓存不能容忍(最坏是备份里是旧代码)。
|
|
168
|
+
*
|
|
169
|
+
* 成本实测(2026-11-07,真机):8810 文件 3.6 s、51502 文件 14.9 s —— 仍比一次 210 MB 插件的
|
|
170
|
+
* 44.7 s npm pack 便宜一个量级;超过 CONTENT_FP_MAX_ENTRIES 或遇到链接/特殊文件一律返回 null
|
|
171
|
+
* (调用方据此**不缓存**,直接照常打包)。
|
|
172
|
+
*/
|
|
173
|
+
async function deepSourceFingerprint(absPath: string): Promise<string | null> {
|
|
174
|
+
let st;
|
|
175
|
+
try {
|
|
176
|
+
st = await fsp.stat(absPath);
|
|
177
|
+
} catch {
|
|
178
|
+
return null;
|
|
179
|
+
}
|
|
180
|
+
if (st.isFile()) return 'file:' + st.size + ':' + Math.trunc(st.mtimeMs);
|
|
181
|
+
if (!st.isDirectory()) return null;
|
|
182
|
+
|
|
183
|
+
const hash = createHash('sha256');
|
|
184
|
+
let entries = 0;
|
|
185
|
+
const walk = async (dir: string, rel: string): Promise<boolean> => {
|
|
186
|
+
let list;
|
|
187
|
+
try {
|
|
188
|
+
list = await fsp.readdir(dir, { withFileTypes: true });
|
|
189
|
+
} catch {
|
|
190
|
+
return false;
|
|
191
|
+
}
|
|
192
|
+
list.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
|
|
193
|
+
for (const entry of list) {
|
|
194
|
+
// 与 npm pack 同口径:node_modules 不进产物;.git 不参与内容身份
|
|
195
|
+
if (entry.name === 'node_modules' || entry.name === '.git') continue;
|
|
196
|
+
const abs = path.join(dir, entry.name);
|
|
197
|
+
const relPath = rel === '' ? entry.name : rel + '/' + entry.name;
|
|
198
|
+
if (entry.isDirectory()) {
|
|
199
|
+
if (!(await walk(abs, relPath))) return false;
|
|
200
|
+
continue;
|
|
201
|
+
}
|
|
202
|
+
if (!entry.isFile()) return false; // 链接 / 设备文件:不猜它指向什么,放弃缓存
|
|
203
|
+
const s = await fsp.stat(abs).catch(() => null);
|
|
204
|
+
if (s === null) return false;
|
|
205
|
+
entries += 1;
|
|
206
|
+
if (entries > CONTENT_FP_MAX_ENTRIES) return false;
|
|
207
|
+
hash.update(relPath + '\u0000' + s.size + '\u0000' + Math.trunc(s.mtimeMs) + '\n');
|
|
208
|
+
}
|
|
209
|
+
return true;
|
|
210
|
+
};
|
|
211
|
+
if (!(await walk(absPath, ''))) return null;
|
|
212
|
+
hash.update('entries:' + entries);
|
|
213
|
+
return 'deep:' + hash.digest('hex');
|
|
214
|
+
}
|
|
215
|
+
|
|
143
216
|
export function createLocalPluginPackHook(opts: LocalPluginPackHookOptions): LocalPluginPackHook {
|
|
144
217
|
const exec = opts.exec ?? defaultExec;
|
|
145
218
|
const oversizeTtlMs = opts.oversizeTtlMs ?? OVERSIZE_NEGATIVE_TTL_MS;
|
|
@@ -152,6 +225,42 @@ export function createLocalPluginPackHook(opts: LocalPluginPackHookOptions): Loc
|
|
|
152
225
|
*/
|
|
153
226
|
const oversizeCache = new Map<string, { fingerprint: string; at: number; oversize: OversizeLocalPlugin }>();
|
|
154
227
|
|
|
228
|
+
/**
|
|
229
|
+
* 内容缓存(正缓存):解析后的源路径 → 上次打出的 tarball 字节 + 当时的内容指纹。
|
|
230
|
+
*
|
|
231
|
+
* 与超限负缓存的区别:负缓存存「结论」,这里存**产物本身**,命中即跳过 npm pack。
|
|
232
|
+
* 命中判据是 deepSourceFingerprint(文件级 rel/size/mtime),不是目录 mtime —— 见该函数注释。
|
|
233
|
+
* 上限双保险:总字节数 + 条目数,超出按「最久未用」淘汰;单条超过上限则根本不入缓存。
|
|
234
|
+
*/
|
|
235
|
+
const packedMaxBytes = opts.packedCacheMaxBytes ?? PACKED_CACHE_MAX_BYTES;
|
|
236
|
+
const packedMaxEntries = opts.packedCacheMaxEntries ?? PACKED_CACHE_MAX_ENTRIES;
|
|
237
|
+
const contentFp = opts.contentFingerprint ?? deepSourceFingerprint;
|
|
238
|
+
const packedCache = new Map<string, { fingerprint: string; entry: PackedLocalPlugin; bytes: number; usedAt: number }>();
|
|
239
|
+
let packedCacheBytes = 0;
|
|
240
|
+
const evictPacked = (): void => {
|
|
241
|
+
while (packedCache.size > packedMaxEntries || packedCacheBytes > packedMaxBytes) {
|
|
242
|
+
let oldestKey: string | null = null;
|
|
243
|
+
let oldestAt = Number.POSITIVE_INFINITY;
|
|
244
|
+
for (const [key, value] of packedCache) {
|
|
245
|
+
if (value.usedAt < oldestAt) {
|
|
246
|
+
oldestAt = value.usedAt;
|
|
247
|
+
oldestKey = key;
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
if (oldestKey === null) return;
|
|
251
|
+
const removed = packedCache.get(oldestKey);
|
|
252
|
+
if (removed !== undefined) packedCacheBytes -= removed.bytes;
|
|
253
|
+
packedCache.delete(oldestKey);
|
|
254
|
+
}
|
|
255
|
+
};
|
|
256
|
+
/** 按入参顺序输出打包结果(缓存命中与本轮打包混在一起时,保持确定性顺序)。 */
|
|
257
|
+
const orderPacked = (input: readonly { name: string }[], packed: readonly PackedLocalPlugin[]): PackedLocalPlugin[] => {
|
|
258
|
+
const byName = new Map(packed.map((p) => [p.packageName, p] as const));
|
|
259
|
+
return input.map((p) => byName.get(p.name)).filter((p): p is PackedLocalPlugin => p !== undefined);
|
|
260
|
+
};
|
|
261
|
+
const rewrittenOf = (packed: readonly PackedLocalPlugin[]): Record<string, string> =>
|
|
262
|
+
Object.fromEntries(packed.map((p) => [p.packageName, p.rewrittenSpec]));
|
|
263
|
+
|
|
155
264
|
const hasLocalSpec = (p: { spec?: string }): boolean =>
|
|
156
265
|
p.spec !== undefined && /^\s*(link|file):/i.test(p.spec);
|
|
157
266
|
|
|
@@ -209,6 +318,46 @@ export function createLocalPluginPackHook(opts: LocalPluginPackHookOptions): Loc
|
|
|
209
318
|
return { packed: [], rewritten: {}, warnings: cacheWarnings, oversize: cacheOversize };
|
|
210
319
|
}
|
|
211
320
|
|
|
321
|
+
// —— 内容缓存命中分流:源内容没变的那几个直接复用上次的 tarball,其余才真的打包 ——
|
|
322
|
+
const hitPacked: PackedLocalPlugin[] = [];
|
|
323
|
+
const toPack: { name: string; version: string; spec?: string }[] = [];
|
|
324
|
+
if (packedMaxBytes > 0) {
|
|
325
|
+
for (const p of kept) {
|
|
326
|
+
const spec = p.spec;
|
|
327
|
+
if (spec === undefined || !hasLocalSpec(p)) {
|
|
328
|
+
toPack.push(p);
|
|
329
|
+
continue;
|
|
330
|
+
}
|
|
331
|
+
const abs = resolveLocalPluginPath(spec, { homeDir: opts.homeDir, profileDir });
|
|
332
|
+
const hit = packedCache.get(abs);
|
|
333
|
+
if (hit === undefined) {
|
|
334
|
+
toPack.push(p);
|
|
335
|
+
continue;
|
|
336
|
+
}
|
|
337
|
+
const fp = await contentFp(abs).catch(() => null);
|
|
338
|
+
if (fp === null || fp !== hit.fingerprint) {
|
|
339
|
+
packedCacheBytes -= hit.bytes;
|
|
340
|
+
packedCache.delete(abs);
|
|
341
|
+
toPack.push(p);
|
|
342
|
+
continue;
|
|
343
|
+
}
|
|
344
|
+
hit.usedAt = Date.now();
|
|
345
|
+
hitPacked.push(hit.entry);
|
|
346
|
+
}
|
|
347
|
+
} else {
|
|
348
|
+
toPack.push(...kept);
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
if (!toPack.some(hasLocalSpec)) {
|
|
352
|
+
// 全部命中:不建临时目录、不 spawn 一次 npm。
|
|
353
|
+
return {
|
|
354
|
+
packed: orderPacked(plugins, hitPacked),
|
|
355
|
+
rewritten: rewrittenOf(hitPacked),
|
|
356
|
+
warnings: cacheWarnings,
|
|
357
|
+
oversize: cacheOversize,
|
|
358
|
+
};
|
|
359
|
+
}
|
|
360
|
+
|
|
212
361
|
const tmpRoot = path.join(opts.dataDir, 'tmp');
|
|
213
362
|
let packDir: string;
|
|
214
363
|
try {
|
|
@@ -227,8 +376,12 @@ export function createLocalPluginPackHook(opts: LocalPluginPackHookOptions): Loc
|
|
|
227
376
|
}
|
|
228
377
|
|
|
229
378
|
try {
|
|
379
|
+
const specOfName = new Map<string, string>();
|
|
380
|
+
for (const p of toPack) {
|
|
381
|
+
if (p.spec !== undefined && hasLocalSpec(p)) specOfName.set(p.name, p.spec);
|
|
382
|
+
}
|
|
230
383
|
const result = await packLocalPlugins({
|
|
231
|
-
plugins:
|
|
384
|
+
plugins: toPack.map((p) => ({ name: p.name, version: p.version, spec: p.spec })),
|
|
232
385
|
homeDir: opts.homeDir,
|
|
233
386
|
profileDir,
|
|
234
387
|
packDir,
|
|
@@ -257,8 +410,28 @@ export function createLocalPluginPackHook(opts: LocalPluginPackHookOptions): Loc
|
|
|
257
410
|
}
|
|
258
411
|
}
|
|
259
412
|
}
|
|
413
|
+
// 内容缓存记账:本轮真打出来的 tarball 按「源内容指纹」入缓存;超限/算不出指纹的跳过(不猜)。
|
|
414
|
+
if (packedMaxBytes > 0) {
|
|
415
|
+
for (const entry of result.packed) {
|
|
416
|
+
const spec = specOfName.get(entry.packageName);
|
|
417
|
+
if (spec === undefined) continue;
|
|
418
|
+
const bytes = entry.data.byteLength;
|
|
419
|
+
if (bytes > packedMaxBytes) continue;
|
|
420
|
+
const abs = resolveLocalPluginPath(spec, { homeDir: opts.homeDir, profileDir });
|
|
421
|
+
const fp = await contentFp(abs).catch(() => null);
|
|
422
|
+
if (fp === null) continue;
|
|
423
|
+
const prev = packedCache.get(abs);
|
|
424
|
+
if (prev !== undefined) packedCacheBytes -= prev.bytes;
|
|
425
|
+
packedCache.set(abs, { fingerprint: fp, entry, bytes, usedAt: Date.now() });
|
|
426
|
+
packedCacheBytes += bytes;
|
|
427
|
+
}
|
|
428
|
+
evictPacked();
|
|
429
|
+
}
|
|
430
|
+
const allPacked = [...hitPacked, ...result.packed];
|
|
260
431
|
return {
|
|
261
432
|
...result,
|
|
433
|
+
packed: orderPacked(plugins, allPacked),
|
|
434
|
+
rewritten: { ...result.rewritten, ...rewrittenOf(hitPacked) },
|
|
262
435
|
oversize: [...cacheOversize, ...result.oversize],
|
|
263
436
|
warnings: [...cacheWarnings, ...result.warnings],
|
|
264
437
|
};
|
package/src/core/messages.ts
CHANGED
|
@@ -441,6 +441,10 @@ export const zh = {
|
|
|
441
441
|
'sync.git.adoptNotSyncRepo': '远端仓库顶层出现了快照布局以外的内容({entries}):它看起来不是本插件的同步仓库,已拒绝合并(不会把别的仓库内容搬进工作副本)。',
|
|
442
442
|
'sync.git.adoptMergeConflict': '合并远端 {branch} 时发生冲突:已撤销这次合并(merge --abort),工作副本回到操作前的状态。请手工解决冲突后重试,或改用「重新克隆工作副本」。',
|
|
443
443
|
'sync.workdirModeInvalidFull': '重建工作副本的模式非法: {mode}(只允许 relink(重指向地址)、adopt(采纳远端历史)或 reclone(重新克隆))',
|
|
444
|
+
// issue #131:git 通道的仓库内子目录前缀(多工具共用一个备份仓库时各占一个目录)。
|
|
445
|
+
'sync.git.subdirInvalid': '同步子目录前缀不合法:{subdir}(不得以 / 开头或结尾,不得含反斜杠、空段、. 段、.. 段或 .git 段)',
|
|
446
|
+
'sync.git.subdirRoot': '仓库根',
|
|
447
|
+
'sync.git.subdirChanged': '工作副本的同步布局是「{stored}」,当前配置是「{expected}」:sparse-checkout 只在首次克隆时生效,旧工作副本里没有新前缀的目录树 —— 照常同步会表现为「远端没有快照」。请在「同步 → 通道配置」里重建工作副本(重新克隆)后再同步。',
|
|
444
448
|
|
|
445
449
|
'sync.git.cmdFailed': 'git {args} 失败 (exit {code}): {err}',
|
|
446
450
|
// 本机提交身份缺失(真机 issue:commit exit 128 ⇒ 交易 NEEDS_ATTENTION ⇒ 被误升 SAFE MODE)。
|
|
@@ -957,6 +961,10 @@ export const en: Record<keyof typeof zh, string> = {
|
|
|
957
961
|
'sync.git.adoptNotSyncRepo': 'The remote repository root contains entries outside the snapshot layout ({entries}): it does not look like this plugin\'s sync repository, so the merge was refused (another repository\'s content is never pulled into the working copy).',
|
|
958
962
|
'sync.git.adoptMergeConflict': 'Merging remote {branch} produced conflicts: the merge was aborted (merge --abort) and the working copy is back to its previous state. Resolve the conflicts manually and retry, or use "clone the working copy again".',
|
|
959
963
|
'sync.workdirModeInvalidFull': 'Invalid working-copy rebuild mode: {mode} (only relink (re-point the address), adopt (merge the remote history) or reclone (clone again) are allowed).',
|
|
964
|
+
// issue #131: in-repo subdirectory prefix for the git channel (several tools sharing one backup repository).
|
|
965
|
+
'sync.git.subdirInvalid': 'Invalid sync subdirectory prefix: {subdir} (must not start or end with /, and must not contain a backslash, an empty segment, a . segment, a .. segment, or a .git segment)',
|
|
966
|
+
'sync.git.subdirRoot': 'repository root',
|
|
967
|
+
'sync.git.subdirChanged': 'This working copy uses the sync layout "{stored}" but the current config is "{expected}": sparse-checkout only applies on the first clone, so the old working copy has no tree for the new prefix — syncing would look like "the remote has no snapshots". Rebuild the working copy (clone again) under Sync → Channel configuration, then sync again.',
|
|
960
968
|
|
|
961
969
|
'sync.git.cmdFailed': 'git {args} failed (exit {code}): {err}',
|
|
962
970
|
// Missing local commit identity (real-world issue: commit exit 128 → NEEDS_ATTENTION → wrongly escalated to SAFE MODE).
|
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
import test from 'node:test';
|
|
9
9
|
import assert from 'node:assert/strict';
|
|
10
10
|
|
|
11
|
-
import { RunRegistry } from './run-registry.ts';
|
|
11
|
+
import { RunRegistry, isIdleAutosyncRun } from './run-registry.ts';
|
|
12
12
|
|
|
13
13
|
test('pendingDecision:登记后可见,终态 run 上的晚到写入被忽略', () => {
|
|
14
14
|
const runs = new RunRegistry({ now: () => 1000 });
|
|
@@ -69,3 +69,28 @@ test('requestCancel:记录首个请求时刻(重复请求不刷新,界面
|
|
|
69
69
|
assert.equal(runs.requestCancel(run.runId)?.cancelRequestedAt, 1_000, '终态后的晚到请求被忽略');
|
|
70
70
|
assert.equal(runs.requestCancel('nope'), undefined, '未知 runId 返回 undefined(不伪造状态)');
|
|
71
71
|
});
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* 2026-11-09:空转的自动同步轮次不进运行中心。
|
|
75
|
+
*
|
|
76
|
+
* 现场:realtime 开着时每 60s 一轮远端探测,每轮都 register('autosync') → 运行中心每分钟一张
|
|
77
|
+
* 「自动同步 · 已完成」卡片(与迁移历史同一种噪音)。判据只认调度器写入的 result.idle,
|
|
78
|
+
* 不在 UI 猜 skipReason;running 与真干活的轮次必须照常显示。
|
|
79
|
+
*/
|
|
80
|
+
test('isIdleAutosyncRun:只认 result.idle(running / 其它 kind / 无 result 一律不算)', () => {
|
|
81
|
+
const runs = new RunRegistry({ now: () => 1000 });
|
|
82
|
+
const idle = runs.register('autosync');
|
|
83
|
+
runs.finish(idle.runId, { kind: 'autosync', idle: true });
|
|
84
|
+
assert.equal(isIdleAutosyncRun(runs.get(idle.runId)!), true);
|
|
85
|
+
|
|
86
|
+
const real = runs.register('autosync');
|
|
87
|
+
runs.finish(real.runId, { kind: 'autosync' });
|
|
88
|
+
assert.equal(isIdleAutosyncRun(runs.get(real.runId)!), false, '真推/真拉的轮次必须留卡片');
|
|
89
|
+
|
|
90
|
+
const running = runs.register('autosync');
|
|
91
|
+
assert.equal(isIdleAutosyncRun(runs.get(running.runId)!), false, '进行中的轮次不得被过滤(否则看不到在跑的任务)');
|
|
92
|
+
|
|
93
|
+
const other = runs.register('import');
|
|
94
|
+
runs.finish(other.runId, { idle: true });
|
|
95
|
+
assert.equal(isIdleAutosyncRun(runs.get(other.runId)!), false, '标志只对 autosync 生效');
|
|
96
|
+
});
|
package/src/core/run-registry.ts
CHANGED
|
@@ -136,6 +136,24 @@ export interface RunRegistryOptions {
|
|
|
136
136
|
* 内存 run 注册表。Node 单线程 + 同步 Map 读写,无并发竞争;
|
|
137
137
|
* 所有公开读方法返回状态副本,防止外部直接篡改内部状态。
|
|
138
138
|
*/
|
|
139
|
+
/**
|
|
140
|
+
* 自动同步「空转」run:60s 一次的远端探测拿到 upToDate —— 本轮既没上传也没下行、没应用任何分区。
|
|
141
|
+
*
|
|
142
|
+
* 为什么要过滤(2026-11-09 真机):realtime 通道每轮都会 register('autosync'),于是运行中心每分钟
|
|
143
|
+
* 多一张「自动同步 · 已完成」卡片,与「迁移历史」同一种噪音(那边已由 isAutosyncIdleRound 挡住)。
|
|
144
|
+
* 轮询不是活动;真干活(push/pull/冲突/失败)的卡片必须留着 —— 它们才解释「刚才发生了什么」。
|
|
145
|
+
*
|
|
146
|
+
* 判定只认 run 自己的 result.idle(由调度器收尾时写入),不在 UI 猜 skipReason。
|
|
147
|
+
*/
|
|
148
|
+
export function isIdleAutosyncRun(
|
|
149
|
+
state: Pick<RunState, 'kind' | 'status' | 'result'>,
|
|
150
|
+
): boolean {
|
|
151
|
+
if (state.kind !== 'autosync' || state.status === 'running') return false
|
|
152
|
+
const result = state.result
|
|
153
|
+
if (result === null || typeof result !== 'object') return false
|
|
154
|
+
return (result as { idle?: unknown }).idle === true
|
|
155
|
+
}
|
|
156
|
+
|
|
139
157
|
export class RunRegistry {
|
|
140
158
|
private readonly runs = new Map<string, RunState>()
|
|
141
159
|
private readonly retentionMs: number
|
package/src/index.sync.test.ts
CHANGED
|
@@ -73,6 +73,33 @@ test('parseSyncBody: git 分支 repoUrl 含 userinfo(token 拼 URL)→ 拒
|
|
|
73
73
|
);
|
|
74
74
|
});
|
|
75
75
|
|
|
76
|
+
test('issue #131 parseSyncBody: git 分支带 subdir → 归一后进配置;空串/缺省不落字段', async () => {
|
|
77
|
+
const deps = memCreds();
|
|
78
|
+
const withSubdir = await parseSyncBody({ repoUrl: 'https://github.com/foo/bar.git', subdir: ' DSH备份 ' }, deps);
|
|
79
|
+
assert.deepEqual(withSubdir, {
|
|
80
|
+
schemaVersion: 2,
|
|
81
|
+
transport: 'git',
|
|
82
|
+
git: { repoUrl: 'https://github.com/foo/bar.git', subdir: 'DSH备份' },
|
|
83
|
+
});
|
|
84
|
+
const blank = await parseSyncBody({ repoUrl: 'https://github.com/foo/bar.git', subdir: ' ' }, deps);
|
|
85
|
+
assert.deepEqual(blank, {
|
|
86
|
+
schemaVersion: 2,
|
|
87
|
+
transport: 'git',
|
|
88
|
+
git: { repoUrl: 'https://github.com/foo/bar.git' },
|
|
89
|
+
}, '空串 = 仓库根,不落字段(旧宿主/旧配置同形)');
|
|
90
|
+
});
|
|
91
|
+
|
|
92
|
+
test('issue #131 parseSyncBody: 非法 subdir(绝对路径 / .. / .git 段)→ SyncRouteError 且不回显裸值', async () => {
|
|
93
|
+
const deps = memCreds();
|
|
94
|
+
for (const subdir of ['/abs', 'a/../b', '.git', 'a\\b', 'a//b']) {
|
|
95
|
+
await assert.rejects(
|
|
96
|
+
() => parseSyncBody({ repoUrl: 'https://github.com/foo/bar.git', subdir }, deps),
|
|
97
|
+
(err: unknown) => err instanceof SyncRouteError && /子目录前缀不合法/.test(err.message),
|
|
98
|
+
'必须拒绝: ' + subdir,
|
|
99
|
+
);
|
|
100
|
+
}
|
|
101
|
+
});
|
|
102
|
+
|
|
76
103
|
/* ---------------- webdav 分支 ---------------- */
|
|
77
104
|
|
|
78
105
|
test('parseSyncBody: webdav 分支解析 url/username,password 写入 SYNC_WEBDAV_CREDENTIAL_REF', async () => {
|
package/src/index.ts
CHANGED
|
@@ -183,7 +183,7 @@ export const name = 'config-manager'
|
|
|
183
183
|
export const inject = ['settings', 'credentials']
|
|
184
184
|
|
|
185
185
|
/** Plugin version, kept in sync with package.json ("version"). */
|
|
186
|
-
export const PLUGIN_VERSION = '0.
|
|
186
|
+
export const PLUGIN_VERSION = '0.7.0'
|
|
187
187
|
|
|
188
188
|
/** Plugin own package name — excluded from its own exported plugins list. */
|
|
189
189
|
const PLUGIN_NAME = 'dsh-config-manager'
|
|
@@ -2176,7 +2176,7 @@ const WEBDAV_TIMEOUT_MS = 120_000
|
|
|
2176
2176
|
* (见 W1 报告的重测配方),把结果落到这里;makeRoutes 里的 const routeEnv: RouteEnvInferred =
|
|
2177
2177
|
* 注解保证两侧不漂移(新增依赖漏登记会在构造点报错)。
|
|
2178
2178
|
*/
|
|
2179
|
-
export type RouteEnvInferred = { sessionExportFetch: ((input: string, init: RequestInit) => Promise<Response>) | undefined; sessionExportPort: number | undefined; adapters: ConfigAdapter<unknown>[]; sessionHealth: { homeDir: string; targetFormatVersion: () => number | undefined; workspaceKeys: () => Promise<ReadonlySet<string>>; knownSessionIds: () => Promise<ReadonlySet<string>>; sessionMeta: (ids: readonly string[]) => Promise<SessionMetaIndex>; }; backupScheduler: BackupScheduler; bootSafetyAudit: () => Promise<BootSafetyReport>; cancelDecisionTimeoutMs: number; buildMarketSummary: (e: { url: string; addedAt: string; }) => Promise<MarketSummary>; credentials: CredentialProvider; dataDir: string; exportsDir: string; syncRootDir: string; syncScope: SyncScope; githubAuth: GitHubAuthClient; githubClientId: string | undefined; githubClientSecret: string | undefined; githubFlows: DeviceFlowStore; history: MigrationStore; host: ConfigManagerHostContext; itemCached: (url: string, itemId: string) => Promise<boolean>; knownSyncSectionIds: Set<SectionId>; makeImporter: () => Importer; makeMarketReader: () => GitMarketReader; makeRecoveryExecutors: (runId: string) => RecoveryExecutorFns; makeSyncEngine: (cfg: SyncConfig, engineOpts?: { optInSections?: readonly SectionId[]; }) => SyncEngine; marketBootAutoRefreshed: { value: boolean; }; marketCacheIndex: (url: string) => string; marketDir: string; marketCacheItemDir: (url: string) => string; marketStarCache: StarCache; marketWorkDir: (url: string) => string; meGitHubRest: GitHubAuthRest; meService: MyRepoService; meTokenProvider: () => Promise<string>; msg: MsgFunc; prepareSync: (body: Record<string, unknown>) => Promise<SyncConfig>; pluginVersion: string; profileLauncher: DshProfileLauncher; profileRuntime: DshProfileRuntimeRegistry; profiles: DshProfileManager; pruneStagedMarketZips: () => Promise<void>; readCachedIndexObj: (url: string) => Promise<MarketIndex | null>; recoveryOrchestrator: RecoveryOrchestrator; resolveSyncPassword: (ref: string) => Promise<string | undefined>; roots: string[]; runAbortControllers: Map<string, AbortController>; runCancels: Map<string, { signal: AbortController; settle: (d: 'rollback' | 'keep') => void; decided: boolean }>; runs: RunRegistry; scheduler: AutoSyncScheduler; selectionCache: Partial<Record<SyncTransportType, SyncSelection>>; selectionOptInSections: (channel: SyncTransportType, onlyAuto?: boolean) => SectionId[]; selectionView: (channel: SyncTransportType) => Promise<SelectionView>; selectionViewByChannel: () => Promise<Record<SyncTransportType, SelectionView>>; snapshotEntrySections: (snapshotDir: string) => Promise<string[]>; snapshotsDir: string; starPromptRepoUrl: string; syncCredentialsByChannelView: () => Promise<Record<SyncTransportType, { encryptPasswordConfigured: boolean; decryptPasswordConfigured: boolean; }>>; syncDir: string; syncPasswordConfigured: (ref: string) => Promise<boolean>; syncWorkDir: { inspect: (repoUrl: string, opts?: { detail?: boolean; }) => Promise<{ facts: GitWorkDirFacts; } | { error: string; }>; rebuild: (repoUrl: string, mode: 'relink' | 'adopt' | 'reclone') => Promise<GitWorkDirFacts>; }; syncSectionCatalog: { id: SectionId; displayName: string; portability: Portability; defaultIncluded: boolean; }[]; syncSessions: SyncSessionStore; tmpDir: string; tryAppendHistory: (raw: { kind: MigrationKind; result: MigrationResult; sections: string[]; operationId?: string; snapshotId?: string; runId?: string; source: 'api' | 'autosync' | 'backup-scheduler' | 'recovery' | 'cli' | 'internal'; summary: string; error?: string; }) => Promise<string | undefined>; withMutationGate: (op: string, handler: (req: IncomingMessage, res: ServerResponse, lockCtx?: MutationLockContext, journalCtx?: JournalRunContext) => Promise<void>, opts?: { journaled?: boolean; deferredSnapshot?: boolean; }) => ((req: IncomingMessage, res: ServerResponse) => Promise<void>); selfUpdate: (targetVersion: string) => Promise<SelfUpdateOutcome>; writeItemCache: (url: string, itemId: string, manifestRaw: string, zipBytes: Uint8Array) => Promise<void>; }
|
|
2179
|
+
export type RouteEnvInferred = { sessionExportFetch: ((input: string, init: RequestInit) => Promise<Response>) | undefined; sessionExportPort: number | undefined; adapters: ConfigAdapter<unknown>[]; sessionHealth: { homeDir: string; targetFormatVersion: () => number | undefined; workspaceKeys: () => Promise<ReadonlySet<string>>; knownSessionIds: () => Promise<ReadonlySet<string>>; sessionMeta: (ids: readonly string[]) => Promise<SessionMetaIndex>; }; backupScheduler: BackupScheduler; bootSafetyAudit: () => Promise<BootSafetyReport>; cancelDecisionTimeoutMs: number; buildMarketSummary: (e: { url: string; addedAt: string; }) => Promise<MarketSummary>; credentials: CredentialProvider; dataDir: string; exportsDir: string; syncRootDir: string; syncScope: SyncScope; githubAuth: GitHubAuthClient; githubClientId: string | undefined; githubClientSecret: string | undefined; githubFlows: DeviceFlowStore; history: MigrationStore; host: ConfigManagerHostContext; itemCached: (url: string, itemId: string) => Promise<boolean>; knownSyncSectionIds: Set<SectionId>; makeImporter: () => Importer; makeMarketReader: () => GitMarketReader; makeRecoveryExecutors: (runId: string) => RecoveryExecutorFns; makeSyncEngine: (cfg: SyncConfig, engineOpts?: { optInSections?: readonly SectionId[]; }) => SyncEngine; marketBootAutoRefreshed: { value: boolean; }; marketCacheIndex: (url: string) => string; marketDir: string; marketCacheItemDir: (url: string) => string; marketStarCache: StarCache; marketWorkDir: (url: string) => string; meGitHubRest: GitHubAuthRest; meService: MyRepoService; meTokenProvider: () => Promise<string>; msg: MsgFunc; prepareSync: (body: Record<string, unknown>) => Promise<SyncConfig>; pluginVersion: string; profileLauncher: DshProfileLauncher; profileRuntime: DshProfileRuntimeRegistry; profiles: DshProfileManager; pruneStagedMarketZips: () => Promise<void>; readCachedIndexObj: (url: string) => Promise<MarketIndex | null>; recoveryOrchestrator: RecoveryOrchestrator; resolveSyncPassword: (ref: string) => Promise<string | undefined>; roots: string[]; runAbortControllers: Map<string, AbortController>; runCancels: Map<string, { signal: AbortController; settle: (d: 'rollback' | 'keep') => void; decided: boolean }>; runs: RunRegistry; scheduler: AutoSyncScheduler; selectionCache: Partial<Record<SyncTransportType, SyncSelection>>; selectionOptInSections: (channel: SyncTransportType, onlyAuto?: boolean) => SectionId[]; selectionView: (channel: SyncTransportType) => Promise<SelectionView>; selectionViewByChannel: () => Promise<Record<SyncTransportType, SelectionView>>; snapshotEntrySections: (snapshotDir: string) => Promise<string[]>; snapshotsDir: string; starPromptRepoUrl: string; syncCredentialsByChannelView: () => Promise<Record<SyncTransportType, { encryptPasswordConfigured: boolean; decryptPasswordConfigured: boolean; }>>; syncDir: string; syncPasswordConfigured: (ref: string) => Promise<boolean>; syncWorkDir: { inspect: (repoUrl: string, opts?: { detail?: boolean; subdir?: string; }) => Promise<{ facts: GitWorkDirFacts; } | { error: string; }>; rebuild: (repoUrl: string, mode: 'relink' | 'adopt' | 'reclone', subdir?: string) => Promise<GitWorkDirFacts>; }; syncSectionCatalog: { id: SectionId; displayName: string; portability: Portability; defaultIncluded: boolean; }[]; syncSessions: SyncSessionStore; tmpDir: string; tryAppendHistory: (raw: { kind: MigrationKind; result: MigrationResult; sections: string[]; operationId?: string; snapshotId?: string; runId?: string; source: 'api' | 'autosync' | 'backup-scheduler' | 'recovery' | 'cli' | 'internal'; summary: string; error?: string; }) => Promise<string | undefined>; withMutationGate: (op: string, handler: (req: IncomingMessage, res: ServerResponse, lockCtx?: MutationLockContext, journalCtx?: JournalRunContext) => Promise<void>, opts?: { journaled?: boolean; deferredSnapshot?: boolean; }) => ((req: IncomingMessage, res: ServerResponse) => Promise<void>); selfUpdate: (targetVersion: string) => Promise<SelfUpdateOutcome>; writeItemCache: (url: string, itemId: string, manifestRaw: string, zipBytes: Uint8Array) => Promise<void>; }
|
|
2180
2180
|
|
|
2181
2181
|
|
|
2182
2182
|
interface RoutesDeps {
|
|
@@ -2688,8 +2688,10 @@ function makeRoutes(deps: RoutesDeps): {
|
|
|
2688
2688
|
* 构造 git 通道实例(同步引擎与 issue #79 的工作副本自检/重建共用同一份地址与凭据口径)。
|
|
2689
2689
|
* token 只经 credentials 端口现取(值永不落盘/日志/回传)。
|
|
2690
2690
|
*/
|
|
2691
|
-
const makeGitTransport = (repoUrl: string): GitTransport => new GitTransport({
|
|
2691
|
+
const makeGitTransport = (repoUrl: string, subdir?: string): GitTransport => new GitTransport({
|
|
2692
2692
|
repoUrl,
|
|
2693
|
+
// issue #131:子目录前缀与 repoUrl 同源(配置 → 传输层),空串 = 仓库根
|
|
2694
|
+
...(subdir === undefined ? {} : { subdir }),
|
|
2693
2695
|
workDir: gitWorkDir,
|
|
2694
2696
|
credentials: {
|
|
2695
2697
|
getToken: async () => {
|
|
@@ -2752,7 +2754,7 @@ function makeRoutes(deps: RoutesDeps): {
|
|
|
2752
2754
|
msg,
|
|
2753
2755
|
})
|
|
2754
2756
|
} else {
|
|
2755
|
-
transport = makeGitTransport(cfg.git.repoUrl)
|
|
2757
|
+
transport = makeGitTransport(cfg.git.repoUrl, cfg.git.subdir)
|
|
2756
2758
|
}
|
|
2757
2759
|
const channel: SyncTransportType = channelOf(cfg)
|
|
2758
2760
|
const sections = effectiveSections(selectionCache[channel] ?? defaultSyncSelection())
|
|
@@ -3054,20 +3056,20 @@ function makeRoutes(deps: RoutesDeps): {
|
|
|
3054
3056
|
syncWorkDir: {
|
|
3055
3057
|
// 自检失败(git 不可用 / 工作副本异常)→ 返回 { error },**不让整个状态接口 500**,
|
|
3056
3058
|
// 也不伪装成「工作副本不存在」。
|
|
3057
|
-
inspect: async (repoUrl: string, opts: { detail?: boolean } = {}): Promise<{ facts: GitWorkDirFacts } | { error: string }> => {
|
|
3059
|
+
inspect: async (repoUrl: string, opts: { detail?: boolean; subdir?: string } = {}): Promise<{ facts: GitWorkDirFacts } | { error: string }> => {
|
|
3058
3060
|
try {
|
|
3059
3061
|
// issue #104 建议 3:`/sync/status` 要回传「领先远端提交数 / 远端快照数」,
|
|
3060
3062
|
// 用户看不见积压就会在「以为在备份」的状态下一直失败。detail 那几条是本地只读但各起
|
|
3061
3063
|
// 一次 git 进程(Windows 约 80 ms)⇒ 缺省完整(WorkDirCard 要),路由可传 false。
|
|
3062
|
-
return { facts: await makeGitTransport(repoUrl).inspectWorkDir({ detail: opts.detail !== false }) }
|
|
3064
|
+
return { facts: await makeGitTransport(repoUrl, opts.subdir).inspectWorkDir({ detail: opts.detail !== false }) }
|
|
3063
3065
|
} catch (err) {
|
|
3064
3066
|
return { error: err instanceof Error ? err.message : String(err) }
|
|
3065
3067
|
}
|
|
3066
3068
|
},
|
|
3067
3069
|
// 重建:relink 非破坏;adopt 合并远端历史(不改写本地提交,issue #104);
|
|
3068
3070
|
// reclone 删目录重克隆(调用方必须先取得用户确认)
|
|
3069
|
-
rebuild: async (repoUrl: string, mode: 'relink' | 'adopt' | 'reclone'): Promise<GitWorkDirFacts> => {
|
|
3070
|
-
const transport = makeGitTransport(repoUrl)
|
|
3071
|
+
rebuild: async (repoUrl: string, mode: 'relink' | 'adopt' | 'reclone', subdir?: string): Promise<GitWorkDirFacts> => {
|
|
3072
|
+
const transport = makeGitTransport(repoUrl, subdir)
|
|
3071
3073
|
await transport.rebuildWorkDir(mode)
|
|
3072
3074
|
return await transport.inspectWorkDir()
|
|
3073
3075
|
},
|
package/src/routes/import.ts
CHANGED
|
@@ -9,6 +9,7 @@ import { endpoint, requireJsonObject, readJsonBody, writeJson, queryParam } from
|
|
|
9
9
|
import type { WebRoute } from './kit.ts'
|
|
10
10
|
import type { RoutesEnv } from './context.ts'
|
|
11
11
|
import type { RunState } from '../core/run-registry.ts'
|
|
12
|
+
import { isIdleAutosyncRun } from '../core/run-registry.ts'
|
|
12
13
|
import type { ImportPlan } from '../core/types.ts'
|
|
13
14
|
import { DEFAULT_ROLLBACK_ON_ERROR } from '../core/import-defaults.ts'
|
|
14
15
|
import { decryptErrorText, isControlledPath, tryDecryptCredentials, writeRequestBodyToFile } from './route-support.ts'
|
|
@@ -361,7 +362,11 @@ export function importRoutes(env: RoutesEnv): WebRoute[] {
|
|
|
361
362
|
endpoint({ path: '/api/dsh-config-manager/runs', methods: ['GET'] }, async (req, res) => {
|
|
362
363
|
const url = new URL(req.url ?? '/', 'http://localhost')
|
|
363
364
|
const scope = queryParam(url, 'scope')
|
|
364
|
-
|
|
365
|
+
// 空转的自动同步轮次不进「运行中心」:60s 一次轮询,每轮一张「已完成」卡片与迁移历史同属噪音;
|
|
366
|
+
// running / 真干活的轮次照常列出(判据见 core/run-registry.ts 的 isIdleAutosyncRun)。
|
|
367
|
+
writeJson(res, 200, scope === 'recent'
|
|
368
|
+
? runs.listRecent(50).filter((run) => !isIdleAutosyncRun(run))
|
|
369
|
+
: runs.listActive())
|
|
365
370
|
}),
|
|
366
371
|
// ------------------------------------------------------- runs/cancel
|
|
367
372
|
// 运行中心「终止」:只在**计划项边界**生效的协作式取消(abort run 级信号)。
|
|
@@ -36,7 +36,7 @@ import { collectRestoreWalEntries, createRestoreWal, restoreActionStepId, restor
|
|
|
36
36
|
import type { RestoreResumeHint } from '../core/restore-resume.ts'
|
|
37
37
|
import type { RestoreJournalPort, RestoreWalHandle, RestoreWalSettleStatus } from '../core/restore-wal.ts'
|
|
38
38
|
import type { SyncConfig, SyncTransportType } from '../sync/sync-config.ts'
|
|
39
|
-
import { GIST_PROVIDER, cloudSecretRef, isS3CompatProvider, isWebDavConfig, parseSyncChannel, validateCloudChannelInput, validateRepoUrl, validateWebDavUrl } from '../sync/sync-config.ts'
|
|
39
|
+
import { GIST_PROVIDER, cloudSecretRef, isS3CompatProvider, isWebDavConfig, normalizeGitSubdir, parseSyncChannel, validateCloudChannelInput, validateRepoUrl, validateWebDavUrl } from '../sync/sync-config.ts'
|
|
40
40
|
import { DEFAULT_AUTOSYNC_AUTO_APPLY_TIER, DEFAULT_AUTOSYNC_CONFLICT_POLICY, DEFAULT_AUTOSYNC_REALTIME, DEFAULT_AUTOSYNC_REMOTE_CHECK_MS, lastRunFailureMessage, readAllAutosyncConfigs, readAutosyncConfig } from '../sync/autosync-config.ts'
|
|
41
41
|
import type { AutosyncAutoApplyTier, AutosyncConflictPolicy, AutosyncInterval, AutosyncRunStatus } from '../sync/autosync-config.ts'
|
|
42
42
|
import { SYNC_CHANNELS } from '../sync/sync-config.ts'
|
|
@@ -756,7 +756,8 @@ export interface SyncRefScope {
|
|
|
756
756
|
/**
|
|
757
757
|
* 解析同步请求体,按 transport 分支返回归一化的 SyncConfig(可辨识联合,schemaVersion=2)。
|
|
758
758
|
* 请求体形状(flat,M4 契约):
|
|
759
|
-
* - git: { transport:'git', repoUrl, token? } ——
|
|
759
|
+
* - git: { transport:'git', repoUrl, subdir?, token? } —— subdir = 仓库内子目录前缀(issue #131);
|
|
760
|
+
* token 非空写 SYNC_CREDENTIAL_REF;
|
|
760
761
|
* git 可执行文件固定使用系统 PATH 中的 git(不再接受自定义 gitBin)。
|
|
761
762
|
* - webdav: { transport:'webdav', url, username?, password? } —— password 非空写 SYNC_WEBDAV_CREDENTIAL_REF。
|
|
762
763
|
* 返回值不含任何 secret(password/token 只进 credentials,永不回传/落同步文件)。
|
|
@@ -802,6 +803,9 @@ export async function parseSyncBody(
|
|
|
802
803
|
if (repoUrl === '') throw new SyncRouteError('repoUrl is required')
|
|
803
804
|
const urlError = validateRepoUrl(repoUrl)
|
|
804
805
|
if (urlError !== null) throw new SyncRouteError(urlError)
|
|
806
|
+
// issue #131:仓库内子目录前缀(可选;空 = 仓库根)。非法值在这里就拒,绝不先落盘再交给 git。
|
|
807
|
+
const subdirCheck = normalizeGitSubdir(syncStr(body['subdir']))
|
|
808
|
+
if (!subdirCheck.ok) throw new SyncRouteError(engineMsg('sync.git.subdirInvalid', { subdir: syncStr(body['subdir']) }))
|
|
805
809
|
const token = typeof body['token'] === 'string' && body['token'] !== '' ? body['token'] : undefined
|
|
806
810
|
if (token !== undefined) {
|
|
807
811
|
try {
|
|
@@ -816,7 +820,7 @@ export async function parseSyncBody(
|
|
|
816
820
|
return {
|
|
817
821
|
schemaVersion: 2,
|
|
818
822
|
transport: 'git',
|
|
819
|
-
git: { repoUrl },
|
|
823
|
+
git: { repoUrl, ...(subdirCheck.value === '' ? {} : { subdir: subdirCheck.value }) },
|
|
820
824
|
}
|
|
821
825
|
}
|
|
822
826
|
|