-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathdb.js
More file actions
521 lines (457 loc) · 18.6 KB
/
Copy pathdb.js
File metadata and controls
521 lines (457 loc) · 18.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
(function (global) {
const Domain = global.AISummaryDomain || (typeof require === 'function' ? require('./shared/domain.js') : null);
const SummaryText = global.AISummarySummaryText || (typeof require === 'function' ? require('./shared/summary-text.js') : null);
const DB_NAME = 'aiSummaryDB';
const DB_VERSION = 2;
const LEGACY_STORE = 'history';
const RECORD_STORE = 'summaryRecords';
function toPromise(request) {
return new Promise((resolve, reject) => {
request.onsuccess = () => resolve(request.result);
request.onerror = () => reject(request.error);
});
}
const markdownToPlainText = SummaryText?.markdownToPlainText || function markdownToPlainTextFallback(markdown) {
return String(markdown || '')
.replace(/```[\s\S]*?```/g, ' ')
.replace(/`([^`]+)`/g, '$1')
.replace(/!\[[^\]]*\]\([^)]*\)/g, ' ')
.replace(/\[([^\]]+)\]\([^)]*\)/g, '$1')
.replace(/^[>#\-*+\d.\s]+/gm, '')
.replace(/\n{2,}/g, '\n')
.replace(/\s+/g, ' ')
.trim();
};
function buildDedupeKey(record) {
const seed = [
record.articleId || record.normalizedUrl || record.sourceUrl || '',
record.summaryMode || 'medium',
record.targetLanguage || 'auto',
record.promptProfile || 'primary',
record.parentRecordId || '',
record.originSummaryHash || ''
].join('|');
return Domain.createDeterministicId('dedupe', seed);
}
function normalizeArray(value) {
return Array.isArray(value) ? value : [];
}
function getRecordSiteHost(record) {
return String(record?.sourceHost || record?.articleSnapshot?.sourceHost || '').trim() || '未知来源';
}
function shouldPersistRecord(record) {
const allowHistory = record?.allowHistory !== false;
const retentionHint = String(record?.retentionHint || '').toLowerCase();
if (!allowHistory) return false;
if (retentionHint === 'session_only' || retentionHint === 'none') return false;
return true;
}
function buildSiteBuckets(records) {
const groups = new Map();
(records || []).forEach((record) => {
const host = getRecordSiteHost(record);
const existing = groups.get(host) || {
host,
count: 0,
favoriteCount: 0,
latestUpdatedAt: '',
sourceTypes: new Set()
};
existing.count += 1;
if (record?.favorite) existing.favoriteCount += 1;
const updatedAt = String(record?.updatedAt || record?.createdAt || '');
if (!existing.latestUpdatedAt || updatedAt > existing.latestUpdatedAt) {
existing.latestUpdatedAt = updatedAt;
}
const sourceType = String(record?.articleSnapshot?.sourceType || 'unknown');
if (sourceType) existing.sourceTypes.add(sourceType);
groups.set(host, existing);
});
return Array.from(groups.values())
.map((bucket) => ({
host: bucket.host,
count: bucket.count,
favoriteCount: bucket.favoriteCount,
latestUpdatedAt: bucket.latestUpdatedAt,
sourceTypes: Array.from(bucket.sourceTypes)
}))
.sort((a, b) => {
if (b.count !== a.count) return b.count - a.count;
if (b.latestUpdatedAt !== a.latestUpdatedAt) return String(b.latestUpdatedAt).localeCompare(String(a.latestUpdatedAt));
return String(a.host).localeCompare(String(b.host));
});
}
function filterRecordsBySite(records, selectedSiteHost) {
const siteHost = String(selectedSiteHost || '').trim();
if (!siteHost) return Array.isArray(records) ? records.slice() : [];
return (records || []).filter((record) => getRecordSiteHost(record) === siteHost);
}
function groupRecordsBySite(records) {
const buckets = buildSiteBuckets(records);
return buckets.map((bucket) => ({
host: bucket.host,
count: bucket.count,
favoriteCount: bucket.favoriteCount,
latestUpdatedAt: bucket.latestUpdatedAt,
sourceTypes: bucket.sourceTypes,
records: filterRecordsBySite(records, bucket.host)
}));
}
function getRecordTimestamp(record) {
return new Date(record?.updatedAt || record?.completedAt || record?.createdAt || 0).getTime();
}
function isReusablePrimaryRecord(record) {
const promptProfile = String(record?.promptProfile || 'primary').toLowerCase();
const status = String(record?.status || 'completed').toLowerCase();
const summaryMarkdown = String(record?.summaryMarkdown || '').trim();
if (!summaryMarkdown) return false;
if (status !== 'completed') return false;
if (record?.parentRecordId) return false;
return promptProfile === 'primary' || promptProfile === 'legacy';
}
function getReusableRecordMatch(record, article) {
if (!record || !article || !isReusablePrimaryRecord(record)) return null;
const articleId = String(article?.articleId || '').trim();
const normalizedUrl = Domain.normalizeUrl(article?.normalizedUrl || article?.canonicalUrl || article?.sourceUrl || '');
const sourceUrl = Domain.normalizeUrl(article?.sourceUrl || '');
const recordArticleId = String(record?.articleId || record?.articleSnapshot?.articleId || '').trim();
const recordNormalizedUrl = Domain.normalizeUrl(
record?.normalizedUrl || record?.articleSnapshot?.normalizedUrl || record?.sourceUrl || record?.articleSnapshot?.sourceUrl || ''
);
const recordSourceUrl = Domain.normalizeUrl(record?.sourceUrl || record?.articleSnapshot?.sourceUrl || '');
if (articleId && recordArticleId && articleId === recordArticleId) {
return { score: 3, matchType: 'articleId' };
}
if (normalizedUrl && recordNormalizedUrl && normalizedUrl === recordNormalizedUrl) {
return { score: 2, matchType: 'normalizedUrl' };
}
if (sourceUrl && recordSourceUrl && sourceUrl === recordSourceUrl) {
return { score: 1, matchType: 'sourceUrl' };
}
return null;
}
function findBestReusableRecordForArticle(records, article) {
/** @type {any} */
let best = null;
(records || []).forEach((record) => {
const match = getReusableRecordMatch(record, article);
if (!match) return;
const candidate = {
record,
matchType: match.matchType,
score: match.score,
updatedAtMs: getRecordTimestamp(record),
favorite: !!record?.favorite
};
if (!best) {
best = candidate;
return;
}
if (candidate.score !== best.score) {
if (candidate.score > best.score) best = candidate;
return;
}
if (candidate.updatedAtMs !== best.updatedAtMs) {
if (candidate.updatedAtMs > best.updatedAtMs) best = candidate;
return;
}
if (candidate.favorite !== best.favorite) {
if (candidate.favorite) best = candidate;
return;
}
if (String(candidate.record?.recordId || '') < String(best.record?.recordId || '')) {
best = candidate;
}
});
if (!best) return null;
return {
record: best.record,
matchType: best.matchType,
exact: best.score === 3
};
}
function normalizeRecord(input, existing) {
const now = new Date().toISOString();
const base = Object.assign({}, existing || {}, input || {});
const summaryMarkdown = String(base.summaryMarkdown || base.summary || '');
const sourceUrl = String(base.sourceUrl || base.url || '');
const normalizedUrl = base.normalizedUrl || Domain.normalizeUrl(sourceUrl);
const titleSnapshot = base.titleSnapshot || base.title || '未命名页面';
const contentHash = base.contentHash || Domain.hashString(base.articleSnapshot?.cleanText || summaryMarkdown || titleSnapshot);
const articleId = base.articleId || Domain.createDeterministicId('art', (normalizedUrl || sourceUrl || titleSnapshot) + '|' + contentHash);
const recordId = existing?.recordId || base.recordId || Domain.createRuntimeId('sum');
const allowHistory = typeof base.allowHistory === 'boolean' ? base.allowHistory : base.articleSnapshot?.allowHistory !== false;
const allowShare = typeof base.allowShare === 'boolean' ? base.allowShare : base.articleSnapshot?.allowShare !== false;
const retentionHint = base.retentionHint || base.articleSnapshot?.retentionHint || (allowHistory ? 'persistent' : 'session_only');
const record = {
recordId,
articleId,
parentRecordId: base.parentRecordId || '',
runId: base.runId || Domain.createRuntimeId('run'),
createdAt: existing?.createdAt || base.createdAt || now,
updatedAt: now,
sourceUrl,
normalizedUrl,
sourceHost: base.sourceHost || Domain.getSourceHost(normalizedUrl || sourceUrl),
titleSnapshot,
languageSnapshot: base.languageSnapshot || base.articleSnapshot?.language || '',
contentHash,
articleSnapshotRef: base.articleSnapshotRef || '',
articleSnapshot: base.articleSnapshot || existing?.articleSnapshot || null,
summaryMode: base.summaryMode || 'medium',
targetLanguage: base.targetLanguage || 'auto',
promptProfile: base.promptProfile || 'primary',
customPromptUsed: !!base.customPromptUsed,
promptVersion: base.promptVersion || '2026-03-25',
adapterId: base.adapterId || '',
provider: base.provider || '',
model: base.model || '',
endpointMode: base.endpointMode || '',
requestOptionsSnapshot: base.requestOptionsSnapshot || null,
privacyMode: !!base.privacyMode,
allowHistory,
allowShare,
retentionHint,
status: base.status || 'completed',
startedAt: base.startedAt || now,
completedAt: base.completedAt || '',
durationMs: typeof base.durationMs === 'number' ? base.durationMs : 0,
retryCount: typeof base.retryCount === 'number' ? base.retryCount : 0,
errorCode: base.errorCode || '',
errorMessage: base.errorMessage || '',
finishReason: base.finishReason || '',
summaryMarkdown,
summaryPlainText: base.summaryPlainText || markdownToPlainText(summaryMarkdown),
summaryTitle: base.summaryTitle || titleSnapshot,
bullets: normalizeArray(base.bullets),
usage: base.usage || null,
shareCardTitle: base.shareCardTitle || titleSnapshot,
shareCardSubtitle: base.shareCardSubtitle || '',
shareSourceUrl: base.shareSourceUrl || normalizedUrl || sourceUrl,
exportVariants: normalizeArray(base.exportVariants).length ? normalizeArray(base.exportVariants) : ['markdown', 'image'],
pinned: allowHistory ? !!base.pinned : false,
favorite: allowHistory ? (typeof base.favorite === 'boolean' ? base.favorite : !!existing?.favorite) : false,
tags: allowHistory ? normalizeArray(base.tags) : [],
notes: allowHistory ? (base.notes || '') : '',
lastViewedAt: base.lastViewedAt || now,
diagnostics: base.diagnostics || existing?.diagnostics || null,
originSummaryHash: base.originSummaryHash || '',
dedupeKey: base.dedupeKey || ''
};
record.dedupeKey = record.dedupeKey || buildDedupeKey(record);
return record;
}
function migrateLegacyRecord(item) {
const timestamp = item?.timestamp || Date.now();
const iso = new Date(timestamp).toISOString();
const sourceUrl = String(item?.url || '');
const normalizedUrl = Domain.normalizeUrl(sourceUrl);
const summaryMarkdown = String(item?.summary || '');
const contentHash = Domain.hashString(summaryMarkdown || item?.title || sourceUrl || String(timestamp));
const articleId = Domain.createDeterministicId('art', (normalizedUrl || sourceUrl || item?.title || 'legacy') + '|' + contentHash);
return normalizeRecord({
recordId: Domain.createDeterministicId('sum', String(timestamp) + '|' + contentHash),
articleId,
runId: Domain.createDeterministicId('run', 'legacy|' + timestamp),
createdAt: iso,
updatedAt: iso,
sourceUrl,
normalizedUrl,
sourceHost: Domain.getSourceHost(normalizedUrl || sourceUrl),
titleSnapshot: item?.title || '未命名页面',
contentHash,
summaryMode: 'medium',
targetLanguage: 'auto',
promptProfile: 'legacy',
customPromptUsed: false,
promptVersion: 'legacy',
adapterId: 'legacy_import',
provider: 'legacy',
model: '',
endpointMode: '',
privacyMode: false,
allowHistory: true,
allowShare: true,
retentionHint: 'persistent',
status: 'completed',
startedAt: iso,
completedAt: iso,
durationMs: 0,
retryCount: 0,
finishReason: 'legacy_import',
summaryMarkdown,
summaryTitle: item?.title || '未命名页面',
shareCardTitle: item?.title || '未命名页面',
shareCardSubtitle: '历史迁移记录',
shareSourceUrl: normalizedUrl || sourceUrl,
articleSnapshot: {
articleId,
sourceUrl,
normalizedUrl,
sourceHost: Domain.getSourceHost(normalizedUrl || sourceUrl),
title: item?.title || '未命名页面',
language: '',
cleanText: '',
contentHash,
extractor: 'legacy_import',
contentLength: 0,
isTruncated: false,
warnings: ['legacy_import'],
allowHistory: true,
allowShare: true,
retentionHint: 'persistent'
}
});
}
function initDB() {
return new Promise((resolve, reject) => {
const request = indexedDB.open(DB_NAME, DB_VERSION);
request.onerror = () => reject(request.error);
request.onsuccess = () => resolve(request.result);
request.onupgradeneeded = (event) => {
const db = event.target.result;
const transaction = event.target.transaction;
let recordStore = null;
if (!db.objectStoreNames.contains(RECORD_STORE)) {
recordStore = db.createObjectStore(RECORD_STORE, { keyPath: 'recordId' });
recordStore.createIndex('updatedAt', 'updatedAt', { unique: false });
recordStore.createIndex('dedupeKey', 'dedupeKey', { unique: false });
recordStore.createIndex('favorite', 'favorite', { unique: false });
recordStore.createIndex('normalizedUrl', 'normalizedUrl', { unique: false });
recordStore.createIndex('status', 'status', { unique: false });
} else {
recordStore = transaction.objectStore(RECORD_STORE);
}
if (db.objectStoreNames.contains(LEGACY_STORE)) {
const legacyStore = transaction.objectStore(LEGACY_STORE);
legacyStore.openCursor().onsuccess = (cursorEvent) => {
const cursor = cursorEvent.target.result;
if (!cursor) return;
const migrated = migrateLegacyRecord(cursor.value);
recordStore.put(migrated);
cursor.continue();
};
}
};
});
}
async function getStore(mode) {
const database = await initDB();
const transaction = database.transaction([RECORD_STORE], mode);
return {
database,
transaction,
store: transaction.objectStore(RECORD_STORE)
};
}
async function getRecordById(recordId) {
const { store } = await getStore('readonly');
return toPromise(store.get(recordId));
}
async function saveRecord(input) {
const candidate = normalizeRecord(input, null);
if (!shouldPersistRecord(candidate)) {
return candidate;
}
const { store, transaction } = await getStore('readwrite');
return new Promise((resolve, reject) => {
const dedupeRequest = store.index('dedupeKey').get(candidate.dedupeKey);
dedupeRequest.onerror = () => reject(dedupeRequest.error);
dedupeRequest.onsuccess = () => {
const existing = dedupeRequest.result || null;
const nextRecord = normalizeRecord(candidate, existing);
const putRequest = store.put(nextRecord);
putRequest.onerror = () => reject(putRequest.error);
putRequest.onsuccess = () => resolve(nextRecord);
};
transaction.onerror = () => reject(transaction.error);
});
}
async function getAll(options) {
const { store } = await getStore('readonly');
const items = await toPromise(store.getAll());
const normalized = (items || []).sort((a, b) => {
return new Date(b.updatedAt || b.createdAt || 0).getTime() - new Date(a.updatedAt || a.createdAt || 0).getTime();
});
if (options?.favoritesOnly) {
return normalized.filter((item) => item.favorite);
}
return normalized;
}
async function searchRecords(query, options) {
const keyword = String(query || '').trim().toLowerCase();
const items = await getAll(options);
if (!keyword) return items;
return items.filter((item) => {
return [
item.titleSnapshot,
item.sourceHost,
item.summaryPlainText,
item.summaryMode,
item.provider,
item.model,
item.articleSnapshot?.sourceType,
item.articleSnapshot?.sourceStrategy?.label,
item.articleSnapshot?.sourceStrategyId
].some((field) => String(field || '').toLowerCase().includes(keyword));
});
}
async function findReusableRecordForArticle(article) {
const items = await getAll();
return findBestReusableRecordForArticle(items, article);
}
async function toggleFavorite(recordId) {
const existing = await getRecordById(recordId);
if (!existing) return null;
return saveRecord(Object.assign({}, existing, { favorite: !existing.favorite }));
}
async function updateRecord(recordId, patch) {
const existing = await getRecordById(recordId);
if (!existing) return null;
return saveRecord(Object.assign({}, existing, patch || {}));
}
async function deleteRecord(recordId) {
const { store, transaction } = await getStore('readwrite');
return new Promise((resolve, reject) => {
const request = store.delete(recordId);
request.onerror = () => reject(request.error);
request.onsuccess = () => resolve();
transaction.onerror = () => reject(transaction.error);
});
}
async function clearAll() {
const { store, transaction } = await getStore('readwrite');
return new Promise((resolve, reject) => {
const request = store.clear();
request.onerror = () => reject(request.error);
request.onsuccess = () => resolve();
transaction.onerror = () => reject(transaction.error);
});
}
const api = {
markdownToPlainText,
buildDedupeKey,
getRecordSiteHost,
buildSiteBuckets,
filterRecordsBySite,
groupRecordsBySite,
migrateLegacyRecord,
shouldPersistRecord,
isReusablePrimaryRecord,
getReusableRecordMatch,
findBestReusableRecordForArticle,
saveRecord,
getAll,
searchRecords,
findReusableRecordForArticle,
getRecordById,
toggleFavorite,
updateRecord,
deleteRecord,
clearAll
};
global.db = api;
if (typeof module !== 'undefined' && module.exports) {
module.exports = api;
}
})(typeof globalThis !== 'undefined' ? globalThis : self);