@kayjs/kay 2.0.0-alpha.7 → 2.0.0-beta.0
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/compile.ts +15 -3
- package/src/build/index.ts +301 -49
- package/src/cli/check.ts +41 -37
- package/src/cli/index.ts +27 -11
- package/src/cli/new.ts +24 -8
- package/src/compiler/dom.ts +153 -30
- package/src/compiler/server-only.ts +62 -0
- package/src/compiler/ssr.ts +101 -22
- package/src/dev/index.ts +26 -7
- package/src/dom/extras.ts +85 -43
- package/src/dom/index.ts +110 -17
- package/src/dom/island.ts +67 -24
- package/src/dom/loop.ts +6 -1
- package/src/plugins/index.ts +8 -1
- package/src/reactivity/index.ts +141 -40
- package/src/reactivity/store.ts +5 -1
- package/src/server/action.ts +98 -26
- package/src/server/compress.ts +87 -8
- package/src/server/cookies.ts +15 -8
- package/src/server/http.ts +121 -6
- package/src/server/index.ts +453 -242
- package/src/server/router.ts +6 -1
- package/src/server/security.ts +76 -18
- package/src/ssr/context.ts +2 -1
- package/src/ssr/index.ts +88 -20
- package/src/test/index.ts +4 -0
package/src/cli/check.ts
CHANGED
|
@@ -4,6 +4,7 @@ import type { AstNode, ModuleAnalysis } from '../compiler/analyze'
|
|
|
4
4
|
import { existsSync, readdirSync, readFileSync } from 'node:fs'
|
|
5
5
|
import { basename, dirname, join, relative, resolve } from 'node:path'
|
|
6
6
|
import { analyzeModule, walk } from '../compiler/analyze'
|
|
7
|
+
import { readsPrivateEnv, SERVER_ONLY_MODULES } from '../compiler/server-only'
|
|
7
8
|
import { loadConfig } from '../plugins/index'
|
|
8
9
|
|
|
9
10
|
export interface CheckResult {
|
|
@@ -12,33 +13,6 @@ export interface CheckResult {
|
|
|
12
13
|
errors: string[]
|
|
13
14
|
}
|
|
14
15
|
|
|
15
|
-
const SERVER_ONLY_MODULES = new Set([
|
|
16
|
-
'kay/server',
|
|
17
|
-
'@kayjs/kay/server',
|
|
18
|
-
'bun:sqlite',
|
|
19
|
-
'bun:ffi',
|
|
20
|
-
'bun:dns',
|
|
21
|
-
'node:fs',
|
|
22
|
-
'node:fs/promises',
|
|
23
|
-
'node:child_process',
|
|
24
|
-
'node:net',
|
|
25
|
-
'node:http',
|
|
26
|
-
'node:https',
|
|
27
|
-
'node:http2',
|
|
28
|
-
'node:os',
|
|
29
|
-
'node:worker_threads',
|
|
30
|
-
'node:cluster',
|
|
31
|
-
'node:dgram',
|
|
32
|
-
'node:tls',
|
|
33
|
-
'node:readline',
|
|
34
|
-
'fs',
|
|
35
|
-
'fs/promises',
|
|
36
|
-
'child_process',
|
|
37
|
-
'net',
|
|
38
|
-
'http',
|
|
39
|
-
'https',
|
|
40
|
-
])
|
|
41
|
-
|
|
42
16
|
const SERIALIZABLE_NEW_CTORS = new Set(['Date', 'Map', 'Set', 'URL', 'RegExp'])
|
|
43
17
|
|
|
44
18
|
function walkTsFiles(dir: string, out: string[] = []): string[] {
|
|
@@ -69,6 +43,42 @@ function resolveLocalModule(fromFile: string, specifier: string): string | undef
|
|
|
69
43
|
return undefined
|
|
70
44
|
}
|
|
71
45
|
|
|
46
|
+
// Walks the local imports of an island the way the client build follows them: a module that only declares actions is stubbed there, so its imports stop the walk.
|
|
47
|
+
function checkIslandReach(island: string, root: string, analyses: Map<string, ModuleAnalysis>, reported: Set<string>, errors: string[]): void {
|
|
48
|
+
const islandRel = relative(root, island).replace(/\\/g, '/')
|
|
49
|
+
const seen = new Set<string>()
|
|
50
|
+
const stack = [island]
|
|
51
|
+
while (stack.length > 0) {
|
|
52
|
+
const file = stack.pop()!
|
|
53
|
+
if (seen.has(file))
|
|
54
|
+
continue
|
|
55
|
+
seen.add(file)
|
|
56
|
+
const analysis = analyses.get(file)
|
|
57
|
+
if (analysis === undefined || (file !== island && !analysis.isInteractive && analysis.exportedActions.length > 0))
|
|
58
|
+
continue
|
|
59
|
+
const rel = relative(root, file).replace(/\\/g, '/')
|
|
60
|
+
const report = (key: string, message: string): void => {
|
|
61
|
+
if (reported.has(`${file}\0${key}`))
|
|
62
|
+
return
|
|
63
|
+
reported.add(`${file}\0${key}`)
|
|
64
|
+
errors.push(message)
|
|
65
|
+
}
|
|
66
|
+
for (const source of [...analysis.imports.map(i => i.source), ...analysis.reexports.map(r => r.source)]) {
|
|
67
|
+
if (SERVER_ONLY_MODULES.has(source)) {
|
|
68
|
+
report(source, file === island
|
|
69
|
+
? `kay check: ${rel}: interactive island imports server-only module "${source}". Move server logic to a server action or async server component.`
|
|
70
|
+
: `kay check: ${rel}: imports server-only module "${source}" and is reachable from the island in ${islandRel}. Move server logic to a server action or async server component.`)
|
|
71
|
+
continue
|
|
72
|
+
}
|
|
73
|
+
const target = resolveLocalModule(file, source)
|
|
74
|
+
if (target !== undefined)
|
|
75
|
+
stack.push(target)
|
|
76
|
+
}
|
|
77
|
+
if (readsPrivateEnv(analysis.program))
|
|
78
|
+
report('process.env', `kay check: ${rel}: reads process.env and is reachable from the island in ${islandRel}. Only process.env.PUBLIC_* reaches the browser.`)
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
72
82
|
function normalizeRouteConflictKey(routesDir: string, file: string): string {
|
|
73
83
|
const rel = relative(routesDir, file).replace(/\\/g, '/').replace(/\.(tsx|ts)$/, '')
|
|
74
84
|
if (rel === 'index')
|
|
@@ -118,20 +128,14 @@ export async function checkProject(rootDir: string, options: { skipTypecheck?: b
|
|
|
118
128
|
|
|
119
129
|
// 3b. Static guardrails: server-only imports in islands, non-serializable island props, route conflicts, missing paths()
|
|
120
130
|
const seenRoutes = new Map<string, string>()
|
|
131
|
+
const reported = new Set<string>()
|
|
121
132
|
|
|
122
133
|
for (const [file, analysis] of analyses) {
|
|
123
134
|
const rel = relative(root, file).replace(/\\/g, '/')
|
|
124
135
|
|
|
125
|
-
// Guardrail 1: server-only imports
|
|
126
|
-
if (analysis.isInteractive)
|
|
127
|
-
|
|
128
|
-
if (SERVER_ONLY_MODULES.has(imp.source)) {
|
|
129
|
-
errors.push(
|
|
130
|
-
`kay check: ${rel}: interactive island imports server-only module "${imp.source}". Move server logic to a server action or async server component.`,
|
|
131
|
-
)
|
|
132
|
-
}
|
|
133
|
-
}
|
|
134
|
-
}
|
|
136
|
+
// Guardrail 1: server-only imports and private env reads in an island or any module it imports
|
|
137
|
+
if (analysis.isInteractive)
|
|
138
|
+
checkIslandReach(file, root, analyses, reported, errors)
|
|
135
139
|
|
|
136
140
|
// Guardrail 2: non-serializable props (functions / unsupported class instances) passed from static server code into an island
|
|
137
141
|
if (!analysis.isInteractive && file.endsWith('.tsx')) {
|
package/src/cli/index.ts
CHANGED
|
@@ -13,22 +13,35 @@ const args = Bun.argv.slice(2)
|
|
|
13
13
|
const cmd = args[0]
|
|
14
14
|
|
|
15
15
|
function flagValue(name: string): string | undefined {
|
|
16
|
-
const
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
16
|
+
const prefix = `${name}=`
|
|
17
|
+
for (let i = 0; i < args.length; i++) {
|
|
18
|
+
const a = args[i]!
|
|
19
|
+
if (a.startsWith(prefix))
|
|
20
|
+
return a.slice(prefix.length)
|
|
21
|
+
if (a === name) {
|
|
22
|
+
const next = args[i + 1]
|
|
23
|
+
return next !== undefined && !next.startsWith('-') ? next : ''
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
return undefined
|
|
21
27
|
}
|
|
22
28
|
|
|
23
29
|
function hasFlag(name: string): boolean {
|
|
24
30
|
return args.includes(name)
|
|
25
31
|
}
|
|
26
32
|
|
|
33
|
+
function resolveHostname(): string {
|
|
34
|
+
const hostFlag = flagValue('--host')
|
|
35
|
+
if (hostFlag !== undefined)
|
|
36
|
+
return hostFlag === '' ? '0.0.0.0' : hostFlag
|
|
37
|
+
return process.env.HOST || '127.0.0.1'
|
|
38
|
+
}
|
|
39
|
+
|
|
27
40
|
const dirArg = args.slice(1).find((a, i, arr) => {
|
|
28
41
|
if (a.startsWith('-'))
|
|
29
42
|
return false
|
|
30
43
|
const prev = arr[i - 1]
|
|
31
|
-
if (prev === '--port' || prev === '--compile' || prev === '--template')
|
|
44
|
+
if (prev === '--port' || prev === '--host' || prev === '--compile' || prev === '--template')
|
|
32
45
|
return false
|
|
33
46
|
return true
|
|
34
47
|
})
|
|
@@ -72,14 +85,15 @@ else if (cmd === 'start') {
|
|
|
72
85
|
process.env.NODE_ENV ??= 'production'
|
|
73
86
|
const config = await loadConfig(root)
|
|
74
87
|
const port = Number(flagValue('--port') || process.env.PORT || config.port || 3000)
|
|
75
|
-
const hostname =
|
|
88
|
+
const hostname = resolveHostname()
|
|
76
89
|
const app = await createServer({ root })
|
|
77
90
|
const server = app.serve(port, hostname)
|
|
78
|
-
console.log(`kay server listening on http://${hostname
|
|
91
|
+
console.log(`kay server listening on http://${hostname}:${server.port}`)
|
|
79
92
|
}
|
|
80
93
|
else if (cmd === 'dev') {
|
|
81
94
|
const port = Number(flagValue('--port') || process.env.PORT || 3000)
|
|
82
|
-
|
|
95
|
+
const hostname = resolveHostname()
|
|
96
|
+
await devServer({ root, port, hostname })
|
|
83
97
|
}
|
|
84
98
|
else {
|
|
85
99
|
// Check plugin-registered CLI commands from kay.config.ts
|
|
@@ -98,10 +112,12 @@ Commands:
|
|
|
98
112
|
kay new <dir> [--template minimal|fullstack|blog|app] [--force]
|
|
99
113
|
Scaffold a new Kay project
|
|
100
114
|
kay check [dir] Validate routes, compiler rules, and TypeScript types
|
|
101
|
-
kay dev [dir] [--port 3000]
|
|
115
|
+
kay dev [dir] [--port 3000] [--host [addr]]
|
|
116
|
+
Run dev server with fast reload (binds 127.0.0.1 by default)
|
|
102
117
|
kay build [dir] [--static] [--compile [out]]
|
|
103
118
|
Build production app, static site, or single executable
|
|
104
|
-
kay start [dir] [--port 3000]
|
|
119
|
+
kay start [dir] [--port 3000] [--host [addr]]
|
|
120
|
+
Serve the built production app (binds 127.0.0.1 by default)`)
|
|
105
121
|
process.exit(cmd === '--help' || cmd === '-h' || cmd === undefined ? 0 : 1)
|
|
106
122
|
}
|
|
107
123
|
}
|
package/src/cli/new.ts
CHANGED
|
@@ -15,7 +15,7 @@ export function scaffoldProject(targetDir: string, options: ScaffoldOptions = {}
|
|
|
15
15
|
const root = resolve(targetDir)
|
|
16
16
|
const name = basename(root).toLowerCase().replace(/[^a-z0-9-_]/g, '-') || 'kay-app'
|
|
17
17
|
const template: ScaffoldTemplate = options.template ?? 'minimal'
|
|
18
|
-
const kayVersion = options.kayVersion ?? '^2.0.0-
|
|
18
|
+
const kayVersion = options.kayVersion ?? '^2.0.0-beta.0'
|
|
19
19
|
|
|
20
20
|
if (existsSync(root) && readdirSync(root).length > 0 && !options.force)
|
|
21
21
|
throw new Error(`kay new: directory "${root}" is not empty (pass --force to overwrite)`)
|
|
@@ -323,7 +323,8 @@ export default async function BlogIndex() {
|
|
|
323
323
|
)
|
|
324
324
|
}
|
|
325
325
|
`
|
|
326
|
-
files['src/routes/blog/[slug].tsx'] = `import {
|
|
326
|
+
files['src/routes/blog/[slug].tsx'] = `import type { RequestContext } from 'kay/server'
|
|
327
|
+
import { Button, Stack } from '@kayjs/ui'
|
|
327
328
|
import { Head } from 'kay'
|
|
328
329
|
import { posts } from '../../posts'
|
|
329
330
|
|
|
@@ -332,11 +333,15 @@ export function paths() {
|
|
|
332
333
|
return posts.paths('/blog')
|
|
333
334
|
}
|
|
334
335
|
|
|
335
|
-
export
|
|
336
|
-
const post = posts.get(params.slug)
|
|
336
|
+
export async function load(ctx: RequestContext) {
|
|
337
|
+
const post = posts.get(ctx.params.slug ?? '')
|
|
337
338
|
if (!post)
|
|
338
|
-
return
|
|
339
|
+
return new Response('Not found', { status: 404 })
|
|
340
|
+
return { post }
|
|
341
|
+
}
|
|
339
342
|
|
|
343
|
+
export default function PostPage({ data }: { data: { post: NonNullable<ReturnType<typeof posts.get>> } }) {
|
|
344
|
+
const { post } = data
|
|
340
345
|
return (
|
|
341
346
|
<Stack gap="1.25rem">
|
|
342
347
|
<Head><title>{post.data.title}</title></Head>
|
|
@@ -355,14 +360,25 @@ export default async function PostPage({ params }: { params: { slug: string } })
|
|
|
355
360
|
delete files['src/styles/app.css']
|
|
356
361
|
delete files['src/components/Counter.tsx']
|
|
357
362
|
|
|
358
|
-
files['src/auth.ts'] = `import {
|
|
363
|
+
files['src/auth.ts'] = `import { join } from 'node:path'
|
|
364
|
+
import { createAuth } from '@kayjs/auth'
|
|
359
365
|
import { sqliteAuthStore } from '@kayjs/auth/sqlite'
|
|
360
366
|
|
|
367
|
+
// Set AUTH_SECRET (at least 32 bytes) in production — see .env.example.
|
|
368
|
+
const defaultDb = import.meta.dir.startsWith('/$bunfs')
|
|
369
|
+
? './data/auth.sqlite'
|
|
370
|
+
: join(import.meta.dir, '../data/auth.sqlite')
|
|
371
|
+
|
|
361
372
|
export const auth = createAuth({
|
|
362
|
-
store: sqliteAuthStore(process.env.AUTH_DB ||
|
|
363
|
-
secret: process.env.AUTH_SECRET ||
|
|
373
|
+
store: sqliteAuthStore(process.env.AUTH_DB || defaultDb),
|
|
374
|
+
secret: process.env.AUTH_SECRET || undefined,
|
|
364
375
|
defaultRedirect: '/dashboard',
|
|
365
376
|
})
|
|
377
|
+
`
|
|
378
|
+
files['.env.example'] = `# Generate a 32+ byte secret for production, e.g.:
|
|
379
|
+
# openssl rand -base64 32
|
|
380
|
+
AUTH_SECRET=
|
|
381
|
+
AUTH_DB=./data/auth.sqlite
|
|
366
382
|
`
|
|
367
383
|
files['kay.config.ts'] = `import { ui } from '@kayjs/ui/plugin'
|
|
368
384
|
import { defineConfig } from 'kay/server'
|
package/src/compiler/dom.ts
CHANGED
|
@@ -26,6 +26,106 @@ const DELEGATED_EVENTS = new Set([
|
|
|
26
26
|
|
|
27
27
|
const DOM_PROPS = new Set(['value', 'checked', 'selected', 'muted', 'indeterminate'])
|
|
28
28
|
const EVENT_ATTR = /^on([A-Z]\w*)$/
|
|
29
|
+
const URL_ATTRS = new Set(['href', 'src', 'action', 'formaction', 'xlink:href'])
|
|
30
|
+
const UNSAFE_URL_RE = /^(?:javascript|vbscript):/i
|
|
31
|
+
const STRING_BOOL_ATTRS = new Set(['draggable', 'spellcheck', 'contenteditable'])
|
|
32
|
+
|
|
33
|
+
function isStringBoolAttr(name: string): boolean {
|
|
34
|
+
const lower = name.toLowerCase()
|
|
35
|
+
return lower.startsWith('aria-') || STRING_BOOL_ATTRS.has(lower)
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function isUnsafeUrlAttr(name: string, value: unknown): boolean {
|
|
39
|
+
if (!URL_ATTRS.has(name.toLowerCase()))
|
|
40
|
+
return false
|
|
41
|
+
return UNSAFE_URL_RE.test(String(value).replace(/[\u0000-\u0020]+/g, ''))
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
const HTML_ENTITIES: Record<string, string> = {
|
|
45
|
+
amp: '&', lt: '<', gt: '>', quot: '"', apos: '\'', nbsp: '\u00A0',
|
|
46
|
+
ndash: '\u2013', mdash: '\u2014', lsquo: '\u2018', rsquo: '\u2019',
|
|
47
|
+
ldquo: '\u201C', rdquo: '\u201D', hellip: '\u2026', bull: '\u2022',
|
|
48
|
+
middot: '\u00B7', laquo: '\u00AB', raquo: '\u00BB', lsaquo: '\u2039',
|
|
49
|
+
rsaquo: '\u203A', shy: '\u00AD', ensp: '\u2002', emsp: '\u2003',
|
|
50
|
+
thinsp: '\u2009', zwnj: '\u200C', zwj: '\u200D', lrm: '\u200E',
|
|
51
|
+
rlm: '\u200F', prime: '\u2032', Prime: '\u2033', sect: '\u00A7',
|
|
52
|
+
para: '\u00B6', dagger: '\u2020', Dagger: '\u2021', permil: '\u2030',
|
|
53
|
+
copy: '\u00A9', reg: '\u00AE', trade: '\u2122', euro: '\u20AC',
|
|
54
|
+
pound: '\u00A3', yen: '\u00A5', cent: '\u00A2', curren: '\u00A4',
|
|
55
|
+
deg: '\u00B0', plusmn: '\u00B1', times: '\u00D7', divide: '\u00F7',
|
|
56
|
+
frac12: '\u00BD', frac14: '\u00BC', frac34: '\u00BE', sup1: '\u00B9',
|
|
57
|
+
sup2: '\u00B2', sup3: '\u00B3', micro: '\u00B5', minus: '\u2212',
|
|
58
|
+
ne: '\u2260', le: '\u2264', ge: '\u2265', approx: '\u2248', infin: '\u221E',
|
|
59
|
+
larr: '\u2190', uarr: '\u2191', rarr: '\u2192', darr: '\u2193',
|
|
60
|
+
harr: '\u2194', crarr: '\u21B5', check: '\u2713', cross: '\u2717',
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const ENTITY_RE = /&(?:#(\d+)|#x([0-9a-fA-F]+)|([A-Za-z][A-Za-z0-9]*));/g
|
|
64
|
+
|
|
65
|
+
function decodeHtmlEntities(str: string): string {
|
|
66
|
+
if (!str.includes('&'))
|
|
67
|
+
return str
|
|
68
|
+
return str.replace(ENTITY_RE, (match, dec: string | undefined, hex: string | undefined, named: string | undefined) => {
|
|
69
|
+
if (dec !== undefined) {
|
|
70
|
+
const cp = Number.parseInt(dec, 10)
|
|
71
|
+
return cp === 0 || cp > 0x10FFFF || (cp >= 0xD800 && cp <= 0xDFFF) ? '\uFFFD' : String.fromCodePoint(cp)
|
|
72
|
+
}
|
|
73
|
+
if (hex !== undefined) {
|
|
74
|
+
const cp = Number.parseInt(hex, 16)
|
|
75
|
+
return cp === 0 || cp > 0x10FFFF || (cp >= 0xD800 && cp <= 0xDFFF) ? '\uFFFD' : String.fromCodePoint(cp)
|
|
76
|
+
}
|
|
77
|
+
if (named !== undefined && Object.prototype.hasOwnProperty.call(HTML_ENTITIES, named))
|
|
78
|
+
return HTML_ENTITIES[named]!
|
|
79
|
+
return match
|
|
80
|
+
})
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
const PRIMITIVE_GLOBALS = new Set([
|
|
84
|
+
'String', 'Number', 'Boolean', 'parseInt', 'parseFloat',
|
|
85
|
+
'encodeURI', 'encodeURIComponent', 'decodeURI', 'decodeURIComponent',
|
|
86
|
+
])
|
|
87
|
+
|
|
88
|
+
const PRIMITIVE_METHODS = new Set([
|
|
89
|
+
'toString', 'toFixed', 'toPrecision', 'toExponential', 'toLocaleString',
|
|
90
|
+
'toLocaleDateString', 'toLocaleTimeString', 'toISOString', 'toUpperCase',
|
|
91
|
+
'toLowerCase', 'toLocaleUpperCase', 'toLocaleLowerCase', 'trim', 'trimStart',
|
|
92
|
+
'trimEnd', 'join', 'padStart', 'padEnd', 'repeat', 'replace', 'replaceAll',
|
|
93
|
+
'substring', 'substr', 'charAt', 'charCodeAt', 'codePointAt', 'indexOf',
|
|
94
|
+
'lastIndexOf', 'includes', 'startsWith', 'endsWith', 'getTime', 'getFullYear',
|
|
95
|
+
'getMonth', 'getDate', 'getHours', 'getMinutes', 'getSeconds',
|
|
96
|
+
])
|
|
97
|
+
|
|
98
|
+
function isKnownPrimitiveCall(node: AstNode): boolean {
|
|
99
|
+
const callee = node.callee as AstNode | undefined
|
|
100
|
+
if (!callee)
|
|
101
|
+
return false
|
|
102
|
+
if (callee.type === 'Identifier' && PRIMITIVE_GLOBALS.has(callee.name as string))
|
|
103
|
+
return true
|
|
104
|
+
if (callee.type === 'MemberExpression' && !callee.computed && callee.property?.type === 'Identifier') {
|
|
105
|
+
const prop = callee.property.name as string
|
|
106
|
+
if (callee.object?.type === 'Identifier') {
|
|
107
|
+
const obj = callee.object.name as string
|
|
108
|
+
if (obj === 'Math' || (obj === 'JSON' && prop === 'stringify') || (obj === 'Date' && prop === 'now'))
|
|
109
|
+
return true
|
|
110
|
+
}
|
|
111
|
+
if (PRIMITIVE_METHODS.has(prop))
|
|
112
|
+
return true
|
|
113
|
+
}
|
|
114
|
+
return false
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
function mayReturnNode(node: AstNode): boolean {
|
|
118
|
+
const cur = unwrapParens(node)
|
|
119
|
+
if (cur.type === 'TSAsExpression' || cur.type === 'TSNonNullExpression' || cur.type === 'TSSatisfiesExpression' || cur.type === 'TSTypeAssertion')
|
|
120
|
+
return mayReturnNode(cur.expression as AstNode)
|
|
121
|
+
if (cur.type === 'CallExpression')
|
|
122
|
+
return !isKnownPrimitiveCall(cur)
|
|
123
|
+
if (cur.type === 'LogicalExpression')
|
|
124
|
+
return mayReturnNode(cur.left as AstNode) || mayReturnNode(cur.right as AstNode)
|
|
125
|
+
if (cur.type === 'ConditionalExpression')
|
|
126
|
+
return mayReturnNode(cur.consequent as AstNode) || mayReturnNode(cur.alternate as AstNode)
|
|
127
|
+
return false
|
|
128
|
+
}
|
|
29
129
|
|
|
30
130
|
export interface CompileDomOptions {
|
|
31
131
|
analysis?: ModuleAnalysis | undefined
|
|
@@ -442,7 +542,7 @@ export function compileDom(filename: string, code: string, options: CompileDomOp
|
|
|
442
542
|
if (meaningful.length === 1) {
|
|
443
543
|
const child = meaningful[0]!
|
|
444
544
|
if (child.type === 'JSXText')
|
|
445
|
-
propEntries.push(`children: ${JSON.stringify(cleanJsxText(child.value as string))}`)
|
|
545
|
+
propEntries.push(`children: ${JSON.stringify(decodeHtmlEntities(cleanJsxText(child.value as string)))}`)
|
|
446
546
|
else if (child.type === 'JSXElement' || child.type === 'JSXFragment')
|
|
447
547
|
propEntries.push(`get children() { return ${compileRootJsx(child, scopeRewrites)} }`)
|
|
448
548
|
else if (child.type === 'JSXExpressionContainer')
|
|
@@ -451,7 +551,7 @@ export function compileDom(filename: string, code: string, options: CompileDomOp
|
|
|
451
551
|
else if (meaningful.length > 1) {
|
|
452
552
|
const items = meaningful.map((c) => {
|
|
453
553
|
if (c.type === 'JSXText')
|
|
454
|
-
return JSON.stringify(cleanJsxText(c.value as string))
|
|
554
|
+
return JSON.stringify(decodeHtmlEntities(cleanJsxText(c.value as string)))
|
|
455
555
|
if (c.type === 'JSXElement' || c.type === 'JSXFragment')
|
|
456
556
|
return compileRootJsx(c, scopeRewrites)
|
|
457
557
|
return compileExpression(c.expression, scopeRewrites)
|
|
@@ -508,6 +608,7 @@ export function compileDom(filename: string, code: string, options: CompileDomOp
|
|
|
508
608
|
|
|
509
609
|
const walkPlan: { parentVar: string, index: number, varName: string }[] = []
|
|
510
610
|
const dynamicTextSlots = new Set<string>() // "parentVar:textIndex" for optional SSR text between <!---->...<!---->
|
|
611
|
+
const dynamicRangeSlots = new Set<string>() // "parentVar:closeIndex" for SSR range between <!---->...<!---->
|
|
511
612
|
|
|
512
613
|
function requestChild(parentVar: string, index: number): string {
|
|
513
614
|
const key = `${parentVar}:${index}`
|
|
@@ -562,19 +663,25 @@ export function compileDom(filename: string, code: string, options: CompileDomOp
|
|
|
562
663
|
|
|
563
664
|
const name = rawName === 'className' ? 'class' : rawName === 'htmlFor' ? 'for' : rawName
|
|
564
665
|
if (attr.value === null) {
|
|
565
|
-
html += ` ${name}`
|
|
666
|
+
html += isStringBoolAttr(name) ? ` ${name}="true"` : ` ${name}`
|
|
566
667
|
}
|
|
567
668
|
else if (attr.value.type === 'Literal') {
|
|
568
|
-
|
|
669
|
+
if (!isUnsafeUrlAttr(name, attr.value.value))
|
|
670
|
+
html += ` ${name}="${escapeStaticAttr(String(attr.value.value))}"`
|
|
569
671
|
}
|
|
570
672
|
else if (attr.value.type === 'JSXExpressionContainer') {
|
|
571
673
|
const expr = attr.value.expression as AstNode
|
|
572
674
|
const lit = !DOM_PROPS.has(name) && name !== 'style' ? staticLiteral(expr) : { ok: false as const }
|
|
573
675
|
if (lit.ok) {
|
|
574
|
-
if (lit.value ===
|
|
575
|
-
|
|
576
|
-
|
|
676
|
+
if (typeof lit.value === 'boolean') {
|
|
677
|
+
if (isStringBoolAttr(name))
|
|
678
|
+
html += ` ${name}="${lit.value ? 'true' : 'false'}"`
|
|
679
|
+
else if (lit.value === true)
|
|
680
|
+
html += ` ${name}`
|
|
681
|
+
}
|
|
682
|
+
else if (lit.value !== null && !isUnsafeUrlAttr(name, lit.value)) {
|
|
577
683
|
html += ` ${name}="${escapeStaticAttr(String(lit.value))}"`
|
|
684
|
+
}
|
|
578
685
|
continue
|
|
579
686
|
}
|
|
580
687
|
const exprCode = compileExpression(expr, scopeRewrites)
|
|
@@ -654,6 +761,12 @@ export function compileDom(filename: string, code: string, options: CompileDomOp
|
|
|
654
761
|
dynamicTextSlots.add(`${realVar}:${slot.slice(prefix.length)}`)
|
|
655
762
|
}
|
|
656
763
|
}
|
|
764
|
+
for (const slot of [...dynamicRangeSlots]) {
|
|
765
|
+
if (slot.startsWith(prefix)) {
|
|
766
|
+
dynamicRangeSlots.delete(slot)
|
|
767
|
+
dynamicRangeSlots.add(`${realVar}:${slot.slice(prefix.length)}`)
|
|
768
|
+
}
|
|
769
|
+
}
|
|
657
770
|
}
|
|
658
771
|
html += subHtml
|
|
659
772
|
domIndex++
|
|
@@ -808,17 +921,28 @@ export function compileDom(filename: string, code: string, options: CompileDomOp
|
|
|
808
921
|
}
|
|
809
922
|
}
|
|
810
923
|
|
|
811
|
-
// Case 4: Dynamic children slot / Node insertion (`{children}`, `{props.children}`,
|
|
924
|
+
// Case 4: Dynamic children slot / Node insertion (`{children}`, `{props.children}`, JSX expressions, or call expressions)
|
|
812
925
|
const isChildrenExpr = (expr.type === 'Identifier' && expr.name === 'children')
|
|
813
926
|
|| (expr.type === 'MemberExpression' && !expr.computed && expr.property?.name === 'children')
|
|
814
927
|
const exprCode = compileExpression(expr, scopeRewrites)
|
|
815
|
-
if (isChildrenExpr || hasJsxDescendant(expr)) {
|
|
816
|
-
|
|
817
|
-
|
|
928
|
+
if (isChildrenExpr || hasJsxDescendant(expr) || mayReturnNode(expr)) {
|
|
929
|
+
if (meaningful.length === 1) {
|
|
930
|
+
ops.push(`${use('insert')}(${elVar}, () => ${exprCode}, null, null);`)
|
|
931
|
+
}
|
|
932
|
+
else if (isLast) {
|
|
933
|
+
const startVar = requestChild(elVar, domIndex)
|
|
818
934
|
html += '<!---->'
|
|
819
935
|
domIndex++
|
|
936
|
+
ops.push(`${use('insert')}(${elVar}, () => ${exprCode}, null, ${startVar});`)
|
|
937
|
+
}
|
|
938
|
+
else {
|
|
939
|
+
const startVar = requestChild(elVar, domIndex)
|
|
940
|
+
const endVar = requestChild(elVar, domIndex + 1)
|
|
941
|
+
html += '<!----><!---->'
|
|
942
|
+
dynamicRangeSlots.add(`${elVar}:${domIndex + 1}`)
|
|
943
|
+
domIndex += 2
|
|
944
|
+
ops.push(`${use('insert')}(${elVar}, () => ${exprCode}, ${endVar}, ${startVar});`)
|
|
820
945
|
}
|
|
821
|
-
ops.push(`${use('insert')}(${elVar}, () => ${exprCode}, ${anchorVar});`)
|
|
822
946
|
continue
|
|
823
947
|
}
|
|
824
948
|
|
|
@@ -899,6 +1023,10 @@ export function compileDom(filename: string, code: string, options: CompileDomOp
|
|
|
899
1023
|
expr = `${use('skipText')}(${expr})`
|
|
900
1024
|
pos += 2
|
|
901
1025
|
}
|
|
1026
|
+
else if (dynamicRangeSlots.has(`${pVar}:${pos + 1}`)) {
|
|
1027
|
+
expr = `${use('skipRange')}(${expr})`
|
|
1028
|
+
pos += 1
|
|
1029
|
+
}
|
|
902
1030
|
else {
|
|
903
1031
|
expr = `${expr}.nextSibling`
|
|
904
1032
|
pos += 1
|
|
@@ -932,7 +1060,7 @@ export function compileDom(filename: string, code: string, options: CompileDomOp
|
|
|
932
1060
|
if (child.type === 'JSXElement' || child.type === 'JSXFragment')
|
|
933
1061
|
return compileRootJsx(child, scopeRewrites)
|
|
934
1062
|
if (child.type === 'JSXText')
|
|
935
|
-
return `document.createTextNode(${JSON.stringify(cleanJsxText(child.value as string))})`
|
|
1063
|
+
return `document.createTextNode(${JSON.stringify(decodeHtmlEntities(cleanJsxText(child.value as string)))})`
|
|
936
1064
|
return `document.createTextNode(String(${compileExpression(child.expression, scopeRewrites)} ?? ""))`
|
|
937
1065
|
})
|
|
938
1066
|
return `${use('frag')}(${items.join(', ')})`
|
|
@@ -1001,30 +1129,25 @@ export function compileDom(filename: string, code: string, options: CompileDomOp
|
|
|
1001
1129
|
}
|
|
1002
1130
|
return undefined
|
|
1003
1131
|
})
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
active.set(k, v)
|
|
1009
|
-
}
|
|
1010
|
-
if (active.size > 0)
|
|
1011
|
-
editor.replace(stmt.start, stmt.end, rewriteFreeIdentifiers(code, stmt, active))
|
|
1012
|
-
}
|
|
1013
|
-
else {
|
|
1014
|
-
walk(stmt, (child) => {
|
|
1015
|
-
if (child.type === 'JSXElement' || child.type === 'JSXFragment') {
|
|
1016
|
-
editor.replace(child.start, child.end, compileRootJsx(child, propRewrites))
|
|
1017
|
-
return false
|
|
1018
|
-
}
|
|
1019
|
-
return undefined
|
|
1020
|
-
})
|
|
1132
|
+
const active = new Map<string, string>()
|
|
1133
|
+
for (const [k, v] of propRewrites) {
|
|
1134
|
+
if (!shadowed.has(k))
|
|
1135
|
+
active.set(k, v)
|
|
1021
1136
|
}
|
|
1137
|
+
// A statement holding JSX also reads props around it (`if (on) return <b/>`): compile both in one pass.
|
|
1138
|
+
if (stmtHasJsx)
|
|
1139
|
+
editor.replace(stmt.start, stmt.end, compileExpression(stmt, active))
|
|
1140
|
+
else if (active.size > 0)
|
|
1141
|
+
editor.replace(stmt.start, stmt.end, rewriteFreeIdentifiers(code, stmt, active))
|
|
1022
1142
|
if (stmt.type === 'VariableDeclaration') {
|
|
1023
1143
|
for (const d of stmt.declarations as AstNode[])
|
|
1024
1144
|
collectPatternNames(d.id, shadowed)
|
|
1025
1145
|
}
|
|
1026
1146
|
}
|
|
1027
1147
|
}
|
|
1148
|
+
else if (propRewrites.size > 0) {
|
|
1149
|
+
editor.replace(fn.body.start, fn.body.end, compileExpression(fn.body, propRewrites))
|
|
1150
|
+
}
|
|
1028
1151
|
else {
|
|
1029
1152
|
walk(fn.body, (child) => {
|
|
1030
1153
|
if (child.type === 'JSXElement' || child.type === 'JSXFragment') {
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
// What must never reach a browser bundle, shared by `kay build` and `kay check`.
|
|
2
|
+
|
|
3
|
+
import type { AstNode } from './analyze'
|
|
4
|
+
import { walk } from './analyze'
|
|
5
|
+
|
|
6
|
+
export const SERVER_ONLY_MODULES = new Set([
|
|
7
|
+
'kay/server',
|
|
8
|
+
'@kayjs/kay/server',
|
|
9
|
+
'bun:sqlite',
|
|
10
|
+
'bun:ffi',
|
|
11
|
+
'bun:dns',
|
|
12
|
+
'node:fs',
|
|
13
|
+
'node:fs/promises',
|
|
14
|
+
'node:child_process',
|
|
15
|
+
'node:net',
|
|
16
|
+
'node:http',
|
|
17
|
+
'node:https',
|
|
18
|
+
'node:http2',
|
|
19
|
+
'node:os',
|
|
20
|
+
'node:worker_threads',
|
|
21
|
+
'node:cluster',
|
|
22
|
+
'node:dgram',
|
|
23
|
+
'node:tls',
|
|
24
|
+
'node:readline',
|
|
25
|
+
'fs',
|
|
26
|
+
'fs/promises',
|
|
27
|
+
'child_process',
|
|
28
|
+
'net',
|
|
29
|
+
'http',
|
|
30
|
+
'https',
|
|
31
|
+
])
|
|
32
|
+
|
|
33
|
+
export const SERVER_ONLY_FILTER = new RegExp(`^(?:${[...SERVER_ONLY_MODULES].map(m => m.replace(/[.*+?^${}()|[\]\\/]/g, '\\$&')).join('|')})$`)
|
|
34
|
+
|
|
35
|
+
// The client build inlines PUBLIC_* (from its own environment) and NODE_ENV; any other read ships a server variable name and crashes in the browser.
|
|
36
|
+
const CLIENT_ENV_KEY = /^(?:PUBLIC_\w*|NODE_ENV)$/
|
|
37
|
+
|
|
38
|
+
function isProcessEnv(node: AstNode | null | undefined): boolean {
|
|
39
|
+
return node?.type === 'MemberExpression' && !node.computed && node.object?.type === 'Identifier' && node.object.name === 'process' && node.property?.name === 'env'
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** True when the module reads `process.env` outside its `load()` (stripped from client code) for a key the client build does not inline. */
|
|
43
|
+
export function readsPrivateEnv(program: AstNode, isInlined: (key: string) => boolean = key => CLIENT_ENV_KEY.test(key)): boolean {
|
|
44
|
+
let found = false
|
|
45
|
+
walk(program, (node) => {
|
|
46
|
+
if (found)
|
|
47
|
+
return false
|
|
48
|
+
if (node.type === 'ExportNamedDeclaration' && node.declaration?.type === 'FunctionDeclaration' && node.declaration.id?.name === 'load')
|
|
49
|
+
return false
|
|
50
|
+
if (node.type === 'MemberExpression' && isProcessEnv(node.object)) {
|
|
51
|
+
const key = node.computed ? node.property?.value : node.property?.name
|
|
52
|
+
found = typeof key !== 'string' || !isInlined(key)
|
|
53
|
+
return false
|
|
54
|
+
}
|
|
55
|
+
if (isProcessEnv(node)) {
|
|
56
|
+
found = true
|
|
57
|
+
return false
|
|
58
|
+
}
|
|
59
|
+
return undefined
|
|
60
|
+
})
|
|
61
|
+
return found
|
|
62
|
+
}
|