@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
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) {