fix: drain accepted exports and close failed store initialization

This commit is contained in:
abaishu0730 committed 2026-10-19 09:11:40 +08:00
1 parent 54e5bafd86
commit a420d2d9fb
12 files changed
+204 -71

No files matched your search

+12 -6
View File
@@ -9,12 +9,18 @@ function installedRuntime(dir){try{
}catch{return '';}}
class AssistantStore{
constructor(dir){
this.dir=path.resolve(dir);this.defaultRuntime=installedRuntime(this.dir);this.vault=new BpmVault({stateDir:this.dir});this.db=new DatabaseSync(path.join(this.dir,'assistant.sqlite'));
this.db.exec(`PRAGMA journal_mode=WAL; PRAGMA busy_timeout=5000; PRAGMA secure_delete=ON;
CREATE TABLE IF NOT EXISTS config(id INTEGER PRIMARY KEY,version INTEGER NOT NULL,payload BLOB NOT NULL);
CREATE TABLE IF NOT EXISTS conversations(id TEXT PRIMARY KEY,owner TEXT NOT NULL,payload BLOB NOT NULL,created_at TEXT NOT NULL,updated_at TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS turns(id TEXT PRIMARY KEY,conversation_id TEXT NOT NULL,status TEXT NOT NULL,payload BLOB NOT NULL,day TEXT NOT NULL,created_at TEXT NOT NULL);
CREATE INDEX IF NOT EXISTS conversation_turns ON turns(conversation_id,created_at);`);
try {
this.dir=path.resolve(dir);this.defaultRuntime=installedRuntime(this.dir);this.vault=new BpmVault({stateDir:this.dir});this.db=new DatabaseSync(path.join(this.dir,'assistant.sqlite'));
this.db.exec(`PRAGMA journal_mode=WAL; PRAGMA busy_timeout=5000; PRAGMA secure_delete=ON;
CREATE TABLE IF NOT EXISTS config(id INTEGER PRIMARY KEY,version INTEGER NOT NULL,payload BLOB NOT NULL);
CREATE TABLE IF NOT EXISTS conversations(id TEXT PRIMARY KEY,owner TEXT NOT NULL,payload BLOB NOT NULL,created_at TEXT NOT NULL,updated_at TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS turns(id TEXT PRIMARY KEY,conversation_id TEXT NOT NULL,status TEXT NOT NULL,payload BLOB NOT NULL,day TEXT NOT NULL,created_at TEXT NOT NULL);
CREATE INDEX IF NOT EXISTS conversation_turns ON turns(conversation_id,created_at);`);
} catch(error) {
try { this.db?.close(); } catch {}
try { this.vault?.destroy(); } catch {}
throw error;
}
}
transaction(work){this.db.exec('BEGIN IMMEDIATE');try{const result=work();this.db.exec('COMMIT');return result;}catch(e){this.db.exec('ROLLBACK');throw e;}}
encode(id,value){return this.vault.encode('assistant:'+id,value);}
+14 -7
View File
@@ -2,13 +2,20 @@
const fs=require('node:fs');const path=require('node:path');const crypto=require('node:crypto');const {DatabaseSync}=require('node:sqlite');
const invalid=message=>Object.assign(new Error(message),{status:400});
class BpmScanStore{
constructor(dir){fs.mkdirSync(dir,{recursive:true});this.db=new DatabaseSync(path.join(dir,'scan.sqlite'));this.db.exec(`PRAGMA busy_timeout=5000; PRAGMA journal_mode=WAL;
CREATE TABLE IF NOT EXISTS config(id INTEGER PRIMARY KEY CHECK(id=1),value TEXT NOT NULL);
INSERT OR IGNORE INTO config VALUES(1,'{"enabled":true,"intervalMinutes":5}');
CREATE TABLE IF NOT EXISTS arrivals(connection_id TEXT NOT NULL,source TEXT NOT NULL,task_id TEXT NOT NULL,day TEXT NOT NULL,value TEXT NOT NULL,first_seen TEXT NOT NULL,last_seen TEXT NOT NULL,PRIMARY KEY(connection_id,source,task_id));
CREATE INDEX IF NOT EXISTS arrivals_day ON arrivals(day DESC);
CREATE TABLE IF NOT EXISTS runs(id TEXT PRIMARY KEY,connection_id TEXT NOT NULL,actor TEXT NOT NULL,started_at TEXT NOT NULL,finished_at TEXT,status TEXT NOT NULL,seen INTEGER,added INTEGER,message TEXT);
UPDATE runs SET status='error',message='服务重启,扫描未完成。',finished_at=CURRENT_TIMESTAMP WHERE status='running';`);}
constructor(dir){
try {
fs.mkdirSync(dir,{recursive:true});this.db=new DatabaseSync(path.join(dir,'scan.sqlite'));this.db.exec(`PRAGMA busy_timeout=5000; PRAGMA journal_mode=WAL;
CREATE TABLE IF NOT EXISTS config(id INTEGER PRIMARY KEY CHECK(id=1),value TEXT NOT NULL);
INSERT OR IGNORE INTO config VALUES(1,'{"enabled":true,"intervalMinutes":5}');
CREATE TABLE IF NOT EXISTS arrivals(connection_id TEXT NOT NULL,source TEXT NOT NULL,task_id TEXT NOT NULL,day TEXT NOT NULL,value TEXT NOT NULL,first_seen TEXT NOT NULL,last_seen TEXT NOT NULL,PRIMARY KEY(connection_id,source,task_id));
CREATE INDEX IF NOT EXISTS arrivals_day ON arrivals(day DESC);
CREATE TABLE IF NOT EXISTS runs(id TEXT PRIMARY KEY,connection_id TEXT NOT NULL,actor TEXT NOT NULL,started_at TEXT NOT NULL,finished_at TEXT,status TEXT NOT NULL,seen INTEGER,added INTEGER,message TEXT);
UPDATE runs SET status='error',message='服务重启,扫描未完成。',finished_at=CURRENT_TIMESTAMP WHERE status='running';`);
} catch(error) {
try { this.db?.close(); } catch {}
throw error;
}
}
transaction(fn){this.db.exec('BEGIN IMMEDIATE');try{const r=fn();this.db.exec('COMMIT');return r;}catch(e){this.db.exec('ROLLBACK');throw e;}}
config(){return JSON.parse(this.db.prepare('SELECT value FROM config WHERE id=1').get().value);}
saveConfig(input){if(!input||Object.keys(input).some(k=>!['enabled','intervalMinutes'].includes(k))||typeof input.enabled!=='boolean'||!Number.isInteger(input.intervalMinutes)||input.intervalMinutes<1||input.intervalMinutes>1440)throw invalid('扫描间隔需为 1–1440 分钟。');this.db.prepare('UPDATE config SET value=? WHERE id=1').run(JSON.stringify(input));return this.config();}
+7 -2
View File
@@ -7,8 +7,13 @@ const SESSION_MS=30*DAY;
const digest=token=>crypto.createHash('sha256').update(token).digest('hex');
class SessionStore {
constructor(dir){
fs.mkdirSync(dir,{recursive:true});this.db=new DatabaseSync(path.join(dir,'auth.sqlite'));
this.db.exec('PRAGMA busy_timeout=5000; CREATE TABLE IF NOT EXISTS sessions(hash TEXT PRIMARY KEY,userId TEXT NOT NULL,expires INTEGER NOT NULL,renewedAt INTEGER NOT NULL);');
try {
fs.mkdirSync(dir,{recursive:true});this.db=new DatabaseSync(path.join(dir,'auth.sqlite'));
this.db.exec('PRAGMA busy_timeout=5000; CREATE TABLE IF NOT EXISTS sessions(hash TEXT PRIMARY KEY,userId TEXT NOT NULL,expires INTEGER NOT NULL,renewedAt INTEGER NOT NULL);');
} catch(error) {
try { this.db?.close(); } catch {}
throw error;
}
}
issue(userId,now=Date.now()){
this.db.prepare('DELETE FROM sessions WHERE expires<=?').run(now);
+8 -3
View File
@@ -5,9 +5,14 @@ const latest=(...values)=>values.map(timestamp).filter(Boolean).sort().at(-1)||n
const groupStatus=items=>!items.length?'unconfigured':['error','unknown','running','pending','healthy','paused','disabled'].find(s=>items.some(i=>i.status===s))||'pending';
class RuntimeHealth {
constructor({stateDir,startedAt=new Date().toISOString(),instanceId='',...sources}){
Object.assign(this,{stateDir,startedAt,instanceId,sources});const dir=path.join(stateDir,'health');fs.mkdirSync(dir,{recursive:true,mode:0o700});this.db=new DatabaseSync(path.join(dir,'health.sqlite'));
this.db.exec(`PRAGMA journal_mode=WAL; PRAGMA busy_timeout=2000;
CREATE TABLE IF NOT EXISTS observations(kind TEXT NOT NULL,id TEXT NOT NULL,last_success TEXT,last_failure TEXT,PRIMARY KEY(kind,id));`);
try {
Object.assign(this,{stateDir,startedAt,instanceId,sources});const dir=path.join(stateDir,'health');fs.mkdirSync(dir,{recursive:true,mode:0o700});this.db=new DatabaseSync(path.join(dir,'health.sqlite'));
this.db.exec(`PRAGMA journal_mode=WAL; PRAGMA busy_timeout=2000;
CREATE TABLE IF NOT EXISTS observations(kind TEXT NOT NULL,id TEXT NOT NULL,last_success TEXT,last_failure TEXT,PRIMARY KEY(kind,id));`);
} catch(error) {
try { this.db?.close(); } catch {}
throw error;
}
}
remember(kind,id,{successAt,failureAt}={}){
const old=this.db.prepare('SELECT last_success AS lastSuccessAt,last_failure AS lastFailureAt FROM observations WHERE kind=? AND id=?').get(kind,id)||{};
+16 -9
View File
@@ -5,15 +5,22 @@ const email=value=>{if(typeof value!=='string'||value.length>254||!/^[A-Za-z0-9.
const text=(v,label,max=200)=>{if(typeof v!=='string'||!v.trim()||v.length>max||/[\x00-\x1f]/.test(v))fail(label+'格式不正确。');return v.trim();};
const at=()=>new Date().toISOString();const hash=raw=>crypto.createHash('sha256').update(raw).digest('hex');
class MailStore{
constructor(dir){this.vault=new BpmVault({stateDir:path.join(dir,'secrets')});this.db=new DatabaseSync(path.join(dir,'mail.sqlite'));this.db.exec(`PRAGMA journal_mode=WAL; PRAGMA busy_timeout=5000; PRAGMA secure_delete=ON;
CREATE TABLE IF NOT EXISTS channels(id TEXT PRIMARY KEY,email TEXT NOT NULL UNIQUE,version INTEGER NOT NULL,payload BLOB NOT NULL,state TEXT NOT NULL,cursor TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS templates(id TEXT PRIMARY KEY,channel_id TEXT NOT NULL,source_key TEXT NOT NULL,scope TEXT NOT NULL,status TEXT NOT NULL,version INTEGER NOT NULL,base_id TEXT,payload BLOB NOT NULL,created_at TEXT NOT NULL,UNIQUE(channel_id,source_key));
CREATE UNIQUE INDEX IF NOT EXISTS active_template ON templates(channel_id,scope) WHERE status='active';
CREATE TABLE IF NOT EXISTS receipts(id INTEGER PRIMARY KEY,channel_id TEXT NOT NULL,epoch TEXT NOT NULL,uid INTEGER NOT NULL,status TEXT NOT NULL,detail TEXT NOT NULL,at TEXT NOT NULL,UNIQUE(channel_id,epoch,uid));
CREATE TABLE IF NOT EXISTS sends(id TEXT PRIMARY KEY,channel_id TEXT NOT NULL,template_id TEXT NOT NULL,status TEXT NOT NULL,at TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS meta(key TEXT PRIMARY KEY,value TEXT NOT NULL);`);
if(!this.db.prepare('PRAGMA table_info(templates)').all().some(c=>c.name==='summary'))this.db.exec("ALTER TABLE templates ADD COLUMN summary TEXT NOT NULL DEFAULT '{}'");
for(const r of this.db.prepare("SELECT id,payload FROM templates WHERE summary='{}'").all()){const p=this.decode(r.id,r.payload);this.db.prepare('UPDATE templates SET summary=? WHERE id=?').run(this.summary(p),r.id);}
constructor(dir){
try {
this.vault=new BpmVault({stateDir:path.join(dir,'secrets')});this.db=new DatabaseSync(path.join(dir,'mail.sqlite'));this.db.exec(`PRAGMA journal_mode=WAL; PRAGMA busy_timeout=5000; PRAGMA secure_delete=ON;
CREATE TABLE IF NOT EXISTS channels(id TEXT PRIMARY KEY,email TEXT NOT NULL UNIQUE,version INTEGER NOT NULL,payload BLOB NOT NULL,state TEXT NOT NULL,cursor TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS templates(id TEXT PRIMARY KEY,channel_id TEXT NOT NULL,source_key TEXT NOT NULL,scope TEXT NOT NULL,status TEXT NOT NULL,version INTEGER NOT NULL,base_id TEXT,payload BLOB NOT NULL,created_at TEXT NOT NULL,UNIQUE(channel_id,source_key));
CREATE UNIQUE INDEX IF NOT EXISTS active_template ON templates(channel_id,scope) WHERE status='active';
CREATE TABLE IF NOT EXISTS receipts(id INTEGER PRIMARY KEY,channel_id TEXT NOT NULL,epoch TEXT NOT NULL,uid INTEGER NOT NULL,status TEXT NOT NULL,detail TEXT NOT NULL,at TEXT NOT NULL,UNIQUE(channel_id,epoch,uid));
CREATE TABLE IF NOT EXISTS sends(id TEXT PRIMARY KEY,channel_id TEXT NOT NULL,template_id TEXT NOT NULL,status TEXT NOT NULL,at TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS meta(key TEXT PRIMARY KEY,value TEXT NOT NULL);`);
if(!this.db.prepare('PRAGMA table_info(templates)').all().some(c=>c.name==='summary'))this.db.exec("ALTER TABLE templates ADD COLUMN summary TEXT NOT NULL DEFAULT '{}'");
for(const r of this.db.prepare("SELECT id,payload FROM templates WHERE summary='{}'").all()){const p=this.decode(r.id,r.payload);this.db.prepare('UPDATE templates SET summary=? WHERE id=?').run(this.summary(p),r.id);}
} catch(error) {
try { this.db?.close(); } catch {}
try { this.vault?.destroy(); } catch {}
throw error;
}
}
summary(p){return JSON.stringify({subject:p.subject,sender:p.sender,attachmentCount:p.attachments.length});}
recoverSends(){this.db.prepare("UPDATE sends SET status='unknown' WHERE status='sending'").run();}
+17 -10
View File
@@ -2,16 +2,23 @@
const fail=(message,status=400)=>{throw Object.assign(new Error(message),{status});};
const fs=require('node:fs');const path=require('node:path');const crypto=require('node:crypto');const {DatabaseSync}=require('node:sqlite');const {BpmVault}=require('../../platform/security/vault.cjs');const {DEFAULT_MAP,validateMap,hash}=require('./mapping.cjs');
class NotificationStore{
constructor(dir){fs.mkdirSync(dir,{recursive:true});this.vault=new BpmVault({stateDir:path.join(dir,'secrets')});this.db=new DatabaseSync(path.join(dir,'notifications.sqlite'));this.db.exec(`PRAGMA journal_mode=WAL; PRAGMA busy_timeout=5000; PRAGMA secure_delete=ON;
CREATE TABLE IF NOT EXISTS settings(id INTEGER PRIMARY KEY CHECK(id=1),value TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS items(id TEXT PRIMARY KEY,payload BLOB NOT NULL,status TEXT NOT NULL,attempts INTEGER NOT NULL DEFAULT 0,error TEXT,batch_id TEXT,created_at TEXT NOT NULL,industry TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS batches(id TEXT PRIMARY KEY,status TEXT NOT NULL,payload BLOB NOT NULL,error TEXT,created_at TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS metadata(key TEXT PRIMARY KEY,value TEXT NOT NULL);
`);
this.db.exec('CREATE TABLE IF NOT EXISTS retry_audit(id TEXT PRIMARY KEY,item_id TEXT NOT NULL,payload BLOB NOT NULL)');
this.db.prepare('INSERT OR IGNORE INTO settings VALUES(1,?)').run(JSON.stringify({version:1,enabled:false,sourceKey:crypto.randomUUID(),sourceName:'业务来源',channelId:'',fieldMap:DEFAULT_MAP,maxAttempts:3}));
if(!this.db.prepare('PRAGMA table_info(items)').all().some(c=>c.name==='industry')){this.db.exec("ALTER TABLE items ADD COLUMN industry TEXT NOT NULL DEFAULT ''");for(const row of this.db.prepare('SELECT id,payload FROM items').all())this.db.prepare('UPDATE items SET industry=? WHERE id=?').run(this.decode(row.id,row.payload).industry,row.id);}
this.db.exec('CREATE INDEX IF NOT EXISTS notification_pending ON items(status,industry,attempts)');
constructor(dir){
try {
fs.mkdirSync(dir,{recursive:true});this.vault=new BpmVault({stateDir:path.join(dir,'secrets')});this.db=new DatabaseSync(path.join(dir,'notifications.sqlite'));this.db.exec(`PRAGMA journal_mode=WAL; PRAGMA busy_timeout=5000; PRAGMA secure_delete=ON;
CREATE TABLE IF NOT EXISTS settings(id INTEGER PRIMARY KEY CHECK(id=1),value TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS items(id TEXT PRIMARY KEY,payload BLOB NOT NULL,status TEXT NOT NULL,attempts INTEGER NOT NULL DEFAULT 0,error TEXT,batch_id TEXT,created_at TEXT NOT NULL,industry TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS batches(id TEXT PRIMARY KEY,status TEXT NOT NULL,payload BLOB NOT NULL,error TEXT,created_at TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS metadata(key TEXT PRIMARY KEY,value TEXT NOT NULL);
`);
this.db.exec('CREATE TABLE IF NOT EXISTS retry_audit(id TEXT PRIMARY KEY,item_id TEXT NOT NULL,payload BLOB NOT NULL)');
this.db.prepare('INSERT OR IGNORE INTO settings VALUES(1,?)').run(JSON.stringify({version:1,enabled:false,sourceKey:crypto.randomUUID(),sourceName:'业务来源',channelId:'',fieldMap:DEFAULT_MAP,maxAttempts:3}));
if(!this.db.prepare('PRAGMA table_info(items)').all().some(c=>c.name==='industry')){this.db.exec("ALTER TABLE items ADD COLUMN industry TEXT NOT NULL DEFAULT ''");for(const row of this.db.prepare('SELECT id,payload FROM items').all())this.db.prepare('UPDATE items SET industry=? WHERE id=?').run(this.decode(row.id,row.payload).industry,row.id);}
this.db.exec('CREATE INDEX IF NOT EXISTS notification_pending ON items(status,industry,attempts)');
} catch(error) {
try { this.db?.close(); } catch {}
try { this.vault?.destroy(); } catch {}
throw error;
}
}
recover(){return this.transaction(()=>{
this.db.exec("UPDATE items SET status='pending' WHERE status='reserved' AND batch_id IN(SELECT id FROM batches WHERE status='prepared'); UPDATE items SET status='unknown',error='服务重启,发送结果需要核实。' WHERE batch_id IN(SELECT id FROM batches WHERE status='sending') AND status IN('reserved','sending'); UPDATE batches SET status='cancelled' WHERE status='prepared'; UPDATE batches SET status='unknown',error='服务重启,发送结果需要核实。' WHERE status='sending';");this.exhaustEligible();
+13 -7
View File
@@ -10,13 +10,19 @@ const text=(v,label,max=200)=>{if(typeof v!=='string'||!v.trim()||v.length>max||
const now=()=>new Date().toISOString();
class StorageStore{
constructor(dir){
fs.mkdirSync(dir,{recursive:true});this.vault=new BpmVault({stateDir:path.join(dir,'secrets')});
this.db=new DatabaseSync(path.join(dir,'storage.sqlite'));this.db.exec(`PRAGMA journal_mode=WAL; PRAGMA busy_timeout=5000; PRAGMA secure_delete=ON;
CREATE TABLE IF NOT EXISTS servers(id TEXT PRIMARY KEY,version INTEGER NOT NULL,payload BLOB NOT NULL,state TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS settings(id INTEGER PRIMARY KEY CHECK(id=1),value TEXT NOT NULL);
INSERT OR IGNORE INTO settings VALUES(1,'{"serverId":"","enabled":false,"since":null}');
CREATE TABLE IF NOT EXISTS archives(id TEXT PRIMARY KEY,server_id TEXT NOT NULL,job_id TEXT NOT NULL,status TEXT NOT NULL,value TEXT NOT NULL,UNIQUE(server_id,job_id));
UPDATE archives SET status='interrupted' WHERE status='running';`);
try {
fs.mkdirSync(dir,{recursive:true});this.vault=new BpmVault({stateDir:path.join(dir,'secrets')});
this.db=new DatabaseSync(path.join(dir,'storage.sqlite'));this.db.exec(`PRAGMA journal_mode=WAL; PRAGMA busy_timeout=5000; PRAGMA secure_delete=ON;
CREATE TABLE IF NOT EXISTS servers(id TEXT PRIMARY KEY,version INTEGER NOT NULL,payload BLOB NOT NULL,state TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS settings(id INTEGER PRIMARY KEY CHECK(id=1),value TEXT NOT NULL);
INSERT OR IGNORE INTO settings VALUES(1,'{"serverId":"","enabled":false,"since":null}');
CREATE TABLE IF NOT EXISTS archives(id TEXT PRIMARY KEY,server_id TEXT NOT NULL,job_id TEXT NOT NULL,status TEXT NOT NULL,value TEXT NOT NULL,UNIQUE(server_id,job_id));
UPDATE archives SET status='interrupted' WHERE status='running';`);
} catch(error) {
try { this.db?.close(); } catch {}
try { this.vault?.destroy(); } catch {}
throw error;
}
}
row(id){if(typeof id!=='string')fail('请选择存储服务器。');const row=this.db.prepare('SELECT * FROM servers WHERE id=?').get(id);if(!row)fail('存储服务器不存在。',404);return row;}
secret(id){const row=this.row(id);try{const saved=this.vault.decode(id,row.payload);return {authMode:'credentials',passwordless:false,...saved,id,version:row.version,state:JSON.parse(row.state)};}catch{fail('存储凭据无法解密,请联系管理员。',503);}}
+18 -13
View File
@@ -9,19 +9,24 @@ const validDate=date=>typeof date==='string' && /^\d{4}-\d{2}-\d{2}$/.test(date)
class WorkspaceStore {
constructor(dir){
fs.mkdirSync(dir,{recursive:true});this.db=new DatabaseSync(path.join(dir,'workspace.sqlite'));
this.db.exec(`PRAGMA busy_timeout=5000; PRAGMA journal_mode=WAL; PRAGMA foreign_keys=ON;
CREATE TABLE IF NOT EXISTS metadata(key TEXT PRIMARY KEY,value TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS exceptions(id TEXT PRIMARY KEY,value TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS connections(id TEXT PRIMARY KEY,value TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS audit(seq INTEGER PRIMARY KEY AUTOINCREMENT,value TEXT NOT NULL);`);
const insert=this.db.prepare('INSERT OR IGNORE INTO metadata(key,value) VALUES(?,?)');
insert.run('calendar',JSON.stringify({version:1,overrides:[]}));insert.run('supervisor',JSON.stringify({version:1,defaultOwner:'',notifyChannel:'none',maxAttempts:0}));
this.transaction(()=>{for(const row of this.db.prepare('SELECT id,value FROM connections').all()){
const item=JSON.parse(row.value);if(!('detailUrl' in item) && !item.checks?.detail && item.status!=='partial')continue;
delete item.detailUrl;if(item.checks)delete item.checks.detail;if(item.status==='partial')item.status='unchecked';
this.db.prepare('UPDATE connections SET value=? WHERE id=?').run(JSON.stringify(item),row.id);
}});
try {
fs.mkdirSync(dir,{recursive:true});this.db=new DatabaseSync(path.join(dir,'workspace.sqlite'));
this.db.exec(`PRAGMA busy_timeout=5000; PRAGMA journal_mode=WAL; PRAGMA foreign_keys=ON;
CREATE TABLE IF NOT EXISTS metadata(key TEXT PRIMARY KEY,value TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS exceptions(id TEXT PRIMARY KEY,value TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS connections(id TEXT PRIMARY KEY,value TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS audit(seq INTEGER PRIMARY KEY AUTOINCREMENT,value TEXT NOT NULL);`);
const insert=this.db.prepare('INSERT OR IGNORE INTO metadata(key,value) VALUES(?,?)');
insert.run('calendar',JSON.stringify({version:1,overrides:[]}));insert.run('supervisor',JSON.stringify({version:1,defaultOwner:'',notifyChannel:'none',maxAttempts:0}));
this.transaction(()=>{for(const row of this.db.prepare('SELECT id,value FROM connections').all()){
const item=JSON.parse(row.value);if(!('detailUrl' in item) && !item.checks?.detail && item.status!=='partial')continue;
delete item.detailUrl;if(item.checks)delete item.checks.detail;if(item.status==='partial')item.status='unchecked';
this.db.prepare('UPDATE connections SET value=? WHERE id=?').run(JSON.stringify(item),row.id);
}});
} catch(error) {
try { this.db?.close(); } catch {}
throw error;
}
}
transaction(work){this.db.exec('BEGIN IMMEDIATE');try{const result=work();this.db.exec('COMMIT');return result;}catch(error){this.db.exec('ROLLBACK');throw error;}}
meta(key){return JSON.parse(this.db.prepare('SELECT value FROM metadata WHERE key=?').get(key).value);}