constlegacySources=db.prepare("SELECT id,token_encrypted FROM sources WHERE base_url=? AND remote_user IS NULL").all(baseUrl)as{id: number;token_encrypted: string}[];
for(constlegacyoflegacySources){
try{constlegacyIdentity=awaitgetMemosIdentity(baseUrl,decrypt(legacy.token_encrypted));db.prepare("UPDATE sources SET remote_user=? WHERE id=? AND remote_user IS NULL").run(legacyIdentity.name,legacy.id);}catch{/* Retry on a future connection. */}
}
constshared=db.prepare("SELECT id FROM sources WHERE base_url=? AND remote_user=?").get(baseUrl,identity.name)as{id: number}|undefined;
if(shared){db.prepare("INSERT OR IGNORE INTO source_members(source_id,user_id) VALUES(?,?)").run(shared.id,user.id);returnNextResponse.redirect(externalUrl(req,"/dashboard?source=shared"));}
constexisting=db.prepare("SELECT id FROM sources WHERE user_id=? AND base_url=?").get(user.id,baseUrl)as{id: number}|undefined;
if(existing){db.prepare("UPDATE sources SET name=?,token_encrypted=?,remote_user=?,sync_status='queued',last_connection_error=NULL WHERE id=?").run(name,encrypt(token),identity.name,existing.id);queuePull(existing.id,"source-created");returnNextResponse.redirect(externalUrl(req,"/dashboard?source=reconnected"));}
constout=db.prepare("INSERT INTO sources(user_id,name,base_url,token_encrypted,remote_user,sync_status) VALUES(?,?,?,?,?, 'queued')").run(user.id,name,baseUrl,encrypt(token),identity.name);
constsourceId=Number(out.lastInsertRowid);
db.prepare("INSERT INTO source_members(source_id,user_id,role) VALUES(?,?,'owner')").run(sourceId,user.id);
try{constremote=awaitcreateUserWebhook(baseUrl,token,identity.name,{url:`${publicOrigin}/api/sync/webhook/${sourceId}/${pathSecret}`,displayName:"Mebbling",signingSecret});db.prepare("UPDATE sources SET webhook_secret_hash=?,webhook_mode='signed',webhook_remote_name=?,webhook_signing_secret_encrypted=? WHERE id=?").run(webhookSecretHash(pathSecret),remote.name,encrypt(signingSecret),sourceId);}
catch(webhookError){constmessage=webhookErrorinstanceofError?webhookError.message:"Webhook unsupported";db.prepare("UPDATE sources SET webhook_mode=? WHERE id=?").run(message.includes("Memos API 404")?"manual":"unavailable",sourceId);}