dsh-workbench-salary 0.4.19 → 0.4.23

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/CHANGELOG.md ADDED
@@ -0,0 +1,17 @@
1
+ # 工资插件 CHANGELOG
2
+
3
+ > 包名:`dsh-workbench-salary`;当前版本:0.4.23(以 `package.json` 为准)。
4
+ > 源码入口 `lib/index.js` 只保留用途与当前版本,版本历史统一记录在这里;此后发版只追加本文件,不再往源码写版本史。
5
+
6
+ ## 0.4.23 — 2026-12-06
7
+
8
+ - DDL 改声明式(共享 `lib/backend/schema.js`),建库顺序统一为「建表 → 补列 → 建索引」。
9
+
10
+ ## 0.4.22 — 2026-12-06
11
+
12
+ - 清理样式里写死的兜底色:`var(--token,#hex)` 统一改为 `var(--token)`,散落的裸色值改用 `--wb-*` 主题 token;浅色、深色都跟随宿主主题,不再为单个模块保留色板。
13
+ - 删除域内自带的 `<域>.actionSchema` 副本,Action 页统一读宿主注册表。
14
+
15
+ ## 更早的变更
16
+
17
+ - 本次迁移在源码入口未发现逐版本记录;更早的变更请查 git 提交记录。
@@ -0,0 +1,521 @@
1
+ /**
2
+ * 备份导入导出的共享骨架。
3
+ *
4
+ * 四个业务域(tasks / sites / tags / storage)的备份格式、列映射与特有校验由插件
5
+ * 声明,这里只负责共同部分:表读取、版本与结构校验、行转换与重复 ID 检测、
6
+ * 按 updated_at 的幂等 UPSERT(newest / skip / overwrite)、按本机表结构做列对齐、
7
+ * 错误聚合与结果骨架。
8
+ *
9
+ * 约定:
10
+ * - 本模块不 import 任何业务域;域差异全部经 spec.tables 的 hooks 接入;
11
+ * - 不直接落库导出,导入的写操作由调用方提供的 transaction 包裹;
12
+ * - 输入行只读,转换结果写入新的 row 对象;
13
+ * - 列对齐以本机 PRAGMA 形状为准,主键与 updated_at 必须保留;
14
+ * - 本模块不 emit:事件由 spec.emit 在导入成功后触发。
15
+ */
16
+
17
+ import { tableColumns } from "./schema.js";
18
+
19
+ /** 受支持的导入策略;非法值统一回退 newest(storage 由 spec.validate 另做严格校验)。 */
20
+ export function normalizePolicy(options) {
21
+ const policy = options && options.policy;
22
+ return policy === "skip" || policy === "overwrite" ? policy : "newest";
23
+ }
24
+
25
+ export function hasTable(db, name) {
26
+ if (!db || !name) return false;
27
+ const row = db.prepare("SELECT name FROM sqlite_master WHERE type IN ('table','view') AND name=?").get(String(name));
28
+ return !!row;
29
+ }
30
+
31
+ /** 表存在时按声明排序读取;表不存在返回空数组(老库/未安装插件都能导出)。 */
32
+ export function readTable(db, table) {
33
+ if (!hasTable(db, table.table)) return [];
34
+ const where = table.where ? " WHERE " + table.where : "";
35
+ const order = table.orderBy ? " ORDER BY " + table.orderBy : "";
36
+ return db.prepare("SELECT * FROM " + table.table + where + order).all();
37
+ }
38
+
39
+ /** 生成按主键幂等 UPSERT的语句;列顺序与 select * 的列序无关,只影响写入。 */
40
+ export function upsertStatement(db, table) {
41
+ const columns = table.columns;
42
+ const holders = columns.map(() => "?").join(",");
43
+ const updates = columns
44
+ .slice(1)
45
+ .map((column) => column + "=excluded." + column)
46
+ .join(",");
47
+ return db.prepare(
48
+ "INSERT INTO " + table.table + " (" + columns.join(",") + ") VALUES(" + holders + ") ON CONFLICT(id) DO UPDATE SET " + updates,
49
+ );
50
+ }
51
+
52
+ /** 列值数组 → 行对象,按声明列序装配(转换函数保持旧实现的数组写法)。 */
53
+ export function rowFrom(columns, values) {
54
+ const row = {};
55
+ for (let i = 0; i < columns.length; i += 1) row[columns[i]] = values[i];
56
+ return row;
57
+ }
58
+
59
+ /** 行转换的通用类型助手:保持旧实现「宽松转换、缺省回退」的语义。 */
60
+ export function text(value, fallback) {
61
+ if (value === undefined || value === null) return fallback === undefined ? "" : fallback;
62
+ return String(value);
63
+ }
64
+
65
+ export function integer(value, fallback) {
66
+ const n = Number(value);
67
+ return Number.isFinite(n) ? Math.trunc(n) : fallback;
68
+ }
69
+
70
+ export function numberOrNull(value) {
71
+ if (value === undefined || value === null || value === "") return null;
72
+ const n = Number(value);
73
+ return Number.isFinite(n) ? n : null;
74
+ }
75
+
76
+ export function textOrNull(value) {
77
+ if (value === undefined || value === null) return null;
78
+ const s = String(value);
79
+ return s === "" ? null : s;
80
+ }
81
+
82
+ /** 严格标识:不 trim、不数值化,001 与 1 是不同实体。 */
83
+ export function identity(value, field) {
84
+ if (typeof value !== "string" || !value.length) throw new Error(field + " 必须为非空字符串");
85
+ return value;
86
+ }
87
+
88
+ /** 严格时间戳:物品域使用;nullable 只接受显式 null,undefined 仍算非法。 */
89
+ export function timestamp(value, field, nullable) {
90
+ if (nullable && value === null) return null;
91
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0 || value > 8640000000000000) {
92
+ throw new Error(field + " 必须是非负整数时间戳");
93
+ }
94
+ return value;
95
+ }
96
+
97
+ /**
98
+ * 版本门禁:低于支持区间的备份用当前版本重新导出,高于支持区间的备份说明本机插件旧,
99
+ * 必须整批拒绝并提示升级插件——此时一行都不能写,避免半截数据。
100
+ *
101
+ * 各域的旧版本仍要能导入(min 默认 1),只有备份比本机新才是危险方向。
102
+ */
103
+ export function assertBackupVersion(version, options) {
104
+ const opts = options || {};
105
+ const min = opts.min === undefined ? 1 : Number(opts.min);
106
+ const max = Number(opts.max);
107
+ const label = opts.label ? opts.label + "备份" : "备份";
108
+ const value = Number(version);
109
+ if (!Number.isInteger(value)) throw new Error(label + "版本标识无效(" + String(version) + "),无法导入");
110
+ if (value < min) throw new Error(label + "版本 " + value + " 过低(本机支持 " + min + "–" + max + "),请用当前版本重新导出后再导入");
111
+ if (value > max) throw new Error(label + "版本 " + value + " 高于本机支持的 " + max + ",请先升级插件后再导入(未写入任何数据)");
112
+ return value;
113
+ }
114
+
115
+ /** SQLite 列亲和性:对齐时的类型兼容判断按亲和性走,而不是按声明字面量。 */
116
+ function affinityOf(type) {
117
+ const text = String(type || "").toUpperCase();
118
+ if (text.includes("INT")) return "NUMERIC";
119
+ if (text.includes("CHAR") || text.includes("CLOB") || text.includes("TEXT")) return "TEXT";
120
+ if (text.includes("REAL") || text.includes("FLOA") || text.includes("DOUB")) return "NUMERIC";
121
+ if (text.includes("BLOB") || text === "") return "BLOB";
122
+ return "NUMERIC";
123
+ }
124
+
125
+ /**
126
+ * 单值类型兼容判断:本机列决定可接受的值形状。
127
+ * 数值亲和接受数字、数字字符串与布尔;文本亲和接受标量;对象/数组一律拒绝。
128
+ * id 与 updated_at 必填,缺值或空串直接拒绝该行(主键与 updated_at 必须保留)。
129
+ */
130
+ export function valueProblem(name, column, value, required) {
131
+ if (required && (value === undefined || value === null || value === "")) return name + " 缺失(主键与 updated_at 必须保留)";
132
+ if (value === undefined || value === null) {
133
+ if (column.notNull && !column.defaultValue) return name + " 不能为空(本机列为 NOT NULL 且无默认值)";
134
+ return null;
135
+ }
136
+ const kind = typeof value;
137
+ if (kind === "object" || kind === "function") return name + " 值类型不兼容(本机列 " + column.type + " 收到对象)";
138
+ const affinity = affinityOf(column.type);
139
+ if (affinity === "NUMERIC") {
140
+ if (kind === "number") return Number.isFinite(value) ? null : name + " 数值非法(" + String(value) + ")";
141
+ if (kind === "boolean") return null;
142
+ if (kind === "string") {
143
+ const trimmed = value.trim();
144
+ if (trimmed === "") return name + " 是数值列 " + column.type + ",但备份值为空字符串";
145
+ return Number.isFinite(Number(trimmed)) ? null : name + " 是数值列 " + column.type + ",但备份值为非数值文本 " + JSON.stringify(value.slice(0, 40));
146
+ }
147
+ return name + " 是数值列 " + column.type + ",但备份值类型为 " + kind;
148
+ }
149
+ if (affinity === "TEXT") {
150
+ return kind === "string" || kind === "number" || kind === "boolean" ? null : name + " 是文本列 " + column.type + ",但备份值类型为 " + kind;
151
+ }
152
+ return null;
153
+ }
154
+
155
+ /**
156
+ * 按本机表结构计算对齐计划(语义对齐宿主 sync 的 dropUnknownColumns/fillMissingFromLocal):
157
+ * - 备份声明了、本机没有的列:丢弃,记入 skippedColumns;
158
+ * - 本机有、备份没声明的列:不写,交给本机默认值(NOT NULL 有默认取默认,可空取 null),
159
+ * 记入 filledColumns,保证「补齐」在回执里可见;
160
+ * - 主键与 updated_at 必须存在于本机且可写,否则整张表拒绝导入。
161
+ * 表不存在时同样拒绝,避免 SQLite 抛 no such table 让调用方误以为写了一半。
162
+ */
163
+ export function tableAlignment(db, table) {
164
+ const name = table.table;
165
+ const idColumn = table.idColumn || table.columns[0];
166
+ const local = tableColumns(db, name);
167
+ if (!local.length) throw new Error("本机缺少表 " + name + ",无法按本机结构对齐导入;请升级插件后重试");
168
+ const byName = new Map(local.map((column) => [column.name, column]));
169
+ const declared = table.columns;
170
+ const declaredSet = new Set(declared);
171
+ const dropped = declared.filter((column) => !byName.has(column));
172
+ if (dropped.includes(idColumn)) throw new Error("本机表 " + name + " 缺少主键列 " + idColumn + ",拒绝导入");
173
+ if (dropped.includes("updated_at") || !byName.has("updated_at"))
174
+ throw new Error("本机表 " + name + " 缺少 updated_at 列,拒绝导入(主键与 updated_at 必须保留)");
175
+ const filled = local.map((column) => column.name).filter((column) => !declaredSet.has(column));
176
+ return {
177
+ table: name,
178
+ idColumn,
179
+ localByName: byName,
180
+ writeColumns: declared.filter((column) => byName.has(column)),
181
+ dropped,
182
+ filled,
183
+ skippedColumns: dropped.map((column) => name + "." + column),
184
+ filledColumns: filled.map((column) => name + "." + column),
185
+ };
186
+ }
187
+
188
+ /**
189
+ * 把一行转换结果对齐到本机列:声明列按本机形状校验,备份行里出现、本机也有但
190
+ * 未声明的列原样保留(不丢数据),本机没有的列直接丢掉。
191
+ */
192
+ export function alignRow(alignment, row, original) {
193
+ const columns = alignment.writeColumns.slice();
194
+ const values = {};
195
+ for (const column of columns) values[column] = row[column];
196
+ if (original && typeof original === "object" && !Array.isArray(original)) {
197
+ for (const key of Object.keys(original)) {
198
+ if (columns.includes(key)) continue;
199
+ if (!alignment.localByName.has(key)) continue;
200
+ // 备份行没带这一列时不写它:交给本机默认值,避免把 NOT NULL DEFAULT 覆盖成 null
201
+ if (original[key] === undefined) continue;
202
+ columns.push(key);
203
+ values[key] = row[key] === undefined ? original[key] : row[key];
204
+ }
205
+ }
206
+ const write = [];
207
+ for (const column of columns) {
208
+ const meta = alignment.localByName.get(column);
209
+ const required = column === alignment.idColumn || column === "updated_at";
210
+ const problem = valueProblem(column, meta, values[column], required);
211
+ if (problem) return { ok: false, reason: problem };
212
+ if (values[column] === undefined) {
213
+ // 本机声明了默认值的 NOT NULL 列缺值时整列不写,让 SQLite 取默认值
214
+ if (meta.notNull && meta.defaultValue) continue;
215
+ values[column] = null;
216
+ }
217
+ write.push(column);
218
+ }
219
+ return { ok: true, columns: write, values };
220
+ }
221
+
222
+ /**
223
+ * 导出。
224
+ * spec = {
225
+ * schemaVersion,
226
+ * transaction?(db, fn), // 需要整体快照时提供(tasks 用)
227
+ * extras?(ctx), // 在表字段之前追加的标量字段
228
+ * tables: [{ table, key, where?, orderBy?, read?(ctx), ...导入侧字段 }]
229
+ * }
230
+ */
231
+ export function exportBackup(api, spec) {
232
+ const ctx = { api, db: api.db };
233
+ const read = () => {
234
+ const data = { schemaVersion: spec.schemaVersion };
235
+ if (spec.extras) Object.assign(data, spec.extras(ctx));
236
+ for (const table of spec.tables) {
237
+ data[table.key] = table.read ? table.read(ctx) : readTable(ctx.db, table);
238
+ }
239
+ return data;
240
+ };
241
+ return spec.transaction ? spec.transaction(ctx.db, read) : read();
242
+ }
243
+
244
+ /**
245
+ * 导入。
246
+ * spec.fail(ctx, message, stage) 决定失败回执形状(各域互不相同);
247
+ * spec.success(ctx) 决定成功回执形状。
248
+ * mode="atomic"(tasks/storage):先整体转换,再在一个事务里写入,出错整批回滚;
249
+ * mode="rows"(sites/tags):逐行转换与写入,单行失败只累加 failed。
250
+ */
251
+ export function importBackup(api, raw, options, spec) {
252
+ const ctx = {
253
+ api,
254
+ db: api.db,
255
+ options: options || {},
256
+ policy: normalizePolicy(options),
257
+ data: null,
258
+ imported: 0,
259
+ skipped: 0,
260
+ failed: 0,
261
+ errors: [],
262
+ counts: {},
263
+ changed: [],
264
+ merged: 0,
265
+ alignments: new Map(),
266
+ skippedColumns: [],
267
+ filledColumns: [],
268
+ rejectedRows: [],
269
+ };
270
+ ctx.spec = spec;
271
+ try {
272
+ spec.checkOptions?.(ctx.options);
273
+ ctx.data = (spec.parse || defaultParse)(raw);
274
+ if (!ctx.data || typeof ctx.data !== "object" || Array.isArray(ctx.data)) throw new Error(spec.invalidMessage || "备份内容不是对象");
275
+ spec.validate?.(ctx);
276
+ } catch (error) {
277
+ return spec.fail(ctx, messageOf(error), "validate");
278
+ }
279
+ try {
280
+ spec.prepare?.(ctx);
281
+ if (spec.guard) {
282
+ const early = spec.guard(ctx);
283
+ if (early) return early;
284
+ }
285
+ if (spec.mode === "rows") {
286
+ for (const table of spec.tables) applyRows(ctx, table);
287
+ return finish(ctx, spec);
288
+ }
289
+ let plans;
290
+ try {
291
+ plans = spec.tables.map((table) => planTable(ctx, table));
292
+ spec.beforeTx?.(ctx);
293
+ } catch (error) {
294
+ return spec.fail(ctx, messageOf(error), "validate");
295
+ }
296
+ try {
297
+ const write = () => {
298
+ for (const plan of plans) writePlan(ctx, plan);
299
+ spec.afterWrite?.(ctx);
300
+ };
301
+ if (spec.transaction) spec.transaction(ctx.db, write);
302
+ else write();
303
+ } catch (error) {
304
+ return spec.fail(ctx, messageOf(error), "write", { rolledBack: true });
305
+ }
306
+ return finish(ctx, spec);
307
+ } catch (error) {
308
+ return spec.fail(ctx, messageOf(error), "prepare");
309
+ }
310
+ }
311
+
312
+ function defaultParse(raw) {
313
+ return JSON.parse(String(raw || "{}"));
314
+ }
315
+
316
+ function messageOf(error) {
317
+ return String((error && error.message) || error);
318
+ }
319
+
320
+ /** 读取数据里的表数组,并完成结构校验(调用方未自定义结构错误时使用)。 */
321
+ function rowsOf(ctx, table) {
322
+ const data = ctx.data;
323
+ if (table.skipWhen && table.skipWhen(ctx)) return [];
324
+ let rows = data[table.key];
325
+ if (rows === undefined && table.optional) rows = [];
326
+ if (!Array.isArray(rows)) {
327
+ throw new Error(ctx.spec.structureMessage ? ctx.spec.structureMessage(table.key) : "备份结构不完整:" + table.key);
328
+ }
329
+ return rows;
330
+ }
331
+
332
+ /** 表级对齐计划:同一张表只算一次,并把丢弃/补齐的列记进回执。 */
333
+ function alignmentFor(ctx, table) {
334
+ const cached = ctx.alignments.get(table.table);
335
+ if (cached) return cached;
336
+ const alignment = tableAlignment(ctx.db, table);
337
+ ctx.alignments.set(table.table, alignment);
338
+ for (const column of alignment.skippedColumns) if (!ctx.skippedColumns.includes(column)) ctx.skippedColumns.push(column);
339
+ for (const column of alignment.filledColumns) if (!ctx.filledColumns.includes(column)) ctx.filledColumns.push(column);
340
+ return alignment;
341
+ }
342
+
343
+ /** 单行拒绝:累加 failed 并结构化记录,不中断同批其余行。 */
344
+ function rejectRow(ctx, table, id, reason) {
345
+ ctx.failed += 1;
346
+ ctx.rejectedRows.push({ table: table.table, id: id === undefined || id === null ? "" : String(id), reason });
347
+ if (ctx.errors.length < 5) ctx.errors.push(reason);
348
+ }
349
+
350
+ /** 同表不同列集(本机遗留列)各自一份语句,避免每行重新 prepare。 */
351
+ function statementFor(cache, db, table, columns) {
352
+ const key = columns.join("\u0001");
353
+ let statement = cache.get(key);
354
+ if (!statement) {
355
+ statement = upsertStatement(db, { table, columns });
356
+ cache.set(key, statement);
357
+ }
358
+ return statement;
359
+ }
360
+
361
+ function planTable(ctx, table) {
362
+ const rows = rowsOf(ctx, table);
363
+ const out = [];
364
+ const seen = table.unique ? new Set() : null;
365
+ const idColumn = table.idColumn || table.columns[0];
366
+ if (!rows.length) return { table, rows: out, idColumn, alignment: null };
367
+ const alignment = alignmentFor(ctx, table);
368
+ for (const original of rows) {
369
+ if (table.skipIf && table.skipIf(original, ctx)) {
370
+ ctx.skipped += 1;
371
+ continue;
372
+ }
373
+ if (!original || typeof original !== "object" || Array.isArray(original)) {
374
+ throw new Error(table.rowMessage || "非法备份行:" + table.table);
375
+ }
376
+ const row = table.convert(original, ctx);
377
+ const id = row[alignment.idColumn];
378
+ if (seen) {
379
+ if (seen.has(id)) throw new Error(table.duplicateMessage ? table.duplicateMessage(id) : "备份行 ID 重复:" + table.table + "/" + id);
380
+ seen.add(id);
381
+ }
382
+ out.push({ row, original });
383
+ }
384
+ table.validateRows?.(ctx, out.map((entry) => entry.row));
385
+ return { table, rows: out, idColumn: alignment.idColumn, alignment };
386
+ }
387
+
388
+ function writePlan(ctx, plan) {
389
+ const { table, rows, alignment } = plan;
390
+ // 旧版本没有的表不写、也不出现在 tables 计数里(保持旧回执形状)。
391
+ if (table.skipWhen && table.skipWhen(ctx)) return;
392
+ const counts = (ctx.counts[table.table] = { imported: 0, skipped: 0 });
393
+ if (!rows.length) return;
394
+ const select = ctx.db.prepare("SELECT * FROM " + table.table + " WHERE id=?");
395
+ const statements = new Map();
396
+ for (const entry of rows) {
397
+ const { row, original } = entry;
398
+ const existing = select.get(row[plan.idColumn]);
399
+ table.resolve?.(ctx, row, existing);
400
+ table.conflict?.(existing, row);
401
+ if (table.preWrite && table.preWrite(ctx, row, existing) === "skip") {
402
+ counts.skipped += 1;
403
+ ctx.skipped += 1;
404
+ continue;
405
+ }
406
+ if (shouldSkip(ctx, table, existing, row)) {
407
+ counts.skipped += 1;
408
+ ctx.skipped += 1;
409
+ continue;
410
+ }
411
+ // 列对齐放在 resolve/preWrite 之后:resolve 可能改写 tag_id 等列,必须写最终值。
412
+ const aligned = alignRow(alignment, row, original);
413
+ if (!aligned.ok) {
414
+ rejectRow(ctx, table, row[plan.idColumn], aligned.reason);
415
+ continue;
416
+ }
417
+ statementFor(statements, ctx.db, table.table, aligned.columns).run(...aligned.columns.map((column) => aligned.values[column]));
418
+ counts.imported += 1;
419
+ ctx.imported += 1;
420
+ ctx.changed.push({ table: table.table, row, original, existing, columns: aligned.columns });
421
+ }
422
+ }
423
+
424
+ function applyRows(ctx, table) {
425
+ const rows = rowsOf(ctx, table);
426
+ if (!rows.length) return;
427
+ const enabled = table.enabled ? table.enabled(ctx) : true;
428
+ // 未启用的表(如未安装标签插件时的 tag_mapping)整表跳过,逐行计 skipped 与旧行为一致。
429
+ if (!enabled) {
430
+ ctx.skipped += rows.length;
431
+ return;
432
+ }
433
+ const alignment = alignmentFor(ctx, table);
434
+ const select = ctx.db.prepare("SELECT * FROM " + table.table + " WHERE id=?");
435
+ const statements = new Map();
436
+ const idColumn = alignment.idColumn;
437
+ const seen = table.unique ? new Set() : null;
438
+ for (const original of rows) {
439
+ if (table.skipIf && table.skipIf(original, ctx)) {
440
+ ctx.skipped += 1;
441
+ continue;
442
+ }
443
+ try {
444
+ if (!original || typeof original !== "object" || Array.isArray(original)) {
445
+ throw new Error(table.rowMessage || "非法备份行:" + table.table);
446
+ }
447
+ const row = table.convert(original, ctx);
448
+ const id = row[idColumn];
449
+ if (seen) {
450
+ if (seen.has(id)) throw new Error(table.duplicateMessage ? table.duplicateMessage(id) : "备份行 ID 重复:" + table.table + "/" + id);
451
+ seen.add(id);
452
+ }
453
+ table.resolve?.(ctx, row);
454
+ const existing = select.get(id);
455
+ table.conflict?.(existing, row);
456
+ if (table.preWrite && table.preWrite(ctx, row, existing) === "skip") {
457
+ ctx.skipped += 1;
458
+ continue;
459
+ }
460
+ if (shouldSkip(ctx, table, existing, row)) {
461
+ ctx.skipped += 1;
462
+ continue;
463
+ }
464
+ const aligned = alignRow(alignment, row, original);
465
+ if (!aligned.ok) {
466
+ rejectRow(ctx, table, id, aligned.reason);
467
+ continue;
468
+ }
469
+ statementFor(statements, ctx.db, table.table, aligned.columns).run(...aligned.columns.map((column) => aligned.values[column]));
470
+ ctx.imported += 1;
471
+ } catch (error) {
472
+ ctx.failed += 1;
473
+ if (ctx.errors.length < 5) ctx.errors.push(messageOf(error));
474
+ }
475
+ }
476
+ }
477
+
478
+ /** LWW 跳过:已有行在 skip 下必跳过;newest 下本地更新或同时间戳跳过;任务额外跳过全列相同。 */
479
+ function shouldSkip(ctx, table, existing, row) {
480
+ if (!existing) return false;
481
+ if (ctx.policy === "skip") return true;
482
+ if (table.skipIdentical && table.columns.every((column) => existing[column] === row[column])) return true;
483
+ return ctx.policy === "newest" && Number(existing.updated_at) >= Number(row.updated_at);
484
+ }
485
+
486
+ /** 回执摘要:丢弃列、补齐列、拒绝行都要能在备份页看到,不能静默。 */
487
+ function alignmentSummary(ctx) {
488
+ const parts = [];
489
+ if (ctx.skippedColumns.length) parts.push("已丢弃本机没有的列 " + ctx.skippedColumns.length + " 个:" + preview(ctx.skippedColumns));
490
+ if (ctx.filledColumns.length)
491
+ parts.push("已按本机结构补齐备份缺失列 " + ctx.filledColumns.length + " 个(取本机默认值):" + preview(ctx.filledColumns));
492
+ if (ctx.rejectedRows.length)
493
+ parts.push(
494
+ "拒绝 " +
495
+ ctx.rejectedRows.length +
496
+ " 行类型不兼容数据:" +
497
+ preview(
498
+ ctx.rejectedRows.map(
499
+ (item) => item.table + "/" + item.id + "(" + (item.reason.length > 40 ? item.reason.slice(0, 40) + "…" : item.reason) + ")",
500
+ ),
501
+ ),
502
+ );
503
+ return parts.join(";");
504
+ }
505
+
506
+ function preview(list) {
507
+ const LIMIT = 6;
508
+ return list.length > LIMIT ? list.slice(0, LIMIT).join("、") + " 等 " + list.length + " 项" : list.join("、");
509
+ }
510
+
511
+ function finish(ctx, spec) {
512
+ if (ctx.imported > 0 && spec.emit) spec.emit(ctx.api, ctx);
513
+ const receipt = spec.success(ctx);
514
+ receipt.skippedColumns = ctx.skippedColumns.slice();
515
+ receipt.filledColumns = ctx.filledColumns.slice();
516
+ receipt.rejectedRows = ctx.rejectedRows.slice();
517
+ const summary = alignmentSummary(ctx);
518
+ if (summary) receipt.message = receipt.message ? receipt.message + ";" + summary : summary;
519
+ return receipt;
520
+ }
521
+
@@ -0,0 +1,51 @@
1
+ /**
2
+ * 跨插件共享的 LWW 合并骨架:tasks 与 sites 的整表同步都按 updated_at 取最新一版。
3
+ *
4
+ * 两个域的差异只有增强项,统一用 hooks 注入,骨架本身不感知业务字段:
5
+ * - hooks.missingColumn(row, localRow):远端行胜出时的缺列保护。旧端省略某列(如 description)
6
+ * 时用本地值补回,避免升级后新列被整列覆盖成空;只有远端胜出才需要处理。
7
+ * - hooks.normalizeRow(row):合并完成后逐行归一(补默认值、统一类型),返回新行对象。
8
+ * - hooks.checkSiblingConflicts(liveRows):存活行的同级同名冲突检测;抛错即阻断本次收敛,
9
+ * 调用方保证传入的行对象不会被改写,失败后可直接重试。
10
+ *
11
+ * 约定:胜负只看 updated_at,时间戳相等时远端胜出(与历史实现一致);合并不修改入参行,
12
+ * 也不写数据库,调用方负责落库与推送。
13
+ */
14
+
15
+ /** 行是否存活(没有软删墓碑)。墓碑仍参与 stableTs 与合并,只是不参与冲突检测。 */
16
+ export function isLiveRow(row) {
17
+ return !!row && (row.deleted_at === null || row.deleted_at === undefined);
18
+ }
19
+
20
+ /** 合并基准时间戳:所有行(含墓碑)updated_at 的最大值,缺失按 0 计。 */
21
+ export function stableTs(rows) {
22
+ let max = 0;
23
+ for (const row of rows) max = Math.max(max, Number(row.updated_at) || 0);
24
+ return max;
25
+ }
26
+
27
+ /**
28
+ * 把远端行按 updated_at 合并进本地行集合。
29
+ * @param {Array<object>} remoteRows 远端快照行。
30
+ * @param {Array<object>} localRows 本地行;同 id 时作为被比较的一方。
31
+ * @param {{ missingColumn?: Function, normalizeRow?: Function, checkSiblingConflicts?: Function }} [hooks]
32
+ * @returns {Array<object>} 合并后的行,顺序为本地先插入、远端新行随后插入。
33
+ */
34
+ export function mergeRows(remoteRows, localRows, hooks = {}) {
35
+ const { missingColumn, normalizeRow, checkSiblingConflicts } = hooks || {};
36
+ const map = new Map();
37
+ for (const row of localRows || []) if (row && row.id) map.set(String(row.id), row);
38
+ for (const row of remoteRows || []) {
39
+ if (!row || !row.id) continue;
40
+ const id = String(row.id);
41
+ const cur = map.get(id);
42
+ // 远端严格更新或时间戳相同才覆盖;时间戳更旧的行直接丢弃,交给 stableTs 判断快照版本。
43
+ if (!cur || (Number(row.updated_at) || 0) >= (Number(cur.updated_at) || 0)) {
44
+ map.set(id, missingColumn ? missingColumn(row, cur) : row);
45
+ }
46
+ }
47
+ let merged = [...map.values()];
48
+ if (normalizeRow) merged = merged.map((row) => normalizeRow(row));
49
+ if (checkSiblingConflicts) checkSiblingConflicts(merged.filter(isLiveRow));
50
+ return merged;
51
+ }