@kayjs/kay 2.0.0-beta.0 → 2.0.0-beta.1
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/attrs.ts +35 -0
- package/src/build/bundle.ts +442 -0
- package/src/build/compile.ts +10 -10
- package/src/build/files.ts +136 -0
- package/src/build/graph.ts +158 -0
- package/src/build/index.ts +204 -1460
- package/src/build/islands.ts +177 -0
- package/src/build/manifest.ts +224 -0
- package/src/build/plugin-host.ts +184 -0
- package/src/build/prerender.ts +93 -0
- package/src/build/report.ts +157 -0
- package/src/build/resolve.ts +58 -0
- package/src/build/routes.ts +135 -0
- package/src/build/static.ts +73 -0
- package/src/cli/check.ts +228 -114
- package/src/cli/index.ts +297 -94
- package/src/cli/new.ts +53 -32
- package/src/compiler/analyze.ts +666 -91
- package/src/compiler/dom.ts +808 -743
- package/src/compiler/mistakes.ts +354 -0
- package/src/compiler/patch.ts +1 -1
- package/src/compiler/server-only.ts +164 -21
- package/src/compiler/shared.ts +442 -0
- package/src/compiler/ssr.ts +329 -342
- package/src/context.ts +120 -0
- package/src/dev/index.ts +271 -75
- package/src/dom/action.ts +23 -13
- package/src/dom/extras.ts +121 -83
- package/src/dom/index.ts +114 -77
- package/src/dom/island.ts +71 -36
- package/src/dom/loop.ts +28 -20
- package/src/index.ts +2 -1
- package/src/jsx-runtime.ts +11 -0
- package/src/plugins/context.ts +57 -0
- package/src/plugins/index.ts +114 -18
- package/src/reactivity/index.ts +237 -213
- package/src/reactivity/selector.ts +11 -9
- package/src/reactivity/store.ts +36 -11
- package/src/server/action.ts +147 -76
- package/src/server/compress.ts +116 -96
- package/src/server/cookies.ts +46 -16
- package/src/server/env.ts +18 -13
- package/src/server/http.ts +107 -54
- package/src/server/index.ts +887 -870
- package/src/server/loader.ts +120 -0
- package/src/server/router.ts +22 -8
- package/src/server/security.ts +48 -58
- package/src/server/standard-schema.ts +42 -11
- package/src/server/static-dir.ts +144 -0
- package/src/ssr/context.ts +95 -10
- package/src/ssr/index.ts +167 -66
- package/src/style.ts +33 -0
- package/src/test/index.ts +2 -1
- package/src/unrenderable.ts +35 -0
package/src/ssr/context.ts
CHANGED
|
@@ -1,13 +1,21 @@
|
|
|
1
|
-
// Per-request SSR context for <Head> metadata
|
|
2
|
-
//
|
|
1
|
+
// Per-request SSR context for <Head> metadata, streaming <Suspense>, rendered island tracking,
|
|
2
|
+
// universal createContext/useContext, and deterministic hydration-safe useId().
|
|
3
3
|
|
|
4
4
|
import type { Html, KayChild } from '../jsx-runtime'
|
|
5
5
|
import { AsyncLocalStorage } from 'node:async_hooks'
|
|
6
|
+
import { registerServerContextBridge } from '../context'
|
|
6
7
|
import { raw, ssrChild } from './index'
|
|
7
8
|
|
|
9
|
+
export interface SettledChunk {
|
|
10
|
+
html: string
|
|
11
|
+
error?: unknown
|
|
12
|
+
}
|
|
13
|
+
|
|
8
14
|
export interface PendingChunk {
|
|
9
15
|
id: number
|
|
10
|
-
|
|
16
|
+
// Settles to the boundary's HTML, or to its error template and the error: it never rejects.
|
|
17
|
+
settled: Promise<SettledChunk>
|
|
18
|
+
renderError: (error: unknown) => string
|
|
11
19
|
}
|
|
12
20
|
|
|
13
21
|
export interface RenderContext {
|
|
@@ -16,13 +24,72 @@ export interface RenderContext {
|
|
|
16
24
|
pending: PendingChunk[]
|
|
17
25
|
nextId: number
|
|
18
26
|
islandDepth: number
|
|
27
|
+
islandSeq: number
|
|
28
|
+
idPrefix: string
|
|
29
|
+
idSeq: number
|
|
30
|
+
contexts: Map<symbol, unknown>
|
|
31
|
+
/** Maps island chunk URL -> eager (true if hydrate is undefined/'load'). */
|
|
32
|
+
renderedIslands: Map<string, boolean>
|
|
33
|
+
hasIslands: boolean
|
|
34
|
+
htmlAttrs: Record<string, string>
|
|
19
35
|
}
|
|
20
36
|
|
|
21
37
|
const STORAGE_KEY = Symbol.for('kay.render.storage')
|
|
22
38
|
const renderStorage: AsyncLocalStorage<RenderContext> = ((globalThis as Record<symbol, AsyncLocalStorage<RenderContext> | undefined>)[STORAGE_KEY] ??= new AsyncLocalStorage<RenderContext>())
|
|
23
39
|
|
|
40
|
+
registerServerContextBridge({
|
|
41
|
+
getContext(key: symbol) {
|
|
42
|
+
const ctx = renderStorage.getStore()
|
|
43
|
+
if (ctx !== undefined && ctx.contexts.has(key))
|
|
44
|
+
return { found: true, value: ctx.contexts.get(key) }
|
|
45
|
+
return undefined
|
|
46
|
+
},
|
|
47
|
+
runWithContext<T>(key: symbol, value: unknown, fn: () => T): T {
|
|
48
|
+
const ctx = renderStorage.getStore()
|
|
49
|
+
if (ctx === undefined)
|
|
50
|
+
return fn()
|
|
51
|
+
const had = ctx.contexts.has(key)
|
|
52
|
+
const prev = ctx.contexts.get(key)
|
|
53
|
+
ctx.contexts.set(key, value)
|
|
54
|
+
try {
|
|
55
|
+
return fn()
|
|
56
|
+
}
|
|
57
|
+
finally {
|
|
58
|
+
if (had)
|
|
59
|
+
ctx.contexts.set(key, prev)
|
|
60
|
+
else
|
|
61
|
+
ctx.contexts.delete(key)
|
|
62
|
+
}
|
|
63
|
+
},
|
|
64
|
+
nextId() {
|
|
65
|
+
const ctx = renderStorage.getStore()
|
|
66
|
+
if (ctx === undefined)
|
|
67
|
+
return undefined
|
|
68
|
+
return `${ctx.idPrefix}${ctx.idSeq++}`
|
|
69
|
+
},
|
|
70
|
+
head(props) {
|
|
71
|
+
return Head(props)
|
|
72
|
+
},
|
|
73
|
+
suspense(props) {
|
|
74
|
+
return Suspense(props)
|
|
75
|
+
},
|
|
76
|
+
})
|
|
77
|
+
|
|
24
78
|
export function createRenderContext(): RenderContext {
|
|
25
|
-
return {
|
|
79
|
+
return {
|
|
80
|
+
headParts: [],
|
|
81
|
+
title: undefined,
|
|
82
|
+
pending: [],
|
|
83
|
+
nextId: 0,
|
|
84
|
+
islandDepth: 0,
|
|
85
|
+
islandSeq: 0,
|
|
86
|
+
idPrefix: '',
|
|
87
|
+
idSeq: 0,
|
|
88
|
+
contexts: new Map(),
|
|
89
|
+
renderedIslands: new Map(),
|
|
90
|
+
hasIslands: false,
|
|
91
|
+
htmlAttrs: {},
|
|
92
|
+
}
|
|
26
93
|
}
|
|
27
94
|
|
|
28
95
|
export function runWithRenderContext<T>(ctx: RenderContext, fn: () => T): T {
|
|
@@ -33,7 +100,7 @@ export function currentRenderContext(): RenderContext | undefined {
|
|
|
33
100
|
return renderStorage.getStore()
|
|
34
101
|
}
|
|
35
102
|
|
|
36
|
-
const TITLE_RE = /<title
|
|
103
|
+
const TITLE_RE = /<title\b[^>]*>([\s\S]*?)<\/title>/gi
|
|
37
104
|
|
|
38
105
|
/** Collects document <head> tags during SSR; innermost <title> wins. */
|
|
39
106
|
export function Head(props: { children?: KayChild }): Html {
|
|
@@ -42,10 +109,12 @@ export function Head(props: { children?: KayChild }): Html {
|
|
|
42
109
|
return raw('')
|
|
43
110
|
|
|
44
111
|
let html = ssrChild(props.children)
|
|
112
|
+
TITLE_RE.lastIndex = 0
|
|
45
113
|
const titleMatch = TITLE_RE.exec(html)
|
|
46
114
|
if (titleMatch !== null) {
|
|
47
115
|
// Inner page renders before outer layouts, so the first (innermost) <title> wins.
|
|
48
116
|
ctx.title ??= titleMatch[0]
|
|
117
|
+
TITLE_RE.lastIndex = 0
|
|
49
118
|
html = html.replace(TITLE_RE, '')
|
|
50
119
|
}
|
|
51
120
|
if (html !== '')
|
|
@@ -65,7 +134,7 @@ export function renderCollectedHead(ctx: RenderContext): string {
|
|
|
65
134
|
* Streaming SSR boundary: flushes `fallback` immediately and streams resolved async children
|
|
66
135
|
* with a zero-dependency inline swap script. Islands inside streamed chunks hydrate automatically!
|
|
67
136
|
*/
|
|
68
|
-
export function Suspense(props: { fallback?: KayChild, children?: KayChild | Promise<KayChild> }): Html {
|
|
137
|
+
export function Suspense(props: { fallback?: KayChild, error?: KayChild | ((error: unknown) => KayChild), children?: KayChild | Promise<KayChild> }): Html {
|
|
69
138
|
const ctx = renderStorage.getStore()
|
|
70
139
|
const child = props.children
|
|
71
140
|
|
|
@@ -76,15 +145,31 @@ export function Suspense(props: { fallback?: KayChild, children?: KayChild | Pro
|
|
|
76
145
|
return raw(ssrChild(props.fallback))
|
|
77
146
|
|
|
78
147
|
const id = ctx.nextId++
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
148
|
+
// Capture RenderContext so timeout / error fallback renders still run inside the request context.
|
|
149
|
+
const renderError = (error: unknown): string => {
|
|
150
|
+
try {
|
|
151
|
+
return runWithRenderContext(ctx, () => ssrChild(typeof props.error === 'function' ? props.error(error) : props.error))
|
|
152
|
+
}
|
|
153
|
+
catch {
|
|
154
|
+
return ''
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
ctx.pending.push({ id, settled: settle(ctx, child, renderError), renderError })
|
|
83
158
|
|
|
84
159
|
const fallbackHtml = ssrChild(props.fallback)
|
|
85
160
|
return raw(`<kay-s id="k-s-${id}">${fallbackHtml}</kay-s>`)
|
|
86
161
|
}
|
|
87
162
|
|
|
163
|
+
async function settle(ctx: RenderContext, child: Promise<KayChild>, renderError: (error: unknown) => string): Promise<SettledChunk> {
|
|
164
|
+
try {
|
|
165
|
+
const resolved = await child
|
|
166
|
+
return { html: runWithRenderContext(ctx, () => ssrChild(resolved)) }
|
|
167
|
+
}
|
|
168
|
+
catch (error) {
|
|
169
|
+
return { html: renderError(error), error }
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
|
|
88
173
|
/** Fixed streaming swap bootstrap (constant content -> deterministic SHA-256 CSP hash, zero per-chunk inline scripts). */
|
|
89
174
|
export const KAY_STREAM_SCRIPT = `(()=>{const w=n=>{if(n.nodeType===1&&n.tagName==='TEMPLATE'&&n.dataset.ks){const s=document.getElementById('k-s-'+n.dataset.ks);if(s){s.replaceWith(n.content);n.remove()}}};const o=new MutationObserver(ms=>{for(const m of ms)for(const n of m.addedNodes)w(n)});o.observe(document.documentElement,{childList:true,subtree:true});document.addEventListener('DOMContentLoaded',()=>{document.querySelectorAll('template[data-ks]').forEach(w);o.disconnect()},{once:true})})()`
|
|
90
175
|
|
package/src/ssr/index.ts
CHANGED
|
@@ -1,6 +1,9 @@
|
|
|
1
1
|
// Kay v2 SSR runtime: flat string concatenation with fast-path escaping and zero-overhead islands.
|
|
2
2
|
|
|
3
3
|
import type { Html, HydrateStrategy, KayChild } from '../jsx-runtime'
|
|
4
|
+
import { isBlockedAttr, isStringBoolAttr, isUnsafeUrlAttr } from '../attrs'
|
|
5
|
+
import { styleText } from '../style'
|
|
6
|
+
import { assertRenderable } from '../unrenderable'
|
|
4
7
|
import { currentRenderContext, KAY_STREAM_SCRIPT } from './context'
|
|
5
8
|
|
|
6
9
|
export const KAY_ISLAND_STYLE = 'kay-island,kay-slot{display:contents}'
|
|
@@ -16,14 +19,17 @@ const ESC_TEXT = /[&<>]/
|
|
|
16
19
|
const ESC_ATTR = /[&"<>]/
|
|
17
20
|
const bunEscape = typeof Bun !== 'undefined' && typeof Bun.escapeHTML === 'function' ? Bun.escapeHTML : undefined
|
|
18
21
|
|
|
22
|
+
function escText(str: string): string {
|
|
23
|
+
if (bunEscape !== undefined)
|
|
24
|
+
return bunEscape(str)
|
|
25
|
+
if (!ESC_TEXT.test(str))
|
|
26
|
+
return str
|
|
27
|
+
return str.replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>')
|
|
28
|
+
}
|
|
29
|
+
|
|
19
30
|
export function esc(value: unknown): string {
|
|
20
|
-
if (typeof value === 'string')
|
|
21
|
-
|
|
22
|
-
return bunEscape(value)
|
|
23
|
-
if (!ESC_TEXT.test(value))
|
|
24
|
-
return value
|
|
25
|
-
return value.replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>')
|
|
26
|
-
}
|
|
31
|
+
if (typeof value === 'string')
|
|
32
|
+
return escText(value)
|
|
27
33
|
if (typeof value === 'number')
|
|
28
34
|
return String(value)
|
|
29
35
|
if (value == null || typeof value === 'boolean')
|
|
@@ -36,12 +42,8 @@ export function esc(value: unknown): string {
|
|
|
36
42
|
out += esc(value[i])
|
|
37
43
|
return out
|
|
38
44
|
}
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
return bunEscape(str)
|
|
42
|
-
if (!ESC_TEXT.test(str))
|
|
43
|
-
return str
|
|
44
|
-
return str.replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>')
|
|
45
|
+
assertRenderable(value, 'text')
|
|
46
|
+
return escText(String(value))
|
|
45
47
|
}
|
|
46
48
|
|
|
47
49
|
export function ssrRaw(value: unknown): string {
|
|
@@ -49,9 +51,14 @@ export function ssrRaw(value: unknown): string {
|
|
|
49
51
|
return ''
|
|
50
52
|
if (isRawHtml(value))
|
|
51
53
|
return String(value.__html)
|
|
54
|
+
if (typeof value === 'object' && '__html' in value)
|
|
55
|
+
throw new TypeError(UNBRANDED_INNER_HTML)
|
|
52
56
|
return String(value)
|
|
53
57
|
}
|
|
54
58
|
|
|
59
|
+
/** React's `{ __html }` shape reaching innerHTML unbranded: kay would print `[object Object]`. */
|
|
60
|
+
const UNBRANDED_INNER_HTML = 'kay: innerHTML takes the HTML string, got a { __html } object; pass the string, or raw(html) for a value typed Html.'
|
|
61
|
+
|
|
55
62
|
const CLOSE_STYLE_RE = /<\/(style)/gi
|
|
56
63
|
const SCRIPT_UNSAFE_RE = /<(\/script|script|!--)/gi
|
|
57
64
|
|
|
@@ -65,11 +72,7 @@ export function ssrRawText(tag: 'style' | 'script', value: unknown): string {
|
|
|
65
72
|
out += ssrRawText(tag, value[i])
|
|
66
73
|
return out
|
|
67
74
|
}
|
|
68
|
-
const str =
|
|
69
|
-
? value
|
|
70
|
-
: isRawHtml(value)
|
|
71
|
-
? String(value.__html)
|
|
72
|
-
: String(value)
|
|
75
|
+
const str = isRawHtml(value) ? String(value.__html) : String(value)
|
|
73
76
|
if (tag === 'script') {
|
|
74
77
|
return str.replace(SCRIPT_UNSAFE_RE, (_, body: string) =>
|
|
75
78
|
body.charCodeAt(0) === 47 ? `<\\${body}` : `\\u003c${body}`)
|
|
@@ -91,30 +94,7 @@ export function escAttr(value: unknown): string {
|
|
|
91
94
|
}
|
|
92
95
|
|
|
93
96
|
export function raw(html: string): Html {
|
|
94
|
-
return { __html: html, [RAW_HTML]: true } as Html
|
|
95
|
-
}
|
|
96
|
-
|
|
97
|
-
const VALID_ATTR_NAME = /^[A-Za-z_:][-\w:.]*$/
|
|
98
|
-
const URL_ATTRS = new Set(['href', 'src', 'action', 'formaction', 'xlink:href'])
|
|
99
|
-
const UNSAFE_URL_RE = /^(?:javascript|vbscript):/i
|
|
100
|
-
const STRING_BOOL_ATTRS = new Set(['draggable', 'spellcheck', 'contenteditable'])
|
|
101
|
-
|
|
102
|
-
function isBlockedAttr(name: string): boolean {
|
|
103
|
-
if (!VALID_ATTR_NAME.test(name))
|
|
104
|
-
return true
|
|
105
|
-
const lower = name.toLowerCase()
|
|
106
|
-
return lower.startsWith('on') || lower === 'innerhtml' || lower === 'srcdoc'
|
|
107
|
-
}
|
|
108
|
-
|
|
109
|
-
function isStringBoolAttr(name: string): boolean {
|
|
110
|
-
const lower = name.toLowerCase()
|
|
111
|
-
return lower.startsWith('aria-') || STRING_BOOL_ATTRS.has(lower)
|
|
112
|
-
}
|
|
113
|
-
|
|
114
|
-
function isUnsafeUrlAttr(name: string, value: unknown): boolean {
|
|
115
|
-
if (!URL_ATTRS.has(name.toLowerCase()))
|
|
116
|
-
return false
|
|
117
|
-
return UNSAFE_URL_RE.test(String(value).replace(/[\u0000-\u0020]+/g, ''))
|
|
97
|
+
return { __html: html, [RAW_HTML]: true } as unknown as Html
|
|
118
98
|
}
|
|
119
99
|
|
|
120
100
|
export function ssrAttr(name: string, value: unknown): string {
|
|
@@ -127,6 +107,7 @@ export function ssrAttr(name: string, value: unknown): string {
|
|
|
127
107
|
}
|
|
128
108
|
if (isUnsafeUrlAttr(name, value))
|
|
129
109
|
return ''
|
|
110
|
+
assertRenderable(value, name)
|
|
130
111
|
return ` ${name}="${escAttr(value)}"`
|
|
131
112
|
}
|
|
132
113
|
|
|
@@ -136,16 +117,14 @@ export function ssrStyle(value: unknown): string {
|
|
|
136
117
|
if (typeof value === 'string')
|
|
137
118
|
return ` style="${escAttr(value)}"`
|
|
138
119
|
if (typeof value === 'object') {
|
|
139
|
-
|
|
140
|
-
for (const [k, v] of Object.entries(value as Record<string, unknown>)) {
|
|
141
|
-
if (v != null && v !== '')
|
|
142
|
-
out += `${k}:${v};`
|
|
143
|
-
}
|
|
120
|
+
const out = styleText(value as Record<string, unknown>)
|
|
144
121
|
return out === '' ? '' : ` style="${escAttr(out)}"`
|
|
145
122
|
}
|
|
146
123
|
return ''
|
|
147
124
|
}
|
|
148
125
|
|
|
126
|
+
const SPREAD_DANGEROUS_HTML = 'kay: dangerouslySetInnerHTML in a spread: write innerHTML={html} on the element.'
|
|
127
|
+
|
|
149
128
|
export function ssrSpread(props: Record<string, unknown> | null | undefined): string {
|
|
150
129
|
if (props == null || typeof props !== 'object')
|
|
151
130
|
return ''
|
|
@@ -153,6 +132,8 @@ export function ssrSpread(props: Record<string, unknown> | null | undefined): st
|
|
|
153
132
|
for (const [rawKey, value] of Object.entries(props)) {
|
|
154
133
|
if (rawKey === 'key' || rawKey === 'ref' || rawKey === '$hydrate' || rawKey === 'children')
|
|
155
134
|
continue
|
|
135
|
+
if (rawKey === 'dangerouslySetInnerHTML')
|
|
136
|
+
throw new TypeError(SPREAD_DANGEROUS_HTML)
|
|
156
137
|
const name = rawKey === 'className' ? 'class' : rawKey === 'htmlFor' ? 'for' : rawKey
|
|
157
138
|
if (isBlockedAttr(name))
|
|
158
139
|
continue
|
|
@@ -161,18 +142,13 @@ export function ssrSpread(props: Record<string, unknown> | null | undefined): st
|
|
|
161
142
|
return out
|
|
162
143
|
}
|
|
163
144
|
|
|
164
|
-
export function ssrLoop<T>(items: Iterable<T> | null | undefined | false, render: (item: T, index: number) => string): string {
|
|
145
|
+
export function ssrLoop<T>(items: Iterable<T> | null | undefined | false, render: (item: T, index: number, array: readonly T[]) => string): string {
|
|
165
146
|
if (!items)
|
|
166
147
|
return ''
|
|
148
|
+
const list: readonly T[] = Array.isArray(items) ? items : [...items]
|
|
167
149
|
let out = ''
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
out += render(items[i] as T, i)
|
|
171
|
-
return out
|
|
172
|
-
}
|
|
173
|
-
let i = 0
|
|
174
|
-
for (const item of items)
|
|
175
|
-
out += render(item, i++)
|
|
150
|
+
for (let i = 0; i < list.length; i++)
|
|
151
|
+
out += render(list[i] as T, i, list)
|
|
176
152
|
return out
|
|
177
153
|
}
|
|
178
154
|
|
|
@@ -191,6 +167,7 @@ export function ssrChild(value: KayChild): string {
|
|
|
191
167
|
out += ssrChild(value[i])
|
|
192
168
|
return out
|
|
193
169
|
}
|
|
170
|
+
assertRenderable(value, 'text')
|
|
194
171
|
return esc(String(value))
|
|
195
172
|
}
|
|
196
173
|
|
|
@@ -198,7 +175,7 @@ function serializeIslandProps(props: Record<string, unknown>): string {
|
|
|
198
175
|
return JSON.stringify(props, function (this: Record<string, unknown>, key: string, value: unknown) {
|
|
199
176
|
const orig = key !== '' && this != null && typeof this === 'object' ? this[key] : value
|
|
200
177
|
if (orig instanceof Date)
|
|
201
|
-
return { __k: 'D', v: orig.toISOString() }
|
|
178
|
+
return { __k: 'D', v: Number.isNaN(orig.getTime()) ? 'NaN' : orig.toISOString() }
|
|
202
179
|
if (orig instanceof Set)
|
|
203
180
|
return { __k: 'S', v: [...orig] }
|
|
204
181
|
if (orig instanceof Map)
|
|
@@ -209,6 +186,10 @@ function serializeIslandProps(props: Record<string, unknown>): string {
|
|
|
209
186
|
return { __k: 'R', v: [orig.source, orig.flags] }
|
|
210
187
|
if (typeof orig === 'bigint')
|
|
211
188
|
return { __k: 'B', v: orig.toString() }
|
|
189
|
+
if (typeof orig === 'function')
|
|
190
|
+
throw new TypeError(`kay: island prop "${key}" is a function, which cannot reach the browser; define it inside the island, or import it there.`)
|
|
191
|
+
if (typeof orig === 'object' && orig !== null && 'peek' in orig && 'value' in orig)
|
|
192
|
+
throw new TypeError(`kay: island prop "${key}" is a signal; pass ${key}.value, or import the signal in the island from a shared module.`)
|
|
212
193
|
return value
|
|
213
194
|
})
|
|
214
195
|
}
|
|
@@ -220,9 +201,23 @@ function getIslandDepth(): number {
|
|
|
220
201
|
return ctx !== undefined ? ctx.islandDepth : fallbackIslandDepth
|
|
221
202
|
}
|
|
222
203
|
|
|
223
|
-
export function
|
|
204
|
+
export function recordRenderedIsland(chunk: string, hydrate?: HydrateStrategy): void {
|
|
205
|
+
const ctx = currentRenderContext()
|
|
206
|
+
if (ctx === undefined)
|
|
207
|
+
return
|
|
208
|
+
ctx.hasIslands = true
|
|
209
|
+
const eager = hydrate === undefined || hydrate === 'load'
|
|
210
|
+
if (eager)
|
|
211
|
+
ctx.renderedIslands.set(chunk, true)
|
|
212
|
+
else if (!ctx.renderedIslands.has(chunk))
|
|
213
|
+
ctx.renderedIslands.set(chunk, false)
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
export function ssrInIsland(render: () => string, chunk?: string, hydrate?: HydrateStrategy): string {
|
|
224
217
|
const ctx = currentRenderContext()
|
|
225
218
|
if (ctx !== undefined) {
|
|
219
|
+
if (chunk !== undefined && ctx.islandDepth === 0)
|
|
220
|
+
recordRenderedIsland(chunk, hydrate)
|
|
226
221
|
ctx.islandDepth++
|
|
227
222
|
try {
|
|
228
223
|
return render()
|
|
@@ -240,25 +235,120 @@ export function ssrInIsland(render: () => string): string {
|
|
|
240
235
|
}
|
|
241
236
|
}
|
|
242
237
|
|
|
238
|
+
/** Lazily evaluates non-async component children on first read inside the component's dynamic context, memoizing the result. */
|
|
239
|
+
export function ssrChildProp<P extends Record<string, unknown>>(props: P, fn: () => Html): P {
|
|
240
|
+
let cached: Html | undefined
|
|
241
|
+
let evaluated = false
|
|
242
|
+
return Object.defineProperty(props, 'children', {
|
|
243
|
+
enumerable: true,
|
|
244
|
+
configurable: true,
|
|
245
|
+
get() {
|
|
246
|
+
if (!evaluated) {
|
|
247
|
+
evaluated = true
|
|
248
|
+
cached = fn()
|
|
249
|
+
}
|
|
250
|
+
return cached
|
|
251
|
+
},
|
|
252
|
+
})
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
export function ssrIslandStatic(
|
|
256
|
+
chunk: string,
|
|
257
|
+
openTag: string,
|
|
258
|
+
render: (() => string) | undefined,
|
|
259
|
+
hydrate?: HydrateStrategy,
|
|
260
|
+
): string {
|
|
261
|
+
if (getIslandDepth() > 0)
|
|
262
|
+
return render !== undefined ? render() : ''
|
|
263
|
+
|
|
264
|
+
const ctx = currentRenderContext()
|
|
265
|
+
if (ctx !== undefined)
|
|
266
|
+
recordRenderedIsland(chunk, hydrate)
|
|
267
|
+
|
|
268
|
+
let idAttr = ''
|
|
269
|
+
let inner = ''
|
|
270
|
+
if (render !== undefined && hydrate !== 'client') {
|
|
271
|
+
if (ctx !== undefined) {
|
|
272
|
+
const prevPrefix = ctx.idPrefix
|
|
273
|
+
const prevSeq = ctx.idSeq
|
|
274
|
+
const islandPrefix = `i${ctx.islandSeq++}-`
|
|
275
|
+
ctx.idPrefix = islandPrefix
|
|
276
|
+
ctx.idSeq = 0
|
|
277
|
+
try {
|
|
278
|
+
inner = ssrInIsland(render)
|
|
279
|
+
if (ctx.idSeq > 0)
|
|
280
|
+
idAttr = ` i="${islandPrefix}"`
|
|
281
|
+
}
|
|
282
|
+
finally {
|
|
283
|
+
ctx.idPrefix = prevPrefix
|
|
284
|
+
ctx.idSeq = prevSeq
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
else {
|
|
288
|
+
inner = ssrInIsland(render)
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
const tag = idAttr === '' ? openTag : `${openTag.slice(0, -1)}${idAttr}>`
|
|
293
|
+
return `${tag}${inner}</kay-island>`
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
function safeJsonScript(json: string): string {
|
|
297
|
+
return json.replace(/</g, '\\u003c')
|
|
298
|
+
}
|
|
299
|
+
|
|
243
300
|
export function ssrIsland(
|
|
244
|
-
_id: string,
|
|
245
301
|
chunk: string,
|
|
246
302
|
render: () => string,
|
|
247
303
|
props: Record<string, unknown>,
|
|
248
304
|
hydrate?: HydrateStrategy,
|
|
305
|
+
scriptProps = false,
|
|
249
306
|
): string {
|
|
250
307
|
if (getIslandDepth() > 0)
|
|
251
308
|
return render()
|
|
252
309
|
|
|
253
|
-
const
|
|
254
|
-
|
|
255
|
-
|
|
310
|
+
const ctx = currentRenderContext()
|
|
311
|
+
if (ctx !== undefined)
|
|
312
|
+
recordRenderedIsland(chunk, hydrate)
|
|
313
|
+
|
|
314
|
+
let propsAttr = ''
|
|
315
|
+
let propsScript = ''
|
|
316
|
+
if (Object.keys(props).length > 0) {
|
|
317
|
+
const json = serializeIslandProps(props)
|
|
318
|
+
if (scriptProps)
|
|
319
|
+
propsScript = `<script type="application/json">${safeJsonScript(json)}</script>`
|
|
320
|
+
else
|
|
321
|
+
propsAttr = ` p="${escAttr(json)}"`
|
|
322
|
+
}
|
|
256
323
|
const hydrateAttr = hydrate !== undefined && hydrate !== 'load'
|
|
257
324
|
? ` h="${escAttr(hydrate)}"`
|
|
258
325
|
: ''
|
|
259
|
-
const inner = hydrate === 'client' ? '' : ssrInIsland(render)
|
|
260
326
|
|
|
261
|
-
|
|
327
|
+
let idAttr = ''
|
|
328
|
+
let inner = ''
|
|
329
|
+
if (hydrate !== 'client') {
|
|
330
|
+
if (ctx !== undefined) {
|
|
331
|
+
const prevPrefix = ctx.idPrefix
|
|
332
|
+
const prevSeq = ctx.idSeq
|
|
333
|
+
const islandPrefix = `i${ctx.islandSeq++}-`
|
|
334
|
+
ctx.idPrefix = islandPrefix
|
|
335
|
+
ctx.idSeq = 0
|
|
336
|
+
try {
|
|
337
|
+
inner = ssrInIsland(render)
|
|
338
|
+
if (ctx.idSeq > 0)
|
|
339
|
+
idAttr = ` i="${islandPrefix}"`
|
|
340
|
+
}
|
|
341
|
+
finally {
|
|
342
|
+
ctx.idPrefix = prevPrefix
|
|
343
|
+
ctx.idSeq = prevSeq
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
else {
|
|
347
|
+
inner = ssrInIsland(render)
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
return `<kay-island c="${escAttr(chunk)}"${propsAttr}${hydrateAttr}${idAttr}>${inner}${propsScript}</kay-island>`
|
|
262
352
|
}
|
|
263
353
|
|
|
264
354
|
export interface DocumentOptions {
|
|
@@ -266,6 +356,7 @@ export interface DocumentOptions {
|
|
|
266
356
|
head?: string | undefined
|
|
267
357
|
headTags?: Iterable<string> | undefined
|
|
268
358
|
lang?: string | undefined
|
|
359
|
+
htmlAttrs?: Record<string, string> | undefined
|
|
269
360
|
runtimeScript?: string | undefined
|
|
270
361
|
alwaysLoadRuntime?: boolean | undefined
|
|
271
362
|
preloadChunks?: Iterable<string> | undefined
|
|
@@ -275,7 +366,7 @@ export interface DocumentOptions {
|
|
|
275
366
|
}
|
|
276
367
|
|
|
277
368
|
export function renderDocument(options: DocumentOptions): string {
|
|
278
|
-
const { body, head = '', headTags, lang = 'en', runtimeScript, alwaysLoadRuntime, preloadChunks, styles, hasIslands, hasSuspense } = options
|
|
369
|
+
const { body, head = '', headTags, lang = 'en', htmlAttrs, runtimeScript, alwaysLoadRuntime, preloadChunks, styles, hasIslands, hasSuspense } = options
|
|
279
370
|
let headExtra = head
|
|
280
371
|
|
|
281
372
|
if (headTags !== undefined) {
|
|
@@ -302,5 +393,15 @@ export function renderDocument(options: DocumentOptions): string {
|
|
|
302
393
|
if (runtimeScript !== undefined && (hasIslands || alwaysLoadRuntime))
|
|
303
394
|
headExtra += `<script type="module" src="${escAttr(runtimeScript)}"></script>`
|
|
304
395
|
|
|
305
|
-
|
|
396
|
+
let attrStr = ''
|
|
397
|
+
const effectiveLang = htmlAttrs?.lang ?? lang
|
|
398
|
+
attrStr += ` lang="${escAttr(effectiveLang)}"`
|
|
399
|
+
if (htmlAttrs !== undefined) {
|
|
400
|
+
for (const [k, v] of Object.entries(htmlAttrs)) {
|
|
401
|
+
if (k !== 'lang' && !isBlockedAttr(k))
|
|
402
|
+
attrStr += ` ${k}="${escAttr(v)}"`
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
return `<!DOCTYPE html><html${attrStr}><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">${headExtra}</head><body>${body}</body></html>`
|
|
306
407
|
}
|
package/src/style.ts
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
// The CSS text of a style object, shared by the server and the browser so both render the same declarations.
|
|
2
|
+
|
|
3
|
+
// Properties that take a bare number; any other number gets `px`.
|
|
4
|
+
const UNITLESS = new Set([
|
|
5
|
+
'animation-iteration-count', 'aspect-ratio', 'border-image-outset', 'border-image-slice', 'border-image-width',
|
|
6
|
+
'column-count', 'columns', 'fill-opacity', 'flex', 'flex-grow', 'flex-shrink', 'flood-opacity', 'font-weight',
|
|
7
|
+
'grid-area', 'grid-column', 'grid-column-end', 'grid-column-start', 'grid-row', 'grid-row-end', 'grid-row-start',
|
|
8
|
+
'line-clamp', '-webkit-line-clamp', 'line-height', 'opacity', 'order', 'orphans', 'scale', 'stop-opacity',
|
|
9
|
+
'stroke-dasharray', 'stroke-dashoffset', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'tab-size',
|
|
10
|
+
'widows', 'z-index', 'zoom',
|
|
11
|
+
])
|
|
12
|
+
const UPPER = /[A-Z]/g
|
|
13
|
+
const MS_PREFIX = /^ms[A-Z]/
|
|
14
|
+
|
|
15
|
+
// `backgroundColor` becomes `background-color` and `msTransform` `-ms-transform`; a custom property keeps its case.
|
|
16
|
+
function cssName(key: string): string {
|
|
17
|
+
if (key.startsWith('--'))
|
|
18
|
+
return key
|
|
19
|
+
const name = key.replace(UPPER, c => `-${c.toLowerCase()}`)
|
|
20
|
+
return MS_PREFIX.test(key) ? `-${name}` : name
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export function styleText(style: Record<string, unknown>): string {
|
|
24
|
+
let out = ''
|
|
25
|
+
for (const [key, value] of Object.entries(style)) {
|
|
26
|
+
if (value == null || value === '' || value === false)
|
|
27
|
+
continue
|
|
28
|
+
const name = cssName(key)
|
|
29
|
+
const px = typeof value === 'number' && !name.startsWith('--') && !UNITLESS.has(name)
|
|
30
|
+
out += `${name}:${value}${px ? 'px' : ''};`
|
|
31
|
+
}
|
|
32
|
+
return out
|
|
33
|
+
}
|
package/src/test/index.ts
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
import type { BuildManifest, BuildOptions } from '../build/index'
|
|
4
4
|
import type { KayApp, ServerOptions } from '../server/index'
|
|
5
|
+
import type { TrustProxy } from '../server/security'
|
|
5
6
|
import { build } from '../build/index'
|
|
6
7
|
import { createServer } from '../server/index'
|
|
7
8
|
|
|
@@ -10,7 +11,7 @@ export interface TestAppOptions extends Omit<BuildOptions, 'compile' | 'static'>
|
|
|
10
11
|
lang?: string | undefined
|
|
11
12
|
security?: ServerOptions['security']
|
|
12
13
|
trustedOrigins?: string[] | undefined
|
|
13
|
-
trustProxy?:
|
|
14
|
+
trustProxy?: TrustProxy | undefined
|
|
14
15
|
maxRequestBodySize?: number | undefined
|
|
15
16
|
}
|
|
16
17
|
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
// Values whose String() is never what the author meant, shared by the SSR and DOM renderers so both refuse them alike.
|
|
2
|
+
|
|
3
|
+
// A value with its own toString, such as a server action printing its URL, renders as that string on purpose.
|
|
4
|
+
function hasOwnToString(value: object): boolean {
|
|
5
|
+
const { toString } = value
|
|
6
|
+
return typeof toString === 'function' && toString !== Function.prototype.toString && toString !== Object.prototype.toString && toString !== Array.prototype.toString
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
function describe(value: unknown, asClass: boolean): [string, string] | undefined {
|
|
10
|
+
if (typeof value === 'function')
|
|
11
|
+
return hasOwnToString(value) ? undefined : ['a function', 'call it, or pass it to an event prop']
|
|
12
|
+
if (typeof value !== 'object' || value === null)
|
|
13
|
+
return undefined
|
|
14
|
+
if (typeof (value as { then?: unknown }).then === 'function')
|
|
15
|
+
return ['a Promise', 'await it in an async component, or make that component the only child of <Suspense>']
|
|
16
|
+
if ('peek' in value && 'value' in value)
|
|
17
|
+
return ['a signal', 'read its .value']
|
|
18
|
+
if ('__html' in value)
|
|
19
|
+
return ['a { __html } object', 'pass the string to innerHTML, or wrap trusted HTML in raw()']
|
|
20
|
+
if (asClass && Array.isArray(value))
|
|
21
|
+
return ['an array', 'join the names into one string']
|
|
22
|
+
if (hasOwnToString(value))
|
|
23
|
+
return undefined
|
|
24
|
+
const proto = Object.getPrototypeOf(value)
|
|
25
|
+
if (proto === Object.prototype || proto === null)
|
|
26
|
+
return ['a plain object', 'render one of its fields']
|
|
27
|
+
return undefined
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** Throws when `value` would print as `[object Object]`, `[object Promise]` or a function's source; `place` is `text` or an attribute name. */
|
|
31
|
+
export function assertRenderable(value: unknown, place: string): void {
|
|
32
|
+
const found = describe(value, place === 'class')
|
|
33
|
+
if (found !== undefined)
|
|
34
|
+
throw new TypeError(`kay: cannot render ${found[0]} as ${place === 'text' ? 'text' : `the ${place} attribute`}; ${found[1]}.`)
|
|
35
|
+
}
|