8 changed files with 84 additions and 10 deletions
@ -0,0 +1,20 @@
@@ -0,0 +1,20 @@
|
||||
// storage-bridge.js - двухслойный клиент памяти dsh-memory
|
||||
var LK="dsm_state",TK="dshmem-bridge-token",BU="http://127.0.0.1:8766"; |
||||
|
||||
function empty() {return {version:1,updatedAt:new Date().toISOString(),memories:{},skills:[]};} |
||||
function loadLocal() {return new Promise(function(res){chrome.storage.local.get([LK],function(o){res(o[LK] || empty())})})}; |
||||
function saveLocal(s) {return new Promise(function(res){chrome.storage.local.set({dsm_state:s},function(){res(true)})})}; |
||||
function authHeaders() {return new Promise(function(res){chrome.storage.local.get([TK],function(o){var h={};h["Content-Type"]="application/json";if(o[TK])h.Authorization="Bearer "+o[TK];res(h)})})}; |
||||
|
||||
function fetchRemote() {return authHeaders().then(function(h){return fetch(BU+"/"+"memory/state",{method:"GET",headers:h})}).then(function(r){if(!r.ok)throw new Error("GET "+r.status);return r.json()}).then(function(j){if(!j||!j.ok)throw new Error("bad payload");return j.data||empty()})}; |
||||
function putRemote(s) {return authHeaders().then(function(h){return fetch(BU+"/"+"memory/state",{method:"PUT",headers:h,body:JSON.stringify(s)})}).then(function(r){if(!r.ok)throw new Error("PUT "+r.status);return r.json()}).then(function(j){return j&&j.ok})}; |
||||
|
||||
function newer(a,b) {return (a&&a.updatedAt?a.updatedAt:"") >= (b&&b.updatedAt?b.updatedAt:"")}; |
||||
function sync() {return Promise.all([loadLocal(),fetchRemote().catch(function(){return null})]).then(function(arr){var loc=arr[0],rem=arr[1];if(!rem)return loc;if(newer(loc,rem)){putRemote(loc).catch(function(){});return loc};return saveLocal(rem).then(function(){return rem})})}; |
||||
|
||||
function getState() {return sync()}; |
||||
function putState(s) {var v={version:1,updatedAt:new Date().toISOString(),memories:s.memories||{},skills:s.skills||[]};return saveLocal(v).then(function(){return putRemote(v).catch(function(){return false})}).then(function(){return v})}; |
||||
|
||||
var API={empty:empty,loadLocal:loadLocal,saveLocal:saveLocal,authHeaders:authHeaders,fetchRemote:fetchRemote,putRemote:putRemote,sync:sync,getState:getState,putState:putState,LK:LK,TK:TK,BU:BU}; |
||||
if(typeof module!=="undefined"&&module.exports){module.exports=API}; |
||||
if(typeof globalThis!=="undefined"){globalThis.STORAGE_BRIDGE=API}; |
||||
Loading…
Reference in new issue