context.ts
This file
Path
src/jsx/context.ts
266 lines · 9.3 KiB · TypeScript
Last changed by
chore: let oxfmt sort imports instead of eslint (#5442)Yusuke Wadabefore adoption859e2c2
History of this fileTake it
The walk stopped after 200 commits: lines older than f0b094d point at it.
Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 1–2why, one step back1import { raw } from '../helper/html'2import type { HtmlEscapedString } from '../utils/html'chore: let oxfmt sort imports instead of eslint (#5442)Yusuke Wadabefore adoption859e2c2
line 3why, one step back3import type { FC, PropsWithChildren } from './'Merge commit from forkTaku Amanobefore adoption2b8ed40
line 4why, one step back4import { isUntrustedObject, JSXFragmentNode, renderChildren, renderUntrustedObject } from './base'Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 5–14why, one step back5import { DOM_RENDERER } from './constants'6import { createContextProviderFunction } from './dom/context'78export interface Context<T> extends FC<PropsWithChildren<{ value: T }>> {9 values: T[]10 Provider: FC<PropsWithChildren<{ value: T }>>11}1213export const globalContexts: Context<unknown>[] = []14Merge commit from forkTaku Amanobefore adoptionfab3b13
lines 15–212why, one step back15/** Per-render context store, isolated per request so values never leak across renders. */16type RenderStore = WeakMap<Context<unknown>, unknown[]>1718type AsyncLocalStorageLike<T> = {19 getStore(): T | undefined20 run<R>(store: T, callback: () => R): R21}22type AsyncLocalStorageClass = new <T>() => AsyncLocalStorageLike<T>23type AsyncHooksModule = { AsyncLocalStorage?: AsyncLocalStorageClass }2425let alsProbed = false26let asyncLocalStorage: AsyncLocalStorageLike<RenderStore> | undefined27let fallbackStore: RenderStore | undefined28// Unsettled async renders on the fallback path. While > 0, a store-less29// context access is a post-`await` read that degraded to the default value30// — worth a one-time warning. Stays 0 in the browser DOM renderer.31let fallbackRendersInFlight = 032let warnedFallbackDefault = false3334const loadAsyncLocalStorage = (): AsyncLocalStorageLike<RenderStore> | undefined => {35 if (alsProbed) {36 return asyncLocalStorage37 }38 alsProbed = true3940 const global = globalThis as unknown as {41 process?: {42 getBuiltinModule?: (specifier: string) => AsyncHooksModule43 mainModule?: { require?: (specifier: string) => AsyncHooksModule }44 }45 }46 let AsyncLocalStorage: AsyncLocalStorageClass | undefined47 for (const probe of [48 // Node.js >= 20.16, Deno, Bun, Cloudflare Workers (nodejs_compat). Property49 // access only, so bundlers don't statically resolve `node:async_hooks`.50 () => global.process?.getBuiltinModule?.('node:async_hooks')?.AsyncLocalStorage,51 // Node.js < 20.16 has no `process.getBuiltinModule`, but a CJS entrypoint52 // exposes the main module's `require` here.53 () => global.process?.mainModule?.require?.('node:async_hooks')?.AsyncLocalStorage,54 ]) {55 try {56 AsyncLocalStorage = probe()57 } catch {}58 if (AsyncLocalStorage) {59 break60 }61 }6263 if (AsyncLocalStorage) {64 asyncLocalStorage = new AsyncLocalStorage<RenderStore>()65 }66 return asyncLocalStorage67}6869const getCurrentStore = (): RenderStore | undefined => {70 return loadAsyncLocalStorage()?.getStore() || fallbackStore71}7273const warnIfStorelessAccess = (): void => {74 if (fallbackRendersInFlight > 0 && !warnedFallbackDefault) {75 warnedFallbackDefault = true76 console.warn(77 'hono/jsx: AsyncLocalStorage is unavailable in this runtime, so useContext() after an await in an async component falls back to the context default value during server-side rendering. To get provided values across await boundaries, use a runtime with AsyncLocalStorage (Node.js >= 20.16, Deno, Bun, or Cloudflare Workers with the nodejs_compat flag).'78 )79 }80}8182// Write path: materializes the store entry so a Provider's push/pop pair83// operates on a per-render array.84const getContextValuesIn = <T>(store: RenderStore | undefined, context: Context<T>): T[] => {85 if (!store) {86 warnIfStorelessAccess()87 return context.values88 }8990 let values = store.get(context as Context<unknown>) as T[] | undefined91 if (!values) {92 values = [context.values[0]]93 store.set(context as Context<unknown>, values)94 }95 return values96}9798// Read path: never materializes a store entry — a missing entry always99// resolves to the default value, so reads stay allocation-free.100const readContextValueIn = <T>(store: RenderStore | undefined, context: Context<T>): T => {101 if (!store) {102 warnIfStorelessAccess()103 return context.values.at(-1) as T104 }105 const values = store.get(context as Context<unknown>) as T[] | undefined106 return values?.length ? (values.at(-1) as T) : context.values[0]107}108109type LocalContexts = [Context<unknown>, unknown][]110111const captureContextValues = (store: RenderStore | undefined): LocalContexts =>112 (store ? globalContexts.filter((c) => store.has(c)) : globalContexts).map((c) => [113 c,114 readContextValueIn(store, c),115 ])116117const resumeWithContextValues = <T>(118 callback: () => T,119 store: RenderStore | undefined,120 contexts: LocalContexts121): T =>122 runWithRenderContext(() => {123 // Resolve each target array once so every pop operates on the same array124 // as its push, as the Provider in `createContext` does.125 const currentStore = getCurrentStore()126 const valuesPerContext = contexts.map(([context, value]) => {127 const values = getContextValuesIn(currentStore, context)128 values.push(value)129 return values130 })131 const popContextValues = () => {132 valuesPerContext.forEach((values) => {133 values.pop()134 })135 }136 try {137 const result = callback()138 if (result instanceof Promise) {139 return result.finally(popContextValues) as T140 }141 popContextValues()142 return result143 } catch (e) {144 popContextValues()145 throw e146 }147 }, store)148149/**150 * Establish the request-scoped context store for a render.151 *152 * `resumeStore` continues a suspended subtree in the same store on the fallback153 * path (ignored when `AsyncLocalStorage` is available, where isolation is154 * automatic).155 *156 * Without `AsyncLocalStorage` a render can't be followed across `await`, so the157 * store lives in `fallbackStore` only during synchronous work (mirroring158 * React's request storage). Reading context after `await` then finds no store159 * and falls back to the default value — never another request's value.160 */161export const runWithRenderContext = <T>(callback: () => T, resumeStore?: RenderStore): T => {162 if (getCurrentStore()) {163 // Already inside a render (synchronously nested or resumed subtree).164 return callback()165 }166167 const store = resumeStore ?? new WeakMap()168 const storage = loadAsyncLocalStorage()169 if (storage) {170 // AsyncLocalStorage path: request isolation propagates across `await`.171 return storage.run(store, callback)172 }173174 // Fallback path (no AsyncLocalStorage).175 fallbackStore = store176 let result: T177 try {178 result = callback()179 } finally {180 fallbackStore = undefined181 }182 if (!warnedFallbackDefault && result instanceof Promise) {183 fallbackRendersInFlight++184 result = result.finally(() => {185 fallbackRendersInFlight--186 }) as T187 }188 return result189}190191/**192 * Capture the current render store and return a resumer that re-establishes it193 * around a deferred continuation (e.g. a re-render after a suspended promise194 * settles). Shared by every suspension point so none reimplements it.195 */196export const captureRenderContext = (): (<T>(callback: () => T) => T) => {197 const store = getCurrentStore()198 const contexts = captureContextValues(store)199 return (callback) => resumeWithContextValues(callback, store, contexts)200}201202/**203 * Create a context whose value can be provided with `<Context.Provider>` and204 * read with {@link useContext}.205 *206 * Server-side renders are isolated per request, so a provided value never leaks207 * into a concurrent request — even across `await` in an async component, when208 * `AsyncLocalStorage` is available (Node.js >= 20.16, Deno, Bun, Cloudflare209 * Workers with `nodejs_compat`). Without it, reading context after `await`210 * returns the default value; synchronous components and `use()`-based211 * suspension are unaffected.212 */Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 213–215why, one step back213export const createContext = <T>(defaultValue: T): Context<T> => {214 const values = [defaultValue]215 const context: Context<T> = ((props): HtmlEscapedString | Promise<HtmlEscapedString> => {Merge commit from forkTaku Amanobefore adoptionfab3b13
lines 216–219why, one step back216 // Resolve the target array once, synchronously: the pop in `.finally()`217 // below may run later and must operate on the same array as the push.218 const contextValues = getContextValuesIn(getCurrentStore(), context)219 contextValues.push(props.value)Merge commit from forkTaku Amanobefore adoption2b8ed40
line 220why, one step back220 let renderedMerge commit from forkYusuke Wadabefore adoptionf0b094d
line 221why, one step back221 try {Merge commit from forkTaku Amanobefore adoption2b8ed40
lines 222–226why, one step back222 rendered =223 typeof props.children === 'string'224 ? renderChildren([props.children])225 : isUntrustedObject(props.children)226 ? renderUntrustedObject(props.children)Merge commit from forkYusuke Wadabefore adoptionf0b094d
line 227why, one step back227 : props.childrenMerge commit from forkTaku Amanobefore adoption2b8ed40
lines 228–232why, one step back228 ? (Array.isArray(props.children)229 ? new JSXFragmentNode('', {}, props.children)230 : props.children231 ).toString()232 : raw('')Merge commit from forkYusuke Wadabefore adoptionf0b094d
line 233why, one step back233 } catch (e) {Merge commit from forkTaku Amanobefore adoptionfab3b13
line 234why, one step back234 contextValues.pop()Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 235–237why, one step back235 throw e236 }237Merge commit from forkTaku Amanobefore adoption2b8ed40
lines 238–239why, one step back238 if (rendered instanceof Promise) {239 return renderedMerge commit from forkTaku Amanobefore adoptionfab3b13
line 240why, one step back240 .finally(() => contextValues.pop())Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 241–242why, one step back241 .then((resString) => raw(resString, (resString as HtmlEscapedString).callbacks))242 } else {Merge commit from forkTaku Amanobefore adoptionfab3b13
line 243why, one step back243 contextValues.pop()Merge commit from forkTaku Amanobefore adoption2b8ed40
line 244why, one step back244 return raw(rendered)Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 245–257why, one step back245 }246 }) as Context<T>247 context.values = values248 context.Provider = context249250 // eslint-disable-next-line @typescript-eslint/no-explicit-any251 ;(context as any)[DOM_RENDERER] = createContextProviderFunction(values)252253 globalContexts.push(context as Context<unknown>)254255 return context256}257Merge commit from forkTaku Amanobefore adoptionfab3b13
lines 258–263why, one step back258/**259 * Read the current value of a context created with {@link createContext}.260 *261 * Safe to call from async components after `await`. See {@link createContext}262 * for the per-runtime isolation guarantees.263 */Merge commit from forkYusuke Wadabefore adoptionf0b094d
line 264why, one step back264export const useContext = <T>(context: Context<T>): T => {Merge commit from forkTaku Amanobefore adoptionfab3b13
line 265why, one step back265 return readContextValueIn(getCurrentStore(), context)Merge commit from forkYusuke Wadabefore adoptionf0b094d
line 266why, one step back266}