@kayjs/kay 2.0.0-beta.3 → 2.0.0-beta.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (91) hide show
  1. package/llms.txt +42 -0
  2. package/package.json +24 -13
  3. package/src/build/bundle.ts +11 -51
  4. package/src/build/client-plugin.ts +108 -0
  5. package/src/build/compile.ts +4 -2
  6. package/src/build/graph.ts +16 -3
  7. package/src/build/index.ts +23 -15
  8. package/src/build/islands.ts +28 -30
  9. package/src/build/manifest.ts +6 -3
  10. package/src/build/report.ts +82 -13
  11. package/src/build/resolve.ts +6 -7
  12. package/src/build/routes.ts +12 -21
  13. package/src/build/server-entry.ts +1 -1
  14. package/src/cli/check.ts +49 -43
  15. package/src/cli/commands.ts +224 -0
  16. package/src/cli/index.ts +46 -302
  17. package/src/cli/new.ts +15 -509
  18. package/src/cli/upgrade-plugins.ts +168 -0
  19. package/src/cli/upgrade.ts +220 -0
  20. package/src/compiler/analyze.ts +319 -565
  21. package/src/compiler/ast.ts +39 -0
  22. package/src/compiler/data-keys.ts +233 -0
  23. package/src/compiler/dom.ts +18 -15
  24. package/src/compiler/interactivity.ts +174 -0
  25. package/src/compiler/mistakes.ts +19 -1
  26. package/src/compiler/server-only.ts +4 -1
  27. package/src/compiler/shared.ts +1 -1
  28. package/src/compiler/ssr.ts +28 -28
  29. package/src/context.ts +1 -1
  30. package/src/dev/index.ts +15 -23
  31. package/src/dom/extras.ts +43 -12
  32. package/src/dom/index.ts +25 -1
  33. package/src/index.ts +0 -13
  34. package/src/jsx-runtime.ts +1 -1
  35. package/src/plugins/context.ts +8 -6
  36. package/src/plugins/index.ts +2 -2
  37. package/src/plugins/load.ts +25 -2
  38. package/src/plugins/public.ts +6 -0
  39. package/src/plugins/services.ts +15 -3
  40. package/src/plugins/types.ts +7 -11
  41. package/src/server/action-registry.ts +10 -4
  42. package/src/server/action.ts +8 -2
  43. package/src/server/document.ts +13 -1
  44. package/src/server/errors.ts +7 -5
  45. package/src/server/index.ts +9 -10
  46. package/src/server/lifecycle.ts +22 -0
  47. package/src/server/plugin-host.ts +6 -8
  48. package/src/server/public.ts +15 -0
  49. package/src/server/request-scope.ts +22 -0
  50. package/src/server/stream.ts +4 -3
  51. package/src/ssr/context.ts +25 -0
  52. package/src/ssr/index.ts +10 -7
  53. package/src/test/browser.ts +180 -0
  54. package/src/test/index.ts +4 -1
  55. package/templates/_shared/AGENTS.md +5 -0
  56. package/templates/_shared/CLAUDE.md +1 -0
  57. package/templates/_shared/public/robots.txt +2 -0
  58. package/templates/_shared/tsconfig.json +19 -0
  59. package/templates/app/.env.example +4 -0
  60. package/templates/app/kay.config.ts +11 -0
  61. package/templates/app/package.json +20 -0
  62. package/templates/app/src/auth.ts +14 -0
  63. package/templates/app/src/routes/_layout.tsx +32 -0
  64. package/templates/app/src/routes/dashboard/_middleware.ts +3 -0
  65. package/templates/app/src/routes/dashboard/index.tsx +13 -0
  66. package/templates/app/src/routes/index.tsx +15 -0
  67. package/templates/app/src/routes/login.tsx +34 -0
  68. package/templates/app/src/styles/app.css +7 -0
  69. package/templates/blog/content/posts/welcome.md +9 -0
  70. package/templates/blog/kay.config.ts +23 -0
  71. package/templates/blog/package.json +21 -0
  72. package/templates/blog/src/posts.ts +26 -0
  73. package/templates/blog/src/routes/_layout.tsx +20 -0
  74. package/templates/blog/src/routes/blog/[slug].tsx +31 -0
  75. package/templates/blog/src/routes/index.tsx +29 -0
  76. package/templates/blog/src/styles/app.css +10 -0
  77. package/templates/fullstack/kay.config.ts +6 -0
  78. package/templates/fullstack/package.json +18 -0
  79. package/templates/fullstack/src/actions/greet.ts +19 -0
  80. package/templates/fullstack/src/components/Counter.tsx +10 -0
  81. package/templates/fullstack/src/components/GreetForm.tsx +26 -0
  82. package/templates/fullstack/src/routes/_layout.tsx +14 -0
  83. package/templates/fullstack/src/routes/api/health.ts +5 -0
  84. package/templates/fullstack/src/routes/index.tsx +13 -0
  85. package/templates/fullstack/src/styles/app.css +29 -0
  86. package/templates/minimal/kay.config.ts +6 -0
  87. package/templates/minimal/package.json +18 -0
  88. package/templates/minimal/src/components/Counter.tsx +10 -0
  89. package/templates/minimal/src/routes/_layout.tsx +14 -0
  90. package/templates/minimal/src/routes/index.tsx +11 -0
  91. package/templates/minimal/src/styles/app.css +22 -0
@@ -4,6 +4,7 @@ import type { ActionResult, ServerAction } from './action'
4
4
  import type { Middleware, RequestContext } from './http'
5
5
  import { invokeActionCore } from './action'
6
6
  import { runChain } from './http'
7
+ import { runInRequest } from './request-scope'
7
8
 
8
9
  export interface RegisteredAction {
9
10
  act: ServerAction<unknown, unknown>
@@ -12,11 +13,13 @@ export interface RegisteredAction {
12
13
  }
13
14
 
14
15
  export interface ActionRegistry {
15
- /** Gives `act` its live URL and records the middlewares a request to it runs behind. */
16
- register: (act: ServerAction<unknown, unknown>, url: string, dirMiddlewares: Middleware[], pluginMiddlewares: readonly Middleware[]) => void
16
+ /** Gives `act` its name and live URL and records the middlewares a request to it runs behind. */
17
+ register: (act: ServerAction<unknown, unknown>, name: string, url: string, dirMiddlewares: Middleware[], pluginMiddlewares: readonly Middleware[]) => void
17
18
  byUrl: (url: string) => RegisteredAction | undefined
18
19
  /** Runs an action with schema validation behind its folder's `_middleware.ts` chain, as an island call would. */
19
20
  invoke: <I, O>(act: ServerAction<I, O>, input: I, ctx: RequestContext) => Promise<ActionResult<O>>
21
+ /** Runs `fn` as part of the request `ctx`, so the actions it calls run in that request. */
22
+ run: <T>(ctx: RequestContext, fn: () => T) => T
20
23
  }
21
24
 
22
25
  export function createActionRegistry(): ActionRegistry {
@@ -60,13 +63,16 @@ export function createActionRegistry(): ActionRegistry {
60
63
  }
61
64
  }
62
65
 
63
- return {
64
- register(act, url, dirMiddlewares, pluginMiddlewares) {
66
+ const registry: ActionRegistry = {
67
+ register(act, name, url, dirMiddlewares, pluginMiddlewares) {
65
68
  ;(act as { url: string }).url = url
69
+ Object.defineProperty(act, 'name', { value: name, configurable: true })
66
70
  dirMiddlewaresByRef.set(act, dirMiddlewares)
67
71
  handlers.set(url, { act, middlewares: [...pluginMiddlewares, ...dirMiddlewares] })
68
72
  },
69
73
  byUrl: url => handlers.get(url),
70
74
  invoke,
75
+ run: (ctx, fn) => runInRequest({ ctx, actions: registry }, fn),
71
76
  }
77
+ return registry
72
78
  }
@@ -5,6 +5,7 @@ import type { KayLocals } from './index'
5
5
  import type { TrustProxy } from './security'
6
6
  import type { InferInput, InferOutput, StandardSchemaIssue, StandardSchemaV1, ValidationFailure, ValidationResult } from './standard-schema'
7
7
  import { wantsJson } from './http'
8
+ import { currentRequest } from './request-scope'
8
9
  import { isTrustedOrigin } from './security'
9
10
  import { validateSchema } from './standard-schema'
10
11
 
@@ -86,11 +87,16 @@ export function action(
86
87
  : ((_input: never, ctx: ActionContext) => (schemaOrHandler as (c: ActionContext) => unknown)(ctx))
87
88
  const options = hasSchema ? maybeOpts : (maybeHandlerOrOpts as ActionOptions | undefined)
88
89
 
89
- const fn = (async () => {
90
- throw new Error('kay: server action cannot be called directly without a request context; invoke it from an island or via HTTP POST')
90
+ const fn = (async (input: unknown) => {
91
+ const scope = currentRequest()
92
+ if (scope === undefined)
93
+ throw new Error(`kay: ${fn.name || 'a server action'} was called outside a request; call it from a route, load(), middleware or another action, or with app.submit in a test.`)
94
+ return scope.actions.invoke(fn, input, scope.ctx)
91
95
  }) as unknown as ServerAction<unknown, unknown> & { url: string }
92
96
 
93
97
  Object.defineProperties(fn, {
98
+ // The registry names it after its export.
99
+ name: { value: '', configurable: true },
94
100
  __kayAction: { value: true, enumerable: false },
95
101
  schema: { value: schema, enumerable: false },
96
102
  flashFields: { value: options?.flashFields, enumerable: false },
@@ -5,7 +5,7 @@ import type { RenderContext } from '../ssr/context'
5
5
  import type { RequestContext } from './http'
6
6
  import type { SecurityHeadersOptions, TrustProxy } from './security'
7
7
  import { extractRenderedIslands, makeRequestContext } from './http'
8
- import { KAY_ISLAND_STYLE_HASH, KAY_STREAM_SCRIPT_HASH, KAY_SUSPENSE_STYLE_HASH, resolveCspPolicy, withCspHashes } from './security'
8
+ import { inlineStyleHashes, KAY_ISLAND_STYLE_HASH, KAY_STREAM_SCRIPT_HASH, KAY_SUSPENSE_STYLE_HASH, resolveCspPolicy, withCspHashes } from './security'
9
9
 
10
10
  const TITLE_INNER_RE = /^<title\b[^>]*>([\s\S]*?)<\/title>$/i
11
11
 
@@ -61,6 +61,18 @@ export function createHtmlHeaders(security: SecurityHeadersOptions | false | und
61
61
  }
62
62
  }
63
63
 
64
+ /** A plugin's HTML page without a CSP of its own gets the app's, its `<style>` blocks hashed like a rendered page's. */
65
+ export async function withPluginHtmlCsp(res: Response, htmlHeaders: HtmlHeaders): Promise<Response> {
66
+ if (res.body === null || res.headers.has('content-security-policy') || !(res.headers.get('content-type') ?? '').startsWith('text/html'))
67
+ return res
68
+ const html = await res.text()
69
+ const headers = new Headers(res.headers)
70
+ const csp = htmlHeaders(false, false, true, inlineStyleHashes(html))['content-security-policy']
71
+ if (csp !== undefined)
72
+ headers.set('content-security-policy', csp)
73
+ return new Response(html, { status: res.status, statusText: res.statusText, headers })
74
+ }
75
+
64
76
  export function resolveRenderedIslands(rctx: RenderContext, body: string): { hasIslands: boolean, eagerChunks: string[] } {
65
77
  if (rctx.hasIslands) {
66
78
  const eagerChunks: string[] = []
@@ -16,19 +16,21 @@ import { inlineStyleHashes } from './security'
16
16
  export type NotifyError = (error: unknown, request: Request, source: ServerErrorInfo['source']) => void
17
17
 
18
18
  export function createErrorNotifier(onError: ((info: ServerErrorInfo) => void) | undefined, plugins: readonly KayPlugin[]): NotifyError {
19
- const errorHooks: ((info: ServerErrorInfo) => void)[] = []
19
+ const errorHooks: { owner: string, hook: (info: ServerErrorInfo) => void }[] = []
20
20
  if (onError !== undefined)
21
- errorHooks.push(onError)
21
+ errorHooks.push({ owner: 'kay.config.ts', hook: onError })
22
22
  for (const p of plugins) {
23
23
  if (p.onError !== undefined)
24
- errorHooks.push(p.onError)
24
+ errorHooks.push({ owner: p.name, hook: p.onError })
25
25
  }
26
26
  return (error, request, source) => {
27
- for (const hook of errorHooks) {
27
+ for (const { owner, hook } of errorHooks) {
28
28
  try {
29
29
  hook({ error, request, source })
30
30
  }
31
- catch {}
31
+ catch (hookError) {
32
+ console.error(`kay: the onError hook of ${owner} threw; the other hooks still run.`, hookError)
33
+ }
32
34
  }
33
35
  }
34
36
  }
@@ -20,7 +20,7 @@ import { ACTION_ERROR_COOKIE, executeAction, isServerAction } from './action'
20
20
  import { createActionRegistry } from './action-registry'
21
21
  import { createAssets } from './assets'
22
22
  import { CompressionCache, compressedHtmlResponse, maybeCompressResponse } from './compress'
23
- import { createDocumentHooks, createHtmlHeaders, resolveRenderedIslands } from './document'
23
+ import { createDocumentHooks, createHtmlHeaders, resolveRenderedIslands, withPluginHtmlCsp } from './document'
24
24
  import { createErrorNotifier, createFallbackPages } from './errors'
25
25
  import { applyHstsHeader, DEFAULT_MAX_REQUEST_BODY_SIZE, enforceRequestBodyLimit, finalizeResponse, isNotFound, makeRequestContext, runChain, wantsJson } from './http'
26
26
  import { allowedMethodsHeader, isPlainObject, mergedHeadTags, pickPageIslandProps, stripHeadBody } from './page'
@@ -143,7 +143,6 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
143
143
  trustProxy,
144
144
  trustedOriginsList,
145
145
  trustedOrigins,
146
- invokeAction: actions.invoke,
147
146
  })
148
147
  const { router: pluginRouter, middlewaresFor } = pluginHost
149
148
  const hasPluginRewrites = pluginHost.rewrites.length > 0
@@ -153,7 +152,7 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
153
152
  const mod = modules[entry.file] as Record<string, unknown> | undefined
154
153
  const act = mod?.[entry.exportName]
155
154
  if (isServerAction(act))
156
- actions.register(act, entry.url, entry.middlewares.map(m => (modules[m] as LoadedMiddlewareModule).default), middlewaresFor(entry.url))
155
+ actions.register(act, entry.exportName, entry.url, entry.middlewares.map(m => (modules[m] as LoadedMiddlewareModule).default), middlewaresFor(entry.url))
157
156
  }
158
157
 
159
158
  const { all: prerenderedMap, fast: fastPrerenderedMap } = files.collectPrerendered(manifest.routes, {
@@ -273,7 +272,7 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
273
272
  () => ssrChild(mod.default!(pageProps) as Html),
274
273
  pickPageIslandProps(data, entry, mod),
275
274
  entry.islandHydrate as HydrateStrategy | undefined,
276
- true,
275
+ true, mod.default!.name,
277
276
  ), request, url, locals, cookieStore, ctx)
278
277
  }
279
278
  const rendered = mod.default!(pageProps)
@@ -290,7 +289,7 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
290
289
  const { ctx, cookieStore } = makeRequestContext(request, {}, { trustProxy, remoteIp, url })
291
290
  return (async () => {
292
291
  try {
293
- const loaded = await mod.load!(ctx)
292
+ const loaded = await actions.run(ctx, () => mod.load!(ctx))
294
293
  if (isNotFound(loaded))
295
294
  return finish(await buildNotFoundResponse(url, request, ctx), request, cookieStore)
296
295
  if (loaded instanceof Response)
@@ -391,7 +390,7 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
391
390
  () => ssrChild(mod.default!(pageProps) as Html),
392
391
  pickPageIslandProps(data, entry, mod),
393
392
  entry.islandHydrate as HydrateStrategy | undefined,
394
- true,
393
+ true, mod.default!.name,
395
394
  )
396
395
  }
397
396
  else {
@@ -479,7 +478,7 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
479
478
  const { act, middlewares } = actionHandler
480
479
  const { ctx, cookieStore } = makeRequestContext(req, {}, { trustProxy, remoteIp, url })
481
480
  try {
482
- return finish(await runChain(ctx, middlewares, () => executeAction(act, req, ctx, trustedOrigins, trustProxy)), req, cookieStore)
481
+ return finish(await actions.run(ctx, () => runChain(ctx, middlewares, () => executeAction(act, req, ctx, trustedOrigins, trustProxy))), req, cookieStore)
483
482
  }
484
483
  catch (error) {
485
484
  notifyError(error, req, 'action')
@@ -523,12 +522,12 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
523
522
  }
524
523
  ctx.params = pluginMatch.params
525
524
  try {
526
- let res = await runChain(ctx, pluginHost.allMiddlewares, () => routeDef.handler(ctx))
525
+ let res = await actions.run(ctx, () => runChain(ctx, pluginHost.allMiddlewares, () => routeDef.handler(ctx)))
527
526
  if (headFallbackPluginDef !== undefined)
528
527
  res = stripHeadBody(res)
529
528
  else if (isEventStream(res))
530
529
  disableTimeout?.()
531
- return finish(await maybeCompressResponse(res, req, compressCache), req, cookieStore)
530
+ return finish(await maybeCompressResponse(await withPluginHtmlCsp(res, htmlHeaders), req, compressCache), req, cookieStore)
532
531
  }
533
532
  catch (error) {
534
533
  notifyError(error, req, 'plugin')
@@ -565,7 +564,7 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
565
564
  }
566
565
 
567
566
  try {
568
- const res = await runChain(ctx, route.middlewares, () => renderCompiledRoute(route, ctx, disableTimeout))
567
+ const res = await actions.run(ctx, () => runChain(ctx, route.middlewares, () => renderCompiledRoute(route, ctx, disableTimeout)))
569
568
  if (isEventStream(res))
570
569
  disableTimeout?.()
571
570
  // Compress uncompressed API/middleware responses after the middleware chain unwinds.
@@ -0,0 +1,22 @@
1
+ // Graceful stop for `kay start` and compiled binaries; `kay dev` keeps its own.
2
+
3
+ import type { KayApp } from './http'
4
+
5
+ const SIGNALS = ['SIGTERM', 'SIGINT', 'SIGHUP'] as const
6
+
7
+ // On the first signal the server stops taking connections and the app's onShutdown hooks run; the process exits 0 once the open requests finish, or 1 after `timeoutMs`, which closes what is left.
8
+ export function handleSignals(app: KayApp, server: ReturnType<KayApp['serve']>, { timeoutMs = 10_000 } = {}): void {
9
+ const stop = async (): Promise<void> => {
10
+ const forced = setTimeout(() => {
11
+ console.error(`kay: requests still open after ${timeoutMs} ms; closing them`)
12
+ process.exit(1)
13
+ }, timeoutMs)
14
+ const drained = server.stop()
15
+ await app.dispose?.()
16
+ await drained
17
+ clearTimeout(forced)
18
+ process.exit(0)
19
+ }
20
+ for (const signal of SIGNALS)
21
+ process.once(signal, () => void stop())
22
+ }
@@ -33,7 +33,6 @@ export interface ServerPluginHostOptions {
33
33
  trustProxy: TrustProxy
34
34
  trustedOriginsList: readonly string[]
35
35
  trustedOrigins: Set<string> | undefined
36
- invokeAction: ServerPluginAPI['invokeAction']
37
36
  }
38
37
 
39
38
  function middlewareAppliesToPath(scope: ScopedMiddleware['scope'], path: string, isStaticFast: boolean): boolean {
@@ -59,7 +58,7 @@ export function allowedPluginMethodsHeader(methods: ReadonlyMap<string, PluginRo
59
58
  export async function createServerPluginHost(options: ServerPluginHostOptions) {
60
59
  const { plugins, config, manifest, appCtx, trustedOrigins, trustProxy } = options
61
60
  const scopedMiddlewares: ScopedMiddleware[] = []
62
- const shutdownHooks: (() => void | Promise<void>)[] = []
61
+ const shutdownHooks: { plugin: string, hook: () => void | Promise<void> }[] = []
63
62
  const rewrites: ((pathname: string, ctx: RequestContext) => string | undefined)[] = []
64
63
  const router = new Router<Map<string, PluginRouteDef>>()
65
64
  const routeEntries = new Map<string, Map<string, PluginRouteDef>>()
@@ -102,8 +101,6 @@ export async function createServerPluginHost(options: ServerPluginHostOptions) {
102
101
  const readonlyRuntimeConfig: Readonly<Record<string, unknown>> = Object.freeze({ ...forwardedConfig })
103
102
 
104
103
  for (const plugin of plugins) {
105
- if (plugin.dispose !== undefined)
106
- shutdownHooks.push(() => plugin.dispose!())
107
104
  if (plugin.server !== undefined) {
108
105
  const pluginApi: ServerPluginAPI = {
109
106
  root: options.root,
@@ -127,9 +124,8 @@ export async function createServerPluginHost(options: ServerPluginHostOptions) {
127
124
  return manifest.pluginData?.[pluginName ?? plugin.name] as T | undefined
128
125
  },
129
126
  onShutdown(fn) {
130
- shutdownHooks.push(fn)
127
+ shutdownHooks.push({ plugin: plugin.name, hook: fn })
131
128
  },
132
- invokeAction: options.invokeAction,
133
129
  }
134
130
  await runWithAppContext(appCtx, () => plugin.server!(pluginApi))
135
131
  }
@@ -153,11 +149,13 @@ export async function createServerPluginHost(options: ServerPluginHostOptions) {
153
149
  if (disposed)
154
150
  return
155
151
  disposed = true
156
- for (const hook of shutdownHooks) {
152
+ for (const { plugin, hook } of shutdownHooks) {
157
153
  try {
158
154
  await hook()
159
155
  }
160
- catch {}
156
+ catch (error) {
157
+ console.error(`kay: the onShutdown hook of ${plugin} threw; the other hooks still run.`, error)
158
+ }
161
159
  }
162
160
  }
163
161
 
@@ -0,0 +1,15 @@
1
+ // `@kayjs/kay/server`: what an app's routes, actions and middleware use, and `createServer` to run a built app inside another program. Anything not listed here stays internal.
2
+
3
+ export { action, getActionError } from './action'
4
+ export type { ActionContext, ActionErrorFlash, ActionOptions, ActionResult, ServerAction } from './action'
5
+ export type { CookieOptions, Cookies } from './cookies'
6
+ export { defineEnv, nodeEnv } from './env'
7
+ export { notFound } from './http'
8
+ export type { ExtractRouteParams, KayApp, LayoutProps, LoaderData, LoaderFn, Middleware, NotFoundResult, PageProps, RequestContext, RouteContext, ServerOptions } from './http'
9
+ export type { KayLocals } from './index'
10
+ export { createServer } from './loader'
11
+ export { getClientIp, isHttpsRequest, isTrustedOrigin, verifyOrigin } from './security'
12
+ export type { SecurityHeadersOptions, TrustProxy } from './security'
13
+ export { formatIssuePath, formatSchemaIssues, validateSchema, validateSchemaSync } from './standard-schema'
14
+ export type { InferInput, InferOutput, StandardSchemaIssue, StandardSchemaV1, ValidationFailure, ValidationResult, ValidationSuccess } from './standard-schema'
15
+ export { esc, escAttr, raw } from '../ssr/index'
@@ -0,0 +1,22 @@
1
+ // The request a server action called from server code runs in, entered by the action registry on the dynamic path only.
2
+
3
+ import type { ActionRegistry } from './action-registry'
4
+ import type { RequestContext } from './http'
5
+ import { AsyncLocalStorage } from 'node:async_hooks'
6
+
7
+ export interface RequestScope {
8
+ ctx: RequestContext
9
+ actions: ActionRegistry
10
+ }
11
+
12
+ const STORAGE_KEY = Symbol.for('kay.requestScope')
13
+ // One storage per process: a test's own copy of kay and the app's bundled one must see the same request.
14
+ const storage: AsyncLocalStorage<RequestScope> = ((globalThis as Record<symbol, AsyncLocalStorage<RequestScope> | undefined>)[STORAGE_KEY] ??= new AsyncLocalStorage<RequestScope>())
15
+
16
+ export function runInRequest<T>(scope: RequestScope, fn: () => T): T {
17
+ return storage.run(scope, fn)
18
+ }
19
+
20
+ export function currentRequest(): RequestScope | undefined {
21
+ return storage.getStore()
22
+ }
@@ -7,7 +7,8 @@ const textEncoder = new TextEncoder()
7
7
  // Where a streamed page's document splits: everything before it flushes first, resolved boundaries go in between.
8
8
  export const STREAM_TAIL_MARK = '<!--kay:stream-tail-->'
9
9
 
10
- async function settleWithin(chunk: PendingChunk, deadlineMs: number, signal: AbortSignal): Promise<SettledChunk | undefined> {
10
+ /** `streamTimeout` is only named in the error: the page's boundaries share one `deadlineMs`. */
11
+ async function settleWithin(chunk: PendingChunk, deadlineMs: number, streamTimeout: number, signal: AbortSignal): Promise<SettledChunk | undefined> {
11
12
  if (signal.aborted)
12
13
  return undefined
13
14
  const remaining = Math.max(0, deadlineMs - Date.now())
@@ -17,7 +18,7 @@ async function settleWithin(chunk: PendingChunk, deadlineMs: number, signal: Abo
17
18
  signal.addEventListener('abort', onAbort, { once: true })
18
19
  timer = setTimeout(() => {
19
20
  signal.removeEventListener('abort', onAbort)
20
- const error = new Error(`<Suspense> boundary ${chunk.id} did not resolve within ${remaining} ms`)
21
+ const error = new Error(`<Suspense> boundary ${chunk.id} did not resolve within ${streamTimeout} ms`)
21
22
  resolve({ html: chunk.renderError(error), error })
22
23
  }, remaining)
23
24
  })
@@ -67,7 +68,7 @@ export function streamDocument(shell: string, rctx: RenderContext, streamTimeout
67
68
  const chunks = rctx.pending.slice(flushed)
68
69
  flushed = rctx.pending.length
69
70
  await Promise.all(chunks.map(async (chunk) => {
70
- const settled = await settleWithin(chunk, deadline, abortCtrl.signal)
71
+ const settled = await settleWithin(chunk, deadline, streamTimeout, abortCtrl.signal)
71
72
  if (settled === undefined || closed || abortCtrl.signal.aborted)
72
73
  return
73
74
  if ('error' in settled)
@@ -28,6 +28,10 @@ export interface RenderContext {
28
28
  idPrefix: string
29
29
  idSeq: number
30
30
  contexts: Map<symbol, unknown>
31
+ /** While an island renders, the contexts provided outside it, which the browser never sees. */
32
+ outerContexts: Map<symbol, unknown> | undefined
33
+ /** The island rendering, as its tag. */
34
+ island: string | undefined
31
35
  /** Maps island chunk URL -> eager (true if hydrate is undefined/'load'). */
32
36
  renderedIslands: Map<string, boolean>
33
37
  hasIslands: boolean
@@ -42,6 +46,8 @@ registerServerContextBridge({
42
46
  const ctx = renderStorage.getStore()
43
47
  if (ctx !== undefined && ctx.contexts.has(key))
44
48
  return { found: true, value: ctx.contexts.get(key) }
49
+ if (ctx?.outerContexts?.has(key) === true)
50
+ throw new Error(`kay: <${ctx.island}> reads a context provided outside the island, which the browser never sees; pass its value as a prop.`)
45
51
  return undefined
46
52
  },
47
53
  runWithContext<T>(key: symbol, value: unknown, fn: () => T): T {
@@ -86,12 +92,31 @@ export function createRenderContext(): RenderContext {
86
92
  idPrefix: '',
87
93
  idSeq: 0,
88
94
  contexts: new Map(),
95
+ outerContexts: undefined,
96
+ island: undefined,
89
97
  renderedIslands: new Map(),
90
98
  hasIslands: false,
91
99
  htmlAttrs: {},
92
100
  }
93
101
  }
94
102
 
103
+ // An island sees only the contexts provided inside it, as in the browser.
104
+ export function renderIsland(ctx: RenderContext, name: string, render: () => string): string {
105
+ const outer = ctx.contexts
106
+ ctx.contexts = new Map()
107
+ ctx.outerContexts = outer
108
+ ctx.island = name
109
+ try {
110
+ return render()
111
+ }
112
+ finally {
113
+ ctx.contexts = outer
114
+ ctx.outerContexts = undefined
115
+ ctx.island = undefined
116
+ }
117
+ }
118
+
119
+
95
120
  export function runWithRenderContext<T>(ctx: RenderContext, fn: () => T): T {
96
121
  return renderStorage.run(ctx, fn)
97
122
  }
package/src/ssr/index.ts CHANGED
@@ -4,7 +4,7 @@ import type { Html, HydrateStrategy, KayChild } from '../jsx-runtime'
4
4
  import { isBlockedAttr, isStringBoolAttr, isUnsafeUrlAttr } from '../attrs'
5
5
  import { styleText } from '../style'
6
6
  import { assertRenderable } from '../unrenderable'
7
- import { currentRenderContext, KAY_STREAM_SCRIPT } from './context'
7
+ import { currentRenderContext, KAY_STREAM_SCRIPT, renderIsland } from './context'
8
8
 
9
9
  export const KAY_ISLAND_STYLE = 'kay-island,kay-slot{display:contents}'
10
10
  export const KAY_SUSPENSE_STYLE = 'kay-s{display:contents}'
@@ -213,14 +213,14 @@ export function recordRenderedIsland(chunk: string, hydrate?: HydrateStrategy):
213
213
  ctx.renderedIslands.set(chunk, false)
214
214
  }
215
215
 
216
- export function ssrInIsland(render: () => string, chunk?: string, hydrate?: HydrateStrategy): string {
216
+ export function ssrInIsland(render: () => string, chunk?: string, hydrate?: HydrateStrategy, name = 'island'): string {
217
217
  const ctx = currentRenderContext()
218
218
  if (ctx !== undefined) {
219
219
  if (chunk !== undefined && ctx.islandDepth === 0)
220
220
  recordRenderedIsland(chunk, hydrate)
221
221
  ctx.islandDepth++
222
222
  try {
223
- return render()
223
+ return ctx.islandDepth === 1 ? renderIsland(ctx, name, render) : render()
224
224
  }
225
225
  finally {
226
226
  ctx.islandDepth--
@@ -235,6 +235,7 @@ export function ssrInIsland(render: () => string, chunk?: string, hydrate?: Hydr
235
235
  }
236
236
  }
237
237
 
238
+
238
239
  /** Lazily evaluates non-async component children on first read inside the component's dynamic context, memoizing the result. */
239
240
  export function ssrChildProp<P extends Record<string, unknown>>(props: P, fn: () => Html): P {
240
241
  let cached: Html | undefined
@@ -257,6 +258,7 @@ export function ssrIslandStatic(
257
258
  openTag: string,
258
259
  render: (() => string) | undefined,
259
260
  hydrate?: HydrateStrategy,
261
+ name?: string,
260
262
  ): string {
261
263
  if (getIslandDepth() > 0)
262
264
  return render !== undefined ? render() : ''
@@ -275,7 +277,7 @@ export function ssrIslandStatic(
275
277
  ctx.idPrefix = islandPrefix
276
278
  ctx.idSeq = 0
277
279
  try {
278
- inner = ssrInIsland(render)
280
+ inner = ssrInIsland(render, undefined, undefined, name)
279
281
  if (ctx.idSeq > 0)
280
282
  idAttr = ` i="${islandPrefix}"`
281
283
  }
@@ -285,7 +287,7 @@ export function ssrIslandStatic(
285
287
  }
286
288
  }
287
289
  else {
288
- inner = ssrInIsland(render)
290
+ inner = ssrInIsland(render, undefined, undefined, name)
289
291
  }
290
292
  }
291
293
 
@@ -303,6 +305,7 @@ export function ssrIsland(
303
305
  props: Record<string, unknown>,
304
306
  hydrate?: HydrateStrategy,
305
307
  scriptProps = false,
308
+ name?: string,
306
309
  ): string {
307
310
  if (getIslandDepth() > 0)
308
311
  return render()
@@ -334,7 +337,7 @@ export function ssrIsland(
334
337
  ctx.idPrefix = islandPrefix
335
338
  ctx.idSeq = 0
336
339
  try {
337
- inner = ssrInIsland(render)
340
+ inner = ssrInIsland(render, undefined, undefined, name)
338
341
  if (ctx.idSeq > 0)
339
342
  idAttr = ` i="${islandPrefix}"`
340
343
  }
@@ -344,7 +347,7 @@ export function ssrIsland(
344
347
  }
345
348
  }
346
349
  else {
347
- inner = ssrInIsland(render)
350
+ inner = ssrInIsland(render, undefined, undefined, name)
348
351
  }
349
352
  }
350
353