@nelsonlongxiang/dsh-prompt-templates 0.4.4 → 0.13.2
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/README.md +113 -62
- package/README_zh.md +112 -62
- package/cordis.patch.yml +4 -0
- package/lib/cli/app.js +169 -0
- package/lib/cli/database.js +162 -0
- package/lib/cli/main.js +6 -0
- package/lib/cli/model.js +247 -0
- package/lib/client/Library.js +290 -0
- package/lib/client/Panel.js +37 -201
- package/lib/client/PanelButton.js +27 -3
- package/lib/client/PromptTab.js +11 -0
- package/lib/client/api.js +16 -0
- package/lib/client/filter.js +27 -0
- package/lib/client/index.js +53 -36
- package/lib/client/locales.js +34 -2
- package/lib/client/meta.js +10 -0
- package/lib/client/service.js +57 -37
- package/lib/client/slots.js +5 -3
- package/lib/client/store.js +12 -1
- package/lib/client/tab.js +32 -0
- package/lib/client.js +798 -286
- package/lib/client.js.map +1 -1
- package/lib/index.js +35 -16
- package/lib/inject.js +236 -0
- package/lib/invariant.js +1 -1
- package/lib/store.js +108 -32
- package/lib/types/cli/app.d.ts +1 -0
- package/lib/types/cli/database.d.ts +69 -0
- package/lib/types/cli/main.d.ts +2 -0
- package/lib/types/cli/model.d.ts +62 -0
- package/lib/types/client/Library.d.ts +34 -0
- package/lib/types/client/Panel.d.ts +1 -1
- package/lib/types/client/PanelButton.d.ts +10 -9
- package/lib/types/client/PromptTab.d.ts +17 -0
- package/lib/types/client/api.d.ts +11 -1
- package/lib/types/client/filter.d.ts +10 -0
- package/lib/types/client/index.d.ts +6 -2
- package/lib/types/client/locales.d.ts +34 -2
- package/lib/types/client/meta.d.ts +6 -0
- package/lib/types/client/service.d.ts +50 -6
- package/lib/types/client/slots.d.ts +57 -5
- package/lib/types/client/store.d.ts +14 -1
- package/lib/types/client/tab.d.ts +31 -0
- package/lib/types/index.d.ts +8 -1
- package/lib/types/inject.d.ts +150 -0
- package/lib/types/store.d.ts +27 -4
- package/lib/types/types.d.ts +49 -0
- package/lib/types/variables.d.ts +24 -0
- package/lib/variables.js +36 -0
- package/package.json +98 -105
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { existsSync, mkdirSync, realpathSync } from 'node:fs';
|
|
3
|
+
import { dirname, extname, resolve } from 'node:path';
|
|
4
|
+
import { backup, DatabaseSync } from 'node:sqlite';
|
|
5
|
+
import { createSnapshot, diffSnapshots } from "./model.js";
|
|
6
|
+
/** A valid operation blocked by a safety/business gate (CLI exit 1). */
|
|
7
|
+
export class ImportBlockedError extends Error {
|
|
8
|
+
constructor(message) { super(message); this.name = 'ImportBlockedError'; }
|
|
9
|
+
}
|
|
10
|
+
export function exportDatabase(dbPath, filters = {}) {
|
|
11
|
+
const path = safeDatabasePath(dbPath);
|
|
12
|
+
const db = new DatabaseSync(path, { readOnly: true });
|
|
13
|
+
try {
|
|
14
|
+
db.exec('PRAGMA query_only=ON');
|
|
15
|
+
const version = Number(db.prepare('PRAGMA user_version').get().user_version);
|
|
16
|
+
if (version !== 4)
|
|
17
|
+
throw new Error(`${path} has schema version ${version}, expected 4`);
|
|
18
|
+
const clauses = [];
|
|
19
|
+
const args = [];
|
|
20
|
+
if (filters.scope !== undefined) {
|
|
21
|
+
clauses.push('scope = ?');
|
|
22
|
+
args.push(filters.scope);
|
|
23
|
+
}
|
|
24
|
+
if (filters.sessionId !== undefined) {
|
|
25
|
+
clauses.push('session_id = ?');
|
|
26
|
+
args.push(filters.sessionId);
|
|
27
|
+
}
|
|
28
|
+
const where = clauses.length > 0 ? ` WHERE ${clauses.join(' AND ')}` : '';
|
|
29
|
+
const templateRows = db.prepare(`SELECT id,name,content,scope,session_id,description,position,category,inject_enabled,inject_every,mode,created_at,updated_at FROM templates${where}`).all(...args);
|
|
30
|
+
// SQLite stores the switch as 0/1; the wire view is boolean end to end.
|
|
31
|
+
const templates = templateRows.map(row => ({ ...row, inject_enabled: row.inject_enabled === 1 }));
|
|
32
|
+
const categories = db.prepare(`SELECT name,scope,session_id FROM categories${where}`).all(...args);
|
|
33
|
+
return createSnapshot(categories, templates, { exported_at: new Date().toISOString(), source: path });
|
|
34
|
+
}
|
|
35
|
+
finally {
|
|
36
|
+
db.close();
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Read-only template search for agents. Privacy boundary mirrors the panel:
|
|
41
|
+
* every global template is searchable; session-private rows only when the
|
|
42
|
+
* caller names that session via sessionId. Never searches other sessions.
|
|
43
|
+
*/
|
|
44
|
+
export function searchTemplates(dbPath, options) {
|
|
45
|
+
const snapshot = exportDatabase(dbPath, options.sessionId !== undefined ? {} : { scope: 'global' });
|
|
46
|
+
const needle = (options.query ?? '').trim().toLowerCase();
|
|
47
|
+
let rows = snapshot.templates.filter(row => options.sessionId === undefined
|
|
48
|
+
? row.scope === 'global'
|
|
49
|
+
: (row.scope === 'global' || (row.scope === 'session' && row.session_id === options.sessionId)));
|
|
50
|
+
if (options.category !== undefined)
|
|
51
|
+
rows = rows.filter(row => row.category === options.category);
|
|
52
|
+
if (needle !== '')
|
|
53
|
+
rows = rows.filter(row => row.name.toLowerCase().includes(needle) || row.content.toLowerCase().includes(needle));
|
|
54
|
+
rows = rows.sort((a, b) => a.name.localeCompare(b.name, 'zh-CN'));
|
|
55
|
+
const total = rows.length;
|
|
56
|
+
const scopes = [...new Set(rows.map(row => row.scope))].sort();
|
|
57
|
+
const items = rows.slice(0, options.limit).map(row => ({
|
|
58
|
+
id: row.id, name: row.name, content: row.content, scope: row.scope, category: row.category, updated_at: row.updated_at,
|
|
59
|
+
}));
|
|
60
|
+
return { items, total, limit: options.limit, matched_scopes: scopes };
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* Logical database hash: the canonical schema/categories/templates snapshot,
|
|
64
|
+
* not raw file bytes. This works against a live WAL database on Windows
|
|
65
|
+
* (where the main file may be locked and WAL pages are not in its byte hash)
|
|
66
|
+
* and binds exactly the business data an import may replace.
|
|
67
|
+
*/
|
|
68
|
+
export function databaseSha256(dbPath) {
|
|
69
|
+
return exportDatabase(dbPath).data_sha256;
|
|
70
|
+
}
|
|
71
|
+
export function planImport(dbPath, incoming) {
|
|
72
|
+
const current = exportDatabase(dbPath);
|
|
73
|
+
const diff = diffSnapshots(current, incoming);
|
|
74
|
+
const templateInserts = diff.templates.only_right.length;
|
|
75
|
+
const templateUpdates = diff.templates.changed.length;
|
|
76
|
+
const categoryInserts = diff.categories.only_right.length;
|
|
77
|
+
const changes = templateInserts + templateUpdates + categoryInserts;
|
|
78
|
+
const raw = JSON.stringify({ changes, templateInserts, templateUpdates, categoryInserts, data_sha256: incoming.data_sha256 });
|
|
79
|
+
return {
|
|
80
|
+
changes,
|
|
81
|
+
template_inserts: templateInserts,
|
|
82
|
+
template_updates: templateUpdates,
|
|
83
|
+
category_inserts: categoryInserts,
|
|
84
|
+
name_conflicts: diff.templates.name_conflicts,
|
|
85
|
+
summary_sha256: createHash('sha256').update(raw).digest('hex'),
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
export async function importDatabase(dbPath, incoming, options) {
|
|
89
|
+
const path = safeDatabasePath(dbPath);
|
|
90
|
+
const plan = planImport(path, incoming);
|
|
91
|
+
if (plan.name_conflicts.length > 0)
|
|
92
|
+
throw new ImportBlockedError('import blocked by same-name/different-id conflicts');
|
|
93
|
+
if (plan.changes > options.maxChanges)
|
|
94
|
+
throw new ImportBlockedError(`import has ${plan.changes} changes, exceeding --max-changes ${options.maxChanges}`);
|
|
95
|
+
if (!options.apply)
|
|
96
|
+
return { applied: false, plan };
|
|
97
|
+
if (options.expectedDbSha256 === undefined)
|
|
98
|
+
throw new Error('--apply requires --expect-db-sha256');
|
|
99
|
+
if (options.confirmedSummarySha256 === undefined)
|
|
100
|
+
throw new Error('--apply requires --confirm-summary-hash from the reviewed dry-run');
|
|
101
|
+
if (options.confirmedSummarySha256.toLowerCase() !== plan.summary_sha256.toLowerCase())
|
|
102
|
+
throw new ImportBlockedError(`dry-run summary changed (expected ${options.confirmedSummarySha256}, actual ${plan.summary_sha256})`);
|
|
103
|
+
const actualHash = databaseSha256(path);
|
|
104
|
+
if (actualHash.toLowerCase() !== options.expectedDbSha256.toLowerCase())
|
|
105
|
+
throw new ImportBlockedError(`database sha256 changed (expected ${options.expectedDbSha256}, actual ${actualHash})`);
|
|
106
|
+
const db = new DatabaseSync(path);
|
|
107
|
+
let backupPath;
|
|
108
|
+
try {
|
|
109
|
+
db.exec(`PRAGMA busy_timeout=${options.busyTimeoutMs ?? 5000}`);
|
|
110
|
+
const version = Number(db.prepare('PRAGMA user_version').get().user_version);
|
|
111
|
+
if (version !== 4)
|
|
112
|
+
throw new Error(`${path} has schema version ${version}, expected 4`);
|
|
113
|
+
backupPath = resolve(options.backupOut ?? `${path}.${timestampName()}.bak`);
|
|
114
|
+
mkdirSync(dirname(backupPath), { recursive: true });
|
|
115
|
+
await backup(db, backupPath);
|
|
116
|
+
db.exec('BEGIN IMMEDIATE');
|
|
117
|
+
try {
|
|
118
|
+
// SQLite treats NULL values as distinct for uniqueness, including the
|
|
119
|
+
// legacy composite PRIMARY KEY (scope, session_id, name). Therefore
|
|
120
|
+
// INSERT OR IGNORE does NOT deduplicate global categories whose
|
|
121
|
+
// session_id is NULL. Mirror the store's semantic key explicitly with
|
|
122
|
+
// `IS ?` before inserting; this keeps zero-change apply idempotent.
|
|
123
|
+
const findCategory = db.prepare('SELECT 1 FROM categories WHERE scope = ? AND session_id IS ? AND name = ? LIMIT 1');
|
|
124
|
+
const insertCategory = db.prepare('INSERT INTO categories (name,scope,session_id) VALUES (?,?,?)');
|
|
125
|
+
for (const item of incoming.categories) {
|
|
126
|
+
if (findCategory.get(item.scope, item.session_id, item.name) === undefined) {
|
|
127
|
+
insertCategory.run(item.name, item.scope, item.session_id);
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
const upsertTemplate = db.prepare(`INSERT INTO templates
|
|
131
|
+
(id,name,content,scope,session_id,description,position,category,inject_enabled,inject_every,mode,created_at,updated_at)
|
|
132
|
+
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)
|
|
133
|
+
ON CONFLICT(id) DO UPDATE SET name=excluded.name,content=excluded.content,scope=excluded.scope,
|
|
134
|
+
session_id=excluded.session_id,description=excluded.description,position=excluded.position,
|
|
135
|
+
category=excluded.category,inject_enabled=excluded.inject_enabled,inject_every=excluded.inject_every,
|
|
136
|
+
mode=excluded.mode,created_at=excluded.created_at,updated_at=excluded.updated_at`);
|
|
137
|
+
for (const item of incoming.templates)
|
|
138
|
+
upsertTemplate.run(item.id, item.name, item.content, item.scope, item.session_id, item.description, item.position, item.category, item.inject_enabled ? 1 : 0, item.inject_every ?? null, item.mode, item.created_at, item.updated_at);
|
|
139
|
+
db.exec('COMMIT');
|
|
140
|
+
}
|
|
141
|
+
catch (error) {
|
|
142
|
+
db.exec('ROLLBACK');
|
|
143
|
+
throw error;
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
finally {
|
|
147
|
+
db.close();
|
|
148
|
+
}
|
|
149
|
+
return { applied: true, backup: backupPath, plan };
|
|
150
|
+
}
|
|
151
|
+
function safeDatabasePath(input) {
|
|
152
|
+
const absolute = resolve(input);
|
|
153
|
+
if (!existsSync(absolute))
|
|
154
|
+
throw new Error(`database not found: ${absolute}`);
|
|
155
|
+
if (extname(absolute).toLowerCase() !== '.sqlite3' && extname(absolute).toLowerCase() !== '.db')
|
|
156
|
+
throw new Error(`database path must end with .sqlite3 or .db: ${absolute}`);
|
|
157
|
+
const real = realpathSync(absolute);
|
|
158
|
+
if (real !== absolute)
|
|
159
|
+
throw new Error(`symbolic-link database paths are not allowed: ${absolute}`);
|
|
160
|
+
return real;
|
|
161
|
+
}
|
|
162
|
+
function timestampName() { return new Date().toISOString().replaceAll(':', '').replaceAll('.', '').replace('Z', 'Z'); }
|
package/lib/cli/main.js
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/** Package-bin entrypoint. Keep this wrapper unconditional: npm/pnpm may
|
|
3
|
+
* launch it through a symlink or platform shim whose argv[1] differs from the
|
|
4
|
+
* real module path. The reusable/testable command logic lives in app.ts. */
|
|
5
|
+
import { run } from "./app.js";
|
|
6
|
+
process.exitCode = await run(process.argv.slice(2));
|
package/lib/cli/model.js
ADDED
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { DEFAULT_INJECT_MAX_EVERY } from "../store.js";
|
|
3
|
+
export const SNAPSHOT_SCHEMA_VERSION = 4;
|
|
4
|
+
/** Schema 2 (pre-auto-inject) and 3 (pre-mode) snapshots still import; missing facts default. */
|
|
5
|
+
const SUPPORTED_SCHEMA_VERSIONS = [2, 3, 4];
|
|
6
|
+
const TEMPLATE_KEYS = ['id', 'name', 'content', 'scope', 'session_id', 'description', 'position', 'category', 'inject_enabled', 'inject_every', 'mode', 'created_at', 'updated_at'];
|
|
7
|
+
/** Key set of schema-3 template records (no delivery mode). */
|
|
8
|
+
const TEMPLATE_KEYS_V3 = TEMPLATE_KEYS.filter(key => key !== 'mode');
|
|
9
|
+
/** Key set of schema-2 template records (no auto-inject facts). */
|
|
10
|
+
const TEMPLATE_KEYS_V2 = TEMPLATE_KEYS_V3.filter(key => key !== 'inject_enabled' && key !== 'inject_every');
|
|
11
|
+
const CATEGORY_KEYS = ['name', 'scope', 'session_id'];
|
|
12
|
+
export function parseSnapshot(value) {
|
|
13
|
+
const root = object(value, 'snapshot');
|
|
14
|
+
exactKeys(root, ['schema_version', 'categories', 'templates', 'data_sha256', 'exported_at', 'source'], 'snapshot');
|
|
15
|
+
if (!SUPPORTED_SCHEMA_VERSIONS.includes(root.schema_version))
|
|
16
|
+
throw new Error(`unsupported schema_version ${String(root.schema_version)} (expected 2, 3 or 4)`);
|
|
17
|
+
const version = root.schema_version;
|
|
18
|
+
if (!Array.isArray(root.categories) || !Array.isArray(root.templates))
|
|
19
|
+
throw new Error('categories and templates must be arrays');
|
|
20
|
+
const categories = root.categories.map((entry, index) => parseCategory(entry, `categories[${index}]`));
|
|
21
|
+
const templates = root.templates.map((entry, index) => parseTemplate(entry, `templates[${index}]`, version));
|
|
22
|
+
const canonical = canonicalData(categories, templates);
|
|
23
|
+
if (typeof root.data_sha256 !== 'string')
|
|
24
|
+
throw new Error('data_sha256 must be a string');
|
|
25
|
+
const expected = dataHash(canonical);
|
|
26
|
+
if (root.data_sha256 !== expected)
|
|
27
|
+
throw new Error(`data_sha256 mismatch (expected ${expected})`);
|
|
28
|
+
return {
|
|
29
|
+
...canonical,
|
|
30
|
+
data_sha256: expected,
|
|
31
|
+
...(typeof root.exported_at === 'string' ? { exported_at: root.exported_at } : {}),
|
|
32
|
+
...(typeof root.source === 'string' ? { source: root.source } : {}),
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
export function createSnapshot(categories, templates, metadata = {}) {
|
|
36
|
+
const canonical = canonicalData(categories, templates);
|
|
37
|
+
return { ...canonical, data_sha256: dataHash(canonical), ...metadata };
|
|
38
|
+
}
|
|
39
|
+
export function canonicalJson(snapshot) {
|
|
40
|
+
return `${JSON.stringify(snapshot, null, 2)}\n`;
|
|
41
|
+
}
|
|
42
|
+
export function diffSnapshots(left, right) {
|
|
43
|
+
const leftById = new Map(left.templates.map(item => [item.id, item]));
|
|
44
|
+
const rightById = new Map(right.templates.map(item => [item.id, item]));
|
|
45
|
+
const onlyLeft = left.templates.filter(item => !rightById.has(item.id));
|
|
46
|
+
const onlyRight = right.templates.filter(item => !leftById.has(item.id));
|
|
47
|
+
const changed = [];
|
|
48
|
+
for (const [id, l] of leftById) {
|
|
49
|
+
const r = rightById.get(id);
|
|
50
|
+
if (r === undefined)
|
|
51
|
+
continue;
|
|
52
|
+
const fields = TEMPLATE_KEYS.filter(key => l[key] !== r[key]);
|
|
53
|
+
if (fields.length > 0)
|
|
54
|
+
changed.push({ id, name: l.name, fields: [...fields], left: l, right: r });
|
|
55
|
+
}
|
|
56
|
+
const leftNames = idsByName(left.templates);
|
|
57
|
+
const rightNames = idsByName(right.templates);
|
|
58
|
+
const nameConflicts = [];
|
|
59
|
+
for (const name of new Set([...leftNames.keys(), ...rightNames.keys()])) {
|
|
60
|
+
const a = leftNames.get(name) ?? [];
|
|
61
|
+
const b = rightNames.get(name) ?? [];
|
|
62
|
+
if (a.length > 0 && b.length > 0 && a.join('\0') !== b.join('\0'))
|
|
63
|
+
nameConflicts.push({ name, left_ids: a, right_ids: b });
|
|
64
|
+
}
|
|
65
|
+
const leftCategoryKeys = new Set(left.categories.map(categoryKey));
|
|
66
|
+
const rightCategoryKeys = new Set(right.categories.map(categoryKey));
|
|
67
|
+
const categoryOnlyLeft = left.categories.filter(item => !rightCategoryKeys.has(categoryKey(item)));
|
|
68
|
+
const categoryOnlyRight = right.categories.filter(item => !leftCategoryKeys.has(categoryKey(item)));
|
|
69
|
+
const identical = onlyLeft.length === 0 && onlyRight.length === 0 && changed.length === 0 && categoryOnlyLeft.length === 0 && categoryOnlyRight.length === 0;
|
|
70
|
+
return {
|
|
71
|
+
identical,
|
|
72
|
+
templates: { left: left.templates.length, right: right.templates.length, only_left: onlyLeft, only_right: onlyRight, changed, name_conflicts: nameConflicts },
|
|
73
|
+
categories: { left: left.categories.length, right: right.categories.length, only_left: categoryOnlyLeft, only_right: categoryOnlyRight },
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
export function mergeSnapshots(base, incoming, strategy, allowNameConflicts = false) {
|
|
77
|
+
const conflicts = [];
|
|
78
|
+
const selected = new Map(base.templates.map(item => [item.id, item]));
|
|
79
|
+
let inserted = 0;
|
|
80
|
+
let incomingSelected = 0;
|
|
81
|
+
let baseSelected = 0;
|
|
82
|
+
for (const item of incoming.templates) {
|
|
83
|
+
const current = selected.get(item.id);
|
|
84
|
+
if (current === undefined) {
|
|
85
|
+
selected.set(item.id, item);
|
|
86
|
+
inserted++;
|
|
87
|
+
continue;
|
|
88
|
+
}
|
|
89
|
+
if (sameTemplate(current, item))
|
|
90
|
+
continue;
|
|
91
|
+
if (strategy === 'keep-base') {
|
|
92
|
+
baseSelected++;
|
|
93
|
+
continue;
|
|
94
|
+
}
|
|
95
|
+
if (strategy === 'keep-incoming') {
|
|
96
|
+
selected.set(item.id, item);
|
|
97
|
+
incomingSelected++;
|
|
98
|
+
continue;
|
|
99
|
+
}
|
|
100
|
+
const leftTime = timestamp(current.updated_at);
|
|
101
|
+
const rightTime = timestamp(item.updated_at);
|
|
102
|
+
if (leftTime === null || rightTime === null) {
|
|
103
|
+
conflicts.push({ kind: 'invalid-timestamp', message: `template ${item.id} has an invalid updated_at`, ids: [item.id] });
|
|
104
|
+
}
|
|
105
|
+
else if (leftTime === rightTime) {
|
|
106
|
+
conflicts.push({ kind: 'same-time-different-content', message: `template ${item.id} differs at the same updated_at`, ids: [item.id] });
|
|
107
|
+
}
|
|
108
|
+
else if (rightTime > leftTime) {
|
|
109
|
+
selected.set(item.id, item);
|
|
110
|
+
incomingSelected++;
|
|
111
|
+
}
|
|
112
|
+
else
|
|
113
|
+
baseSelected++;
|
|
114
|
+
}
|
|
115
|
+
const mergedTemplates = [...selected.values()];
|
|
116
|
+
// Historical same-name rows already present in both snapshots are not a
|
|
117
|
+
// new merge conflict (session-scoped templates may legitimately share a
|
|
118
|
+
// label). Block only when the two inputs disagree on that name's ID set.
|
|
119
|
+
if (!allowNameConflicts) {
|
|
120
|
+
for (const conflict of diffSnapshots(base, incoming).templates.name_conflicts) {
|
|
121
|
+
conflicts.push({
|
|
122
|
+
kind: 'same-name-different-id',
|
|
123
|
+
message: `template name ${JSON.stringify(conflict.name)} resolves to different ids across inputs`,
|
|
124
|
+
ids: [...new Set([...conflict.left_ids, ...conflict.right_ids])].sort(),
|
|
125
|
+
});
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
const categories = new Map();
|
|
129
|
+
for (const item of [...base.categories, ...incoming.categories])
|
|
130
|
+
categories.set(categoryKey(item), item);
|
|
131
|
+
const summary = { templates: mergedTemplates.length, categories: categories.size, inserted, incoming_selected: incomingSelected, base_selected: baseSelected };
|
|
132
|
+
if (conflicts.length > 0)
|
|
133
|
+
return { conflicts, summary };
|
|
134
|
+
return { snapshot: createSnapshot([...categories.values()], mergedTemplates, { source: `merge:${strategy}` }), conflicts, summary };
|
|
135
|
+
}
|
|
136
|
+
function canonicalData(categories, templates) {
|
|
137
|
+
const sortedCategories = categories.map(item => ({ ...item })).sort((a, b) => categoryKey(a).localeCompare(categoryKey(b)));
|
|
138
|
+
const sortedTemplates = templates.map(item => ({ ...item })).sort((a, b) => a.id.localeCompare(b.id));
|
|
139
|
+
return { schema_version: SNAPSHOT_SCHEMA_VERSION, categories: sortedCategories, templates: sortedTemplates };
|
|
140
|
+
}
|
|
141
|
+
function dataHash(data) {
|
|
142
|
+
return createHash('sha256').update(JSON.stringify(data)).digest('hex');
|
|
143
|
+
}
|
|
144
|
+
function parseCategory(value, label) {
|
|
145
|
+
const item = object(value, label);
|
|
146
|
+
exactKeys(item, CATEGORY_KEYS, label);
|
|
147
|
+
const name = nonEmpty(item.name, `${label}.name`);
|
|
148
|
+
const scope = parseScope(item.scope, `${label}.scope`);
|
|
149
|
+
const sessionId = nullableString(item.session_id, `${label}.session_id`);
|
|
150
|
+
scopeSession(scope, sessionId, label);
|
|
151
|
+
return { name, scope, session_id: sessionId };
|
|
152
|
+
}
|
|
153
|
+
function parseTemplate(value, label, version) {
|
|
154
|
+
const item = object(value, label);
|
|
155
|
+
exactKeys(item, version === 2 ? TEMPLATE_KEYS_V2 : version === 3 ? TEMPLATE_KEYS_V3 : TEMPLATE_KEYS, label);
|
|
156
|
+
const scope = parseScope(item.scope, `${label}.scope`);
|
|
157
|
+
const sessionId = nullableString(item.session_id, `${label}.session_id`);
|
|
158
|
+
scopeSession(scope, sessionId, label);
|
|
159
|
+
if (!Number.isInteger(item.position) || Number(item.position) < 0)
|
|
160
|
+
throw new Error(`${label}.position must be a non-negative integer`);
|
|
161
|
+
const inject_enabled = version >= 3 ? booleanField(item.inject_enabled, `${label}.inject_enabled`) : false;
|
|
162
|
+
const inject_every = version >= 3 ? nullablePositiveInteger(item.inject_every, `${label}.inject_every`) : null;
|
|
163
|
+
const mode = version === 4 ? parseMode(item.mode, `${label}.mode`) : 'inject';
|
|
164
|
+
return {
|
|
165
|
+
id: nonEmpty(item.id, `${label}.id`),
|
|
166
|
+
name: nonEmpty(item.name, `${label}.name`),
|
|
167
|
+
content: nonEmpty(item.content, `${label}.content`),
|
|
168
|
+
scope,
|
|
169
|
+
session_id: sessionId,
|
|
170
|
+
description: nullableString(item.description, `${label}.description`),
|
|
171
|
+
position: Number(item.position),
|
|
172
|
+
category: nullableString(item.category, `${label}.category`),
|
|
173
|
+
inject_enabled,
|
|
174
|
+
inject_every,
|
|
175
|
+
mode,
|
|
176
|
+
created_at: nonEmpty(item.created_at, `${label}.created_at`),
|
|
177
|
+
updated_at: nonEmpty(item.updated_at, `${label}.updated_at`),
|
|
178
|
+
};
|
|
179
|
+
}
|
|
180
|
+
function parseMode(value, label) {
|
|
181
|
+
if (value !== 'inject' && value !== 'visible')
|
|
182
|
+
throw new Error(`${label}.mode must be inject or visible`);
|
|
183
|
+
return value;
|
|
184
|
+
}
|
|
185
|
+
function object(value, label) {
|
|
186
|
+
if (typeof value !== 'object' || value === null || Array.isArray(value))
|
|
187
|
+
throw new Error(`${label} must be an object`);
|
|
188
|
+
return value;
|
|
189
|
+
}
|
|
190
|
+
function exactKeys(value, allowed, label) {
|
|
191
|
+
const extras = Object.keys(value).filter(key => !allowed.includes(key));
|
|
192
|
+
if (extras.length > 0)
|
|
193
|
+
throw new Error(`${label} has unknown fields: ${extras.join(', ')}`);
|
|
194
|
+
}
|
|
195
|
+
function nonEmpty(value, label) {
|
|
196
|
+
if (typeof value !== 'string' || value.length === 0)
|
|
197
|
+
throw new Error(`${label} must be a non-empty string`);
|
|
198
|
+
return value;
|
|
199
|
+
}
|
|
200
|
+
function nullableString(value, label) {
|
|
201
|
+
if (value === null)
|
|
202
|
+
return null;
|
|
203
|
+
if (typeof value !== 'string')
|
|
204
|
+
throw new Error(`${label} must be a string or null`);
|
|
205
|
+
return value;
|
|
206
|
+
}
|
|
207
|
+
function booleanField(value, label) {
|
|
208
|
+
if (typeof value !== 'boolean')
|
|
209
|
+
throw new Error(`${label} must be a boolean`);
|
|
210
|
+
return value;
|
|
211
|
+
}
|
|
212
|
+
function nullablePositiveInteger(value, label) {
|
|
213
|
+
if (value === null)
|
|
214
|
+
return null;
|
|
215
|
+
if (typeof value !== 'number' || !Number.isInteger(value) || value < 1)
|
|
216
|
+
throw new Error(`${label} must be a positive integer or null`);
|
|
217
|
+
// Snapshots interchange under the default interval bound: an out-of-range N
|
|
218
|
+
// imported offline would poison later store patches that fall back to the
|
|
219
|
+
// stored value. Deployments with a larger injectMaxEvery export/import via
|
|
220
|
+
// that deployment's own store, not through the snapshot bound.
|
|
221
|
+
if (value > DEFAULT_INJECT_MAX_EVERY)
|
|
222
|
+
throw new Error(`${label} must be at most ${DEFAULT_INJECT_MAX_EVERY}`);
|
|
223
|
+
return value;
|
|
224
|
+
}
|
|
225
|
+
function parseScope(value, label) {
|
|
226
|
+
if (value !== 'global' && value !== 'session')
|
|
227
|
+
throw new Error(`${label} must be global or session`);
|
|
228
|
+
return value;
|
|
229
|
+
}
|
|
230
|
+
function scopeSession(scope, sessionId, label) {
|
|
231
|
+
if (scope === 'global' && sessionId !== null)
|
|
232
|
+
throw new Error(`${label}: global scope must have null session_id`);
|
|
233
|
+
if (scope === 'session' && (sessionId === null || sessionId === ''))
|
|
234
|
+
throw new Error(`${label}: session scope requires session_id`);
|
|
235
|
+
}
|
|
236
|
+
function categoryKey(item) { return `${item.scope}\0${item.session_id ?? ''}\0${item.name}`; }
|
|
237
|
+
function idsByName(items) {
|
|
238
|
+
const map = new Map();
|
|
239
|
+
for (const item of items)
|
|
240
|
+
map.set(item.name, [...map.get(item.name) ?? [], item.id].sort());
|
|
241
|
+
return map;
|
|
242
|
+
}
|
|
243
|
+
function sameTemplate(left, right) { return TEMPLATE_KEYS.every(key => left[key] === right[key]); }
|
|
244
|
+
function timestamp(value) {
|
|
245
|
+
const parsed = Date.parse(value.includes('T') ? value : `${value.replace(' ', 'T')}Z`);
|
|
246
|
+
return Number.isFinite(parsed) ? parsed : null;
|
|
247
|
+
}
|