Open History to see the last commit
1import { AsyncLocalStorage } from 'node:async_hooks'
2import type { Awaitable, RegisteredRouter } from '@tanstack/router-core'
3β
4export interface StartStorageContext {
5 getRouter: () => Awaitable<RegisteredRouter>
6 request: Request
7 // TODO type this properly
8 startOptions: /* AnyStartInstanceOptions*/ any
9β
10 contextAfterGlobalMiddlewares: any
11}
12β
13const startStorage = new AsyncLocalStorage<StartStorageContext>()
14β
15export async function runWithStartContext<T>(
16 context: StartStorageContext,
17 fn: () => T | Promise<T>,
18): Promise<T> {
19 return startStorage.run(context, fn)
20}
21β
22export function getStartContext<TThrow extends boolean = true>(opts?: {
23 throwIfNotFound?: TThrow
24}): TThrow extends false
25 ? StartStorageContext | undefined
26 : StartStorageContext {
27 const context = startStorage.getStore()
28 if (!context && opts?.throwIfNotFound !== false) {
29 throw new Error(
30 `No Start context found in AsyncLocalStorage. Make sure you are using the function within the server runtime.`,
31 )
32 }
33 return context as any
34}