@kayjs/kay 2.0.0-beta.1 → 2.0.0-beta.2
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.
- package/package.json +1 -1
- package/src/build/bundle.ts +206 -33
- package/src/build/compile.ts +25 -12
- package/src/build/files.ts +38 -0
- package/src/build/graph.ts +67 -2
- package/src/build/index.ts +57 -7
- package/src/build/manifest.ts +3 -0
- package/src/build/plugin-host.ts +2 -0
- package/src/build/prerender.ts +2 -1
- package/src/build/resolve.ts +11 -18
- package/src/build/routes.ts +33 -5
- package/src/cli/check.ts +102 -45
- package/src/cli/new.ts +6 -7
- package/src/compiler/analyze.ts +65 -10
- package/src/compiler/dom.ts +143 -122
- package/src/compiler/server-only.ts +14 -8
- package/src/compiler/shared.ts +57 -14
- package/src/compiler/ssr.ts +14 -12
- package/src/dev/index.ts +94 -8
- package/src/dom/action.ts +91 -1
- package/src/dom/index.ts +8 -3
- package/src/index.ts +3 -0
- package/src/jsx-runtime.ts +421 -93
- package/src/plugins/context.ts +26 -0
- package/src/plugins/index.ts +174 -8
- package/src/server/action.ts +15 -8
- package/src/server/compress.ts +87 -14
- package/src/server/http.ts +89 -30
- package/src/server/index.ts +191 -62
- package/src/server/loader.ts +53 -35
- package/src/server/router.ts +49 -20
- package/src/server/security.ts +4 -2
- package/src/test/index.ts +5 -16
package/src/server/index.ts
CHANGED
|
@@ -7,8 +7,8 @@
|
|
|
7
7
|
|
|
8
8
|
import type { BuildManifest, RouteManifestEntry } from '../build/index'
|
|
9
9
|
import type { Html, HydrateStrategy } from '../jsx-runtime'
|
|
10
|
-
import type { KayPlugin, MiddlewareOptions, PluginRouteOptions, ServerErrorInfo, ServerPluginAPI } from '../plugins/index'
|
|
11
|
-
import type { PendingChunk, SettledChunk } from '../ssr/context'
|
|
10
|
+
import type { DocumentHeadContext, KayPlugin, MiddlewareOptions, PluginRouteOptions, ServerErrorInfo, ServerPluginAPI } from '../plugins/index'
|
|
11
|
+
import type { PendingChunk, RenderContext, SettledChunk } from '../ssr/context'
|
|
12
12
|
import type { DocumentOptions } from '../ssr/index'
|
|
13
13
|
import type { ActionErrorFlash, ActionResult, ServerAction } from './action'
|
|
14
14
|
import type { CookieStore } from './cookies'
|
|
@@ -16,25 +16,31 @@ import type { EmbeddedBody, EmbeddedServerConfig, KayApp, Middleware, RequestCon
|
|
|
16
16
|
import type { TrustProxy } from './security'
|
|
17
17
|
import { existsSync, statSync } from 'node:fs'
|
|
18
18
|
import { extname, join } from 'node:path'
|
|
19
|
-
import { createAppContext, getAppContext, runWithAppContext } from '../plugins/index'
|
|
20
|
-
import { createRenderContext,
|
|
19
|
+
import { createAppContext, getAppContext, resolvePlugins, runWithAppContext } from '../plugins/index'
|
|
20
|
+
import { createRenderContext, runWithRenderContext, streamChunkScript } from '../ssr/context'
|
|
21
21
|
import { raw, renderDocument, ssrChild, ssrIsland } from '../ssr/index'
|
|
22
22
|
import { ACTION_ERROR_COOKIE, executeAction, invokeActionCore, isServerAction } from './action'
|
|
23
23
|
import { CompressionCache, compressedHtmlResponse, isCompressibleType, maybeCompressResponse, pickEncoding, pickPrecompressedEncoding, toWeakEtag } from './compress'
|
|
24
|
-
import { applyHstsHeader, DEFAULT_MAX_REQUEST_BODY_SIZE, enforceRequestBodyLimit, etagMatches, extractRenderedIslands, finalizeResponse, makeRequestContext, MIME, wantsJson } from './http'
|
|
24
|
+
import { applyHstsHeader, DEFAULT_MAX_REQUEST_BODY_SIZE, enforceRequestBodyLimit, etagMatches, extractRenderedIslands, finalizeResponse, isNotFound, makeRequestContext, MIME, wantsJson } from './http'
|
|
25
25
|
import { Router } from './router'
|
|
26
26
|
import { buildSecurityHeaderEntries, KAY_ISLAND_STYLE_HASH, KAY_STREAM_SCRIPT_HASH, KAY_SUSPENSE_STYLE_HASH, resolveCspPolicy, resolveHstsValue, verifyOrigin, withCspHashes } from './security'
|
|
27
27
|
|
|
28
|
-
|
|
29
|
-
|
|
28
|
+
/**
|
|
29
|
+
* Request-scoped locals bag shared across middlewares, plugins, actions, layouts, and pages.
|
|
30
|
+
* Augment via `declare module '@kayjs/kay/server' { interface KayLocals { ... } }`.
|
|
31
|
+
*/
|
|
32
|
+
export interface KayLocals {}
|
|
33
|
+
|
|
34
|
+
export { CONTENT_IMAGE_RESOLVER_SERVICE, createAppContext, defineConfig, definePlugin, getAppContext, I18N_CONFIG_SERVICE, loadConfig, pickRuntimeConfig, resolvePlugins, resolveServerConfig, runWithAppContext } from '../plugins/index'
|
|
35
|
+
export type { ActiveI18nConfig, AppRuntimeContext, BuildPluginContext, BuildPluginTarget, CheckPluginContext, ContentImageResolver, ContentImageResult, CreateAppContextOptions, DocumentHeadContext, FinalizeBuildContext, KayConfig, KayPlugin, MiddlewareOptions, PluginRouteOptions, ServerErrorInfo, ServerPluginAPI, ServerRuntimeConfig } from '../plugins/index'
|
|
30
36
|
export { action, getActionError } from './action'
|
|
31
37
|
export type { ActionContext, ActionErrorFlash, ActionOptions, ActionResult, ServerAction } from './action'
|
|
32
38
|
export { CompressionCache, isCompressibleType, pickEncoding, pickPrecompressedEncoding, toWeakEtag } from './compress'
|
|
33
39
|
export type { CompressionEncoding, PrecompressedEncoding } from './compress'
|
|
34
40
|
export type { CookieOptions, Cookies } from './cookies'
|
|
35
41
|
export { defineEnv, nodeEnv } from './env'
|
|
36
|
-
export { DEFAULT_MAX_REQUEST_BODY_SIZE } from './http'
|
|
37
|
-
export type { EmbeddedServerConfig, KayApp, Middleware, RequestContext, ServerOptions } from './http'
|
|
42
|
+
export { DEFAULT_MAX_REQUEST_BODY_SIZE, notFound } from './http'
|
|
43
|
+
export type { EmbeddedServerConfig, ExtractRouteParams, KayApp, LayoutProps, LoaderData, LoaderFn, Middleware, NotFoundResult, PageProps, RequestContext, RouteContext, ServerOptions } from './http'
|
|
38
44
|
export { createServer } from './loader'
|
|
39
45
|
export { DEFAULT_CSP, DEFAULT_HSTS, DEFAULT_PERMISSIONS_POLICY, getClientIp, isHttpsRequest, isTrustedOrigin, KAY_ISLAND_STYLE_HASH, KAY_STREAM_SCRIPT_HASH, KAY_SUSPENSE_STYLE_HASH, verifyOrigin, withCspHashes } from './security'
|
|
40
46
|
export type { SecurityHeadersOptions, TrustProxy } from './security'
|
|
@@ -57,7 +63,7 @@ interface LoadedPageModule {
|
|
|
57
63
|
}
|
|
58
64
|
|
|
59
65
|
interface LoadedLayoutModule {
|
|
60
|
-
default: (props: { children: Html, url?: URL, params?: Record<string, string>, locals?:
|
|
66
|
+
default: (props: { children: Html, url?: URL, params?: Record<string, string>, locals?: KayLocals }) => Html | string | Promise<Html | string>
|
|
61
67
|
}
|
|
62
68
|
|
|
63
69
|
interface LoadedMiddlewareModule {
|
|
@@ -203,9 +209,16 @@ function allowedPluginMethodsHeader(methods: ReadonlyMap<string, PluginRouteDef>
|
|
|
203
209
|
return [...allowed].join(', ')
|
|
204
210
|
}
|
|
205
211
|
|
|
212
|
+
async function cancelBodyQuietly(body: ReadableStream<Uint8Array>): Promise<void> {
|
|
213
|
+
try {
|
|
214
|
+
await body.cancel()
|
|
215
|
+
}
|
|
216
|
+
catch {}
|
|
217
|
+
}
|
|
218
|
+
|
|
206
219
|
function stripHeadBody(res: Response): Response {
|
|
207
220
|
if (res.body !== null)
|
|
208
|
-
void res.body
|
|
221
|
+
void cancelBodyQuietly(res.body)
|
|
209
222
|
return new Response(null, { status: res.status, statusText: res.statusText, headers: res.headers })
|
|
210
223
|
}
|
|
211
224
|
|
|
@@ -251,26 +264,6 @@ function pickPageIslandProps(data: unknown, entry: RouteManifestEntry, mod: Load
|
|
|
251
264
|
return { data }
|
|
252
265
|
}
|
|
253
266
|
|
|
254
|
-
function pickRootLayoutFile(manifest: BuildManifest): string | undefined {
|
|
255
|
-
// Prefer a layout attached to a root route (`/`) or shared at the shallowest directory depth.
|
|
256
|
-
const rootRoute = manifest.routes.find(r => r.path === '/' && r.layouts.length > 0)
|
|
257
|
-
if (rootRoute !== undefined)
|
|
258
|
-
return rootRoute.layouts[0]
|
|
259
|
-
let best: string | undefined
|
|
260
|
-
let bestDepth = Number.POSITIVE_INFINITY
|
|
261
|
-
for (const r of manifest.routes) {
|
|
262
|
-
const first = r.layouts[0]
|
|
263
|
-
if (first === undefined)
|
|
264
|
-
continue
|
|
265
|
-
const depth = first.split('/').length
|
|
266
|
-
if (depth < bestDepth) {
|
|
267
|
-
bestDepth = depth
|
|
268
|
-
best = first
|
|
269
|
-
}
|
|
270
|
-
}
|
|
271
|
-
return best
|
|
272
|
-
}
|
|
273
|
-
|
|
274
267
|
function middlewareAppliesToPath(scope: ScopedMiddleware['scope'], path: string, isStaticFast: boolean): boolean {
|
|
275
268
|
if (scope === 'all')
|
|
276
269
|
return true
|
|
@@ -280,8 +273,10 @@ function middlewareAppliesToPath(scope: ScopedMiddleware['scope'], path: string,
|
|
|
280
273
|
}
|
|
281
274
|
|
|
282
275
|
export async function createServerFromEmbedded(config: EmbeddedServerConfig): Promise<KayApp> {
|
|
283
|
-
const { manifest, modules, assets, publicAssets = {}, publicEtags = {}, prerendered, prerenderedFiles = {}, lang = 'en', security
|
|
276
|
+
const { manifest, modules, assets, publicAssets = {}, publicEtags = {}, prerendered = {}, prerenderedFiles = {}, lang = 'en', security } = config
|
|
277
|
+
const plugins = resolvePlugins(config.plugins)
|
|
284
278
|
const assetPrefix = (config.assetPrefix ?? '/_kay').replace(/\/$/, '')
|
|
279
|
+
const site = config.site?.replace(/\/$/, '') || undefined
|
|
285
280
|
const trustedOriginsList = config.trustedOrigins ?? []
|
|
286
281
|
const trustedOrigins = trustedOriginsList.length > 0 ? new Set(trustedOriginsList) : undefined
|
|
287
282
|
const trustProxy = config.trustProxy ?? false
|
|
@@ -294,6 +289,9 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
|
|
|
294
289
|
const parentAppCtx = getAppContext()
|
|
295
290
|
|
|
296
291
|
const alwaysLoadRuntime = plugins.some(p => Boolean(p.clientEntry))
|
|
292
|
+
const headHooks = plugins
|
|
293
|
+
.map(p => p.head)
|
|
294
|
+
.filter((fn): fn is NonNullable<KayPlugin['head']> => typeof fn === 'function')
|
|
297
295
|
const htmlTransformers = plugins
|
|
298
296
|
.map(p => p.transformHtml)
|
|
299
297
|
.filter((fn): fn is NonNullable<KayPlugin['transformHtml']> => typeof fn === 'function')
|
|
@@ -365,6 +363,7 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
|
|
|
365
363
|
outDir: serverOutDir,
|
|
366
364
|
publicDir: serverPublicDir,
|
|
367
365
|
assetPrefix,
|
|
366
|
+
site,
|
|
368
367
|
dev: isDev,
|
|
369
368
|
onRegisterPublicFile: (rel) => {
|
|
370
369
|
parentAppCtx?.registerPublicFile(rel)
|
|
@@ -437,10 +436,15 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
|
|
|
437
436
|
}
|
|
438
437
|
catch {}
|
|
439
438
|
}
|
|
439
|
+
let text = ''
|
|
440
|
+
try {
|
|
441
|
+
text = await res.clone().text()
|
|
442
|
+
}
|
|
443
|
+
catch {}
|
|
440
444
|
return {
|
|
441
445
|
ok: false,
|
|
442
446
|
status: res.status,
|
|
443
|
-
error:
|
|
447
|
+
error: text || res.statusText || 'Forbidden',
|
|
444
448
|
}
|
|
445
449
|
}
|
|
446
450
|
|
|
@@ -464,6 +468,7 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
|
|
|
464
468
|
root: serverRoot,
|
|
465
469
|
outDir: serverOutDir,
|
|
466
470
|
assetPrefix,
|
|
471
|
+
site,
|
|
467
472
|
dev: isDev,
|
|
468
473
|
trustProxy,
|
|
469
474
|
trustedOrigins: trustedOriginsList,
|
|
@@ -489,10 +494,20 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
|
|
|
489
494
|
}
|
|
490
495
|
}
|
|
491
496
|
|
|
492
|
-
const
|
|
493
|
-
|
|
494
|
-
|
|
497
|
+
const allPluginMiddlewares: readonly Middleware[] = scopedMiddlewares.map(m => m.mw)
|
|
498
|
+
const staticFastPluginMiddlewares: readonly Middleware[] = scopedMiddlewares
|
|
499
|
+
.filter(m => m.scope === 'all')
|
|
500
|
+
.map(m => m.mw)
|
|
501
|
+
const hasPathScopedMiddlewares = scopedMiddlewares.some(m => m.scope !== 'all' && m.scope !== 'dynamic')
|
|
502
|
+
const middlewaresFor = (path: string, isStaticFast = false): readonly Middleware[] => {
|
|
503
|
+
if (scopedMiddlewares.length === 0)
|
|
504
|
+
return allPluginMiddlewares
|
|
505
|
+
if (!hasPathScopedMiddlewares)
|
|
506
|
+
return isStaticFast ? staticFastPluginMiddlewares : allPluginMiddlewares
|
|
507
|
+
return scopedMiddlewares.filter(m => middlewareAppliesToPath(m.scope, path, isStaticFast)).map(m => m.mw)
|
|
508
|
+
}
|
|
495
509
|
const hasPluginRewrites = pluginRewrites.length > 0
|
|
510
|
+
const hasHeadHooks = headHooks.length > 0
|
|
496
511
|
const hasHtmlTransformers = htmlTransformers.length > 0
|
|
497
512
|
|
|
498
513
|
const errorHooks: ((info: ServerErrorInfo) => void)[] = []
|
|
@@ -612,8 +627,8 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
|
|
|
612
627
|
const router = new Router<CompiledRoute>()
|
|
613
628
|
const fastStaticPages = new Map<string, FastHandler>()
|
|
614
629
|
|
|
615
|
-
// Error and 404 pages sit outside any route, so they render with the global styles and the
|
|
616
|
-
const rootLayoutFile =
|
|
630
|
+
// Error and 404 pages sit outside any route, so they render with the global styles and the explicit root layout only.
|
|
631
|
+
const rootLayoutFile = manifest.rootLayoutFile
|
|
617
632
|
const rootLayoutMod = rootLayoutFile !== undefined ? modules[rootLayoutFile] as LoadedLayoutModule | undefined : undefined
|
|
618
633
|
const fallbackDoc: DocumentOptions = {
|
|
619
634
|
body: '',
|
|
@@ -624,10 +639,88 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
|
|
|
624
639
|
lang,
|
|
625
640
|
}
|
|
626
641
|
|
|
642
|
+
const TITLE_INNER_RE = /^<title\b[^>]*>([\s\S]*?)<\/title>$/i
|
|
643
|
+
|
|
644
|
+
async function resolveDocumentHead(
|
|
645
|
+
rctx: RenderContext,
|
|
646
|
+
baseHeadTags: readonly string[] | undefined,
|
|
647
|
+
url: URL,
|
|
648
|
+
req?: Request,
|
|
649
|
+
ctx?: RequestContext,
|
|
650
|
+
): Promise<{ head: string, lang: string, htmlAttrs: Record<string, string> }> {
|
|
651
|
+
const collectedParts = rctx.headParts.join('')
|
|
652
|
+
if (!hasHeadHooks) {
|
|
653
|
+
return {
|
|
654
|
+
head: (rctx.title ?? '') + collectedParts,
|
|
655
|
+
lang,
|
|
656
|
+
htmlAttrs: rctx.htmlAttrs,
|
|
657
|
+
}
|
|
658
|
+
}
|
|
659
|
+
|
|
660
|
+
const headCtx = ctx ?? makeRequestContext(req ?? new Request(url.toString()), {}, { trustProxy, url }).ctx
|
|
661
|
+
const htmlAttrs: Record<string, string> = { ...rctx.htmlAttrs }
|
|
662
|
+
const initialTitleTag = rctx.title
|
|
663
|
+
const initialTitleInner = initialTitleTag !== undefined ? TITLE_INNER_RE.exec(initialTitleTag)?.[1] : undefined
|
|
664
|
+
let currentTitle = initialTitleInner
|
|
665
|
+
let titleDirty = false
|
|
666
|
+
let currentLang = htmlAttrs.lang ?? lang
|
|
667
|
+
let headBuf = (initialTitleTag ?? '') + collectedParts
|
|
668
|
+
if (baseHeadTags !== undefined) {
|
|
669
|
+
for (let i = 0; i < baseHeadTags.length; i++)
|
|
670
|
+
headBuf += baseHeadTags[i]
|
|
671
|
+
}
|
|
672
|
+
const added: string[] = []
|
|
673
|
+
|
|
674
|
+
const docHead: DocumentHeadContext = {
|
|
675
|
+
get lang() {
|
|
676
|
+
return currentLang
|
|
677
|
+
},
|
|
678
|
+
set lang(v: string) {
|
|
679
|
+
currentLang = v
|
|
680
|
+
htmlAttrs.lang = v
|
|
681
|
+
},
|
|
682
|
+
htmlAttrs,
|
|
683
|
+
get title() {
|
|
684
|
+
return currentTitle
|
|
685
|
+
},
|
|
686
|
+
set title(v: string | undefined) {
|
|
687
|
+
currentTitle = v
|
|
688
|
+
titleDirty = true
|
|
689
|
+
},
|
|
690
|
+
get headHtml() {
|
|
691
|
+
return headBuf
|
|
692
|
+
},
|
|
693
|
+
add(html: string) {
|
|
694
|
+
if (html !== '') {
|
|
695
|
+
added.push(html)
|
|
696
|
+
headBuf += html
|
|
697
|
+
}
|
|
698
|
+
},
|
|
699
|
+
}
|
|
700
|
+
|
|
701
|
+
for (const hook of headHooks) {
|
|
702
|
+
try {
|
|
703
|
+
await hook(docHead, headCtx)
|
|
704
|
+
}
|
|
705
|
+
catch (err) {
|
|
706
|
+
notifyError(err, req ?? headCtx.request, 'plugin')
|
|
707
|
+
}
|
|
708
|
+
}
|
|
709
|
+
|
|
710
|
+
const titleHtml = titleDirty
|
|
711
|
+
? (currentTitle !== undefined ? `<title>${currentTitle}</title>` : '')
|
|
712
|
+
: (initialTitleTag ?? '')
|
|
713
|
+
return {
|
|
714
|
+
head: titleHtml + collectedParts + (added.length > 0 ? added.join('') : ''),
|
|
715
|
+
lang: currentLang,
|
|
716
|
+
htmlAttrs,
|
|
717
|
+
}
|
|
718
|
+
}
|
|
719
|
+
|
|
627
720
|
async function applyHtmlTransforms(html: string, url: URL, req?: Request, ctx?: RequestContext): Promise<string> {
|
|
628
721
|
if (!hasHtmlTransformers)
|
|
629
722
|
return html
|
|
630
|
-
const transformCtx = ctx ?? makeRequestContext(req ?? new Request(url.toString()), {}, { trustProxy }).ctx
|
|
723
|
+
const transformCtx = ctx ?? makeRequestContext(req ?? new Request(url.toString()), {}, { trustProxy, url }).ctx
|
|
631
724
|
let out = html
|
|
632
725
|
for (const transform of htmlTransformers) {
|
|
633
726
|
try {
|
|
@@ -667,11 +760,13 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
|
|
|
667
760
|
return inner
|
|
668
761
|
})
|
|
669
762
|
const { hasIslands, eagerChunks } = resolveRenderedIslands(rctx, body)
|
|
763
|
+
const docHead = await resolveDocumentHead(rctx, manifest.headTags, effUrl, req, ctx)
|
|
670
764
|
const docHtml = renderDocument({
|
|
671
765
|
...fallbackDoc,
|
|
672
766
|
body,
|
|
673
|
-
head:
|
|
674
|
-
|
|
767
|
+
head: docHead.head,
|
|
768
|
+
lang: docHead.lang,
|
|
769
|
+
htmlAttrs: docHead.htmlAttrs,
|
|
675
770
|
preloadChunks: eagerChunks,
|
|
676
771
|
hasIslands,
|
|
677
772
|
})
|
|
@@ -728,6 +823,7 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
|
|
|
728
823
|
// Zero-overhead path for a static route with no middleware, no <Head>/<Suspense>, and no intercepting plugin hook
|
|
729
824
|
const canFastPath = fastPluginMiddlewares.length === 0
|
|
730
825
|
&& !hasPluginRewrites
|
|
826
|
+
&& !hasHeadHooks
|
|
731
827
|
&& !hasHtmlTransformers
|
|
732
828
|
&& pluginRouter.match(entry.path) === undefined
|
|
733
829
|
&& !dynamic
|
|
@@ -744,23 +840,32 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
|
|
|
744
840
|
const singleLayout = layouts.length === 1 ? layouts[0]! : undefined
|
|
745
841
|
const fastHeaders = htmlHeaders(hasIslands, false, true)
|
|
746
842
|
|
|
747
|
-
const fail = (error: unknown, request: Request, cookieStore?: CookieStore, ctx?: RequestContext): Promise<Response> => {
|
|
843
|
+
const fail = (error: unknown, request: Request, url: URL, cookieStore?: CookieStore, ctx?: RequestContext): Promise<Response> => {
|
|
748
844
|
notifyError(error, request, 'route')
|
|
749
|
-
return renderError(error, cookieStore,
|
|
845
|
+
return renderError(error, cookieStore, url, request, ctx)
|
|
750
846
|
}
|
|
751
847
|
const respondHtml = (body: string, request: Request, cookieStore?: CookieStore): Response => {
|
|
752
848
|
const res = compressedHtmlResponse(docPrefix + body + docSuffix, 200, fastHeaders, request, compressCache, !entry.hasLoad)
|
|
753
849
|
return cookieStore?.hasChanges ? finish(res, request, cookieStore) : withHsts(res, request)
|
|
754
850
|
}
|
|
755
|
-
const layoutProps = (inner: string, url: URL, locals:
|
|
851
|
+
const layoutProps = (inner: string, url: URL, locals: KayLocals) => ({ children: raw(inner), url, params: {}, locals })
|
|
756
852
|
|
|
757
|
-
const
|
|
853
|
+
const finishSingleLayout = async (wrapped: Promise<Html | string>, request: Request, url: URL, cookieStore?: CookieStore, ctx?: RequestContext): Promise<Response> => {
|
|
854
|
+
try {
|
|
855
|
+
return respondHtml(ssrChild(await wrapped as Html), request, cookieStore)
|
|
856
|
+
}
|
|
857
|
+
catch (error) {
|
|
858
|
+
return fail(error, request, url, cookieStore, ctx)
|
|
859
|
+
}
|
|
860
|
+
}
|
|
861
|
+
|
|
862
|
+
const wrapLayouts = (inner: string, request: Request, url: URL, locals: KayLocals, cookieStore?: CookieStore, ctx?: RequestContext): Response | Promise<Response> => {
|
|
758
863
|
if (layouts.length === 0)
|
|
759
864
|
return respondHtml(inner, request, cookieStore)
|
|
760
865
|
if (singleLayout !== undefined) {
|
|
761
866
|
const wrapped = singleLayout.default(layoutProps(inner, url, locals))
|
|
762
867
|
if (wrapped instanceof Promise)
|
|
763
|
-
return wrapped
|
|
868
|
+
return finishSingleLayout(wrapped, request, url, cookieStore, ctx)
|
|
764
869
|
return respondHtml(ssrChild(wrapped as Html), request, cookieStore)
|
|
765
870
|
}
|
|
766
871
|
return (async () => {
|
|
@@ -771,12 +876,21 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
|
|
|
771
876
|
return respondHtml(cur, request, cookieStore)
|
|
772
877
|
}
|
|
773
878
|
catch (error) {
|
|
774
|
-
return fail(error, request, cookieStore, ctx)
|
|
879
|
+
return fail(error, request, url, cookieStore, ctx)
|
|
775
880
|
}
|
|
776
881
|
})()
|
|
777
882
|
}
|
|
778
883
|
|
|
779
|
-
const
|
|
884
|
+
const finishAsyncPage = async (rendered: Promise<Html | string>, request: Request, url: URL, locals: KayLocals, cookieStore?: CookieStore, ctx?: RequestContext): Promise<Response> => {
|
|
885
|
+
try {
|
|
886
|
+
return await wrapLayouts(ssrChild(await rendered as Html), request, url, locals, cookieStore, ctx)
|
|
887
|
+
}
|
|
888
|
+
catch (error) {
|
|
889
|
+
return fail(error, request, url, cookieStore, ctx)
|
|
890
|
+
}
|
|
891
|
+
}
|
|
892
|
+
|
|
893
|
+
const renderPage = (data: unknown, request: Request, url: URL, locals: KayLocals, cookieStore?: CookieStore, ctx?: RequestContext): Response | Promise<Response> => {
|
|
780
894
|
const pageProps: Record<string, unknown> = { params: {}, locals, url, ...(data !== undefined ? { data } : {}) }
|
|
781
895
|
if (entry.isIsland && entry.islandChunk !== undefined) {
|
|
782
896
|
return wrapLayouts(ssrIsland(
|
|
@@ -789,7 +903,7 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
|
|
|
789
903
|
}
|
|
790
904
|
const rendered = mod.default!(pageProps)
|
|
791
905
|
if (rendered instanceof Promise)
|
|
792
|
-
return rendered
|
|
906
|
+
return finishAsyncPage(rendered, request, url, locals, cookieStore, ctx)
|
|
793
907
|
return wrapLayouts(ssrChild(rendered as Html), request, url, locals, cookieStore, ctx)
|
|
794
908
|
}
|
|
795
909
|
|
|
@@ -799,21 +913,24 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
|
|
|
799
913
|
return renderPage(undefined, request, url, {})
|
|
800
914
|
|
|
801
915
|
const { ctx, cookieStore } = makeRequestContext(request, {}, { trustProxy, remoteIp, url })
|
|
802
|
-
|
|
916
|
+
return (async () => {
|
|
803
917
|
try {
|
|
804
|
-
const loaded = await
|
|
918
|
+
const loaded = await mod.load!(ctx)
|
|
919
|
+
if (isNotFound(loaded))
|
|
920
|
+
return finish(await buildNotFoundResponse(url, request, ctx), request, cookieStore)
|
|
805
921
|
if (loaded instanceof Response)
|
|
806
922
|
return finish(loaded, request, cookieStore)
|
|
807
923
|
return await renderPage(loaded, request, url, ctx.locals, cookieStore, ctx)
|
|
808
924
|
}
|
|
809
925
|
catch (error) {
|
|
810
|
-
|
|
926
|
+
if (isNotFound(error))
|
|
927
|
+
return finish(await buildNotFoundResponse(url, request, ctx), request, cookieStore)
|
|
928
|
+
return fail(error, request, url, cookieStore, ctx)
|
|
811
929
|
}
|
|
812
|
-
}
|
|
813
|
-
return afterLoad(mod.load(ctx))
|
|
930
|
+
})()
|
|
814
931
|
}
|
|
815
932
|
catch (error) {
|
|
816
|
-
return fail(error, request)
|
|
933
|
+
return fail(error, request, url)
|
|
817
934
|
}
|
|
818
935
|
})
|
|
819
936
|
}
|
|
@@ -868,7 +985,19 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
|
|
|
868
985
|
}
|
|
869
986
|
}
|
|
870
987
|
|
|
871
|
-
|
|
988
|
+
let data: unknown
|
|
989
|
+
if (entry.hasLoad && typeof mod.load === 'function') {
|
|
990
|
+
try {
|
|
991
|
+
data = await mod.load(ctx)
|
|
992
|
+
}
|
|
993
|
+
catch (error) {
|
|
994
|
+
if (isNotFound(error))
|
|
995
|
+
return buildNotFoundResponse(ctx.url, ctx.request, ctx)
|
|
996
|
+
throw error
|
|
997
|
+
}
|
|
998
|
+
}
|
|
999
|
+
if (isNotFound(data))
|
|
1000
|
+
return buildNotFoundResponse(ctx.url, ctx.request, ctx)
|
|
872
1001
|
if (data instanceof Response)
|
|
873
1002
|
return data
|
|
874
1003
|
const pageProps: Record<string, unknown> = {
|
|
@@ -899,7 +1028,7 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
|
|
|
899
1028
|
}
|
|
900
1029
|
|
|
901
1030
|
const body = await runWithRenderContext(rctx, renderBody)
|
|
902
|
-
const
|
|
1031
|
+
const docHead = await resolveDocumentHead(rctx, doc.headTags as readonly string[] | undefined, ctx.url, ctx.request, ctx)
|
|
903
1032
|
const renderedIslands = resolveRenderedIslands(rctx, body)
|
|
904
1033
|
const isStreamed = rctx.pending.length > 0
|
|
905
1034
|
const hasIslands = renderedIslands.hasIslands || (isStreamed && entry.islandChunks.length > 0)
|
|
@@ -910,7 +1039,7 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
|
|
|
910
1039
|
if (ctx.request.method === 'HEAD')
|
|
911
1040
|
return new Response(null, { status: 200, headers: htmlHeaders(hasIslands, true, true) })
|
|
912
1041
|
disableTimeout?.()
|
|
913
|
-
let shell = renderDocument({ ...doc, body: body + STREAM_TAIL_MARK, head:
|
|
1042
|
+
let shell = renderDocument({ ...doc, body: body + STREAM_TAIL_MARK, head: docHead.head, lang: docHead.lang, htmlAttrs: docHead.htmlAttrs, preloadChunks, hasIslands, hasSuspense: true })
|
|
914
1043
|
// Transforms see the document with its initial body; boundaries resolved later stream as they render.
|
|
915
1044
|
for (const transform of htmlTransformers)
|
|
916
1045
|
shell = await transform(shell, ctx)
|
|
@@ -978,7 +1107,7 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
|
|
|
978
1107
|
return new Response(stream, { status: 200, headers: htmlHeaders(hasIslands, true, true) })
|
|
979
1108
|
}
|
|
980
1109
|
|
|
981
|
-
let html = renderDocument({ ...doc, body, head:
|
|
1110
|
+
let html = renderDocument({ ...doc, body, head: docHead.head, lang: docHead.lang, htmlAttrs: docHead.htmlAttrs, preloadChunks, hasIslands })
|
|
982
1111
|
for (const transform of htmlTransformers)
|
|
983
1112
|
html = await transform(html, ctx)
|
|
984
1113
|
|
|
@@ -1016,7 +1145,7 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
|
|
|
1016
1145
|
// Actions are origin-checked before their body is read and before any middleware runs.
|
|
1017
1146
|
const actionHandler = request.method === 'POST' ? registeredAction : undefined
|
|
1018
1147
|
if (actionHandler !== undefined) {
|
|
1019
|
-
const originCheck = verifyOrigin(request, trustedOrigins, trustProxy)
|
|
1148
|
+
const originCheck = verifyOrigin(request, trustedOrigins, trustProxy, url)
|
|
1020
1149
|
if (!originCheck.ok)
|
|
1021
1150
|
return refuseCrossSite(request, originCheck.reason)
|
|
1022
1151
|
}
|
|
@@ -1074,7 +1203,7 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
|
|
|
1074
1203
|
const routeDef = directPluginDef ?? headFallbackPluginDef
|
|
1075
1204
|
if (pluginMatch !== undefined && routeDef !== undefined) {
|
|
1076
1205
|
if (routeDef.csrf) {
|
|
1077
|
-
const originCheck = verifyOrigin(req, routeDef.trustedOrigins, routeDef.trustProxy)
|
|
1206
|
+
const originCheck = verifyOrigin(req, routeDef.trustedOrigins, routeDef.trustProxy, url)
|
|
1078
1207
|
if (!originCheck.ok)
|
|
1079
1208
|
return refuseCrossSite(req, originCheck.reason, cookieStore)
|
|
1080
1209
|
}
|
|
@@ -1116,7 +1245,7 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
|
|
|
1116
1245
|
|
|
1117
1246
|
// CSRF verification for file-based API routes on unsafe methods (opt out via `export const csrf = false`)
|
|
1118
1247
|
if (typeof route.mod[method] === 'function' && route.mod.csrf !== false) {
|
|
1119
|
-
const originCheck = verifyOrigin(req, trustedOrigins, trustProxy)
|
|
1248
|
+
const originCheck = verifyOrigin(req, trustedOrigins, trustProxy, url)
|
|
1120
1249
|
if (!originCheck.ok)
|
|
1121
1250
|
return refuseCrossSite(req, originCheck.reason, cookieStore)
|
|
1122
1251
|
}
|
package/src/server/loader.ts
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
// Filesystem server loader: reads `dist/manifest.json` (or falls back to `--static` dir server) and loads built modules.
|
|
2
2
|
|
|
3
3
|
import type { BuildManifest } from '../build/index'
|
|
4
|
+
import type { KayConfig } from '../plugins/index'
|
|
4
5
|
import type { EmbeddedBody, KayApp, ServerOptions } from './http'
|
|
5
6
|
import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'
|
|
6
7
|
import { join, resolve } from 'node:path'
|
|
7
|
-
import { loadConfig,
|
|
8
|
+
import { loadConfig, resolveServerConfig } from '../plugins/index'
|
|
8
9
|
import { createServerFromEmbedded } from './index'
|
|
9
10
|
import { createStaticDirServer } from './static-dir'
|
|
10
11
|
|
|
@@ -12,31 +13,61 @@ let serverLoadSeq = 0
|
|
|
12
13
|
|
|
13
14
|
export async function createServer(options: ServerOptions): Promise<KayApp> {
|
|
14
15
|
const root = resolve(options.root)
|
|
15
|
-
const
|
|
16
|
-
const
|
|
17
|
-
const outDir = resolve(root, options.outDir ?? fileConfig.outDir ?? 'dist')
|
|
18
|
-
const clientDir = join(outDir, 'client')
|
|
19
|
-
const manifestPath = join(outDir, 'manifest.json')
|
|
20
|
-
const securityOpt = options.security ?? fileConfig.security
|
|
21
|
-
const trustProxy = options.trustProxy ?? fileConfig.trustProxy ?? false
|
|
22
|
-
const maxRequestBodySize = options.maxRequestBodySize ?? fileConfig.maxRequestBodySize
|
|
16
|
+
const loadStamp = `${Date.now()}-${++serverLoadSeq}`
|
|
17
|
+
const importModule = options.importModule ?? ((path: string) => import(`${path}?v=${loadStamp}`))
|
|
23
18
|
const isDev = options.dev ?? (process.env.KAY_DEV === '1')
|
|
24
19
|
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
20
|
+
// When a bundled `manifest.configFile` exists and plugins were not explicitly overridden,
|
|
21
|
+
// load the bundled config module so it shares the exact same chunk instances as routes & actions.
|
|
22
|
+
const initialOutDir = resolve(root, options.outDir ?? 'dist')
|
|
23
|
+
const initialManifestPath = join(initialOutDir, 'manifest.json')
|
|
24
|
+
let fileConfig: KayConfig
|
|
25
|
+
let outDir: string
|
|
26
|
+
let manifest: BuildManifest
|
|
27
|
+
|
|
28
|
+
if (options.plugins === undefined && existsSync(initialManifestPath)) {
|
|
29
|
+
outDir = initialOutDir
|
|
30
|
+
manifest = JSON.parse(readFileSync(initialManifestPath, 'utf8')) as BuildManifest
|
|
31
|
+
if (manifest.configFile !== undefined) {
|
|
32
|
+
const cfgMod = await importModule(join(outDir, manifest.configFile))
|
|
33
|
+
const loaded = (cfgMod.default ?? cfgMod) as KayConfig | undefined
|
|
34
|
+
fileConfig = loaded !== undefined && typeof loaded === 'object' ? loaded : {}
|
|
35
|
+
}
|
|
36
|
+
else {
|
|
37
|
+
fileConfig = await loadConfig(root)
|
|
35
38
|
}
|
|
36
|
-
throw new Error(`kay server: missing ${manifestPath}. Run build() first.`)
|
|
37
39
|
}
|
|
40
|
+
else {
|
|
41
|
+
fileConfig = await loadConfig(root)
|
|
42
|
+
outDir = resolve(root, options.outDir ?? fileConfig.outDir ?? 'dist')
|
|
43
|
+
const manifestPath = join(outDir, 'manifest.json')
|
|
44
|
+
if (!existsSync(manifestPath)) {
|
|
45
|
+
const securityOpt = options.security ?? fileConfig.security
|
|
46
|
+
const trustProxy = options.trustProxy ?? fileConfig.trustProxy ?? false
|
|
47
|
+
if (existsSync(outDir) && readdirSync(outDir).length > 0) {
|
|
48
|
+
return createStaticDirServer(
|
|
49
|
+
outDir,
|
|
50
|
+
options.assetPrefix ?? fileConfig.assetPrefix ?? '/_kay',
|
|
51
|
+
securityOpt,
|
|
52
|
+
(options.compress ?? fileConfig.compress) !== false,
|
|
53
|
+
trustProxy,
|
|
54
|
+
isDev,
|
|
55
|
+
)
|
|
56
|
+
}
|
|
57
|
+
throw new Error(`kay server: missing ${manifestPath}. Run build() first.`)
|
|
58
|
+
}
|
|
59
|
+
manifest = JSON.parse(readFileSync(manifestPath, 'utf8')) as BuildManifest
|
|
60
|
+
if (options.plugins === undefined && manifest.configFile !== undefined) {
|
|
61
|
+
const cfgMod = await importModule(join(outDir, manifest.configFile))
|
|
62
|
+
const loaded = (cfgMod.default ?? cfgMod) as KayConfig | undefined
|
|
63
|
+
if (loaded !== undefined && typeof loaded === 'object')
|
|
64
|
+
fileConfig = loaded
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
const runtimeConfig = resolveServerConfig(fileConfig, options)
|
|
69
|
+
const clientDir = join(outDir, 'client')
|
|
38
70
|
|
|
39
|
-
const manifest = JSON.parse(readFileSync(manifestPath, 'utf8')) as BuildManifest
|
|
40
71
|
const modules: Record<string, unknown> = {}
|
|
41
72
|
const assets: Record<string, EmbeddedBody> = {}
|
|
42
73
|
const publicAssets: Record<string, EmbeddedBody> = {}
|
|
@@ -66,8 +97,6 @@ export async function createServer(options: ServerOptions): Promise<KayApp> {
|
|
|
66
97
|
}
|
|
67
98
|
}
|
|
68
99
|
|
|
69
|
-
const loadStamp = `${Date.now()}-${++serverLoadSeq}`
|
|
70
|
-
const importModule = options.importModule ?? ((path: string) => import(`${path}?v=${loadStamp}`))
|
|
71
100
|
const loadMod = async (rel: string) => {
|
|
72
101
|
if (!(rel in modules))
|
|
73
102
|
modules[rel] = await importModule(join(outDir, rel))
|
|
@@ -85,6 +114,7 @@ export async function createServer(options: ServerOptions): Promise<KayApp> {
|
|
|
85
114
|
}
|
|
86
115
|
}
|
|
87
116
|
}
|
|
117
|
+
if (manifest.rootLayoutFile) await loadMod(manifest.rootLayoutFile)
|
|
88
118
|
if (manifest.errorFile) await loadMod(manifest.errorFile)
|
|
89
119
|
if (manifest.notFoundFile) await loadMod(manifest.notFoundFile)
|
|
90
120
|
for (const a of manifest.actions) {
|
|
@@ -92,7 +122,6 @@ export async function createServer(options: ServerOptions): Promise<KayApp> {
|
|
|
92
122
|
for (const m of a.middlewares) await loadMod(m)
|
|
93
123
|
}
|
|
94
124
|
|
|
95
|
-
const runtimeConfig = pickRuntimeConfig(fileConfig)
|
|
96
125
|
return createServerFromEmbedded({
|
|
97
126
|
...runtimeConfig,
|
|
98
127
|
manifest,
|
|
@@ -100,21 +129,10 @@ export async function createServer(options: ServerOptions): Promise<KayApp> {
|
|
|
100
129
|
assets,
|
|
101
130
|
publicAssets,
|
|
102
131
|
publicEtags,
|
|
103
|
-
prerendered: {},
|
|
104
132
|
prerenderedFiles,
|
|
105
133
|
root,
|
|
106
134
|
outDir,
|
|
107
135
|
publicDir: join(outDir, 'public'),
|
|
108
|
-
assetPrefix: options.assetPrefix ?? fileConfig.assetPrefix,
|
|
109
|
-
lang: options.lang ?? fileConfig.lang,
|
|
110
|
-
security: securityOpt,
|
|
111
|
-
trustedOrigins: options.trustedOrigins ?? fileConfig.trustedOrigins,
|
|
112
|
-
trustProxy,
|
|
113
|
-
maxRequestBodySize,
|
|
114
|
-
streamTimeout: options.streamTimeout ?? fileConfig.streamTimeout,
|
|
115
|
-
compress: options.compress ?? fileConfig.compress,
|
|
116
136
|
dev: isDev,
|
|
117
|
-
onError: options.onError ?? fileConfig.onError,
|
|
118
|
-
plugins,
|
|
119
137
|
})
|
|
120
138
|
}
|