dsh-cloud-backup 0.0.0-stage → 0.1.139

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.
@@ -0,0 +1,139 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ import { createRequire } from "node:module";
5
+
6
+ // 宿主运行版本就是 `dsh --version`(@deepseek-ai/dsh / dsh-app-boot 的版本)。
7
+ // 插件兼容门禁比对插件声明的 engines.dsh,面板自检共用同一取值逻辑。
8
+ const SELF_DIR = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../..");
9
+
10
+ export function readVersion(file) {
11
+ try {
12
+ const v = JSON.parse(fs.readFileSync(file, "utf8")).version;
13
+ return typeof v === "string" && v ? v : null;
14
+ } catch { return null; }
15
+ }
16
+
17
+ /** 插件自己声明的兼容范围(engines.dsh);没声明返回空串。 */
18
+ export function declaredRange() {
19
+ try {
20
+ const pkg = JSON.parse(fs.readFileSync(path.join(SELF_DIR, "package.json"), "utf8"));
21
+ const v = pkg && pkg.engines && pkg.engines.dsh;
22
+ return typeof v === "string" ? v : "";
23
+ } catch { return ""; }
24
+ }
25
+
26
+ // 宿主 CLI 的入口路径形如 .../node_modules/@deepseek-ai/<pkg>/lib/cli.js;
27
+ // desktop 版这一层在 app.asar 里,Electron 的 fs 兼容层能直接读。
28
+ function sibling(entry, name) {
29
+ const m = /^(.*[\/]node_modules[\/]@deepseek-ai[\/])[^\/]+[\/]/.exec(String(entry || ""));
30
+ return m ? path.join(m[1], name, "package.json") : null;
31
+ }
32
+
33
+ // 桌面版把 dsh 运行时装进 app.asar:<resources>/app.asar/dsh/package.json 的版本
34
+ // 就是 `dsh --version` 报的那个(包名 @deepseek-ai/dsh-desktop-runtime)。
35
+ function asarCandidates(entries) {
36
+ const roots = [];
37
+ const res = (process && process.resourcesPath) || "";
38
+ if (res) roots.push(path.join(res, "app.asar"));
39
+ for (const e of entries) {
40
+ const m = /^(.*[\\/]app\.asar)[\\/]/.exec(String(e == null ? "" : e));
41
+ if (m && roots.indexOf(m[1]) < 0) roots.push(m[1]);
42
+ }
43
+ const out = [];
44
+ for (const r of roots) {
45
+ out.push(path.join(r, "dsh", "package.json"));
46
+ for (const n of ["dsh", "dsh-app-boot", "dsh-desktop-runtime"]) {
47
+ out.push(path.join(r, "dsh", "node_modules", "@deepseek-ai", n, "package.json"));
48
+ }
49
+ }
50
+ return out;
51
+ }
52
+
53
+ export function runtimeVersion(argv1 = process.argv[1], env = process.env, argv = process.argv) {
54
+ const forced = env && env.DSH_CLOUD_BACKUP_DSH_VERSION;
55
+ if (forced) return { version: String(forced), source: "env" };
56
+ try {
57
+ const req = createRequire(import.meta.url);
58
+ for (const n of ["@deepseek-ai/dsh", "@deepseek-ai/dsh-app-boot"]) {
59
+ try {
60
+ const v = readVersion(req.resolve(n + "/package.json"));
61
+ if (v) return { version: v, source: "resolve" };
62
+ } catch { /* 该包不在本插件的解析路径上,继续换法子 */ }
63
+ }
64
+ } catch { /* createRequire 不可用时只走路径反推 */ }
65
+ const args = Array.isArray(argv) ? argv.slice() : [];
66
+ if (argv1 && args.indexOf(argv1) < 0) args.unshift(argv1);
67
+ for (const a of args) {
68
+ for (const n of ["dsh", "dsh-app-boot", "dsh-desktop-runtime"]) {
69
+ const p = sibling(a, n);
70
+ if (p) { const v = readVersion(p); if (v) return { version: v, source: "argv" }; }
71
+ }
72
+ }
73
+ for (const p of asarCandidates(args)) {
74
+ const v = readVersion(p);
75
+ if (v) return { version: v, source: "asar" };
76
+ }
77
+ return { version: null, source: "unknown" };
78
+ }
79
+
80
+ function parse(v) {
81
+ const m = /^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?/.exec(String(v == null ? "" : v).trim());
82
+ if (!m) return null;
83
+ return { main: [Number(m[1]), Number(m[2]), Number(m[3])], pre: m[4] ? m[4].split(".") : [] };
84
+ }
85
+ function cmpId(a, b) {
86
+ const an = /^\d+$/.test(a), bn = /^\d+$/.test(b);
87
+ if (an && bn) return Number(a) - Number(b) < 0 ? -1 : (Number(a) === Number(b) ? 0 : 1);
88
+ if (an) return -1; // 数字标识符优先级低于字母标识符
89
+ if (bn) return 1;
90
+ return a === b ? 0 : (a < b ? -1 : 1);
91
+ }
92
+
93
+ /** 标准 semver 优先级比较;无法解析返回 null。 */
94
+ export function compareVersions(a, b) {
95
+ const x = parse(a), y = parse(b);
96
+ if (!x || !y) return null;
97
+ for (let i = 0; i < 3; i++) if (x.main[i] !== y.main[i]) return x.main[i] < y.main[i] ? -1 : 1;
98
+ if (!x.pre.length && !y.pre.length) return 0;
99
+ if (!x.pre.length) return 1;
100
+ if (!y.pre.length) return -1;
101
+ for (let i = 0; i < Math.max(x.pre.length, y.pre.length); i++) {
102
+ if (x.pre[i] === undefined) return -1;
103
+ if (y.pre[i] === undefined) return 1;
104
+ const c = cmpId(x.pre[i], y.pre[i]);
105
+ if (c) return c;
106
+ }
107
+ return 0;
108
+ }
109
+
110
+ /** 只支持空格分隔的比较符(>=、>、<=、<、=),足够表达引擎声明;预发布按 semver 优先级参与。 */
111
+ export function satisfies(version, range) {
112
+ const parts = String(range == null ? "" : range).trim().split(/\s+/).filter(Boolean);
113
+ if (!parts.length || !parse(version)) return null;
114
+ for (const p of parts) {
115
+ const m = /^(>=|<=|>|<|=)?(.+)$/.exec(p);
116
+ const op = m[1] || "=";
117
+ const c = compareVersions(version, m[2]);
118
+ if (c === null) return null;
119
+ const ok = op === ">=" ? c >= 0 : op === ">" ? c > 0 : op === "<=" ? c <= 0 : op === "<" ? c < 0 : c === 0;
120
+ if (!ok) return false;
121
+ }
122
+ return true;
123
+ }
124
+
125
+ // 与宿主一致:没声明就视为任何版本都兼容;声明了但范围无法解析则给 null(未知)。
126
+ export function compatVerdict(runtime, declared) {
127
+ const range = String(declared == null ? "" : declared).trim();
128
+ if (!runtime) return { runtime: null, declared: range, ok: null, reason: "no-runtime" };
129
+ if (!range) return { runtime, declared: "", ok: true, reason: "no-declaration" };
130
+ const r = satisfies(runtime, range);
131
+ if (r === null) return { runtime, declared: range, ok: null, reason: "bad-range" };
132
+ return { runtime, declared: range, ok: r, reason: r ? "ok" : "out-of-range" };
133
+ }
134
+
135
+ export function compatInfo(argv1, env) {
136
+ const rt = runtimeVersion(argv1, env);
137
+ const v = compatVerdict(rt.version, declaredRange());
138
+ return { runtime: v.runtime, declared: v.declared, ok: v.ok, reason: v.reason, source: rt.source };
139
+ }
@@ -0,0 +1,46 @@
1
+ // 本机写操作互斥:备份「先写块、后写清单」,两段之间若块回收在跑会把新块当孤儿删掉。
2
+
3
+ import fs from "node:fs";
4
+ import path from "node:path";
5
+
6
+ const LOCK_NAME = ".run-lock";
7
+ const STALE_MS = 30 * 60 * 1000;
8
+
9
+ function writeLock(lockFile) {
10
+ const fd = fs.openSync(lockFile, "wx");
11
+ fs.writeSync(fd, JSON.stringify({ pid: process.pid, at: new Date().toISOString() }));
12
+ fs.closeSync(fd);
13
+ }
14
+
15
+ /** 取锁;返回 { ok:true, lockFile } 或 { ok:false, reason }(超 30 分钟视为遗留锁) */
16
+ export function acquireLock(storeDir) {
17
+ const lockFile = path.join(storeDir, LOCK_NAME);
18
+ try { fs.mkdirSync(storeDir, { recursive: true }); } catch { /* 目录已存在 */ }
19
+ try {
20
+ writeLock(lockFile);
21
+ return { ok: true, lockFile };
22
+ } catch {
23
+ let age = 0;
24
+ try { age = Date.now() - fs.statSync(lockFile).mtimeMs; } catch { /* 锁刚被释放 */ }
25
+ if (age > STALE_MS) {
26
+ try { fs.unlinkSync(lockFile); } catch { /* 已被他人清理 */ }
27
+ try { writeLock(lockFile); return { ok: true, lockFile, stale: true }; } catch { /* 竞争失败 */ }
28
+ }
29
+ return { ok: false, reason: "another write in progress (" + Math.round(age / 1000) + "s)" };
30
+ }
31
+ }
32
+
33
+ export function releaseLock(lock) {
34
+ if (!lock || !lock.lockFile) return;
35
+ try { fs.unlinkSync(lock.lockFile); } catch { /* 已被清理 */ }
36
+ }
37
+
38
+ /** 给「忙」统一一个可读的响应,避免面板把锁冲突当成删除失败 */
39
+ export function busyResult(lock) {
40
+ return {
41
+ ok: false,
42
+ code: "busy",
43
+ reason: "busy",
44
+ error: "正在备份,请稍后再试(" + String((lock && lock.reason) || "写入进行中") + ")",
45
+ };
46
+ }
@@ -0,0 +1,77 @@
1
+ // lib/engine/manifest.js —— 快照清单与索引
2
+
3
+ import fs from "node:fs";
4
+ import path from "node:path";
5
+ import { writeFileAtomic } from "../store/paths.js";
6
+
7
+ export const SNAPSHOT_KIND = "dsh-backup-snapshot";
8
+
9
+ export function stampNow(d = new Date()) {
10
+ const p = (n) => String(n).padStart(2, "0");
11
+ return d.getFullYear() + p(d.getMonth() + 1) + p(d.getDate()) + "-" + p(d.getHours()) + p(d.getMinutes()) + p(d.getSeconds());
12
+ }
13
+
14
+ export function snapshotsRoot(storeDir) { return path.join(storeDir, "snapshots"); }
15
+ export function snapshotDir(storeDir, stamp) { return path.join(snapshotsRoot(storeDir), stamp); }
16
+ export function manifestPath(storeDir, stamp) { return path.join(snapshotDir(storeDir, stamp), "manifest.json"); }
17
+ export function indexPath(storeDir) { return path.join(storeDir, "index.json"); }
18
+
19
+ export function buildManifest({
20
+ files, stamp, workspace = "all", dshHome, host, provider = "aliyun", skipped = 0, plugins = null, runtime = null }) {
21
+ const byRel = files.map((f) => ({ rel: f.rel, hash: f.hash, size: f.size, mtime: Math.round(f.mtime) }));
22
+ const bytes = byRel.reduce((s, f) => s + f.size, 0);
23
+ const uniq = new Set(byRel.map((f) => f.hash));
24
+ return {
25
+ v: 1,
26
+ kind: SNAPSHOT_KIND,
27
+ stamp,
28
+ created_at: new Date().toISOString(),
29
+ host: host || "",
30
+ workspace,
31
+ dsh_home: dshHome || "",
32
+ provider,
33
+ ...(runtime ? { runtime } : {}),
34
+ stats: { files: byRel.length, bytes, unique_blobs: uniq.size, skipped },
35
+ files: byRel,
36
+ ...(Array.isArray(plugins) && plugins.length ? { plugins } : {}),
37
+ };
38
+ }
39
+
40
+ export function writeManifest(storeDir, m) {
41
+ const file = manifestPath(storeDir, m.stamp);
42
+ fs.mkdirSync(path.dirname(file), { recursive: true });
43
+ writeFileAtomic(file, JSON.stringify(m));
44
+ return file;
45
+ }
46
+
47
+ export function readManifest(file) {
48
+ try { return JSON.parse(fs.readFileSync(file, "utf8")); } catch { return null; }
49
+ }
50
+
51
+ export function listSnapshots(storeDir) {
52
+ const root = snapshotsRoot(storeDir);
53
+ let names = [];
54
+ try { names = fs.readdirSync(root, { withFileTypes: true }).filter((e) => e.isDirectory()).map((e) => e.name); } catch { return []; }
55
+ return names.sort().reverse().map((stamp) => {
56
+ const file = manifestPath(storeDir, stamp);
57
+ const st = (() => { try { return fs.statSync(file); } catch { return null; } })();
58
+ return { stamp, file, exists: !!st, mtime: st ? st.mtimeMs : 0, bytes: st ? st.size : 0 };
59
+ });
60
+ }
61
+
62
+ /** 重建 index.json:快照清单 + 全部被引用的 blob 集合。 */
63
+ export function rebuildIndex(storeDir, { provider = "aliyun", extra = {} } = {}) {
64
+ const snaps = [];
65
+ const refs = new Set();
66
+ const broken = []; // 解析不了的清单必须上报,否则它的独占 blob 会被 GC 当垃圾删掉
67
+ for (const s of listSnapshots(storeDir)) {
68
+ const m = readManifest(s.file);
69
+ if (!m) { broken.push(s.stamp); continue; }
70
+ for (const f of m.files || []) refs.add(f.hash);
71
+ for (const p of m.plugins || []) { if (p && p.blob) refs.add(p.blob); }
72
+ snaps.push({ stamp: s.stamp, created_at: m.created_at, files: (m.files || []).length, bytes: m.stats?.bytes ?? 0, unique_blobs: m.stats?.unique_blobs ?? 0, workspace: m.workspace || "all" });
73
+ }
74
+ const index = { v: 1, kind: "dsh-backup-index", updated_at: new Date().toISOString(), provider, snapshots: snaps, blobs: refs.size, broken, ...extra };
75
+ writeFileAtomic(indexPath(storeDir), JSON.stringify(index, null, 2));
76
+ return { index, refs, broken };
77
+ }