@kayjs/kay 2.0.0-beta.2 → 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.
Files changed (101) hide show
  1. package/llms.txt +42 -0
  2. package/package.json +24 -13
  3. package/src/build/bundle.ts +15 -53
  4. package/src/build/client-plugin.ts +108 -0
  5. package/src/build/compile.ts +9 -44
  6. package/src/build/graph.ts +16 -3
  7. package/src/build/index.ts +45 -25
  8. package/src/build/islands.ts +28 -30
  9. package/src/build/manifest.ts +9 -4
  10. package/src/build/prerender.ts +15 -7
  11. package/src/build/report.ts +82 -13
  12. package/src/build/resolve.ts +6 -7
  13. package/src/build/routes.ts +12 -21
  14. package/src/build/server-entry.ts +38 -0
  15. package/src/cli/check.ts +49 -43
  16. package/src/cli/commands.ts +224 -0
  17. package/src/cli/index.ts +46 -302
  18. package/src/cli/new.ts +15 -509
  19. package/src/cli/upgrade-plugins.ts +168 -0
  20. package/src/cli/upgrade.ts +220 -0
  21. package/src/compiler/analyze.ts +319 -565
  22. package/src/compiler/ast.ts +39 -0
  23. package/src/compiler/data-keys.ts +233 -0
  24. package/src/compiler/dom.ts +18 -15
  25. package/src/compiler/interactivity.ts +174 -0
  26. package/src/compiler/mistakes.ts +19 -1
  27. package/src/compiler/server-only.ts +4 -1
  28. package/src/compiler/shared.ts +1 -1
  29. package/src/compiler/ssr.ts +28 -28
  30. package/src/context.ts +1 -1
  31. package/src/dev/index.ts +19 -46
  32. package/src/dom/extras.ts +43 -12
  33. package/src/dom/index.ts +25 -1
  34. package/src/index.ts +0 -13
  35. package/src/jsx-runtime.ts +1 -1
  36. package/src/plugins/config.ts +49 -0
  37. package/src/plugins/context.ts +8 -28
  38. package/src/plugins/index.ts +10 -385
  39. package/src/plugins/load.ts +61 -0
  40. package/src/plugins/order.ts +107 -0
  41. package/src/plugins/public.ts +6 -0
  42. package/src/plugins/services.ts +35 -0
  43. package/src/plugins/types.ts +193 -0
  44. package/src/server/action-registry.ts +78 -0
  45. package/src/server/action.ts +8 -2
  46. package/src/server/app-entry.ts +23 -0
  47. package/src/server/assets.ts +182 -0
  48. package/src/server/document.ts +204 -0
  49. package/src/server/errors.ts +125 -0
  50. package/src/server/http.ts +14 -0
  51. package/src/server/index.ts +66 -766
  52. package/src/server/lifecycle.ts +22 -0
  53. package/src/server/loader.ts +60 -85
  54. package/src/server/page.ts +107 -0
  55. package/src/server/plugin-host.ts +165 -0
  56. package/src/server/public.ts +15 -0
  57. package/src/server/request-scope.ts +22 -0
  58. package/src/server/security.ts +40 -1
  59. package/src/server/static-dir.ts +22 -3
  60. package/src/server/stream.ts +95 -0
  61. package/src/ssr/context.ts +25 -0
  62. package/src/ssr/index.ts +10 -7
  63. package/src/test/browser.ts +180 -0
  64. package/src/test/index.ts +25 -6
  65. package/templates/_shared/AGENTS.md +5 -0
  66. package/templates/_shared/CLAUDE.md +1 -0
  67. package/templates/_shared/public/robots.txt +2 -0
  68. package/templates/_shared/tsconfig.json +19 -0
  69. package/templates/app/.env.example +4 -0
  70. package/templates/app/kay.config.ts +11 -0
  71. package/templates/app/package.json +20 -0
  72. package/templates/app/src/auth.ts +14 -0
  73. package/templates/app/src/routes/_layout.tsx +32 -0
  74. package/templates/app/src/routes/dashboard/_middleware.ts +3 -0
  75. package/templates/app/src/routes/dashboard/index.tsx +13 -0
  76. package/templates/app/src/routes/index.tsx +15 -0
  77. package/templates/app/src/routes/login.tsx +34 -0
  78. package/templates/app/src/styles/app.css +7 -0
  79. package/templates/blog/content/posts/welcome.md +9 -0
  80. package/templates/blog/kay.config.ts +23 -0
  81. package/templates/blog/package.json +21 -0
  82. package/templates/blog/src/posts.ts +26 -0
  83. package/templates/blog/src/routes/_layout.tsx +20 -0
  84. package/templates/blog/src/routes/blog/[slug].tsx +31 -0
  85. package/templates/blog/src/routes/index.tsx +29 -0
  86. package/templates/blog/src/styles/app.css +10 -0
  87. package/templates/fullstack/kay.config.ts +6 -0
  88. package/templates/fullstack/package.json +18 -0
  89. package/templates/fullstack/src/actions/greet.ts +19 -0
  90. package/templates/fullstack/src/components/Counter.tsx +10 -0
  91. package/templates/fullstack/src/components/GreetForm.tsx +26 -0
  92. package/templates/fullstack/src/routes/_layout.tsx +14 -0
  93. package/templates/fullstack/src/routes/api/health.ts +5 -0
  94. package/templates/fullstack/src/routes/index.tsx +13 -0
  95. package/templates/fullstack/src/styles/app.css +29 -0
  96. package/templates/minimal/kay.config.ts +6 -0
  97. package/templates/minimal/package.json +18 -0
  98. package/templates/minimal/src/components/Counter.tsx +10 -0
  99. package/templates/minimal/src/routes/_layout.tsx +14 -0
  100. package/templates/minimal/src/routes/index.tsx +11 -0
  101. package/templates/minimal/src/styles/app.css +22 -0
@@ -0,0 +1,38 @@
1
+ // The generated server entry (`dist/server/_entry.js`): the one module that assembles an app from its bundled config, routes and actions.
2
+
3
+ /** The entry's path under the server bundle root, and so under `dist/server/`. An underscore file is never a route. */
4
+ export const SERVER_ENTRY_FILE = '_entry.js'
5
+
6
+ export interface ServerEntryModule {
7
+ /** Absolute source path, bundled in the same pass as the entry. */
8
+ file: string
9
+ /** The module's manifest key (`server/index.js`). */
10
+ key: string
11
+ /** Root-relative source path, read by `testApp().import()`. */
12
+ source: string
13
+ }
14
+
15
+ export interface ServerEntryOptions {
16
+ modules: readonly ServerEntryModule[]
17
+ /** `kay.config.ts`, when the app has one. */
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 `@kayjs/kay/server` imports. */
20
+ assembler: string
21
+ }
22
+
23
+ export function serverEntrySource(options: ServerEntryOptions): string {
24
+ const lines: string[] = []
25
+ const { config } = options
26
+ if (config !== undefined)
27
+ lines.push(`import * as configModule from ${JSON.stringify(config.file)}`)
28
+ options.modules.forEach((m, i) => lines.push(`import * as m${i} from ${JSON.stringify(m.file)}`))
29
+ lines.push(`import { createAppFromEntry } from ${JSON.stringify(options.assembler)}`)
30
+ lines.push(`export const kayConfig = ${config !== undefined ? 'configModule.default ?? {}' : '{}'}`)
31
+ lines.push(`export const modules = {${options.modules.map((m, i) => ` ${JSON.stringify(m.key)}: m${i},`).join('')} }`)
32
+ const sources = options.modules.map((m, i) => ` ${JSON.stringify(m.source)}: m${i},`)
33
+ if (config !== undefined)
34
+ sources.push(` ${JSON.stringify(config.source)}: configModule,`)
35
+ lines.push(`export const sources = {${sources.join('')} }`)
36
+ lines.push('export function createApp(options) { return createAppFromEntry(kayConfig, modules, options) }')
37
+ return `${lines.join('\n')}\n`
38
+ }
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, walk } from '../compiler/analyze'
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
- if (DIAGNOSTIC_PREFIX_RE.test(message)) {
73
- if (message.startsWith(`${file}:`))
74
- return `${rel}${message.slice(file.length)}`
75
- return message
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') || analysis.isInteractive)
207
+ if (!file.endsWith('.tsx'))
207
208
  continue
208
- for (const imp of analysis.imports) {
209
+ const promoted = withStateReads(analysis, (imp, imported) => {
209
210
  const resolved = graph.resolve(file, imp.source)
210
211
  if (resolved === undefined || !isTsFile(resolved))
211
- continue
212
- const state = imp.specifiers.find((spec) => {
213
- if (analysis.jsxTags.has(spec.local))
214
- return false
215
- try {
216
- if (spec.imported === '*')
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
- if (routeFileSet.has(file) && SPECIAL_ROUTE_FILES.has(basename(file)) && analysis.isInteractive) {
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, analysis.interactiveOffset ?? 0),
251
- `kay check: ${rel} uses browser interactivity (${analysis.interactiveReason}), but it renders on the server only. Move the interactive part into a component and render that component from ${rel}.`,
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 (!analysis.isInteractive && file.endsWith('.tsx')) {
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)?.isInteractive)
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)?.isInteractive === true
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 (only real route files matching `kay build`)
332
- if (routeFileSet.has(file) && !basename(file).startsWith('_')) {
333
- const problem = routeExportProblemLocation(analysis, rel)
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)
@@ -0,0 +1,224 @@
1
+ // The built-in `kay` commands, declared for @kaynooo/cli-kit: each parses its own arguments first (so `--help` and shell completion work), then loads what it runs.
2
+
3
+ import type { Commands, ExitRow } from '@kaynooo/cli-kit'
4
+ import type { ScaffoldTemplate } from './new'
5
+ import { resolve } from 'node:path'
6
+ import { badUsage, Exit, fail, parse } from '@kaynooo/cli-kit'
7
+
8
+ const TEMPLATES = ['minimal', 'fullstack', 'blog', 'app'] as const
9
+ const SIZE_RE = /^(\d+(?:\.\d+)?)\s*(kb)?$/i
10
+
11
+ const ROOT = { type: 'string', description: 'the app folder, when it is not the current one or the [dir] argument' } as const
12
+ const PORT = { type: 'string', description: 'the port to listen on (PORT, then kay.config.ts port, then 3000; 0 picks a free one)' } as const
13
+ const HOST = { type: 'string', optional: { bare: '0.0.0.0' }, description: 'the address to bind (HOST, then 127.0.0.1); bare, every interface' } as const
14
+
15
+ const OK: ExitRow = [0, 'it did what was asked']
16
+ const USAGE_EXIT: ExitRow = [2, 'a usage error']
17
+
18
+ // `--max-js 40kb`, `--max-js 40KB` or `--max-js 40960` (bytes).
19
+ function parseSize(raw: string): number {
20
+ const match = SIZE_RE.exec(raw.trim())
21
+ if (match === null)
22
+ return badUsage(`invalid --max-js "${raw}": give the gzipped size of a route's eager JS in bytes or KB, e.g. --max-js 40kb`)
23
+ return Math.round(Number(match[1]) * (match[2] === undefined ? 1 : 1024))
24
+ }
25
+
26
+ function parsePort(raw: string | number | undefined, fallback: number): number {
27
+ if (raw === undefined || raw === '')
28
+ return fallback
29
+ const n = Number(raw)
30
+ if (!Number.isInteger(n) || n < 0 || n > 65535)
31
+ return badUsage(`invalid port "${raw}": give an integer between 0 and 65535`)
32
+ return n
33
+ }
34
+
35
+ // A kay error carries its own `kay: ` or `kay <command>: ` prefix, which the kit prints already: strip it and exit 1.
36
+ async function failing<T>(command: string, run: () => Promise<T>): Promise<T> {
37
+ try {
38
+ return await run()
39
+ }
40
+ catch (error) {
41
+ if (error instanceof Exit || !(error instanceof Error))
42
+ throw error
43
+ const prefix = [`kay ${command}: `, 'kay: '].find(each => error.message.startsWith(each))
44
+ if (prefix === undefined)
45
+ throw error
46
+ return fail(error.message.slice(prefix.length), 1)
47
+ }
48
+ }
49
+
50
+ // The app folder: `--root`, else the `[dir]` argument, else where kay runs.
51
+ function rootOf(cwd: string, root: string | undefined, dir: string | undefined): string {
52
+ return resolve(cwd, root ?? dir ?? '.')
53
+ }
54
+
55
+ function newCommand(cwd: string): Commands[string] {
56
+ return {
57
+ summary: 'create an app from a template',
58
+ run: async (args) => {
59
+ const { values, positionals: [dir] } = parse(args, 'kay new [options] <dir>: creates an app from a template', {
60
+ template: { type: 'string', choices: TEMPLATES, description: 'the template (minimal)' },
61
+ force: { type: 'boolean', description: 'write into a folder that is not empty' },
62
+ root: ROOT,
63
+ }, { positionals: ['<dir>'], exits: [OK, [1, 'the folder is not empty'], USAGE_EXIT] })
64
+ const { scaffoldProject } = await import('./new')
65
+ const template = (values.template ?? 'minimal') as ScaffoldTemplate
66
+ const res = await failing('new', async () => scaffoldProject(rootOf(cwd, values.root, dir), { template, force: values.force === true }))
67
+ console.log(`Created Kay (${template}) project in ${res.root} (${res.files.length} files)`)
68
+ console.log(`\nNext steps:\n cd ${dir}\n bun install\n bun run dev`)
69
+ return 0
70
+ },
71
+ }
72
+ }
73
+
74
+ function checkCommand(cwd: string): Commands[string] {
75
+ return {
76
+ summary: 'report every mistake kay can find in the app',
77
+ run: async (args) => {
78
+ const { values, positionals: [dir] } = parse(args, 'kay check [options] [dir]: reports every mistake kay can find in the app: the compile, the config, the routes and the types', {
79
+ 'no-typecheck': { type: 'boolean', description: 'skip the TypeScript check' },
80
+ 'root': ROOT,
81
+ }, { positionals: ['[dir]'], exits: [[0, 'no error found (warnings do not count)'], [1, 'at least one error found'], USAGE_EXIT] })
82
+ const { checkProject } = await import('./check')
83
+ const t0 = performance.now()
84
+ const res = await checkProject(rootOf(cwd, values.root, dir), { skipTypecheck: values['no-typecheck'] === true })
85
+ const ms = (performance.now() - t0).toFixed(1)
86
+ for (const warning of res.warnings)
87
+ console.warn(warning)
88
+ if (res.ok) {
89
+ console.log(`kay check passed (${res.checkedFiles} files) in ${ms} ms`)
90
+ return 0
91
+ }
92
+ for (const e of res.errors)
93
+ console.error(e)
94
+ return 1
95
+ },
96
+ }
97
+ }
98
+
99
+ function upgradeCommand(cwd: string): Commands[string] {
100
+ return {
101
+ summary: 'rewrite an app written for kay v1 to the v2 API',
102
+ run: async (args) => {
103
+ const { values, positionals: [dir] } = parse(args, 'kay upgrade [options] [dir]: rewrites an app written for kay v1 to the v2 API', {
104
+ 'no-install': { type: 'boolean', description: 'do not run bun install after rewriting package.json' },
105
+ 'root': ROOT,
106
+ }, { positionals: ['[dir]'], exits: [[0, 'every file was rewritten and nothing is left to do by hand'], [1, 'bun install failed, or steps are left to do by hand (printed)'], USAGE_EXIT] })
107
+ const root = rootOf(cwd, values.root, dir)
108
+ const { upgradeProject } = await import('./upgrade')
109
+ const res = upgradeProject(root)
110
+ for (const file of res.changed)
111
+ console.log(` ${file}`)
112
+ console.log(`kay upgrade rewrote ${res.changed.length} files`)
113
+ if (res.changed.includes('package.json') && values['no-install'] !== true) {
114
+ const install = Bun.spawnSync(['bun', 'install'], { cwd: root, stdout: 'inherit', stderr: 'inherit' })
115
+ if (install.exitCode !== 0)
116
+ return 1
117
+ }
118
+ for (const line of res.manual)
119
+ console.error(line)
120
+ if (res.manual.length > 0)
121
+ return 1
122
+ console.log('Next: kay check')
123
+ return 0
124
+ },
125
+ }
126
+ }
127
+
128
+ function buildCommand(cwd: string): Commands[string] {
129
+ return {
130
+ summary: 'build the app into dist/',
131
+ run: async (args) => {
132
+ const { values, positionals: [dir] } = parse(args, 'kay build [options] [dir]: builds the app into dist/', {
133
+ 'static': { type: 'boolean', description: 'export plain HTML files instead of a server' },
134
+ 'compile': { type: 'string', optional: { bare: '' }, description: 'also produce one binary, at [out] when given' },
135
+ 'analyze': { type: 'boolean', description: 'list each island with why it is one' },
136
+ 'max-js': { type: 'string', description: 'fail a route whose eager JS gzips over this size (40kb, or bytes)' },
137
+ 'root': ROOT,
138
+ }, { positionals: ['[dir]'], exits: [[0, 'the build succeeded'], [1, 'the build failed, or a route is over --max-js'], USAGE_EXIT] })
139
+ const maxJs = values['max-js'] === undefined ? undefined : parseSize(values['max-js'])
140
+ const compile = values.compile === undefined ? undefined : values.compile === '' ? true : values.compile
141
+ const { build } = await import('../build/index')
142
+ const t0 = performance.now()
143
+ const manifest = await failing('build', async () => build({ root: rootOf(cwd, values.root, dir), static: values.static === true, compile, analyze: values.analyze === true, maxJs }))
144
+ const ms = (performance.now() - t0).toFixed(1)
145
+ console.log(`kay build done in ${ms} ms (${manifest.routes.length} routes, ${manifest.assets.length} client assets, ${manifest.actions.length} actions)`)
146
+ return 0
147
+ },
148
+ }
149
+ }
150
+
151
+ const SERVE_EXITS: ExitRow[] = [[0, 'the server started'], [1, 'the config or the server failed to load'], USAGE_EXIT]
152
+
153
+ function startCommand(cwd: string): Commands[string] {
154
+ return {
155
+ summary: 'serve the built app',
156
+ run: async (args) => {
157
+ const { values, positionals: [dir] } = parse(args, 'kay start [options] [dir]: serves the built app', { port: PORT, host: HOST, root: ROOT }, { positionals: ['[dir]'], exits: SERVE_EXITS })
158
+ const root = rootOf(cwd, values.root, dir)
159
+ process.env.NODE_ENV ??= 'production'
160
+ const { loadConfig } = await import('../plugins/index')
161
+ const config = await failing('start', async () => loadConfig(root))
162
+ const port = parsePort(values.port ?? (process.env.PORT || config.port), 3000)
163
+ const hostname = values.host ?? (process.env.HOST || '127.0.0.1')
164
+ const { createServer } = await import('../server/index')
165
+ const { handleSignals } = await import('../server/lifecycle')
166
+ const app = await failing('start', async () => createServer({ root }))
167
+ const server = app.serve(port, hostname)
168
+ handleSignals(app, server)
169
+ console.log(`kay server listening on http://${hostname}:${server.port}`)
170
+ return 0
171
+ },
172
+ }
173
+ }
174
+
175
+ function devCommand(cwd: string): Commands[string] {
176
+ return {
177
+ summary: 'serve the app with rebuild on change',
178
+ run: async (args) => {
179
+ const { values, positionals: [dir] } = parse(args, 'kay dev [options] [dir]: serves the app and rebuilds it when a file changes', { port: PORT, host: HOST, root: ROOT }, { positionals: ['[dir]'], exits: SERVE_EXITS })
180
+ const root = rootOf(cwd, values.root, dir)
181
+ const { loadConfig } = await import('../plugins/index')
182
+ const config = await failing('dev', async () => loadConfig(root))
183
+ const port = parsePort(values.port ?? (process.env.PORT || config.port), 3000)
184
+ const hostname = values.host ?? (process.env.HOST || '127.0.0.1')
185
+ const { devServer } = await import('../dev/index')
186
+ await failing('dev', async () => devServer({ root, port, hostname }))
187
+ return 0
188
+ },
189
+ }
190
+ }
191
+
192
+ export function builtinCommands(cwd: string): Commands {
193
+ return {
194
+ new: newCommand(cwd),
195
+ check: checkCommand(cwd),
196
+ dev: devCommand(cwd),
197
+ build: buildCommand(cwd),
198
+ start: startCommand(cwd),
199
+ upgrade: upgradeCommand(cwd),
200
+ }
201
+ }
202
+
203
+ // The `--root <dir>` (or `--root=<dir>`) of a plugin command's arguments, and the arguments without it.
204
+ export function takeRoot(args: readonly string[], cwd: string): { root: string, rest: string[] } {
205
+ const rest: string[] = []
206
+ let root: string | undefined
207
+ for (let i = 0; i < args.length; i++) {
208
+ const arg = args[i]!
209
+ if (arg === '--root') {
210
+ const next = args[i + 1]
211
+ if (next === undefined || next.startsWith('-'))
212
+ return badUsage('--root requires a directory path')
213
+ root = next
214
+ i++
215
+ }
216
+ else if (arg.startsWith('--root=')) {
217
+ root = arg.slice('--root='.length)
218
+ }
219
+ else {
220
+ rest.push(arg)
221
+ }
222
+ }
223
+ return { root: resolve(cwd, root ?? '.'), rest }
224
+ }