@netlify/content-engine
Version:
118 lines • 3.23 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
exports.frameworkHooks = void 0;
exports.setFrameworkHook = setFrameworkHook;
exports.frameworkHooks = {
startup: {
before: async () => { },
after: async () => { },
},
sourceNodes: {
before: async () => { },
after: async () => { },
},
customizeSchema: {
before: async () => { },
after: async () => { },
},
buildSchema: {
before: async () => { },
after: async () => { },
},
sync: {
before: async () => { },
after: async () => { },
},
};
const globalState = {
context: {},
};
process.on(`message`, (msg) => {
if (msg?.type === `CONTENT_ENGINE_FRAMEWORK_CONTEXT`) {
globalState.context = msg.context || {};
}
});
function makeInvertedPromise() {
let res = null;
let rej = null;
const promise = new Promise((resolve, reject) => {
res = resolve;
rej = reject;
});
return {
promise,
resolve: res,
reject: rej,
};
}
function setFrameworkHook(name, fn) {
if (typeof fn !== `function`) {
throw new Error(`Framework hook must be a function`);
}
if (!exports.frameworkHooks[name]) {
throw new Error(`Framework hook "${name}" does not exist`);
}
const defaultHookState = {
before: {
resolve: null,
reject: null,
promise: null,
},
after: {
resolve: null,
reject: null,
promise: null,
},
userPromise: null,
};
const hookState = {
...defaultHookState,
};
function runAPI() {
if (hookState.before.resolve) {
hookState.before.resolve(null);
}
return hookState.after.promise || Promise.resolve();
}
exports.frameworkHooks[name].before = async () => {
try {
if (!hookState.before.promise) {
hookState.before = makeInvertedPromise();
hookState.after = makeInvertedPromise();
}
else {
throw new Error(`Framework hook "${name}" is already running. This is a bug or you're calling engine.sync() multiple times at once. Hooks may only run one a time.`);
}
hookState.userPromise = fn({
runAPI,
context: globalState.context,
}).catch((err) => {
hookState.before.reject?.(err);
throw err;
});
await hookState.before.promise;
}
finally {
hookState.before = {
...defaultHookState.before,
};
}
};
exports.frameworkHooks[name].after = async () => {
try {
if (hookState.after.resolve) {
hookState.after.resolve(null);
}
if (hookState.userPromise) {
await hookState.userPromise;
}
}
finally {
hookState.userPromise = null;
hookState.after = {
...defaultHookState.after,
};
}
};
}
//# sourceMappingURL=index.js.map
;