type ContextStore = Record; const contextStack: ContextStore[] = []; const defaultContext: ContextStore = {}; export function setDefaultContext(context: ContextStore) { Object.assign(defaultContext, context); } export function withContext(context: ContextStore, fn: () => T): T { contextStack.push(context); try { return fn(); } finally { contextStack.pop(); } } export const ctx = new Proxy( {}, { get(_, prop: string) { for (let i = contextStack.length - 1; i >= 0; i--) { if (prop in contextStack[i]) return contextStack[i][prop]; } if (prop in defaultContext) return defaultContext[prop]; // ✅ Fallback to default throw new Error(`Context variable '${prop}' is not defined.`); }, }, ) as Record; export function getContext() { return ctx; }