"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.__tsfTypeAliases = void 0;
exports.getContext = getContext;
exports.getContextProp = getContextProp;
exports.setContextProp = setContextProp;
exports.removeContextProp = removeContextProp;
exports.withContext = withContext;
exports.withContextData = withContextData;
const tslib_1 = require("tslib");
const _a = tslib_1.__importStar(require("@zyno-io/ts-server-foundation/type-metadata-runtime"));
const node_async_hooks_1 = require("node:async_hooks");
const context = new node_async_hooks_1.AsyncLocalStorage();
function getContext() {
    return context.getStore();
}
function getContextProp(name) {
    return getContext()?.[name];
}
function setContextProp(name, value) {
    const store = getContext();
    if (store)
        store[name] = value;
}
function removeContextProp(name) {
    const store = getContext();
    if (store)
        delete store[name];
}
async function withContext(cb) {
    if (getContext())
        return cb();
    return context.run({}, cb);
}
async function withContextData(data, cb) {
    return withContext(async () => {
        const store = getContext();
        const dataKeys = [...Object.getOwnPropertyNames(data), ...Object.getOwnPropertySymbols(data)];
        const overwriteKeys = dataKeys.filter(key => key in store);
        const overwriteValues = overwriteKeys.map(key => store[key]);
        Object.assign(store, data);
        try {
            return await cb();
        }
        finally {
            for (const key of dataKeys)
                delete store[key];
            for (let i = 0; i < overwriteKeys.length; i++)
                store[overwriteKeys[i]] = overwriteValues[i];
        }
    });
}
exports.__tsfTypeAliases = _a.decodeCompactMetadataV1("[1,{\"SimpleStore\":{\"kind\":18,\"index\":{\"kind\":1},\"types\":[],\"typeName\":\"SimpleStore\"}}]", []);
//# sourceMappingURL=context.js.map