@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.
Files changed (91) hide show
  1. package/llms.txt +42 -0
  2. package/package.json +24 -13
  3. package/src/build/bundle.ts +11 -51
  4. package/src/build/client-plugin.ts +108 -0
  5. package/src/build/compile.ts +4 -2
  6. package/src/build/graph.ts +16 -3
  7. package/src/build/index.ts +23 -15
  8. package/src/build/islands.ts +28 -30
  9. package/src/build/manifest.ts +6 -3
  10. package/src/build/report.ts +82 -13
  11. package/src/build/resolve.ts +6 -7
  12. package/src/build/routes.ts +12 -21
  13. package/src/build/server-entry.ts +1 -1
  14. package/src/cli/check.ts +49 -43
  15. package/src/cli/commands.ts +224 -0
  16. package/src/cli/index.ts +46 -302
  17. package/src/cli/new.ts +15 -509
  18. package/src/cli/upgrade-plugins.ts +168 -0
  19. package/src/cli/upgrade.ts +220 -0
  20. package/src/compiler/analyze.ts +319 -565
  21. package/src/compiler/ast.ts +39 -0
  22. package/src/compiler/data-keys.ts +233 -0
  23. package/src/compiler/dom.ts +18 -15
  24. package/src/compiler/interactivity.ts +174 -0
  25. package/src/compiler/mistakes.ts +19 -1
  26. package/src/compiler/server-only.ts +4 -1
  27. package/src/compiler/shared.ts +1 -1
  28. package/src/compiler/ssr.ts +28 -28
  29. package/src/context.ts +1 -1
  30. package/src/dev/index.ts +15 -23
  31. package/src/dom/extras.ts +43 -12
  32. package/src/dom/index.ts +25 -1
  33. package/src/index.ts +0 -13
  34. package/src/jsx-runtime.ts +1 -1
  35. package/src/plugins/context.ts +8 -6
  36. package/src/plugins/index.ts +2 -2
  37. package/src/plugins/load.ts +25 -2
  38. package/src/plugins/public.ts +6 -0
  39. package/src/plugins/services.ts +15 -3
  40. package/src/plugins/types.ts +7 -11
  41. package/src/server/action-registry.ts +10 -4
  42. package/src/server/action.ts +8 -2
  43. package/src/server/document.ts +13 -1
  44. package/src/server/errors.ts +7 -5
  45. package/src/server/index.ts +9 -10
  46. package/src/server/lifecycle.ts +22 -0
  47. package/src/server/plugin-host.ts +6 -8
  48. package/src/server/public.ts +15 -0
  49. package/src/server/request-scope.ts +22 -0
  50. package/src/server/stream.ts +4 -3
  51. package/src/ssr/context.ts +25 -0
  52. package/src/ssr/index.ts +10 -7
  53. package/src/test/browser.ts +180 -0
  54. package/src/test/index.ts +4 -1
  55. package/templates/_shared/AGENTS.md +5 -0
  56. package/templates/_shared/CLAUDE.md +1 -0
  57. package/templates/_shared/public/robots.txt +2 -0
  58. package/templates/_shared/tsconfig.json +19 -0
  59. package/templates/app/.env.example +4 -0
  60. package/templates/app/kay.config.ts +11 -0
  61. package/templates/app/package.json +20 -0
  62. package/templates/app/src/auth.ts +14 -0
  63. package/templates/app/src/routes/_layout.tsx +32 -0
  64. package/templates/app/src/routes/dashboard/_middleware.ts +3 -0
  65. package/templates/app/src/routes/dashboard/index.tsx +13 -0
  66. package/templates/app/src/routes/index.tsx +15 -0
  67. package/templates/app/src/routes/login.tsx +34 -0
  68. package/templates/app/src/styles/app.css +7 -0
  69. package/templates/blog/content/posts/welcome.md +9 -0
  70. package/templates/blog/kay.config.ts +23 -0
  71. package/templates/blog/package.json +21 -0
  72. package/templates/blog/src/posts.ts +26 -0
  73. package/templates/blog/src/routes/_layout.tsx +20 -0
  74. package/templates/blog/src/routes/blog/[slug].tsx +31 -0
  75. package/templates/blog/src/routes/index.tsx +29 -0
  76. package/templates/blog/src/styles/app.css +10 -0
  77. package/templates/fullstack/kay.config.ts +6 -0
  78. package/templates/fullstack/package.json +18 -0
  79. package/templates/fullstack/src/actions/greet.ts +19 -0
  80. package/templates/fullstack/src/components/Counter.tsx +10 -0
  81. package/templates/fullstack/src/components/GreetForm.tsx +26 -0
  82. package/templates/fullstack/src/routes/_layout.tsx +14 -0
  83. package/templates/fullstack/src/routes/api/health.ts +5 -0
  84. package/templates/fullstack/src/routes/index.tsx +13 -0
  85. package/templates/fullstack/src/styles/app.css +29 -0
  86. package/templates/minimal/kay.config.ts +6 -0
  87. package/templates/minimal/package.json +18 -0
  88. package/templates/minimal/src/components/Counter.tsx +10 -0
  89. package/templates/minimal/src/routes/_layout.tsx +14 -0
  90. package/templates/minimal/src/routes/index.tsx +11 -0
  91. package/templates/minimal/src/styles/app.css +22 -0
@@ -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
+ }
package/src/cli/index.ts CHANGED
@@ -1,322 +1,66 @@
1
1
  #!/usr/bin/env bun
2
- // Kay v2 minimal CLI: `kay new`, `kay check`, `kay dev`, `kay build [--static] [--compile [out]]`, `kay start`,
3
- // plus plugin-registered commands (e.g. `kay ui-eject <grammar> [dest]`, `kay mcp-footprint`).
2
+ // Kay v2 CLI: `kay new`, `kay check`, `kay dev`, `kay build`, `kay start`, `kay upgrade`, plus plugin-registered commands
3
+ // (e.g. `kay ui-eject <grammar> [dest]`, `kay mcp-footprint`). Parsing, help, typo hints, completion and exit codes come from @kaynooo/cli-kit.
4
4
 
5
- import { resolve } from 'node:path'
6
- import { build } from '../build/index'
7
- import { devServer } from '../dev/index'
5
+ import type { Cli, Commands } from '@kaynooo/cli-kit'
6
+ import { Exit, parse, runCli as runKit } from '@kaynooo/cli-kit'
8
7
  import { loadConfig } from '../plugins/index'
9
- import { createServer } from '../server/index'
10
- import { checkProject } from './check'
11
- import { scaffoldProject } from './new'
8
+ import { builtinCommands, takeRoot } from './commands'
12
9
 
13
- const BUILTIN_COMMANDS = new Set(['new', 'check', 'build', 'start', 'dev'])
14
- const VALID_TEMPLATES = new Set(['minimal', 'fullstack', 'blog', 'app'])
15
-
16
- const VALUE_FLAGS = new Set(['--port', '--host', '--template', '--root'])
17
- const OPTIONAL_VALUE_FLAGS = new Set(['--compile'])
18
- const BOOLEAN_FLAGS = new Set(['--static', '--analyze', '--force', '--no-typecheck', '--help', '-h'])
19
-
20
- const ALLOWED_FLAGS_BY_CMD: Record<string, ReadonlySet<string>> = {
21
- new: new Set(['--template', '--force', '--root', '--help', '-h']),
22
- check: new Set(['--no-typecheck', '--root', '--help', '-h']),
23
- build: new Set(['--static', '--analyze', '--compile', '--root', '--help', '-h']),
24
- start: new Set(['--port', '--host', '--root', '--help', '-h']),
25
- dev: new Set(['--port', '--host', '--root', '--help', '-h']),
26
- }
27
-
28
- export interface ParsedCliArgs {
29
- cmd: string | undefined
30
- isBuiltin: boolean
31
- root: string
32
- dirArg: string | undefined
33
- flags: Map<string, string | true>
34
- positionals: string[]
35
- rawArgs: string[]
36
- pluginArgs: string[]
37
- error?: string | undefined
10
+ export interface RunCliOptions {
11
+ cwd?: string | undefined
38
12
  }
39
13
 
40
- export function parseCliArgs(argv: readonly string[], cwd = process.cwd()): ParsedCliArgs {
41
- const cmd = argv[0]
42
- const rest = argv.slice(1)
43
- const isBuiltin = cmd !== undefined && BUILTIN_COMMANDS.has(cmd)
44
- const flags = new Map<string, string | true>()
45
- const positionals: string[] = []
46
- const pluginArgs: string[] = []
47
-
48
- if (!isBuiltin) {
49
- let rootFlag: string | undefined
50
- for (let i = 0; i < rest.length; i++) {
51
- const arg = rest[i]!
52
- if (arg === '--root') {
53
- const next = rest[i + 1]
54
- if (next === undefined || next.startsWith('-'))
55
- return { cmd, isBuiltin, root: resolve(cwd), dirArg: undefined, flags, positionals, rawArgs: [...rest], pluginArgs, error: 'kay: --root requires a directory path' }
56
- rootFlag = next
57
- i++
58
- }
59
- else if (arg.startsWith('--root=')) {
60
- rootFlag = arg.slice('--root='.length)
61
- }
62
- else {
63
- pluginArgs.push(arg)
64
- if (!arg.startsWith('-'))
65
- positionals.push(arg)
66
- }
67
- }
68
- return {
69
- cmd,
70
- isBuiltin,
71
- root: resolve(cwd, rootFlag ?? '.'),
72
- dirArg: undefined,
73
- flags,
74
- positionals,
75
- rawArgs: [...rest],
76
- pluginArgs,
77
- }
78
- }
79
-
80
- const allowed = ALLOWED_FLAGS_BY_CMD[cmd]!
81
- for (let i = 0; i < rest.length; i++) {
82
- const arg = rest[i]!
83
- if (!arg.startsWith('-')) {
84
- positionals.push(arg)
85
- continue
14
+ // The plugin commands of the app's kay.config.ts, read only when the first word names no built-in command (or for --help and completion).
15
+ function pluginCommands(cwd: string): (words: string[]) => Promise<Commands> {
16
+ return async (words) => {
17
+ const help = words.includes('--help') || words.includes('-h')
18
+ let config: Awaited<ReturnType<typeof loadConfig>>
19
+ try {
20
+ config = await loadConfig(takeRoot(words.filter(word => word !== '--help' && word !== '-h'), cwd).root)
86
21
  }
87
-
88
- const eqIdx = arg.indexOf('=')
89
- const name = eqIdx !== -1 ? arg.slice(0, eqIdx) : arg
90
- const inlineVal = eqIdx !== -1 ? arg.slice(eqIdx + 1) : undefined
91
-
92
- if (!allowed.has(name)) {
93
- return {
94
- cmd,
95
- isBuiltin,
96
- root: resolve(cwd),
97
- dirArg: positionals[0],
98
- flags,
99
- positionals,
100
- rawArgs: [...rest],
101
- pluginArgs,
102
- error: `kay ${cmd}: unknown option "${name}"`,
103
- }
22
+ catch (error) {
23
+ // `kay --help` and completion still list the built-ins; the command typed names why its config did not load.
24
+ const name = words[0]
25
+ if (help || name === undefined || name.startsWith('-'))
26
+ return {}
27
+ const reason = error instanceof Exit ? error : new Exit(error instanceof Error ? error.message : String(error), 1)
28
+ return { [name]: { summary: '', hidden: true, run: async () => { throw reason } } }
104
29
  }
105
-
106
- if (BOOLEAN_FLAGS.has(name)) {
107
- if (inlineVal !== undefined) {
108
- return {
109
- cmd,
110
- isBuiltin,
111
- root: resolve(cwd),
112
- dirArg: positionals[0],
113
- flags,
114
- positionals,
115
- rawArgs: [...rest],
116
- pluginArgs,
117
- error: `kay ${cmd}: option "${name}" does not take a value`,
118
- }
119
- }
120
- flags.set(name, true)
121
- continue
122
- }
123
-
124
- if (VALUE_FLAGS.has(name)) {
125
- if (inlineVal !== undefined) {
126
- flags.set(name, inlineVal)
127
- }
128
- else {
129
- const next = rest[i + 1]
130
- if (name === '--host' && (next === undefined || next.startsWith('-'))) {
131
- flags.set(name, '')
132
- }
133
- else if (next === undefined || next.startsWith('-')) {
134
- return {
135
- cmd,
136
- isBuiltin,
137
- root: resolve(cwd),
138
- dirArg: positionals[0],
139
- flags,
140
- positionals,
141
- rawArgs: [...rest],
142
- pluginArgs,
143
- error: `kay ${cmd}: option "${name}" requires a value`,
144
- }
145
- }
146
- else {
147
- flags.set(name, next)
148
- i++
149
- }
150
- }
151
- continue
152
- }
153
-
154
- if (OPTIONAL_VALUE_FLAGS.has(name)) {
155
- if (inlineVal !== undefined) {
156
- flags.set(name, inlineVal)
157
- }
158
- else {
159
- const next = rest[i + 1]
160
- if (next !== undefined && !next.startsWith('-')) {
161
- flags.set(name, next)
162
- i++
163
- }
164
- else {
165
- flags.set(name, true)
30
+ const commands: Commands = {}
31
+ for (const plugin of config.plugins ?? []) {
32
+ for (const [name, run] of Object.entries(plugin.commands ?? {})) {
33
+ commands[name] = {
34
+ summary: `command of the ${plugin.name} plugin`,
35
+ run: async (args) => {
36
+ // Only --help is the kit's to read: the plugin parses its own arguments.
37
+ parse(args.filter(arg => arg === '--help' || arg === '-h'), `kay ${name} [args...]: the ${name} command of the ${plugin.name} plugin`, {
38
+ root: { type: 'string', description: 'the app directory (default: the current one)' },
39
+ })
40
+ const taken = takeRoot(args, cwd)
41
+ await run(taken.rest, taken.root)
42
+ return 0
43
+ },
166
44
  }
167
45
  }
168
46
  }
47
+ return commands
169
48
  }
49
+ }
170
50
 
171
- const rootFlag = typeof flags.get('--root') === 'string' ? flags.get('--root') as string : undefined
172
- const dirArg = positionals[0]
173
- const root = resolve(cwd, rootFlag ?? dirArg ?? '.')
174
-
51
+ export function kayCli(cwd = process.cwd()): Cli {
175
52
  return {
176
- cmd,
177
- isBuiltin,
178
- root,
179
- dirArg,
180
- flags,
181
- positionals,
182
- rawArgs: [...rest],
183
- pluginArgs,
53
+ name: 'kay',
54
+ about: 'the Bun-native full-stack web framework',
55
+ commands: builtinCommands(cwd),
56
+ extraCommands: pluginCommands(cwd),
57
+ // A public framework writes no usage log into its users' home.
58
+ usage: false,
184
59
  }
185
60
  }
186
61
 
187
- export interface RunCliOptions {
188
- cwd?: string | undefined
189
- stdout?: ((line: string) => void) | undefined
190
- stderr?: ((line: string) => void) | undefined
191
- }
192
-
193
- function resolveHostname(flags: ReadonlyMap<string, string | true>): string {
194
- const hostFlag = flags.get('--host')
195
- if (hostFlag !== undefined)
196
- return hostFlag === '' || hostFlag === true ? '0.0.0.0' : hostFlag
197
- return process.env.HOST || '127.0.0.1'
198
- }
199
-
200
- function parsePort(raw: string | number | true | undefined, fallback: number): { ok: true, port: number } | { ok: false, error: string } {
201
- if (raw === undefined || raw === '' || raw === true)
202
- return { ok: true, port: fallback }
203
- const n = Number(raw)
204
- if (!Number.isInteger(n) || n < 0 || n > 65535)
205
- return { ok: false, error: `kay: invalid port "${raw}" (expected an integer between 0 and 65535)` }
206
- return { ok: true, port: n }
207
- }
208
-
209
- const USAGE_TEXT = `Usage:
210
- kay new <dir> [--template minimal|fullstack|blog|app] [--force]
211
- kay check [dir] [--no-typecheck]
212
- kay dev [dir] [--port 3000] [--host [addr]]
213
- kay build [dir] [--static] [--compile [out]] [--analyze]
214
- kay start [dir] [--port 3000] [--host [addr]]`
215
-
216
- export async function runCli(argv: readonly string[], options: RunCliOptions = {}): Promise<number> {
217
- const cwd = options.cwd ?? process.cwd()
218
- const out = options.stdout ?? ((line: string) => console.log(line))
219
- const err = options.stderr ?? ((line: string) => console.error(line))
220
-
221
- const parsed = parseCliArgs(argv, cwd)
222
- if (parsed.error !== undefined) {
223
- err(parsed.error)
224
- return 1
225
- }
226
-
227
- const { cmd, root, dirArg, flags } = parsed
228
-
229
- if (cmd === undefined || cmd === '--help' || cmd === '-h' || flags.has('--help') || flags.has('-h')) {
230
- out(USAGE_TEXT)
231
- return 0
232
- }
233
-
234
- if (cmd === 'new') {
235
- if (!dirArg) {
236
- err('Usage: kay new <dir> [--template minimal|fullstack|blog|app] [--force]')
237
- return 1
238
- }
239
- const tpl = (typeof flags.get('--template') === 'string' ? flags.get('--template') as string : undefined) ?? 'minimal'
240
- if (!VALID_TEMPLATES.has(tpl)) {
241
- err(`kay new: unknown template "${tpl}" (use minimal, fullstack, blog, or app)`)
242
- return 1
243
- }
244
- const template = tpl as 'minimal' | 'fullstack' | 'blog' | 'app'
245
- const res = scaffoldProject(root, { template, force: flags.has('--force') })
246
- out(`Created Kay (${template}) project in ${res.root} (${res.files.length} files)`)
247
- out(`\nNext steps:\n cd ${dirArg}\n bun install\n bun run dev`)
248
- return 0
249
- }
250
-
251
- if (cmd === 'check') {
252
- const t0 = performance.now()
253
- const res = await checkProject(root, { skipTypecheck: flags.has('--no-typecheck') })
254
- const ms = (performance.now() - t0).toFixed(1)
255
- for (const warning of res.warnings)
256
- console.warn(warning)
257
- if (res.ok) {
258
- out(`kay check passed (${res.checkedFiles} files) in ${ms} ms`)
259
- return 0
260
- }
261
- for (const e of res.errors)
262
- err(e)
263
- return 1
264
- }
265
-
266
- if (cmd === 'build') {
267
- const isStatic = flags.has('--static')
268
- const analyze = flags.has('--analyze')
269
- const compileVal = flags.get('--compile')
270
- const compile = compileVal === undefined ? undefined : (compileVal === true || compileVal === '' ? true : compileVal)
271
- const t0 = performance.now()
272
- const manifest = await build({ root, static: isStatic, compile, analyze })
273
- const ms = (performance.now() - t0).toFixed(1)
274
- out(`kay build done in ${ms} ms (${manifest.routes.length} routes, ${manifest.assets.length} client assets, ${manifest.actions.length} actions)`)
275
- return 0
276
- }
277
-
278
- if (cmd === 'start') {
279
- process.env.NODE_ENV ??= 'production'
280
- const config = await loadConfig(root)
281
- const portRes = parsePort(flags.get('--port') ?? (process.env.PORT || config.port), 3000)
282
- if (!portRes.ok) {
283
- err(portRes.error)
284
- return 1
285
- }
286
- const hostname = resolveHostname(flags)
287
- const app = await createServer({ root })
288
- const server = app.serve(portRes.port, hostname)
289
- out(`kay server listening on http://${hostname}:${server.port}`)
290
- return 0
291
- }
292
-
293
- if (cmd === 'dev') {
294
- const config = await loadConfig(root).catch(() => ({} as Awaited<ReturnType<typeof loadConfig>>))
295
- const portRes = parsePort(flags.get('--port') ?? (process.env.PORT || config.port), 3000)
296
- if (!portRes.ok) {
297
- err(portRes.error)
298
- return 1
299
- }
300
- const hostname = resolveHostname(flags)
301
- await devServer({ root, port: portRes.port, hostname })
302
- return 0
303
- }
304
-
305
- // Resolve plugin-registered CLI commands from kay.config.ts in `root` (cwd or `--root`)
306
- const config = await loadConfig(root)
307
- const pluginCmd = config.plugins
308
- ?.flatMap(p => Object.entries(p.commands ?? {}))
309
- .find(([name]) => name === cmd)?.[1]
310
-
311
- if (pluginCmd !== undefined) {
312
- await pluginCmd(parsed.pluginArgs, root)
313
- return 0
314
- }
315
-
316
- const pluginCmdNames = config.plugins?.flatMap(p => Object.keys(p.commands ?? {})) ?? []
317
- const extra = pluginCmdNames.length > 0 ? `\nPlugin commands:\n ${pluginCmdNames.map(c => `kay ${c}`).join('\n ')}` : ''
318
- err(`kay: unknown command "${cmd}"\n${USAGE_TEXT}${extra}`)
319
- return 1
62
+ export function runCli(argv: readonly string[], options: RunCliOptions = {}): Promise<number> {
63
+ return runKit(kayCli(options.cwd), [...argv])
320
64
  }
321
65
 
322
66
  if (import.meta.main) {