-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbackground.js
2 lines (2 loc) · 22.5 KB
/
background.js
1
2
(()=>{"use strict";var e,t;!function(e){e.SESSION_START="session:start",e.SESSION_END="session:end",e.SESSION_UPDATE="session:update",e.SESSION_LEAVE="session:leave",e.SESSION_RETURN="session:return",e.SESSION_UPDATE_ACTIVITY="session:update_activity",e.SUBMISSION_ADD="session:submission_add",e.DATA_PROBLEM_UPDATE="data:problem_update",e.DATA_CLEAR_ALL="data:clear_all",e.DATA_EXPORT="data:export",e.DATA_IMPORT="data:import",e.DATA_GET_STATS="data:get_stats",e.DATA_GET_SESSIONS="data:get_sessions",e.DATA_GET_PROBLEMS="data:get_problems",e.DATA_GET_SETTINGS="data:get_settings",e.DATA_UPDATE_SETTINGS="data:update_settings"}(e||(e={})),function(e){e.SESSION_INITIALIZE_ERROR="session:initialize_error",e.SESSION_LEAVE_ERROR="session:leave_error",e.SESSION_RETURN_ERROR="session:return_error",e.SESSION_UPDATE_ERROR="session:update_error",e.SESSION_CLOSE_ERROR="session:close_error",e.SESSION_NOT_FOUND="session:not_found",e.SUBMISSION_ADD_ERROR="submission:add_error",e.DATA_CLEAR_ERROR="data:clear_error",e.DATA_EXPORT_ERROR="data:export_error",e.DATA_IMPORT_ERROR="data:import_error",e.DATA_PROBLEM_UPDATE_ERROR="data:problem_update_error",e.DATA_SETTINGS_UPDATE_ERROR="data:settings_update_error",e.DATA_STATS_ERROR="data:stats_error",e.UNKNOWN_ERROR="error:unknown"}(t||(t={}));var s=function(e,t,s,i){return new(s||(s=Promise))((function(a,n){function r(e){try{d(i.next(e))}catch(e){n(e)}}function o(e){try{d(i.throw(e))}catch(e){n(e)}}function d(e){var t;e.done?a(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(r,o)}d((i=i.apply(e,t||[])).next())}))};class i{static wrap(e){return s(this,arguments,void 0,(function*(e,s=t.UNKNOWN_ERROR){try{const t=yield e();return this.response.success(t)}catch(e){return this.response.error(s,e instanceof Error?e.message:"Operation failed")}}))}}i.session={start:(t,s)=>({action:e.SESSION_START,payload:{problem:t,currentTime:s}}),end:(t,s,i)=>({action:e.SESSION_END,payload:{sessionId:t,endTime:s,endReason:i}}),update:(t,s)=>({action:e.SESSION_UPDATE,payload:{sessionId:t,updates:s}}),leave:(t,s)=>({action:e.SESSION_LEAVE,payload:{sessionId:t,leaveTime:s}}),return:(t,s)=>({action:e.SESSION_RETURN,payload:{sessionId:t,returnTime:s}}),updateActivity:(t,s)=>({action:e.SESSION_UPDATE_ACTIVITY,payload:{sessionId:t,activityTime:s}}),addSubmission:(t,s,i,a,n,r)=>({action:e.SUBMISSION_ADD,payload:{sessionId:t,code:s,language:i,status:a,runtime:n,errorMessage:r}})},i.data={export:(t,s)=>({action:e.DATA_EXPORT,payload:{reason:t,details:Object.assign({source:s.source,timestamp:Date.now()},s)}}),import:(t,s)=>({action:e.DATA_IMPORT,payload:{data:t,options:s}}),getStats:()=>({action:e.DATA_GET_STATS,payload:void 0}),getSessions:()=>({action:e.DATA_GET_SESSIONS,payload:void 0}),getProblems:t=>({action:e.DATA_GET_PROBLEMS,payload:{problemIds:t}}),updateProblem:t=>({action:e.DATA_PROBLEM_UPDATE,payload:{problem:t}})},i.settings={get:()=>({action:e.DATA_GET_SETTINGS,payload:void 0}),update:t=>({action:e.DATA_UPDATE_SETTINGS,payload:t})},i.response={success:e=>({success:!0,data:e}),error:(e,t)=>({success:!1,error:{code:e,message:t}}),unknown(e){return this.error(t.UNKNOWN_ERROR,e instanceof Error?e.message:"Unknown error occurred")}};class a{createSession(e,t){return{sessionId:this.generateSessionId(),problemId:e,startTime:t,lastActivityTime:t,leaves:[],submissions:[],createdAt:t,updatedAt:t}}addLeaveRecord(e,t){return Object.assign(Object.assign({},e),{leaves:[...e.leaves||[],{leaveTime:t,returnTime:0,duration:0}],updatedAt:t})}updateReturnRecord(e,t){var s;if(!(null===(s=e.leaves)||void 0===s?void 0:s.length))return e;const i=[...e.leaves],a=i[i.length-1];return 0===a.returnTime&&(a.returnTime=t,a.duration=t-a.leaveTime),Object.assign(Object.assign({},e),{leaves:i,updatedAt:t})}updateActivityTime(e,t){return Object.assign(Object.assign({},e),{lastActivityTime:t,updatedAt:t})}closeSession(e,t,s){return Object.assign(Object.assign({},e),{endTime:t,endReason:s,updatedAt:t})}addSubmission(e,t,s,i,a,n){const r={code:t,language:s,status:i,runtime:a,errorMessage:n,timestamp:Date.now()},o=[...e.submissions||[],r],d=Object.assign(Object.assign({},e),{submissions:o,updatedAt:r.timestamp});if("success"===i&&!e.firstSuccessTime){const e=o.find((e=>"success"===e.status));d.firstSuccessTime=(null==e?void 0:e.timestamp)||r.timestamp}return d}generateSessionId(){return crypto.randomUUID()}}const n="bytebytebunny_metadata",r="bytebytebunny_data",o="bytebytebunny_settings",d=10,l=1,g=18e5;class u{constructor(e){this.logLevel="info",this.logCounter=0,this.lastResetTime=Date.now(),this.prefix=e}setLogLevel(e){this.logLevel=e}log(e,...t){this.logMessage("info",console.log,e,...t)}error(e,t){if(this.shouldLog("error")){let e;if(null==t)e="<no error details>";else if(t instanceof Error)e=`${t.message}\n${t.stack}`;else try{e=JSON.stringify(t)}catch(s){e=String(t)}}}debug(e,...t){this.logMessage("debug",console.debug,e,...t)}shouldLog(e){return u.LOG_LEVELS.indexOf(this.logLevel)<=u.LOG_LEVELS.indexOf(e)}warn(e,...t){this.logMessage("info",console.warn,e,...t)}info(e,...t){this.logMessage("info",console.info,e,...t)}logMessage(e,t,s,...i){this.shouldLog(e)&&!this.shouldThrottle()&&t(`${this.prefix} [${(new Date).toLocaleString()}]: ${s}`,...i)}shouldThrottle(){const e=Date.now();return e-this.lastResetTime>=u.THROTTLE_INTERVAL?(this.logCounter=0,this.lastResetTime=e,!1):(this.logCounter++,this.logCounter>u.MAX_LOGS_PER_INTERVAL)}}u.LOG_LEVELS=["debug","info","error"],u.THROTTLE_INTERVAL=1e3,u.MAX_LOGS_PER_INTERVAL=100;class c{constructor(){this.loggers=new Map,this.defaultPrefix="BBBunny",this.SEPARATOR=":"}static getInstance(){return c.instance||(c.instance=new c),c.instance}setDefaultPrefix(e){this.defaultPrefix=e}getLogger(e){const t=(Array.isArray(e)?e:[e]).join(this.SEPARATOR),s=`${this.defaultPrefix}${this.SEPARATOR}${t}`;return this.loggers.has(t)||this.loggers.set(t,new u(s)),this.loggers.get(t)}setGlobalLogLevel(e){this.loggers.forEach((t=>t.setLogLevel(e)))}}var h=function(e,t,s,i){return new(s||(s=Promise))((function(a,n){function r(e){try{d(i.next(e))}catch(e){n(e)}}function o(e){try{d(i.throw(e))}catch(e){n(e)}}function d(e){var t;e.done?a(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(r,o)}d((i=i.apply(e,t||[])).next())}))};class S{constructor(){this.operationLock=!1,this.operationQueue=Promise.resolve(),this.currentMetadata=null,this.currentData=null,this.currentSettings=null,this.logger=c.getInstance().getLogger("DataManager")}static getInstance(){return S.instance||(S.instance=new S),S.instance}getData(){return h(this,void 0,void 0,(function*(){return this._getData()}))}getMetadata(){return h(this,void 0,void 0,(function*(){return this._getMetadata()}))}getSettings(){return h(this,void 0,void 0,(function*(){return this._getSettings()}))}getSession(e){return h(this,void 0,void 0,(function*(){return(yield this.getData()).sessions.find((t=>t.sessionId===e))||null}))}findReusableSession(e,t){return h(this,void 0,void 0,(function*(){const s=yield this.getData(),i=Object.values(s.sessions).find((s=>{const i=s.problemId===e,a=s.lastActivityTime||s.startTime;return i&&t-a<g}));return i&&this.logger.debug("Found reusable session:",{sessionId:i.sessionId,problemId:e,startTime:new Date(i.startTime).toLocaleString(),lastActivityTime:new Date(i.lastActivityTime||i.startTime).toLocaleString()}),i||null}))}updateSession(e){return h(this,void 0,void 0,(function*(){return this.logger.debug("Updating session:",{sessionId:e.sessionId}),this.operationQueue=this.operationQueue.then((()=>h(this,void 0,void 0,(function*(){if(this.operationLock){const e=new Error("Another operation is in progress");throw this.logger.error("Update session failed:",e),e}try{this.operationLock=!0;const t=yield this.getData(),s=yield this.getMetadata(),i=t.sessions.findIndex((t=>t.sessionId===e.sessionId));i>=0?(t.sessions[i]=e,this.logger.debug("Updated existing session")):(t.sessions.push(e),s.totalSessions=t.sessions.length,this.logger.debug("Added new session")),s.lastUpdateTime=Date.now(),yield Promise.all([this.storageSet({[r]:t}),this.storageSet({[n]:s})]),this.currentData=t,this.currentMetadata=s;const a=yield this.updateStorageUsage();return this.logger.info("Session update completed"),a}catch(e){throw this.logger.error("Failed to update session:",e),e}finally{this.operationLock=!1}})))),yield this.operationQueue}))}updateProblem(e,t){return h(this,void 0,void 0,(function*(){return this.operationQueue=this.operationQueue.then((()=>h(this,void 0,void 0,(function*(){if(this.operationLock)throw new Error("Another operation is in progress");try{this.operationLock=!0;const s=yield this.getData(),i=yield this.getMetadata();return s.problems[e]=t,i.totalProblems=Object.keys(s.problems).length,i.lastUpdateTime=Date.now(),yield Promise.all([this.storageSet({[r]:s}),this.storageSet({[n]:i})]),this.currentData=s,this.currentMetadata=i,yield this.updateStorageUsage()}finally{this.operationLock=!1}})))),yield this.operationQueue}))}updateUserSettings(e){return h(this,void 0,void 0,(function*(){try{const t=yield this.getSettings(),s=Object.assign(Object.assign({},t),e);return yield this.storageSet({[o]:s}),this.currentSettings=s,i.response.success(s)}catch(e){return this.logger.error("Failed to update user settings:",e),i.response.error(t.DATA_SETTINGS_UPDATE_ERROR,e instanceof Error?e.message:"更新设置时发生未知错误")}}))}cleanupOldData(e){return h(this,void 0,void 0,(function*(){this.operationQueue=this.operationQueue.then((()=>h(this,void 0,void 0,(function*(){if(this.operationLock)throw new Error("Another operation is in progress");try{this.operationLock=!0;const t=yield this.getData(),s=yield this.getMetadata();if(e.olderThan){const s=Date.now()-24*e.olderThan*60*60*1e3;t.sessions=t.sessions.filter((e=>e.updatedAt>s))}e.keepLastN&&t.sessions.forEach((t=>{var s;(null===(s=t.submissions)||void 0===s?void 0:s.length)>e.keepLastN&&(t.submissions=t.submissions.slice(-e.keepLastN))})),s.totalSessions=t.sessions.length,s.lastUpdateTime=Date.now(),yield Promise.all([this.storageSet({[r]:t}),this.storageSet({[n]:s})]),this.currentData=t,this.currentMetadata=s,yield this.updateStorageUsage()}finally{this.operationLock=!1}})))),yield this.operationQueue}))}updateStorageUsage(){return h(this,void 0,void 0,(function*(){this.logger.debug("Updating storage usage statistics...");const[e,t,s]=yield Promise.all([this.getData(),this.getSettings(),this.getMetadata()]),a=new Blob([JSON.stringify(e.sessions)]).size,r=new Blob([JSON.stringify(e.problems)]).size,o=new Blob([JSON.stringify(t)]).size,d=new Blob([JSON.stringify(s)]).size,l=new Blob([JSON.stringify({data:e,settings:t,metadata:s})]).size,{QUOTA_BYTES:g}=chrome.storage.local,u={quota:{total:g,used:l,remaining:g-l,usagePercentage:l/g*100},details:{sessions:{size:a,count:e.sessions.length},problems:{size:r,count:Object.keys(e.problems).length},settings:{size:o},metadata:{size:d},total:l},lastCheck:Date.now()};return s.storage={sessionsSize:a,problemsSize:r,settingsSize:o,dataSize:new Blob([JSON.stringify(e)]).size,totalSize:l,lastCheck:u.lastCheck},yield this.storageSet({[n]:s}),this.currentMetadata=s,this.logger.debug("Storage usage updated:",u),i.response.success(u)}))}exportData(e){return h(this,arguments,void 0,(function*(e,t=null){this.logger.debug("Exporting data:",{reason:e,details:t});try{const[s,i,a]=yield Promise.all([this.getData(),this.getMetadata(),this.getSettings()]);return{metadata:i,data:s,settings:a,backupTime:Date.now(),backupReason:{reason:e,details:t}}}catch(s){throw this.logger.error("Failed to export data:",{reason:e,details:t,error:s}),s}}))}importData(e){return h(this,arguments,void 0,(function*(e,t={}){this.logger.info("Starting data import:",{version:e.metadata.version,backupTime:new Date(e.backupTime).toISOString()});try{if(!this.validateImportData(e))throw new Error("Invalid import data format");return yield this.operationQueue.then((()=>h(this,void 0,void 0,(function*(){if(this.operationLock)throw new Error("Another operation is in progress");try{this.operationLock=!0;const s=yield this.getData();"overwrite"===t.mergeStrategy?(s.sessions=e.data.sessions,s.problems=e.data.problems):"smart-merge"===t.mergeStrategy&&(s.sessions=this.mergeSessions(s.sessions,e.data.sessions),s.problems=this.mergeProblems(s.problems,e.data.problems)),t.overwriteSettings&&(yield this.storageSet({[o]:e.settings}),this.currentSettings=e.settings),yield this.storageSet({[r]:s}),this.currentData=s;const i=yield this.getMetadata();i.totalSessions=s.sessions.length,i.totalProblems=Object.keys(s.problems).length,i.lastUpdateTime=Date.now(),yield this.storageSet({[n]:i}),this.currentMetadata=i,yield this.updateStorageUsage()}finally{this.operationLock=!1}})))),this.logger.info("Import completed successfully"),!0}catch(e){return this.logger.error("Import failed:",e),!1}}))}mergeSessions(e,t){const s=new Map;return e.forEach((e=>s.set(e.sessionId,e))),t.forEach((e=>{const t=s.get(e.sessionId);(!t||e.updatedAt>t.updatedAt)&&s.set(e.sessionId,e)})),Array.from(s.values())}mergeProblems(e,t){const s=Object.assign({},e);for(const[e,i]of Object.entries(t))(!s[e]||i.lastUpdated>s[e].lastUpdated)&&(s[e]=i);return s}_getData(){return h(this,void 0,void 0,(function*(){if(!this.currentData){const e=yield this.storageGet(r);e[r]?(this.currentData=e[r],this.currentData&&this.logger.debug("Loaded existing data:",{sessionsCount:this.currentData.sessions.length,problemsCount:Object.keys(this.currentData.problems).length})):(this.currentData=yield this.initializeData(),this.logger.debug("Initialized new data"))}return this.currentData}))}_getMetadata(){return h(this,void 0,void 0,(function*(){if(!this.currentMetadata){const e=yield this.storageGet(n);this.currentMetadata=e[n]||null,null!=this.currentMetadata?(yield this.checkVersion(this.currentMetadata),this.logger.debug("Loaded existing metadata")):(this.currentMetadata=yield this.initializeMetadata(),this.logger.debug("Initialized new metadata"))}return this.currentMetadata}))}_getSettings(){return h(this,void 0,void 0,(function*(){if(!this.currentSettings){const e=yield this.storageGet(o);e[o]?(this.currentSettings=e[o],this.logger.debug("Loaded existing settings")):(this.currentSettings=yield this.initializeSettings(),this.logger.debug("Initialized new settings"))}return this.currentSettings}))}storageGet(e){return h(this,void 0,void 0,(function*(){try{return yield chrome.storage.local.get(e)}catch(t){throw this.logger.error("Failed to get data from storage:",{key:e,error:t}),t}}))}storageSet(e){return h(this,void 0,void 0,(function*(){try{yield chrome.storage.local.set(e),this.logger.debug("Data saved to storage:",{keys:Object.keys(e)})}catch(t){throw this.logger.error("Failed to save data to storage:",{items:e,error:t}),t}}))}checkVersion(e){return h(this,void 0,void 0,(function*(){const t=S.getExtensionVersion(),s=l,i=e.dataVersion===s;return this.logger.info("Version check:",{extension:{current:t,stored:e.version},data:{current:s,stored:e.dataVersion,isMatch:i}}),i||this.logger.warn("Data version mismatch detected"),i}))}static getExtensionVersion(){return chrome.runtime.getManifest().version}validateImportData(e){if(!(e&&e.metadata&&e.data&&e.settings))return this.logger.error("Missing required data sections",null),!1;const t=l;return e.metadata.dataVersion!==t&&this.logger.warn("Data version mismatch:",{imported:e.metadata.dataVersion,current:t}),!(!Array.isArray(e.data.sessions)||"object"!=typeof e.data.problems)||(this.logger.error("Invalid data structure",null),!1)}initializeMetadata(){return h(this,void 0,void 0,(function*(){this.logger.info("Initializing metadata...");const e={version:S.getExtensionVersion(),dataVersion:l,lastUpdateTime:Date.now(),totalSessions:0,totalProblems:0,storage:{sessionsSize:0,problemsSize:0,settingsSize:0,dataSize:0,totalSize:0,lastCheck:Date.now()}};return yield this.storageSet({[n]:e}),e}))}initializeData(){return h(this,void 0,void 0,(function*(){this.logger.info("Initializing core data...");const e={sessions:[],problems:{}};return yield this.storageSet({[r]:e}),e}))}initializeSettings(){return h(this,void 0,void 0,(function*(){this.logger.info("Initializing user settings...");const e={alertTime:d,uiLanguage:"en"};return yield this.storageSet({[o]:e}),e}))}clearAllData(){return h(this,void 0,void 0,(function*(){this.logger.debug("Starting to clear all data...");try{const e=yield this.initializeData(),t=yield this.initializeMetadata();return yield Promise.all([this.storageSet({[r]:e}),this.storageSet({[n]:t})]),this.currentData=e,this.currentMetadata=t,yield this.updateStorageUsage(),this.logger.info("All data cleared successfully"),i.response.success()}catch(e){return this.logger.error("Failed to clear all data:",e),i.response.error(t.DATA_CLEAR_ERROR,e instanceof Error?e.message:"清除数据时发生未知错误")}}))}}var p=function(e,t,s,i){return new(s||(s=Promise))((function(a,n){function r(e){try{d(i.next(e))}catch(e){n(e)}}function o(e){try{d(i.throw(e))}catch(e){n(e)}}function d(e){var t;e.done?a(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(r,o)}d((i=i.apply(e,t||[])).next())}))};new class{constructor(){this.sessionHandler=new a,this.dataManager=S.getInstance(),this.logger=c.getInstance().getLogger("Background"),this.logger.info("BackgroundService initialized"),this.initialize()}initialize(){this.logger.info("Setting up message listener"),chrome.runtime.onMessage.addListener(((e,t,s)=>(this.logger.info("Message received:",{action:e.action,sender:t.id,timestamp:(new Date).toISOString()}),this.handleMessage(e).then(s).catch((e=>{this.logger.error("Error handling message:",e),s(i.response.unknown(e))})),!0)))}handleMessage(s){return p(this,void 0,void 0,(function*(){try{switch(this.logger.debug("Received message:",s),s.action){case e.SESSION_START:{this.logger.debug("Handling SESSION_START");const{problem:e,currentTime:t}=s.payload,a=yield this.dataManager.findReusableSession(e.id,t);if(a){const s=Object.assign(Object.assign({},a),{endTime:void 0,endReason:void 0,lastActivityTime:t,updatedAt:t});return yield this.dataManager.updateSession(s),this.logger.info("Reusing and reactivating session:",{sessionId:a.sessionId,problemId:e.id}),i.response.success(s)}const n=this.sessionHandler.createSession(e.id,t);return yield this.dataManager.updateSession(n),this.logger.debug("New session created:",{sessionId:n.sessionId}),i.response.success(n)}case e.SESSION_END:{const{sessionId:e,endTime:a,endReason:n}=s.payload,r=yield this.dataManager.getSession(e);if(!r)return i.response.error(t.SESSION_NOT_FOUND,"Session not found");const o=this.sessionHandler.closeSession(r,a,n);return yield this.dataManager.updateSession(o),i.response.success()}case e.SESSION_LEAVE:{this.logger.debug("Handling SESSION_LEAVE");const{sessionId:e,leaveTime:a}=s.payload,n=yield this.dataManager.getSession(e);if(!n)return this.logger.warn("Session not found:",{sessionId:e}),i.response.error(t.SESSION_NOT_FOUND,"Session not found");const r=this.sessionHandler.updateReturnRecord(n,a);return yield this.dataManager.updateSession(r),this.logger.debug("Session leave record updated:",{sessionId:e}),i.response.success()}case e.SESSION_UPDATE_ACTIVITY:{this.logger.debug("Handling SESSION_UPDATE_ACTIVITY");const{sessionId:e,activityTime:a}=s.payload,n=yield this.dataManager.getSession(e);if(!n)return this.logger.warn("Session not found:",{sessionId:e}),i.response.error(t.SESSION_NOT_FOUND,"Session not found");const r=this.sessionHandler.updateActivityTime(n,a);return yield this.dataManager.updateSession(r),this.logger.debug("Session activity time updated:",{sessionId:e,activityTime:a}),i.response.success()}case e.SESSION_UPDATE:{this.logger.debug("Handling SESSION_UPDATE");const{sessionId:e,updates:a}=s.payload,n=yield this.dataManager.getSession(e);if(!n)return this.logger.warn("Session not found:",{sessionId:e}),i.response.error(t.SESSION_NOT_FOUND,"Session not found");const r=Object.assign(Object.assign({},n),a);return yield this.dataManager.updateSession(r),this.logger.debug("Session updated:",{sessionId:e}),i.response.success(r)}case e.SESSION_RETURN:{this.logger.debug("Handling SESSION_RETURN");const{sessionId:e,returnTime:a}=s.payload,n=yield this.dataManager.getSession(e);if(!n)return this.logger.warn("Session not found:",{sessionId:e}),i.response.error(t.SESSION_NOT_FOUND,"Session not found");const r=this.sessionHandler.updateReturnRecord(n,a);return yield this.dataManager.updateSession(r),this.logger.debug("Session return record updated:",{sessionId:e}),i.response.success()}case e.SUBMISSION_ADD:{const{sessionId:e,code:a,language:n,status:r,runtime:o,errorMessage:d}=s.payload,l=yield this.dataManager.getSession(e);if(!l)return i.response.error(t.SESSION_NOT_FOUND,"Session not found");const g=this.sessionHandler.addSubmission(l,a,n,r,o,d);return yield this.dataManager.updateSession(g),i.response.success()}case e.DATA_CLEAR_ALL:return yield this.dataManager.clearAllData();case e.DATA_EXPORT:return yield this.handleBackup(s.payload);case e.DATA_IMPORT:return yield this.handleImport(s.payload);case e.DATA_GET_STATS:return yield this.dataManager.updateStorageUsage();case e.DATA_GET_SESSIONS:return yield i.wrap((()=>p(this,void 0,void 0,(function*(){return(yield this.dataManager.getData()).sessions}))));case e.DATA_GET_PROBLEMS:return yield i.wrap((()=>p(this,void 0,void 0,(function*(){const e=yield this.dataManager.getData(),{problemIds:t}=s.payload;return Object.entries(e.problems).filter((([e])=>t.includes(e))).reduce(((e,[t,s])=>Object.assign(Object.assign({},e),{[t]:s})),{})}))));case e.DATA_GET_SETTINGS:return yield i.wrap((()=>p(this,void 0,void 0,(function*(){return yield this.dataManager.getSettings()}))));case e.DATA_UPDATE_SETTINGS:return yield this.dataManager.updateUserSettings(s.payload);case e.DATA_PROBLEM_UPDATE:{this.logger.debug("Handling DATA_PROBLEM_UPDATE");const{problem:e}=s.payload;try{return yield this.dataManager.updateProblem(e.id,e),this.logger.debug("Problem updated successfully:",{problemId:e.id}),i.response.success()}catch(s){return this.logger.error("Failed to update problem:",{problemId:e.id,error:s}),i.response.error(t.DATA_PROBLEM_UPDATE_ERROR,"Failed to update problem data")}}default:return this.logger.warn("Unknown message action:",{action:s.action}),i.response.error(t.UNKNOWN_ERROR,`Unknown message action: ${s.action}`)}}catch(e){return this.logger.error("Message handling failed:",e),i.response.unknown(e)}}))}handleBackup(e){return p(this,void 0,void 0,(function*(){try{const t=yield this.dataManager.exportData(e.reason,e.details);return i.response.success(t)}catch(e){return this.logger.error("Failed to create backup:",e),i.response.error(t.DATA_EXPORT_ERROR,"Failed to create backup")}}))}handleImport(e){return p(this,void 0,void 0,(function*(){return yield i.wrap((()=>p(this,void 0,void 0,(function*(){return yield this.dataManager.importData(e.data,e.options)}))))}))}}})();
//# sourceMappingURL=background.js.map