@kayjs/kay 2.0.0-alpha.6 → 2.0.0-alpha.8
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 +13 -7
- package/src/build/index.ts +129 -32
- package/src/cli/check.ts +41 -37
- package/src/cli/index.ts +5 -3
- package/src/cli/new.ts +10 -5
- package/src/compiler/dom.ts +163 -54
- package/src/compiler/server-only.ts +62 -0
- package/src/compiler/ssr.ts +16 -1
- package/src/dom/extras.ts +8 -1
- package/src/dom/index.ts +23 -14
- package/src/plugins/index.ts +10 -0
- package/src/reactivity/index.ts +61 -29
- package/src/reactivity/store.ts +4 -0
- package/src/server/http.ts +4 -2
- package/src/server/index.ts +130 -89
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kayjs/kay",
|
|
3
|
-
"version": "2.0.0-alpha.
|
|
3
|
+
"version": "2.0.0-alpha.8",
|
|
4
4
|
"description": "Bun-native TSX web framework with zero-directive automatic islands, fine-grained signals, and single-binary deploys",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"homepage": "https://kayjs.kaynooo.fr",
|
package/src/build/compile.ts
CHANGED
|
@@ -15,10 +15,11 @@ export interface CompileExecutableOptions {
|
|
|
15
15
|
outfile: string
|
|
16
16
|
kaySrcRoot: string
|
|
17
17
|
resolveKaySpecifier: (specifier: string) => string | undefined
|
|
18
|
+
bunPlugins?: BunPlugin[] | undefined
|
|
18
19
|
}
|
|
19
20
|
|
|
20
21
|
export async function compileExecutable(opts: CompileExecutableOptions): Promise<void> {
|
|
21
|
-
const { root, outDir, clientDir, manifest, assetPrefix, outfile, kaySrcRoot, resolveKaySpecifier } = opts
|
|
22
|
+
const { root, outDir, clientDir, manifest, assetPrefix, outfile, kaySrcRoot, resolveKaySpecifier, bunPlugins = [] } = opts
|
|
22
23
|
const entryPath = join(outDir, '__compile_entry.ts')
|
|
23
24
|
const imports: string[] = []
|
|
24
25
|
const modEntries: string[] = []
|
|
@@ -41,7 +42,10 @@ export async function compileExecutable(opts: CompileExecutableOptions): Promise
|
|
|
41
42
|
}
|
|
42
43
|
if (manifest.errorFile) addMod(manifest.errorFile)
|
|
43
44
|
if (manifest.notFoundFile) addMod(manifest.notFoundFile)
|
|
44
|
-
for (const a of manifest.actions)
|
|
45
|
+
for (const a of manifest.actions) {
|
|
46
|
+
addMod(a.file)
|
|
47
|
+
for (const m of a.middlewares) addMod(m)
|
|
48
|
+
}
|
|
45
49
|
|
|
46
50
|
const configPath = join(root, 'kay.config.ts')
|
|
47
51
|
const hasConfig = existsSync(configPath)
|
|
@@ -81,7 +85,7 @@ export async function compileExecutable(opts: CompileExecutableOptions): Promise
|
|
|
81
85
|
}
|
|
82
86
|
|
|
83
87
|
const cfgSpread = hasConfig
|
|
84
|
-
? `, plugins: _kayConfig?.plugins, lang: _kayConfig?.lang, security: _kayConfig?.security, trustedOrigins: _kayConfig?.trustedOrigins, compress: _kayConfig?.compress`
|
|
88
|
+
? `, plugins: _kayConfig?.plugins, lang: _kayConfig?.lang, security: _kayConfig?.security, trustedOrigins: _kayConfig?.trustedOrigins, compress: _kayConfig?.compress, onError: _kayConfig?.onError`
|
|
85
89
|
: ''
|
|
86
90
|
|
|
87
91
|
// Default NODE_ENV to 'production' in compiled binaries (dynamic key avoids Bun.build constant-folding).
|
|
@@ -96,10 +100,12 @@ export async function compileExecutable(opts: CompileExecutableOptions): Promise
|
|
|
96
100
|
`const publicEtags = { ${embeddedPublicEtags.join(', ')} };`,
|
|
97
101
|
`const prerendered = {};`,
|
|
98
102
|
`const prerenderedFiles = { ${embeddedPrerenderedFiles.join(', ')} };`,
|
|
103
|
+
`const port = Number(process.env.PORT ?? ${hasConfig ? '_kayConfig?.port ?? ' : ''}3000);`,
|
|
104
|
+
`const hostname = process.env.HOST || undefined;`,
|
|
105
|
+
`if (Bun.argv.includes('--health')) { const r = await fetch(\`http://\${hostname ?? '127.0.0.1'}:\${port}/\`).catch(() => null); process.exit(r && r.status < 500 ? 0 : 1); }`,
|
|
99
106
|
`const app = await createServerFromEmbedded({ manifest, modules, assets, publicAssets, publicEtags, prerendered, prerenderedFiles, assetPrefix: ${JSON.stringify(assetPrefix)}${cfgSpread} });`,
|
|
100
|
-
`const
|
|
101
|
-
`
|
|
102
|
-
`console.log(\`kay server listening on http://localhost:\${server.port}\`);`,
|
|
107
|
+
`const server = app.serve(port, hostname);`,
|
|
108
|
+
`console.log(\`kay server listening on http://\${hostname ?? 'localhost'}:\${server.port}\`);`,
|
|
103
109
|
].join('\n')
|
|
104
110
|
|
|
105
111
|
writeFileSync(entryPath, code)
|
|
@@ -117,7 +123,7 @@ export async function compileExecutable(opts: CompileExecutableOptions): Promise
|
|
|
117
123
|
entrypoints: [entryPath],
|
|
118
124
|
compile: { outfile },
|
|
119
125
|
minify: true,
|
|
120
|
-
plugins: [kayResolvePlugin],
|
|
126
|
+
plugins: [kayResolvePlugin, ...bunPlugins],
|
|
121
127
|
})
|
|
122
128
|
if (!res.success) {
|
|
123
129
|
const msgs = res.logs.map(l => l.message).join('\n')
|
package/src/build/index.ts
CHANGED
|
@@ -10,6 +10,7 @@ import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, wri
|
|
|
10
10
|
import { basename, dirname, extname, isAbsolute, join, relative, resolve } from 'node:path'
|
|
11
11
|
import { brotliCompressSync, constants as zlibConstants } from 'node:zlib'
|
|
12
12
|
import { analyzeModule, compileDom, compileSsr } from '../compiler/index'
|
|
13
|
+
import { readsPrivateEnv, SERVER_ONLY_FILTER } from '../compiler/server-only'
|
|
13
14
|
import { loadConfig } from '../plugins/index'
|
|
14
15
|
import { actionHash } from '../server/action'
|
|
15
16
|
import { compileExecutable } from './compile'
|
|
@@ -54,6 +55,8 @@ export interface ActionManifestEntry {
|
|
|
54
55
|
url: string
|
|
55
56
|
file: string
|
|
56
57
|
exportName: string
|
|
58
|
+
/** `_middleware.ts` chain of the folder declaring the action, outermost first. */
|
|
59
|
+
middlewares: string[]
|
|
57
60
|
}
|
|
58
61
|
|
|
59
62
|
export interface RouteManifestEntry {
|
|
@@ -221,6 +224,10 @@ interface IslandTarget {
|
|
|
221
224
|
defaultHydrate: string | undefined
|
|
222
225
|
}
|
|
223
226
|
|
|
227
|
+
function clientLeakError(leaks: Set<string>): Error {
|
|
228
|
+
return new Error(`kay build (client): server code is reachable from an island:\n${[...leaks].map(l => ` ${l}`).join('\n')}\nMove server logic to a server action or async server component.`)
|
|
229
|
+
}
|
|
230
|
+
|
|
224
231
|
export async function build(options: BuildOptions): Promise<BuildManifest> {
|
|
225
232
|
const root = resolve(options.root)
|
|
226
233
|
const fileConfig = await loadConfig(root)
|
|
@@ -377,6 +384,7 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
|
|
|
377
384
|
|
|
378
385
|
// Discover all island roots referenced from static pages/layouts/errors (or sync interactive pages themselves)
|
|
379
386
|
const islandTargets = new Map<string, IslandTarget>()
|
|
387
|
+
const islandIds = new Set<string>()
|
|
380
388
|
const pageIslandBindings = new Map<string, Map<string, IslandTarget>>()
|
|
381
389
|
|
|
382
390
|
function registerIsland(file: string, exportName: string): IslandTarget {
|
|
@@ -387,7 +395,11 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
|
|
|
387
395
|
const analysis = loadAnalysis(file)
|
|
388
396
|
const baseName = basename(file, extname(file)).toLowerCase()
|
|
389
397
|
const expLower = exportName.toLowerCase()
|
|
390
|
-
|
|
398
|
+
let id = exportName === 'default' || expLower === baseName ? baseName : `${baseName}-${expLower}`
|
|
399
|
+
// The id names the entry file and the chunk: two islands sharing a basename keep it readable and add a hash of their path.
|
|
400
|
+
if (islandIds.has(id))
|
|
401
|
+
id = `${id}-${Bun.hash(relative(root, key)).toString(36).slice(0, 6)}`
|
|
402
|
+
islandIds.add(id)
|
|
391
403
|
const target: IslandTarget = { id, file, exportName, defaultHydrate: analysis.defaultHydrate }
|
|
392
404
|
islandTargets.set(key, target)
|
|
393
405
|
return target
|
|
@@ -444,6 +456,21 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
|
|
|
444
456
|
for (const [, target] of islandTargets)
|
|
445
457
|
collectIslandCss(target.file)
|
|
446
458
|
|
|
459
|
+
// The client compiles every module an island imports to hydrate against SSR markers, so their SSR must emit them too.
|
|
460
|
+
const islandReach = new Set<string>()
|
|
461
|
+
const reachStack = [...islandTargets.values()].map(t => t.file)
|
|
462
|
+
while (reachStack.length > 0) {
|
|
463
|
+
const file = reachStack.pop()!
|
|
464
|
+
if (islandReach.has(file))
|
|
465
|
+
continue
|
|
466
|
+
islandReach.add(file)
|
|
467
|
+
for (const imp of analyses.get(file)?.imports ?? []) {
|
|
468
|
+
const target = resolveImportPath(file, imp.source)
|
|
469
|
+
if (target !== undefined && target.endsWith('.tsx'))
|
|
470
|
+
reachStack.push(target)
|
|
471
|
+
}
|
|
472
|
+
}
|
|
473
|
+
|
|
447
474
|
const standaloneCssSet = new Set<string>(pluginCssFiles)
|
|
448
475
|
for (const [file, analysis] of analyses) {
|
|
449
476
|
for (const imp of analysis.imports) {
|
|
@@ -518,9 +545,22 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
|
|
|
518
545
|
islandEntryToKey.set(entryPath, key)
|
|
519
546
|
}
|
|
520
547
|
|
|
548
|
+
const clientLeaks = new Set<string>()
|
|
549
|
+
const publicEnvDefines: Record<string, string> = {}
|
|
550
|
+
for (const [key, value] of Object.entries(process.env)) {
|
|
551
|
+
if (key.startsWith('PUBLIC_') && value !== undefined)
|
|
552
|
+
publicEnvDefines[`process.env.${key}`] = JSON.stringify(value)
|
|
553
|
+
}
|
|
554
|
+
const inlinedEnvKey = (key: string): boolean => key === 'NODE_ENV' || `process.env.${key}` in publicEnvDefines
|
|
521
555
|
const clientPlugin: BunPlugin = {
|
|
522
556
|
name: 'kay-v2-client',
|
|
523
557
|
setup(b) {
|
|
558
|
+
// Bun swaps node built-ins for empty shims in a browser build, so a server-only import would ship silently.
|
|
559
|
+
b.onResolve({ filter: SERVER_ONLY_FILTER }, (args) => {
|
|
560
|
+
if (!args.importer.includes('/node_modules/'))
|
|
561
|
+
clientLeaks.add(`${relative(root, args.importer).replace(/\\/g, '/')} imports server-only module "${args.path}"`)
|
|
562
|
+
return undefined
|
|
563
|
+
})
|
|
524
564
|
b.onResolve({ filter: /^(?:@kayjs\/)?kay(?:\/.*)?$/ }, (args) => {
|
|
525
565
|
const resolved = resolveKaySpecifier(args.path)
|
|
526
566
|
return resolved !== undefined ? { path: resolved } : undefined
|
|
@@ -571,14 +611,22 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
|
|
|
571
611
|
define: {
|
|
572
612
|
KAY_DEFERRED: hasDeferredHydrate ? 'true' : 'false',
|
|
573
613
|
KAY_CLIENT_ONLY: hasClientOnlyHydrate ? 'true' : 'false',
|
|
614
|
+
...publicEnvDefines,
|
|
574
615
|
},
|
|
575
616
|
plugins: [clientPlugin, ...pluginBunPlugins],
|
|
576
617
|
})
|
|
577
618
|
}
|
|
619
|
+
catch (err) {
|
|
620
|
+
if (clientLeaks.size > 0)
|
|
621
|
+
throw clientLeakError(clientLeaks)
|
|
622
|
+
throw err
|
|
623
|
+
}
|
|
578
624
|
finally {
|
|
579
625
|
rmSync(entriesDir, { recursive: true, force: true })
|
|
580
626
|
}
|
|
581
627
|
|
|
628
|
+
if (clientLeaks.size > 0)
|
|
629
|
+
throw clientLeakError(clientLeaks)
|
|
582
630
|
if (!clientResult.success) {
|
|
583
631
|
const msgs = clientResult.logs.map(l => l.message).join('\n')
|
|
584
632
|
throw new Error(`kay build (client) failed:\n${msgs}`)
|
|
@@ -592,10 +640,28 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
|
|
|
592
640
|
return resolve(clientDir, p)
|
|
593
641
|
}
|
|
594
642
|
|
|
643
|
+
// A process.env left in a chunk is a key the build did not inline: name the app module that put it there.
|
|
644
|
+
for (const output of clientResult.outputs) {
|
|
645
|
+
if (!output.path.endsWith('.js') || !(await output.text()).includes('process.env'))
|
|
646
|
+
continue
|
|
647
|
+
const relFile = relative(clientDir, output.path).replace(/\\/g, '/')
|
|
648
|
+
const info = clientMetafile?.outputs[relFile] ?? clientMetafile?.outputs[`./${relFile}`]
|
|
649
|
+
for (const [inKey, input] of Object.entries(info?.inputs ?? {})) {
|
|
650
|
+
const program = input.bytesInOutput > 0 ? analyses.get(resolveMetaPath(inKey))?.program : undefined
|
|
651
|
+
if (program !== undefined && readsPrivateEnv(program, inlinedEnvKey))
|
|
652
|
+
clientLeaks.add(`${relative(root, resolveMetaPath(inKey)).replace(/\\/g, '/')} reads process.env (only a process.env.PUBLIC_* set at build time is inlined)`)
|
|
653
|
+
}
|
|
654
|
+
}
|
|
655
|
+
if (clientLeaks.size > 0)
|
|
656
|
+
throw clientLeakError(clientLeaks)
|
|
657
|
+
|
|
595
658
|
if (clientMetafile !== undefined) {
|
|
596
659
|
for (const [outKey, info] of Object.entries(clientMetafile.outputs)) {
|
|
597
660
|
const relOut = outKey.replace(/^\.\//, '')
|
|
598
661
|
const url = `${assetPrefix}/${relOut}`
|
|
662
|
+
const islandKey = info.entryPoint !== undefined && relOut.endsWith('.js') ? islandEntryToKey.get(resolveMetaPath(info.entryPoint)) : undefined
|
|
663
|
+
if (islandKey !== undefined)
|
|
664
|
+
islandChunks.set(islandKey, url)
|
|
599
665
|
if (relOut.endsWith('.css')) {
|
|
600
666
|
if (info.entryPoint !== undefined) {
|
|
601
667
|
const absEntry = resolveMetaPath(info.entryPoint)
|
|
@@ -624,16 +690,8 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
|
|
|
624
690
|
if (relFile.endsWith('.css')) {
|
|
625
691
|
styleUrls.push(url)
|
|
626
692
|
}
|
|
627
|
-
else if (output.kind === 'entry-point') {
|
|
628
|
-
|
|
629
|
-
runtimeScript = url
|
|
630
|
-
}
|
|
631
|
-
else {
|
|
632
|
-
for (const [, target] of islandTargets) {
|
|
633
|
-
if (relFile.startsWith(`${target.id}-`))
|
|
634
|
-
islandChunks.set(`${target.file}#${target.exportName}`, url)
|
|
635
|
-
}
|
|
636
|
-
}
|
|
693
|
+
else if (output.kind === 'entry-point' && relFile.startsWith('runtime-')) {
|
|
694
|
+
runtimeScript = url
|
|
637
695
|
}
|
|
638
696
|
}
|
|
639
697
|
}
|
|
@@ -655,6 +713,41 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
|
|
|
655
713
|
'@kayjs/kay/test',
|
|
656
714
|
])
|
|
657
715
|
|
|
716
|
+
const reachesTsxCache = new Map<string, boolean>()
|
|
717
|
+
function reachesTsx(file: string, stack = new Set<string>()): boolean {
|
|
718
|
+
const cached = reachesTsxCache.get(file)
|
|
719
|
+
if (cached !== undefined)
|
|
720
|
+
return cached
|
|
721
|
+
if (file.endsWith('.tsx')) {
|
|
722
|
+
reachesTsxCache.set(file, true)
|
|
723
|
+
return true
|
|
724
|
+
}
|
|
725
|
+
if (stack.has(file))
|
|
726
|
+
return false
|
|
727
|
+
stack.add(file)
|
|
728
|
+
const analysis = analyses.get(file)
|
|
729
|
+
if (analysis === undefined) {
|
|
730
|
+
reachesTsxCache.set(file, false)
|
|
731
|
+
return false
|
|
732
|
+
}
|
|
733
|
+
for (const imp of analysis.imports) {
|
|
734
|
+
const target = resolveImportPath(file, imp.source)
|
|
735
|
+
if (target !== undefined && reachesTsx(target, stack)) {
|
|
736
|
+
reachesTsxCache.set(file, true)
|
|
737
|
+
return true
|
|
738
|
+
}
|
|
739
|
+
}
|
|
740
|
+
for (const re of analysis.reexports) {
|
|
741
|
+
const target = resolveImportPath(file, re.source)
|
|
742
|
+
if (target !== undefined && reachesTsx(target, stack)) {
|
|
743
|
+
reachesTsxCache.set(file, true)
|
|
744
|
+
return true
|
|
745
|
+
}
|
|
746
|
+
}
|
|
747
|
+
reachesTsxCache.set(file, false)
|
|
748
|
+
return false
|
|
749
|
+
}
|
|
750
|
+
|
|
658
751
|
const runServerBuild = async (): Promise<void> => {
|
|
659
752
|
const serverPlugin: BunPlugin = {
|
|
660
753
|
name: 'kay-v2-server',
|
|
@@ -673,33 +766,34 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
|
|
|
673
766
|
return undefined
|
|
674
767
|
}
|
|
675
768
|
})
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
769
|
+
b.onResolve({ filter: /^[^./]/ }, (args) => {
|
|
770
|
+
if (args.path === 'bun' || args.path.startsWith('bun:') || args.path.startsWith('node:') || args.path.startsWith('~') || isAbsolute(args.path))
|
|
771
|
+
return undefined
|
|
772
|
+
let resolved: string | undefined
|
|
773
|
+
try {
|
|
774
|
+
resolved = Bun.resolveSync(args.path, args.resolveDir || root)
|
|
775
|
+
}
|
|
776
|
+
catch {
|
|
681
777
|
try {
|
|
682
|
-
resolved = Bun.resolveSync(args.path,
|
|
778
|
+
resolved = Bun.resolveSync(args.path, root)
|
|
683
779
|
}
|
|
684
780
|
catch {
|
|
685
|
-
|
|
686
|
-
resolved = Bun.resolveSync(args.path, root)
|
|
687
|
-
}
|
|
688
|
-
catch {
|
|
689
|
-
return undefined
|
|
690
|
-
}
|
|
781
|
+
return undefined
|
|
691
782
|
}
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
return
|
|
696
|
-
|
|
697
|
-
|
|
783
|
+
}
|
|
784
|
+
// Bundle any package that exports/re-exports .tsx components so Kay's SSR compiler transforms them.
|
|
785
|
+
if (resolved.endsWith('.tsx') || reachesTsx(resolved))
|
|
786
|
+
return { path: resolved }
|
|
787
|
+
if (outDirOutsideRoot)
|
|
788
|
+
return { path: resolved, external: true }
|
|
789
|
+
return undefined
|
|
790
|
+
})
|
|
698
791
|
b.onLoad({ filter: /\.tsx$/ }, (args) => {
|
|
699
792
|
const analysis = analyses.get(args.path)
|
|
700
793
|
const rawBindings = pageIslandBindings.get(args.path)
|
|
701
794
|
let islandMap: Map<string, IslandBinding> | undefined
|
|
702
|
-
|
|
795
|
+
const inIsland = analysis?.isInteractive === true || islandReach.has(args.path)
|
|
796
|
+
let islandKey = inIsland ? '1' : '0'
|
|
703
797
|
if (rawBindings !== undefined) {
|
|
704
798
|
islandMap = new Map()
|
|
705
799
|
for (const [localName, target] of rawBindings) {
|
|
@@ -722,7 +816,7 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
|
|
|
722
816
|
const compiled = compileSsr(args.path, raw, {
|
|
723
817
|
analysis,
|
|
724
818
|
islands: islandMap,
|
|
725
|
-
isIsland:
|
|
819
|
+
isIsland: inIsland,
|
|
726
820
|
})
|
|
727
821
|
const outCode = applyTransforms(compiled.code, args.path, 'server')
|
|
728
822
|
if (cache !== undefined && stamp !== undefined)
|
|
@@ -919,8 +1013,10 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
|
|
|
919
1013
|
const actionEntries: ActionManifestEntry[] = []
|
|
920
1014
|
for (const [srcFile, list] of actionsByFile) {
|
|
921
1015
|
const outFile = toOutRel(srcFile)
|
|
1016
|
+
const inRoutes = !relative(routesDir, srcFile).startsWith('..')
|
|
1017
|
+
const middlewares = inRoutes ? ancestorFiles(routesDir, srcFile, ['_middleware.ts', '_middleware.tsx']).map(toOutRel) : []
|
|
922
1018
|
for (const a of list)
|
|
923
|
-
actionEntries.push({ url: a.url, file: outFile, exportName: a.exportName })
|
|
1019
|
+
actionEntries.push({ url: a.url, file: outFile, exportName: a.exportName, middlewares })
|
|
924
1020
|
}
|
|
925
1021
|
|
|
926
1022
|
const islandsRecord: Record<string, string> = {}
|
|
@@ -1151,6 +1247,7 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
|
|
|
1151
1247
|
outfile,
|
|
1152
1248
|
kaySrcRoot: KAY_SRC_ROOT,
|
|
1153
1249
|
resolveKaySpecifier,
|
|
1250
|
+
bunPlugins: pluginBunPlugins,
|
|
1154
1251
|
})
|
|
1155
1252
|
}
|
|
1156
1253
|
|
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
|
@@ -70,10 +70,12 @@ else if (cmd === 'build') {
|
|
|
70
70
|
}
|
|
71
71
|
else if (cmd === 'start') {
|
|
72
72
|
process.env.NODE_ENV ??= 'production'
|
|
73
|
-
const
|
|
73
|
+
const config = await loadConfig(root)
|
|
74
|
+
const port = Number(flagValue('--port') || process.env.PORT || config.port || 3000)
|
|
75
|
+
const hostname = process.env.HOST || undefined
|
|
74
76
|
const app = await createServer({ root })
|
|
75
|
-
const server = app.serve(port)
|
|
76
|
-
console.log(`kay server listening on http
|
|
77
|
+
const server = app.serve(port, hostname)
|
|
78
|
+
console.log(`kay server listening on http://${hostname ?? 'localhost'}:${server.port}`)
|
|
77
79
|
}
|
|
78
80
|
else if (cmd === 'dev') {
|
|
79
81
|
const port = Number(flagValue('--port') || process.env.PORT || 3000)
|
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-alpha.
|
|
18
|
+
const kayVersion = options.kayVersion ?? '^2.0.0-alpha.8'
|
|
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>
|