{"version":3,"file":"storeContextManager.mjs","names":[],"sources":["../../../src/domain/context/storeContextManager.ts"],"sourcesContent":["import { combine } from '@openobserve/js-core/util'\nimport { addEventListener, DOM_EVENT } from '../../browser/addEventListener'\nimport type { Context } from '../../tools/serialisation/context'\nimport { isEmptyObject, tryJsonParse } from '../../tools/utils/objectUtils'\nimport type { ContextManager } from './contextManager'\nimport type { CustomerDataType } from './contextConstants'\n\nconst CONTEXT_STORE_KEY_PREFIX = '_oo_c'\n\nconst storageListeners: Array<{ stop: () => void }> = []\n\nexport function storeContextManager(\n  contextManager: ContextManager,\n  productKey: string,\n  customerDataType: CustomerDataType\n) {\n  // window and localStorage are not available in Web Workers or Node.js environments\n  if (typeof window === 'undefined' || typeof localStorage === 'undefined') {\n    return\n  }\n\n  const storageKey = buildStorageKey(productKey, customerDataType)\n\n  storageListeners.push(\n    addEventListener(window, DOM_EVENT.STORAGE, ({ key }) => {\n      if (storageKey === key) {\n        synchronizeWithStorage()\n      }\n    })\n  )\n  contextManager.changeObservable.subscribe(dumpToStorage)\n\n  const contextFromStorage = combine(getFromStorage(), contextManager.getContext())\n  if (!isEmptyObject(contextFromStorage)) {\n    contextManager.setContext(contextFromStorage)\n  }\n\n  function synchronizeWithStorage() {\n    contextManager.setContext(getFromStorage())\n  }\n\n  function dumpToStorage() {\n    localStorage.setItem(storageKey, JSON.stringify(contextManager.getContext()))\n  }\n\n  function getFromStorage() {\n    const rawContext = localStorage.getItem(storageKey)\n    return rawContext ? (tryJsonParse<Context>(rawContext) ?? {}) : {}\n  }\n}\n\nexport function buildStorageKey(productKey: string, customerDataType: CustomerDataType) {\n  return `${CONTEXT_STORE_KEY_PREFIX}_${productKey}_${customerDataType}`\n}\n\nexport function removeStorageListeners() {\n  storageListeners.map((listener) => listener.stop())\n}\n"],"mappings":";;;;AAOA,MAAM,2BAA2B;AAEjC,MAAM,mBAAgD,CAAC;AAEvD,SAAgB,oBACd,gBACA,YACA,kBACA;CAEA,IAAI,OAAO,WAAW,eAAe,OAAO,iBAAiB,aAC3D;CAGF,MAAM,aAAa,gBAAgB,YAAY,gBAAgB;CAE/D,iBAAiB,KACf,iBAAiB,QAAA,YAA4B,EAAE,UAAU;EACvD,IAAI,eAAe,KACjB,uBAAuB;CAE3B,CAAC,CACH;CACA,eAAe,iBAAiB,UAAU,aAAa;CAEvD,MAAM,qBAAqB,QAAQ,eAAe,GAAG,eAAe,WAAW,CAAC;CAChF,IAAI,CAAC,cAAc,kBAAkB,GACnC,eAAe,WAAW,kBAAkB;CAG9C,SAAS,yBAAyB;EAChC,eAAe,WAAW,eAAe,CAAC;CAC5C;CAEA,SAAS,gBAAgB;EACvB,aAAa,QAAQ,YAAY,KAAK,UAAU,eAAe,WAAW,CAAC,CAAC;CAC9E;CAEA,SAAS,iBAAiB;EACxB,MAAM,aAAa,aAAa,QAAQ,UAAU;EAClD,OAAO,aAAc,aAAsB,UAAU,KAAK,CAAC,IAAK,CAAC;CACnE;AACF;AAEA,SAAgB,gBAAgB,YAAoB,kBAAoC;CACtF,OAAO,GAAG,yBAAyB,GAAG,WAAW,GAAG;AACtD;AAEA,SAAgB,yBAAyB;CACvC,iBAAiB,KAAK,aAAa,SAAS,KAAK,CAAC;AACpD"}