import {arrayUnique, flatten, mapObject} from '@avocado/core'; import memoize from 'lodash.memoize'; import {invokeHookFlat, registerHooks} from 'scwp'; export const globals = memoize(() => ( invokeHookFlat('behaviorContextGlobals') .reduce((r, results) => ({ ...r, ...results, }), {}) )); export default class Context { constructor(defaults = {}) { this.map = new Map(); this.clear(); this.addObjectMap(defaults); } add(key, value, type = 'undefined') { if (key) { this.map.set(key, [value, type]); } } addObjectMap(map) { Object.entries(map) .forEach(([key, [variable, type]]) => ( this.add(key, variable, type) )); } all() { return Array.from(this.map.keys()) .reduce((r, key) => ({ ...r, [key]: this.get(key), }), {}); } clear() { this.destroy(); this.add('context', this, 'context'); this.addObjectMap(globals()); } description() { const children = Object.entries(this.all()) .reduce((r, [key, [, type]]) => ({ ...r, [key]: {type}, }), {}); return { children, type: 'context', }; } destroy() { this.map.clear(); } get(key) { return this.has(key) ? this.map.get(key) : [undefined, 'undefined']; } getValue(key) { return this.get(key)[0]; } getType(key) { return this.get(key)[1]; } has(key) { return this.map.has(key); } } registerHooks({ autoreg$accept: (type, M) => { if ('hooks' === type && 'behaviorContextGlobals' in M) { globals.cache.clear(); } }, }, module.id);