@kayjs/kay 2.0.0-beta.3 → 2.0.0-beta.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/llms.txt +42 -0
- package/package.json +24 -13
- package/src/build/bundle.ts +11 -51
- package/src/build/client-plugin.ts +108 -0
- package/src/build/compile.ts +4 -2
- package/src/build/graph.ts +16 -3
- package/src/build/index.ts +23 -15
- package/src/build/islands.ts +28 -30
- package/src/build/manifest.ts +6 -3
- package/src/build/report.ts +82 -13
- package/src/build/resolve.ts +6 -7
- package/src/build/routes.ts +12 -21
- package/src/build/server-entry.ts +1 -1
- package/src/cli/check.ts +49 -43
- package/src/cli/commands.ts +224 -0
- package/src/cli/index.ts +46 -302
- package/src/cli/new.ts +15 -509
- package/src/cli/upgrade-plugins.ts +168 -0
- package/src/cli/upgrade.ts +220 -0
- package/src/compiler/analyze.ts +319 -565
- package/src/compiler/ast.ts +39 -0
- package/src/compiler/data-keys.ts +233 -0
- package/src/compiler/dom.ts +18 -15
- package/src/compiler/interactivity.ts +174 -0
- package/src/compiler/mistakes.ts +19 -1
- package/src/compiler/server-only.ts +4 -1
- package/src/compiler/shared.ts +1 -1
- package/src/compiler/ssr.ts +28 -28
- package/src/context.ts +1 -1
- package/src/dev/index.ts +15 -23
- package/src/dom/extras.ts +43 -12
- package/src/dom/index.ts +25 -1
- package/src/index.ts +0 -13
- package/src/jsx-runtime.ts +1 -1
- package/src/plugins/context.ts +8 -6
- package/src/plugins/index.ts +2 -2
- package/src/plugins/load.ts +25 -2
- package/src/plugins/public.ts +6 -0
- package/src/plugins/services.ts +15 -3
- package/src/plugins/types.ts +7 -11
- package/src/server/action-registry.ts +10 -4
- package/src/server/action.ts +8 -2
- package/src/server/document.ts +13 -1
- package/src/server/errors.ts +7 -5
- package/src/server/index.ts +9 -10
- package/src/server/lifecycle.ts +22 -0
- package/src/server/plugin-host.ts +6 -8
- package/src/server/public.ts +15 -0
- package/src/server/request-scope.ts +22 -0
- package/src/server/stream.ts +4 -3
- package/src/ssr/context.ts +25 -0
- package/src/ssr/index.ts +10 -7
- package/src/test/browser.ts +180 -0
- package/src/test/index.ts +4 -1
- package/templates/_shared/AGENTS.md +5 -0
- package/templates/_shared/CLAUDE.md +1 -0
- package/templates/_shared/public/robots.txt +2 -0
- package/templates/_shared/tsconfig.json +19 -0
- package/templates/app/.env.example +4 -0
- package/templates/app/kay.config.ts +11 -0
- package/templates/app/package.json +20 -0
- package/templates/app/src/auth.ts +14 -0
- package/templates/app/src/routes/_layout.tsx +32 -0
- package/templates/app/src/routes/dashboard/_middleware.ts +3 -0
- package/templates/app/src/routes/dashboard/index.tsx +13 -0
- package/templates/app/src/routes/index.tsx +15 -0
- package/templates/app/src/routes/login.tsx +34 -0
- package/templates/app/src/styles/app.css +7 -0
- package/templates/blog/content/posts/welcome.md +9 -0
- package/templates/blog/kay.config.ts +23 -0
- package/templates/blog/package.json +21 -0
- package/templates/blog/src/posts.ts +26 -0
- package/templates/blog/src/routes/_layout.tsx +20 -0
- package/templates/blog/src/routes/blog/[slug].tsx +31 -0
- package/templates/blog/src/routes/index.tsx +29 -0
- package/templates/blog/src/styles/app.css +10 -0
- package/templates/fullstack/kay.config.ts +6 -0
- package/templates/fullstack/package.json +18 -0
- package/templates/fullstack/src/actions/greet.ts +19 -0
- package/templates/fullstack/src/components/Counter.tsx +10 -0
- package/templates/fullstack/src/components/GreetForm.tsx +26 -0
- package/templates/fullstack/src/routes/_layout.tsx +14 -0
- package/templates/fullstack/src/routes/api/health.ts +5 -0
- package/templates/fullstack/src/routes/index.tsx +13 -0
- package/templates/fullstack/src/styles/app.css +29 -0
- package/templates/minimal/kay.config.ts +6 -0
- package/templates/minimal/package.json +18 -0
- package/templates/minimal/src/components/Counter.tsx +10 -0
- package/templates/minimal/src/routes/_layout.tsx +14 -0
- package/templates/minimal/src/routes/index.tsx +11 -0
- package/templates/minimal/src/styles/app.css +22 -0
package/src/build/manifest.ts
CHANGED
|
@@ -84,7 +84,9 @@ function createReachWalker(graph: ModuleGraph, islands: IslandPlan, islandChunks
|
|
|
84
84
|
if (analysis.defaultHydrate === undefined || analysis.defaultHydrate === 'load')
|
|
85
85
|
reach.eager.add(chunk)
|
|
86
86
|
}
|
|
87
|
-
|
|
87
|
+
// Imports rendered only inside the module's islands ship within them; a static component beside an island renders its own.
|
|
88
|
+
if (analysis.staticJsxTags.size === 0)
|
|
89
|
+
return
|
|
88
90
|
}
|
|
89
91
|
for (const [localName, target] of islands.pageBindings.get(file) ?? []) {
|
|
90
92
|
const chunk = islandChunks.get(islandKey(target))
|
|
@@ -182,6 +184,7 @@ export function buildRouteEntries(options: {
|
|
|
182
184
|
|
|
183
185
|
const routes = options.pageFiles.map((file): RouteManifestEntry => {
|
|
184
186
|
const analysis = graph.analyses.get(file)
|
|
187
|
+
const page = analysis?.exports.get('default')
|
|
185
188
|
const layoutSrcs = ancestorFiles(routesDir, file, ['_layout.tsx'])
|
|
186
189
|
const chunks = new Set<string>()
|
|
187
190
|
const eagerChunks = new Set<string>()
|
|
@@ -203,10 +206,10 @@ export function buildRouteEntries(options: {
|
|
|
203
206
|
layouts: layoutSrcs.map(toOutRel),
|
|
204
207
|
middlewares: ancestorFiles(routesDir, file, MIDDLEWARE_NAMES).map(toOutRel),
|
|
205
208
|
hasLoad: analysis?.hasLoadExport,
|
|
206
|
-
isIsland:
|
|
209
|
+
isIsland: page?.interactive,
|
|
207
210
|
islandChunk: islandChunks.get(`${file}#default`),
|
|
208
211
|
islandHydrate: analysis?.defaultHydrate,
|
|
209
|
-
islandDataKeys:
|
|
212
|
+
islandDataKeys: page?.interactive === true && analysis?.hasLoadExport === true ? analysis.defaultDataKeys : undefined,
|
|
210
213
|
islandChunks: [...chunks],
|
|
211
214
|
eagerIslandChunks: [...eagerChunks],
|
|
212
215
|
styles: [...styles],
|
package/src/build/report.ts
CHANGED
|
@@ -1,8 +1,28 @@
|
|
|
1
|
-
// The `--analyze` report: eager JS and CSS weight per route, from the manifest and the client metafile.
|
|
1
|
+
// The `--analyze` report and the `--max-js` budget: eager JS and CSS weight per route, from the manifest and the client metafile (or the chunks' own imports), and the islands behind it.
|
|
2
2
|
|
|
3
|
+
import type { ModuleGraph } from './graph'
|
|
4
|
+
import type { IslandPlan } from './islands'
|
|
3
5
|
import type { BuildManifest } from './manifest'
|
|
4
6
|
import { existsSync, readFileSync } from 'node:fs'
|
|
5
|
-
import { join } from 'node:path'
|
|
7
|
+
import { join, posix } from 'node:path'
|
|
8
|
+
import { relPosix } from './files'
|
|
9
|
+
|
|
10
|
+
// A static `import ... from "./x.js"` or `import "./x.js"` of an emitted chunk; `import("./x.js")` stays lazy and is left out.
|
|
11
|
+
const STATIC_CHUNK_IMPORT_RE = /\b(?:import|export)\s*(?:[^"'();]*?\bfrom\s*)?["'](\.\.?\/[^"']+\.js)["']/g
|
|
12
|
+
|
|
13
|
+
export interface IslandOrigin {
|
|
14
|
+
/** The component's export name, `default` for a page or a default export. */
|
|
15
|
+
name: string
|
|
16
|
+
/** Root-relative source file. */
|
|
17
|
+
file: string
|
|
18
|
+
/** Why kay runs it in the browser, e.g. `uses onClick`. */
|
|
19
|
+
reason: string
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export interface RouteIsland extends IslandOrigin {
|
|
23
|
+
/** Loaded with the page, so counted in the route's eager JS. */
|
|
24
|
+
eager: boolean
|
|
25
|
+
}
|
|
6
26
|
|
|
7
27
|
export interface RouteBundleMetrics {
|
|
8
28
|
path: string
|
|
@@ -12,6 +32,25 @@ export interface RouteBundleMetrics {
|
|
|
12
32
|
cssGzip: number
|
|
13
33
|
jsFiles: number
|
|
14
34
|
cssFiles: number
|
|
35
|
+
islands: RouteIsland[]
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export interface BundleReport {
|
|
39
|
+
routes: RouteBundleMetrics[]
|
|
40
|
+
totalJsGzip: number
|
|
41
|
+
totalCssGzip: number
|
|
42
|
+
topModules: { path: string, bytes: number }[]
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Each island chunk URL, mapped to the component it hydrates and why that component became an island. */
|
|
46
|
+
export function islandOrigins(islands: IslandPlan, islandChunks: Map<string, string>, graph: ModuleGraph, root: string): Map<string, IslandOrigin> {
|
|
47
|
+
const origins = new Map<string, IslandOrigin>()
|
|
48
|
+
for (const [key, target] of islands.targets) {
|
|
49
|
+
const url = islandChunks.get(key)
|
|
50
|
+
if (url !== undefined)
|
|
51
|
+
origins.set(url, { name: target.exportName, file: relPosix(root, target.file), reason: graph.load(target.file).exports.get(target.exportName)?.reason ?? 'is interactive' })
|
|
52
|
+
}
|
|
53
|
+
return origins
|
|
15
54
|
}
|
|
16
55
|
|
|
17
56
|
export function analyzeBundleWeights(
|
|
@@ -19,7 +58,8 @@ export function analyzeBundleWeights(
|
|
|
19
58
|
clientDir: string,
|
|
20
59
|
assetPrefix = '/_kay',
|
|
21
60
|
metafile?: Bun.BuildOutput['metafile'],
|
|
22
|
-
|
|
61
|
+
origins = new Map<string, IslandOrigin>(),
|
|
62
|
+
): BundleReport {
|
|
23
63
|
const prefix = `${assetPrefix.replace(/\/$/, '')}/`
|
|
24
64
|
const sizeCache = new Map<string, { raw: number, gzip: number }>()
|
|
25
65
|
|
|
@@ -58,6 +98,17 @@ export function analyzeBundleWeights(
|
|
|
58
98
|
}
|
|
59
99
|
}
|
|
60
100
|
|
|
101
|
+
// Without the metafile, a chunk's static imports are read from the emitted file itself.
|
|
102
|
+
const depsOf = (url: string): readonly string[] => {
|
|
103
|
+
const known = jsDeps.get(url)
|
|
104
|
+
if (known !== undefined || metafile !== undefined || !url.startsWith(prefix))
|
|
105
|
+
return known ?? []
|
|
106
|
+
const abs = join(clientDir, url.slice(prefix.length))
|
|
107
|
+
const deps = existsSync(abs) ? [...readFileSync(abs, 'utf8').matchAll(STATIC_CHUNK_IMPORT_RE)].map(m => posix.join(posix.dirname(url), m[1]!)) : []
|
|
108
|
+
jsDeps.set(url, deps)
|
|
109
|
+
return deps
|
|
110
|
+
}
|
|
111
|
+
|
|
61
112
|
const collectTransitiveJs = (urls: readonly string[]): Set<string> => {
|
|
62
113
|
const seen = new Set<string>()
|
|
63
114
|
const stack = [...urls]
|
|
@@ -66,7 +117,7 @@ export function analyzeBundleWeights(
|
|
|
66
117
|
if (seen.has(cur))
|
|
67
118
|
continue
|
|
68
119
|
seen.add(cur)
|
|
69
|
-
for (const dep of
|
|
120
|
+
for (const dep of depsOf(cur))
|
|
70
121
|
stack.push(dep)
|
|
71
122
|
}
|
|
72
123
|
return seen
|
|
@@ -76,8 +127,15 @@ export function analyzeBundleWeights(
|
|
|
76
127
|
const eagerJsRoots: string[] = []
|
|
77
128
|
if (r.islandChunks.length > 0 && manifest.runtimeScript !== undefined)
|
|
78
129
|
eagerJsRoots.push(manifest.runtimeScript)
|
|
79
|
-
|
|
130
|
+
const eager = r.eagerIslandChunks ?? r.islandChunks
|
|
131
|
+
for (const c of eager)
|
|
80
132
|
eagerJsRoots.push(c)
|
|
133
|
+
const islands: RouteIsland[] = []
|
|
134
|
+
for (const chunk of r.islandChunks) {
|
|
135
|
+
const origin = origins.get(chunk)
|
|
136
|
+
if (origin !== undefined)
|
|
137
|
+
islands.push({ ...origin, eager: eager.includes(chunk) })
|
|
138
|
+
}
|
|
81
139
|
|
|
82
140
|
const jsSet = collectTransitiveJs(eagerJsRoots)
|
|
83
141
|
let jsRaw = 0
|
|
@@ -105,6 +163,7 @@ export function analyzeBundleWeights(
|
|
|
105
163
|
cssGzip,
|
|
106
164
|
jsFiles: jsSet.size,
|
|
107
165
|
cssFiles: cssList.length,
|
|
166
|
+
islands,
|
|
108
167
|
}
|
|
109
168
|
})
|
|
110
169
|
|
|
@@ -126,14 +185,10 @@ export function analyzeBundleWeights(
|
|
|
126
185
|
return { routes, totalJsGzip, totalCssGzip, topModules }
|
|
127
186
|
}
|
|
128
187
|
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
metafile?: Bun.BuildOutput['metafile'],
|
|
134
|
-
): string {
|
|
135
|
-
const report = analyzeBundleWeights(manifest, clientDir, assetPrefix, metafile)
|
|
136
|
-
const kb = (b: number) => `${(b / 1024).toFixed(2)} KB`
|
|
188
|
+
const kb = (b: number): string => `${(b / 1024).toFixed(2)} KB`
|
|
189
|
+
const islandLine = (island: RouteIsland): string => `${island.name} (${island.file}) ${island.reason}`
|
|
190
|
+
|
|
191
|
+
export function formatBundleReport(report: BundleReport): string {
|
|
137
192
|
const lines = [
|
|
138
193
|
'\n=== KAY BUNDLE WEIGHT REPORT ===',
|
|
139
194
|
`Total emitted: JS ${kb(report.totalJsGzip)} gz | CSS ${kb(report.totalCssGzip)} gz`,
|
|
@@ -147,6 +202,8 @@ export function formatBundleReport(
|
|
|
147
202
|
+ kb(r.cssGzip).padStart(14)
|
|
148
203
|
+ `${r.jsFiles}j/${r.cssFiles}c`.padStart(10),
|
|
149
204
|
)
|
|
205
|
+
for (const island of r.islands)
|
|
206
|
+
lines.push(` ${island.eager ? 'island' : 'island, deferred'}: ${islandLine(island)}`)
|
|
150
207
|
}
|
|
151
208
|
if (report.topModules.length > 0) {
|
|
152
209
|
lines.push('', 'Top modules (minified output bytes):')
|
|
@@ -155,3 +212,15 @@ export function formatBundleReport(
|
|
|
155
212
|
}
|
|
156
213
|
return lines.join('\n')
|
|
157
214
|
}
|
|
215
|
+
|
|
216
|
+
/** Throws naming each route whose eager JS, gzipped, is over `maxBytes`, with the islands it loads with the page. */
|
|
217
|
+
export function checkJsBudget(report: BundleReport, maxBytes: number): void {
|
|
218
|
+
const over = report.routes.filter(r => r.jsGzip > maxBytes)
|
|
219
|
+
if (over.length === 0)
|
|
220
|
+
return
|
|
221
|
+
const lines = over.map((r) => {
|
|
222
|
+
const eager = r.islands.filter(island => island.eager).map(islandLine)
|
|
223
|
+
return ` ${r.path} ships ${kb(r.jsGzip)} of eager JS: ${eager.length > 0 ? eager.join('; ') : 'the kay runtime alone'}`
|
|
224
|
+
})
|
|
225
|
+
throw new Error(`kay build: eager JS over --max-js ${kb(maxBytes)} (gzip) on ${over.length === 1 ? 'one route' : `${over.length} routes`}:\n${lines.join('\n')}\nDefer an island with export const hydrate = 'visible', move its state into fewer components, or raise --max-js.`)
|
|
226
|
+
}
|
package/src/build/resolve.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// Resolves an import the way kay build follows it: relative files, then packages through Bun's resolver; kay, node:, bun and ~ aliases stay unresolved.
|
|
1
|
+
// Resolves an import the way kay build follows it: relative files, then packages through Bun's resolver; @kayjs/kay, node:, bun and ~ aliases stay unresolved.
|
|
2
2
|
|
|
3
3
|
import { statSync } from 'node:fs'
|
|
4
4
|
import { dirname, join, resolve } from 'node:path'
|
|
@@ -6,6 +6,7 @@ import pkg from '../../package.json' with { type: 'json' }
|
|
|
6
6
|
|
|
7
7
|
export const KAY_SRC_ROOT = resolve(import.meta.dir, '..')
|
|
8
8
|
|
|
9
|
+
|
|
9
10
|
export function resolveImportPath(fromFile: string, specifier: string): string | undefined {
|
|
10
11
|
if (specifier.startsWith('.')) {
|
|
11
12
|
const base = resolve(dirname(fromFile), specifier)
|
|
@@ -17,9 +18,7 @@ export function resolveImportPath(fromFile: string, specifier: string): string |
|
|
|
17
18
|
return undefined
|
|
18
19
|
}
|
|
19
20
|
if (
|
|
20
|
-
specifier === 'kay'
|
|
21
|
-
|| specifier.startsWith('kay/')
|
|
22
|
-
|| specifier === '@kayjs/kay'
|
|
21
|
+
specifier === '@kayjs/kay'
|
|
23
22
|
|| specifier.startsWith('@kayjs/kay/')
|
|
24
23
|
|| specifier.startsWith('node:')
|
|
25
24
|
|| specifier === 'bun'
|
|
@@ -39,13 +38,13 @@ export function resolveImportPath(fromFile: string, specifier: string): string |
|
|
|
39
38
|
|
|
40
39
|
const KAY_SPECIFIER_FILES = new Map<string, string>(
|
|
41
40
|
Object.entries(pkg.exports as Record<string, string>).map(([subpath, target]) => [
|
|
42
|
-
subpath === '.' ? 'kay' :
|
|
41
|
+
subpath === '.' ? '@kayjs/kay' : `@kayjs/kay/${subpath.slice(2)}`,
|
|
43
42
|
target.replace(/^\.\/src\//, ''),
|
|
44
43
|
]),
|
|
45
44
|
)
|
|
46
45
|
|
|
47
|
-
/** Maps
|
|
46
|
+
/** Maps `@kayjs/kay` and its subpaths to their source file. */
|
|
48
47
|
export function resolveKaySpecifier(specifier: string): string | undefined {
|
|
49
|
-
const file = KAY_SPECIFIER_FILES.get(specifier
|
|
48
|
+
const file = KAY_SPECIFIER_FILES.get(specifier)
|
|
50
49
|
return file === undefined ? undefined : join(KAY_SRC_ROOT, file)
|
|
51
50
|
}
|
package/src/build/routes.ts
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
import type { ModuleAnalysis } from '../compiler/index'
|
|
4
4
|
import { existsSync } from 'node:fs'
|
|
5
|
-
import { dirname, join, relative } from 'node:path'
|
|
5
|
+
import { basename, dirname, join, relative } from 'node:path'
|
|
6
6
|
import { relPosix } from './files'
|
|
7
7
|
|
|
8
8
|
export const SPECIAL_ROUTE_FILES = new Set(['_layout.tsx', '_middleware.ts', '_middleware.tsx', '_error.tsx', '_404.tsx'])
|
|
@@ -13,28 +13,19 @@ const CATCH_ALL_RE = /\[\.\.\.([^\]]+)\]/g
|
|
|
13
13
|
const PARAM_RE = /\[([^\]]+)\]/g
|
|
14
14
|
const PATH_SEPARATOR_RE = /[/\\]/
|
|
15
15
|
|
|
16
|
-
interface ExportSpecifierNode {
|
|
17
|
-
type: string
|
|
18
|
-
exportKind?: string
|
|
19
|
-
specifiers?: { exportKind?: string, exported?: { name?: string, value?: string } }[]
|
|
20
|
-
}
|
|
21
|
-
|
|
22
16
|
/** A file in routes/ is a route when it exports a default component or an HTTP method handler, directly or through `export { ... }`. */
|
|
23
17
|
export function hasRouteHandlerExport(analysis: ModuleAnalysis): boolean {
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
}
|
|
36
|
-
}
|
|
37
|
-
return false
|
|
18
|
+
return analysis.exportedNames.some(name => ROUTE_EXPORTS.has(name))
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
const SPECIAL_FILE_DEFAULTS = new Map([['_layout', 'layout component'], ['_middleware', 'middleware function'], ['_error', 'error page component'], ['_404', 'not-found page component']])
|
|
22
|
+
|
|
23
|
+
/** For a route file or a `_layout`, `_middleware`, `_error` or `_404`, what kay would otherwise drop or fail on per request: neither a route nor an action, which its folder's middleware guards, or no default export. `routesRel` is the routes folder as the app writes it. */
|
|
24
|
+
export function routeFileProblem(analysis: ModuleAnalysis, file: string, routesRel: string): string | undefined {
|
|
25
|
+
const name = basename(file)
|
|
26
|
+
if (SPECIAL_ROUTE_FILES.has(name))
|
|
27
|
+
return analysis.exportedNames.includes('default') ? undefined : `${file} has no default export: export default its ${SPECIAL_FILE_DEFAULTS.get(name.replace(TS_EXT_RE, ''))}.`
|
|
28
|
+
return hasRouteHandlerExport(analysis) || analysis.exportedActions.length > 0 ? undefined : `${file} exports no route; move it out of ${routesRel} or prefix it with _.`
|
|
38
29
|
}
|
|
39
30
|
|
|
40
31
|
const LOAD_FIX = 'kay never calls it; export async function load() and read its data with the page\'s load prop'
|
|
@@ -16,7 +16,7 @@ export interface ServerEntryOptions {
|
|
|
16
16
|
modules: readonly ServerEntryModule[]
|
|
17
17
|
/** `kay.config.ts`, when the app has one. */
|
|
18
18
|
config?: { file: string, source: string } | undefined
|
|
19
|
-
/** Absolute path of kay's `server/app-entry.ts`, bundled from source like the app's own
|
|
19
|
+
/** Absolute path of kay's `server/app-entry.ts`, bundled from source like the app's own `@kayjs/kay/server` imports. */
|
|
20
20
|
assembler: string
|
|
21
21
|
}
|
|
22
22
|
|
package/src/cli/check.ts
CHANGED
|
@@ -5,8 +5,11 @@ import { existsSync, readFileSync } from 'node:fs'
|
|
|
5
5
|
import { basename, join, relative, resolve } from 'node:path'
|
|
6
6
|
import { isTsFile, relPosix, walkFiles, walkRoutes } from '../build/files'
|
|
7
7
|
import { ModuleGraph } from '../build/graph'
|
|
8
|
-
import { fileToRoutePath, hasRouteHandlerExport, normalizeRoutePattern, routeExportProblemLocation, SPECIAL_ROUTE_FILES } from '../build/routes'
|
|
9
|
-
import { analyzeModule
|
|
8
|
+
import { fileToRoutePath, hasRouteHandlerExport, normalizeRoutePattern, routeExportProblemLocation, routeFileProblem, SPECIAL_ROUTE_FILES } from '../build/routes'
|
|
9
|
+
import { analyzeModule } from '../compiler/analyze'
|
|
10
|
+
import { walk } from '../compiler/ast'
|
|
11
|
+
import { withStateReads } from '../compiler/interactivity'
|
|
12
|
+
import { serverOnlyTagError } from '../compiler/mistakes'
|
|
10
13
|
import { findPrivateEnvOffset, SERVER_ONLY_MODULES } from '../compiler/server-only'
|
|
11
14
|
import { DIAGNOSTIC_PREFIX_RE, formatDiagnostic, formatLoc, jsxTagName } from '../compiler/shared'
|
|
12
15
|
import { createAppContext, loadConfig, resolvePlugins, runWithAppContext } from '../plugins/index'
|
|
@@ -69,12 +72,10 @@ function findExportedConstOffset(analysis: ModuleAnalysis, name: string): number
|
|
|
69
72
|
|
|
70
73
|
function normalizeDiagnosticPath(root: string, file: string, message: string): string {
|
|
71
74
|
const rel = relPosix(root, file)
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
}
|
|
77
|
-
return formatDiagnostic(`${rel}:1:1`, message)
|
|
75
|
+
const relMessage = message.replaceAll(file, rel)
|
|
76
|
+
if (DIAGNOSTIC_PREFIX_RE.test(relMessage))
|
|
77
|
+
return relMessage
|
|
78
|
+
return formatDiagnostic(`${rel}:1:1`, relMessage)
|
|
78
79
|
}
|
|
79
80
|
|
|
80
81
|
// 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.
|
|
@@ -181,7 +182,7 @@ export async function checkProject(rootDir: string, options: { skipTypecheck?: b
|
|
|
181
182
|
fileSet.add(f)
|
|
182
183
|
}
|
|
183
184
|
const files = [...fileSet].sort()
|
|
184
|
-
const graph = new ModuleGraph()
|
|
185
|
+
const graph = new ModuleGraph(root)
|
|
185
186
|
const { analyses } = graph
|
|
186
187
|
const sources = new Map<string, string>()
|
|
187
188
|
const unparsable = new Set<string>()
|
|
@@ -203,34 +204,31 @@ export async function checkProject(rootDir: string, options: { skipTypecheck?: b
|
|
|
203
204
|
|
|
204
205
|
// 3a. Promote components reading imported reactive state (same rule as `planIslands` in `kay build`)
|
|
205
206
|
for (const [file, analysis] of [...analyses]) {
|
|
206
|
-
if (!file.endsWith('.tsx')
|
|
207
|
+
if (!file.endsWith('.tsx'))
|
|
207
208
|
continue
|
|
208
|
-
|
|
209
|
+
const promoted = withStateReads(analysis, (imp, imported) => {
|
|
209
210
|
const resolved = graph.resolve(file, imp.source)
|
|
210
211
|
if (resolved === undefined || !isTsFile(resolved))
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
if (
|
|
214
|
-
return
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
return (analysisOf(resolved, analyses, sources, unparsable)?.stateExports.length ?? 0) > 0
|
|
218
|
-
const target = graph.exportTarget(resolved, spec.imported)
|
|
219
|
-
return analysisOf(target.file, analyses, sources, unparsable)?.stateExports.includes(target.exportName) === true
|
|
220
|
-
}
|
|
221
|
-
catch {
|
|
222
|
-
return false
|
|
223
|
-
}
|
|
224
|
-
})
|
|
225
|
-
if (state !== undefined) {
|
|
226
|
-
const reason = `reads ${state.local} from '${imp.source}'`
|
|
227
|
-
if (analysis.hasAsyncDefault)
|
|
228
|
-
errors.push(formatDiagnostic(locOf(root, file, sources, imp.start), `kay check: async route component cannot use browser interactivity (${reason}).`))
|
|
229
|
-
else
|
|
230
|
-
analyses.set(file, { ...analysis, isInteractive: true, interactiveReason: reason, interactiveOffset: imp.start })
|
|
231
|
-
break
|
|
212
|
+
return false
|
|
213
|
+
try {
|
|
214
|
+
if (imported === '*')
|
|
215
|
+
return (analysisOf(resolved, analyses, sources, unparsable)?.stateExports.length ?? 0) > 0
|
|
216
|
+
const target = graph.exportTarget(resolved, imported)
|
|
217
|
+
return analysisOf(target.file, analyses, sources, unparsable)?.stateExports.includes(target.exportName) === true
|
|
232
218
|
}
|
|
233
|
-
|
|
219
|
+
catch {
|
|
220
|
+
return false
|
|
221
|
+
}
|
|
222
|
+
})
|
|
223
|
+
const page = promoted?.exports.get('default')
|
|
224
|
+
if (promoted === undefined)
|
|
225
|
+
continue
|
|
226
|
+
if (analysis.hasAsyncDefault && page?.interactive === true)
|
|
227
|
+
errors.push(formatDiagnostic(locOf(root, file, sources, page.offset ?? 0), `kay check: async route component cannot use browser interactivity (${page.reason}).`))
|
|
228
|
+
else if (promoted.serverOnly !== undefined)
|
|
229
|
+
errors.push(formatDiagnostic(locOf(root, file, sources, promoted.serverOnly.offset), serverOnlyTagError(relPosix(root, file), promoted.serverOnly).message))
|
|
230
|
+
else
|
|
231
|
+
analyses.set(file, { ...analysis, ...promoted })
|
|
234
232
|
}
|
|
235
233
|
|
|
236
234
|
// Exact route discovery matching `kay build` (`walkRoutes` skips `_components/` dirs, `.d.ts`, `.test.ts`)
|
|
@@ -245,10 +243,11 @@ export async function checkProject(rootDir: string, options: { skipTypecheck?: b
|
|
|
245
243
|
const rel = relPosix(root, file)
|
|
246
244
|
|
|
247
245
|
// Special route files (`_layout.tsx`, `_error.tsx`, `_404.tsx`) cannot be interactive
|
|
248
|
-
|
|
246
|
+
const page = analysis.exports.get('default')
|
|
247
|
+
if (routeFileSet.has(file) && SPECIAL_ROUTE_FILES.has(basename(file)) && page?.interactive === true) {
|
|
249
248
|
errors.push(formatDiagnostic(
|
|
250
|
-
locOf(root, file, sources,
|
|
251
|
-
`kay check: ${rel} uses browser interactivity (${
|
|
249
|
+
locOf(root, file, sources, page.offset ?? 0),
|
|
250
|
+
`kay check: ${rel} uses browser interactivity (${page.reason}), but it renders on the server only. Move the interactive part into a component and render that component from ${rel}.`,
|
|
252
251
|
))
|
|
253
252
|
}
|
|
254
253
|
|
|
@@ -257,7 +256,7 @@ export async function checkProject(rootDir: string, options: { skipTypecheck?: b
|
|
|
257
256
|
checkIslandReach(file, root, graph, sources, unparsable, reported, errors)
|
|
258
257
|
|
|
259
258
|
// Guardrail 2: non-serializable props passed from static server code into an island (including barrels & namespaces)
|
|
260
|
-
if (
|
|
259
|
+
if (analysis.staticJsxTags.size > 0 && file.endsWith('.tsx')) {
|
|
261
260
|
const islandTags = new Set<string>()
|
|
262
261
|
const islandNamespaces = new Map<string, string>() // localNs -> resolved file
|
|
263
262
|
for (const imp of analysis.imports) {
|
|
@@ -271,7 +270,7 @@ export async function checkProject(rootDir: string, options: { skipTypecheck?: b
|
|
|
271
270
|
}
|
|
272
271
|
try {
|
|
273
272
|
const target = graph.exportTarget(resolved, spec.imported)
|
|
274
|
-
if (analysisOf(target.file, analyses, sources, unparsable)?.
|
|
273
|
+
if (analysisOf(target.file, analyses, sources, unparsable)?.exports.get(target.exportName)?.interactive === true)
|
|
275
274
|
islandTags.add(spec.local)
|
|
276
275
|
}
|
|
277
276
|
catch {}
|
|
@@ -287,7 +286,7 @@ export async function checkProject(rootDir: string, options: { skipTypecheck?: b
|
|
|
287
286
|
if (nsFile !== undefined && member !== undefined) {
|
|
288
287
|
try {
|
|
289
288
|
const target = graph.exportTarget(nsFile, member)
|
|
290
|
-
return analysisOf(target.file, analyses, sources, unparsable)?.
|
|
289
|
+
return analysisOf(target.file, analyses, sources, unparsable)?.exports.get(target.exportName)?.interactive === true
|
|
291
290
|
}
|
|
292
291
|
catch {}
|
|
293
292
|
}
|
|
@@ -296,9 +295,13 @@ export async function checkProject(rootDir: string, options: { skipTypecheck?: b
|
|
|
296
295
|
}
|
|
297
296
|
|
|
298
297
|
if (islandTags.size > 0 || islandNamespaces.size > 0) {
|
|
298
|
+
// JSX inside the module's own islands runs in the browser, where any prop is fine.
|
|
299
|
+
const inIsland = (offset: number): boolean => analysis.islandSpans.some(([start, end]) => offset >= start && offset < end)
|
|
299
300
|
walk(analysis.program, (node) => {
|
|
300
301
|
if (node.type !== 'JSXOpeningElement')
|
|
301
302
|
return
|
|
303
|
+
if (inIsland(node.start))
|
|
304
|
+
return
|
|
302
305
|
const tag = jsxTagName(node.name)
|
|
303
306
|
if (!isIslandTag(tag))
|
|
304
307
|
return
|
|
@@ -328,12 +331,15 @@ export async function checkProject(rootDir: string, options: { skipTypecheck?: b
|
|
|
328
331
|
}
|
|
329
332
|
}
|
|
330
333
|
|
|
331
|
-
// Route-specific guardrails
|
|
332
|
-
|
|
333
|
-
|
|
334
|
+
// Route-specific guardrails, on the files `kay build` reads as routes
|
|
335
|
+
const isSpecial = SPECIAL_ROUTE_FILES.has(basename(file))
|
|
336
|
+
if (routeFileSet.has(file) && (isSpecial || !basename(file).startsWith('_'))) {
|
|
337
|
+
const fileProblem = routeFileProblem(analysis, rel, relPosix(root, routesDir))
|
|
338
|
+
const problem = fileProblem === undefined ? routeExportProblemLocation(analysis, rel) : { message: fileProblem, offset: 0 }
|
|
334
339
|
if (problem !== undefined)
|
|
335
340
|
errors.push(formatDiagnostic(locOf(root, file, sources, problem.offset), `kay check: ${problem.message}`))
|
|
336
|
-
|
|
341
|
+
}
|
|
342
|
+
if (routeFileSet.has(file) && !basename(file).startsWith('_')) {
|
|
337
343
|
if (hasRouteHandlerExport(analysis)) {
|
|
338
344
|
const conflictKey = normalizeRoutePattern(fileToRoutePath(routesDir, file))
|
|
339
345
|
const prev = seenRoutes.get(conflictKey)
|