cloudaxe-opencode/packages/opencode/src/util/context.ts

26 lines
588 B
TypeScript
Raw Normal View History

2025-05-31 18:41:00 +00:00
import { AsyncLocalStorage } from "async_hooks"
2025-05-18 01:31:42 +00:00
export namespace Context {
export class NotFound extends Error {
constructor(public override readonly name: string) {
2025-05-31 18:41:00 +00:00
super(`No context found for ${name}`)
2025-05-18 01:31:42 +00:00
}
}
export function create<T>(name: string) {
2025-05-31 18:41:00 +00:00
const storage = new AsyncLocalStorage<T>()
2025-05-18 01:31:42 +00:00
return {
use() {
2025-05-31 18:41:00 +00:00
const result = storage.getStore()
2025-05-18 01:31:42 +00:00
if (!result) {
2025-05-31 18:41:00 +00:00
throw new NotFound(name)
2025-05-18 01:31:42 +00:00
}
2025-05-31 18:41:00 +00:00
return result
2025-05-18 01:31:42 +00:00
},
provide<R>(value: T, fn: () => R) {
2025-10-10 21:37:03 +00:00
return storage.run(value, fn)
2025-05-18 01:31:42 +00:00
},
2025-05-31 18:41:00 +00:00
}
2025-05-18 01:31:42 +00:00
}
}