UNPKG

@trap_stevo/legendarybuilderproreact-ui

Version:

The legendary UI & utility API that makes your application a legendary application. ~ Created by Steven Compton

319 lines (315 loc) 12.6 kB
import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator"; import _typeof from "@babel/runtime/helpers/typeof"; import _defineProperty from "@babel/runtime/helpers/defineProperty"; import _slicedToArray from "@babel/runtime/helpers/slicedToArray"; import _regeneratorRuntime from "@babel/runtime/regenerator"; function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } /* Created by Hassan Steven Compton. March 7, 2024. */ import React, { createContext, useContext, useState, useEffect, useRef } from "react"; import { generateIdentityKey, encryptData, decryptData } from "../HUDManagers/HUDUniversalEncryptionUtilitiesManager.js"; var AuthContext = /*#__PURE__*/createContext(); /** * HUDSessionProvider provides session cache management within an application, keeping track of session data * with optional encryption-at-rest. */ export var HUDSessionProvider = function HUDSessionProvider(_ref) { var _ref$encryptSessionCa = _ref.encryptSessionCache, encryptSessionCache = _ref$encryptSessionCa === void 0 ? false : _ref$encryptSessionCa, _ref$cacheDepth = _ref.cacheDepth, cacheDepth = _ref$cacheDepth === void 0 ? 100000 : _ref$cacheDepth, cacheOffset = _ref.cacheOffset, cacheSeed = _ref.cacheSeed, children = _ref.children; var offsetStorageID = "_session_cache_offset"; var seedStorageID = "_session_cache_seed"; var storageKey = "HUDSessionCache"; var sessionCacheRef = useRef({}); var _useState = useState({}), _useState2 = _slicedToArray(_useState, 2), sessionCache = _useState2[0], setSessionCache = _useState2[1]; var _useState3 = useState(false), _useState4 = _slicedToArray(_useState3, 2), keysReady = _useState4[0], setKeysReady = _useState4[1]; var encryptionEnabledRef = useRef(!!encryptSessionCache); var resolvedOffsetRef = useRef(null); var resolvedSeedRef = useRef(null); var depthRef = useRef(cacheDepth); var syncSessionCache = function syncSessionCache(next) { sessionCacheRef.current = next; setSessionCache(_objectSpread({}, next)); }; var currentSessionCacheUnencrypted = function currentSessionCacheUnencrypted() { var saved = localStorage.getItem(storageKey); if (!saved) { return {}; } try { var parsed = JSON.parse(saved); return parsed && _typeof(parsed) === "object" ? parsed : {}; } catch (_unused) { return {}; } }; var loadSessionCache = /*#__PURE__*/function () { var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee() { var raw, data; return _regeneratorRuntime.wrap(function _callee$(_context) { while (1) switch (_context.prev = _context.next) { case 0: raw = localStorage.getItem(storageKey); if (raw) { _context.next = 3; break; } return _context.abrupt("return", {}); case 3: if (encryptionEnabledRef.current) { _context.next = 5; break; } return _context.abrupt("return", currentSessionCacheUnencrypted()); case 5: _context.prev = 5; _context.next = 8; return decryptData(raw, resolvedSeedRef.current, resolvedOffsetRef.current, depthRef.current); case 8: data = _context.sent; return _context.abrupt("return", data && _typeof(data) === "object" ? data : {}); case 12: _context.prev = 12; _context.t0 = _context["catch"](5); return _context.abrupt("return", {}); case 15: case "end": return _context.stop(); } }, _callee, null, [[5, 12]]); })); return function loadSessionCache() { return _ref2.apply(this, arguments); }; }(); var persistSessionCache = /*#__PURE__*/function () { var _ref3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(data) { var cipher; return _regeneratorRuntime.wrap(function _callee2$(_context2) { while (1) switch (_context2.prev = _context2.next) { case 0: if (encryptionEnabledRef.current) { _context2.next = 3; break; } localStorage.setItem(storageKey, JSON.stringify(data)); return _context2.abrupt("return"); case 3: _context2.prev = 3; _context2.next = 6; return encryptData(data, resolvedSeedRef.current, resolvedOffsetRef.current, depthRef.current); case 6: cipher = _context2.sent; localStorage.setItem(storageKey, cipher); _context2.next = 12; break; case 10: _context2.prev = 10; _context2.t0 = _context2["catch"](3); case 12: case "end": return _context2.stop(); } }, _callee2, null, [[3, 10]]); })); return function persistSessionCache(_x) { return _ref3.apply(this, arguments); }; }(); var addToSessionCache = function addToSessionCache(id, data) { var multiData = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null; var onComplete = arguments.length > 3 ? arguments[3] : undefined; var updated; if (multiData && _typeof(multiData) === "object" && !Array.isArray(multiData)) { updated = _objectSpread(_objectSpread({}, sessionCacheRef.current), multiData); } else { updated = _objectSpread(_objectSpread({}, sessionCacheRef.current), {}, _defineProperty({}, id, data)); } syncSessionCache(updated); persistSessionCache(updated).then(function () { return typeof onComplete === "function" && onComplete(null); }, function (error) { return typeof onComplete === "function" && onComplete(error || new Error("Did not persist cache.")); }); }; var updateSessionCache = function updateSessionCache() { var data = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var onComplete = arguments.length > 1 ? arguments[1] : undefined; var updated = _objectSpread({}, data || {}); syncSessionCache(updated); persistSessionCache(updated).then(function () { return typeof onComplete === "function" && onComplete(null); }, function (error) { return typeof onComplete === "function" && onComplete(error || new Error("Did not persist cache.")); }); }; var getFromSessionCache = function getFromSessionCache(id) { return sessionCacheRef.current[id] !== undefined ? sessionCacheRef.current[id] : null; }; var getSessionCache = function getSessionCache() { return sessionCacheRef.current; }; var clearFromSessionCache = function clearFromSessionCache(ids, onComplete) { var updated = _objectSpread({}, sessionCacheRef.current); if (Array.isArray(ids)) { ids.forEach(function (id) { delete updated[id]; }); } else { delete updated[ids]; } syncSessionCache(updated); persistSessionCache(updated).then(function () { return typeof onComplete === "function" && onComplete(null); }, function (error) { return typeof onComplete === "function" && onComplete(error || new Error("Did not persist cache.")); }); }; var clearSessionCache = function clearSessionCache(onComplete) { syncSessionCache({}); try { localStorage.removeItem(storageKey); if (typeof onComplete === "function") { onComplete(null); } } catch (error) { if (typeof onComplete === "function") { onComplete(error || new Error("Did not clear cache.")); } } }; useEffect(function () { encryptionEnabledRef.current = !!encryptSessionCache; }, [encryptSessionCache]); useEffect(function () { depthRef.current = cacheDepth; }, [cacheDepth]); useEffect(function () { var _ref4; var seed = (_ref4 = cacheSeed !== null && cacheSeed !== void 0 ? cacheSeed : localStorage.getItem(seedStorageID)) !== null && _ref4 !== void 0 ? _ref4 : generateIdentityKey(); resolvedSeedRef.current = seed; if (!localStorage.getItem(seedStorageID)) { localStorage.setItem(seedStorageID, seed); } }, []); useEffect(function () { var _ref5; var offset = (_ref5 = cacheOffset !== null && cacheOffset !== void 0 ? cacheOffset : localStorage.getItem(offsetStorageID)) !== null && _ref5 !== void 0 ? _ref5 : generateIdentityKey(); resolvedOffsetRef.current = offset; if (!localStorage.getItem(offsetStorageID)) { localStorage.setItem(offsetStorageID, offset); } }, []); useEffect(function () { if (cacheSeed && cacheSeed !== resolvedSeedRef.current) { resolvedSeedRef.current = cacheSeed; localStorage.setItem(seedStorageID, cacheSeed); } }, [cacheSeed]); useEffect(function () { if (cacheOffset && cacheOffset !== resolvedOffsetRef.current) { resolvedOffsetRef.current = cacheOffset; localStorage.setItem(offsetStorageID, cacheOffset); } }, [cacheOffset]); useEffect(function () { if (resolvedSeedRef.current && resolvedOffsetRef.current) { setKeysReady(true); } }, [resolvedSeedRef.current, resolvedOffsetRef.current]); useEffect(function () { var mounted = true; _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3() { var initial; return _regeneratorRuntime.wrap(function _callee3$(_context3) { while (1) switch (_context3.prev = _context3.next) { case 0: if (keysReady) { _context3.next = 2; break; } return _context3.abrupt("return"); case 2: _context3.next = 4; return loadSessionCache(); case 4: initial = _context3.sent; if (mounted) { syncSessionCache(initial); } case 6: case "end": return _context3.stop(); } }, _callee3); }))(); return function () { mounted = false; }; }, [keysReady]); useEffect(function () { var handleStorage = /*#__PURE__*/function () { var _ref7 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee4(e) { var updated; return _regeneratorRuntime.wrap(function _callee4$(_context4) { while (1) switch (_context4.prev = _context4.next) { case 0: if (!(e && e.key && e.key !== storageKey)) { _context4.next = 2; break; } return _context4.abrupt("return"); case 2: _context4.next = 4; return loadSessionCache(); case 4: updated = _context4.sent; syncSessionCache(updated); case 6: case "end": return _context4.stop(); } }, _callee4); })); return function handleStorage(_x2) { return _ref7.apply(this, arguments); }; }(); window.addEventListener("storage", handleStorage); return function () { return window.removeEventListener("storage", handleStorage); }; }, []); return /*#__PURE__*/React.createElement(AuthContext.Provider, { value: { sessionCache: sessionCache, sessionCacheState: sessionCacheRef, addToSessionCache: addToSessionCache, getSessionCache: getSessionCache, getFromSessionCache: getFromSessionCache, updateSessionCache: updateSessionCache, clearFromSessionCache: clearFromSessionCache, clearSessionCache: clearSessionCache } }, children); }; export var useHUDSession = function useHUDSession() { var context = useContext(AuthContext); if (!context) { throw new Error("Must use within an SessionProvider"); } return context; };