Files
bare-operating-system/packages/bare-os-booter/lib/host/bare-os-lifecycle-hooks.js
T
2026-08-18 18:11:28 -04:00

74 lines
2.0 KiB
JavaScript

/**
* Suspend/resume hook registry and kernel reload request methods on `ctx`.
*/
/**
* @param {{
* suspendHooks: Array<() => void | Promise<void>>,
* resumeHooks: Array<() => void | Promise<void>>,
* env: Record<string, string | undefined>
* }} deps
*/
export function createBareOsLifecycleHookMethods(deps) {
const { suspendHooks, resumeHooks, env } = deps
return {
/** @param {() => void | Promise<void>} fn */
bareOsRegisterSuspendHook(fn) {
if (typeof fn === 'function') suspendHooks.push(fn)
return () => {
const i = suspendHooks.indexOf(fn)
if (i >= 0) suspendHooks.splice(i, 1)
}
},
/** @param {() => void | Promise<void>} fn */
bareOsRegisterResumeHook(fn) {
if (typeof fn === 'function') resumeHooks.push(fn)
return () => {
const i = resumeHooks.indexOf(fn)
if (i >= 0) resumeHooks.splice(i, 1)
}
},
async bareOsInvokeSuspendHooks() {
for (const fn of [...suspendHooks]) {
try {
await fn()
} catch {
/* ignore */
}
}
},
async bareOsInvokeResumeHooks() {
for (const fn of [...resumeHooks]) {
try {
await fn()
} catch {
/* ignore */
}
}
},
bareOsRequestKernelReload() {
const err = /** @type {Error & { code?: string }} */ (
new Error('BARE_OS_KERNEL_RELOAD')
)
err.code = 'BARE_OS_KERNEL_RELOAD'
throw err
},
bareOsRequestKernelProfileReload() {
const on =
env.BARE_OS_KERNEL_PROFILE_WARM === '1' ||
env.BARE_OS_KERNEL_PROFILE_WARM === 'true'
if (!on) {
throw new Error(
'bareOsRequestKernelProfileReload: enable BARE_OS_KERNEL_PROFILE_WARM=1'
)
}
const err = /** @type {Error & { code?: string }} */ (
new Error('BARE_OS_KERNEL_PROFILE_RELOAD')
)
err.code = 'BARE_OS_KERNEL_PROFILE_RELOAD'
throw err
}
}
}