@kayjs/kay 2.0.0-alpha.8 → 2.0.0-beta.1

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 (55) hide show
  1. package/package.json +1 -1
  2. package/src/attrs.ts +35 -0
  3. package/src/build/bundle.ts +442 -0
  4. package/src/build/compile.ts +20 -11
  5. package/src/build/files.ts +136 -0
  6. package/src/build/graph.ts +158 -0
  7. package/src/build/index.ts +231 -1296
  8. package/src/build/islands.ts +177 -0
  9. package/src/build/manifest.ts +224 -0
  10. package/src/build/plugin-host.ts +184 -0
  11. package/src/build/prerender.ts +93 -0
  12. package/src/build/report.ts +157 -0
  13. package/src/build/resolve.ts +58 -0
  14. package/src/build/routes.ts +135 -0
  15. package/src/build/static.ts +73 -0
  16. package/src/cli/check.ts +228 -114
  17. package/src/cli/index.ts +298 -79
  18. package/src/cli/new.ts +67 -35
  19. package/src/compiler/analyze.ts +666 -91
  20. package/src/compiler/dom.ts +822 -629
  21. package/src/compiler/mistakes.ts +354 -0
  22. package/src/compiler/patch.ts +1 -1
  23. package/src/compiler/server-only.ts +164 -21
  24. package/src/compiler/shared.ts +442 -0
  25. package/src/compiler/ssr.ts +390 -324
  26. package/src/context.ts +120 -0
  27. package/src/dev/index.ts +291 -76
  28. package/src/dom/action.ts +23 -13
  29. package/src/dom/extras.ts +157 -84
  30. package/src/dom/index.ts +154 -33
  31. package/src/dom/island.ts +117 -39
  32. package/src/dom/loop.ts +34 -21
  33. package/src/index.ts +2 -1
  34. package/src/jsx-runtime.ts +11 -0
  35. package/src/plugins/context.ts +57 -0
  36. package/src/plugins/index.ts +120 -17
  37. package/src/reactivity/index.ts +250 -157
  38. package/src/reactivity/selector.ts +11 -9
  39. package/src/reactivity/store.ts +37 -12
  40. package/src/server/action.ts +217 -74
  41. package/src/server/compress.ts +155 -56
  42. package/src/server/cookies.ts +59 -22
  43. package/src/server/env.ts +18 -13
  44. package/src/server/http.ts +201 -33
  45. package/src/server/index.ts +964 -737
  46. package/src/server/loader.ts +120 -0
  47. package/src/server/router.ts +27 -8
  48. package/src/server/security.ts +87 -39
  49. package/src/server/standard-schema.ts +42 -11
  50. package/src/server/static-dir.ts +144 -0
  51. package/src/ssr/context.ts +96 -10
  52. package/src/ssr/index.ts +225 -56
  53. package/src/style.ts +33 -0
  54. package/src/test/index.ts +5 -0
  55. package/src/unrenderable.ts +35 -0
package/src/cli/index.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  #!/usr/bin/env bun
2
- // Kay v2 minimal CLI: `kay new`, `kay check`, `kay dev`, `kay build [--static] [--compile [out]]`, `kay start`.
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`).
3
4
 
4
5
  import { resolve } from 'node:path'
5
6
  import { build } from '../build/index'
@@ -9,99 +10,317 @@ import { createServer } from '../server/index'
9
10
  import { checkProject } from './check'
10
11
  import { scaffoldProject } from './new'
11
12
 
12
- const args = Bun.argv.slice(2)
13
- const cmd = args[0]
13
+ const BUILTIN_COMMANDS = new Set(['new', 'check', 'build', 'start', 'dev'])
14
+ const VALID_TEMPLATES = new Set(['minimal', 'fullstack', 'blog', 'app'])
14
15
 
15
- function flagValue(name: string): string | undefined {
16
- const idx = args.indexOf(name)
17
- if (idx === -1)
18
- return undefined
19
- const next = args[idx + 1]
20
- return next !== undefined && !next.startsWith('-') ? next : ''
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']),
21
26
  }
22
27
 
23
- function hasFlag(name: string): boolean {
24
- return args.includes(name)
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
25
38
  }
26
39
 
27
- const dirArg = args.slice(1).find((a, i, arr) => {
28
- if (a.startsWith('-'))
29
- return false
30
- const prev = arr[i - 1]
31
- if (prev === '--port' || prev === '--compile' || prev === '--template')
32
- return false
33
- return true
34
- })
35
- const root = resolve(dirArg ?? process.cwd())
36
-
37
- if (cmd === 'new') {
38
- if (!dirArg) {
39
- console.error('Usage: kay new <dir> [--template minimal|fullstack|blog|app] [--force]')
40
- process.exit(1)
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
+ }
41
78
  }
42
- const tpl = flagValue('--template')
43
- const template = tpl === 'fullstack' || tpl === 'blog' || tpl === 'app' ? tpl : 'minimal'
44
- const res = scaffoldProject(root, { template, force: hasFlag('--force') })
45
- console.log(`Created Kay (${template}) project in ${res.root} (${res.files.length} files)`)
46
- console.log(`\nNext steps:\n cd ${dirArg}\n bun install\n bun run dev`)
47
- }
48
- else if (cmd === 'check') {
49
- const t0 = performance.now()
50
- const res = await checkProject(root, { skipTypecheck: hasFlag('--no-typecheck') })
51
- const ms = (performance.now() - t0).toFixed(1)
52
- if (res.ok) {
53
- console.log(`kay check passed (${res.checkedFiles} files) in ${ms} ms`)
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
86
+ }
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
+ }
104
+ }
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)
166
+ }
167
+ }
168
+ }
54
169
  }
55
- else {
56
- for (const err of res.errors)
57
- console.error(err)
58
- process.exit(1)
170
+
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
+
175
+ return {
176
+ cmd,
177
+ isBuiltin,
178
+ root,
179
+ dirArg,
180
+ flags,
181
+ positionals,
182
+ rawArgs: [...rest],
183
+ pluginArgs,
59
184
  }
60
185
  }
61
- else if (cmd === 'build') {
62
- const isStatic = hasFlag('--static')
63
- const analyze = hasFlag('--analyze')
64
- const compileFlag = flagValue('--compile')
65
- const compile = compileFlag === undefined ? undefined : (compileFlag === '' ? true : compileFlag)
66
- const t0 = performance.now()
67
- const manifest = await build({ root, static: isStatic, compile, analyze })
68
- const ms = (performance.now() - t0).toFixed(1)
69
- console.log(`kay build done in ${ms} ms (${manifest.routes.length} routes, ${manifest.assets.length} client assets, ${manifest.actions.length} actions)`)
186
+
187
+ export interface RunCliOptions {
188
+ cwd?: string | undefined
189
+ stdout?: ((line: string) => void) | undefined
190
+ stderr?: ((line: string) => void) | undefined
70
191
  }
71
- else if (cmd === 'start') {
72
- process.env.NODE_ENV ??= 'production'
73
- const config = await loadConfig(root)
74
- const port = Number(flagValue('--port') || process.env.PORT || config.port || 3000)
75
- const hostname = process.env.HOST || undefined
76
- const app = await createServer({ root })
77
- const server = app.serve(port, hostname)
78
- console.log(`kay server listening on http://${hostname ?? 'localhost'}:${server.port}`)
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'
79
198
  }
80
- else if (cmd === 'dev') {
81
- const port = Number(flagValue('--port') || process.env.PORT || 3000)
82
- await devServer({ root, port })
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 }
83
207
  }
84
- else {
85
- // Check plugin-registered CLI commands from kay.config.ts
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`)
86
306
  const config = await loadConfig(root)
87
- const pluginCmd = cmd !== undefined
88
- ? config.plugins?.flatMap(p => Object.entries(p.commands ?? {})).find(([name]) => name === cmd)?.[1]
89
- : undefined
307
+ const pluginCmd = config.plugins
308
+ ?.flatMap(p => Object.entries(p.commands ?? {}))
309
+ .find(([name]) => name === cmd)?.[1]
90
310
 
91
311
  if (pluginCmd !== undefined) {
92
- await pluginCmd(args.slice(1), root)
312
+ await pluginCmd(parsed.pluginArgs, root)
313
+ return 0
93
314
  }
94
- else {
95
- console.log(`Usage: kay <command> [dir] [options]
96
315
 
97
- Commands:
98
- kay new <dir> [--template minimal|fullstack|blog|app] [--force]
99
- Scaffold a new Kay project
100
- kay check [dir] Validate routes, compiler rules, and TypeScript types
101
- kay dev [dir] [--port 3000] Run dev server with fast reload
102
- kay build [dir] [--static] [--compile [out]]
103
- Build production app, static site, or single executable
104
- kay start [dir] [--port 3000] Serve the built production app`)
105
- process.exit(cmd === '--help' || cmd === '-h' || cmd === undefined ? 0 : 1)
106
- }
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
320
+ }
321
+
322
+ if (import.meta.main) {
323
+ const code = await runCli(Bun.argv.slice(2))
324
+ if (code !== 0)
325
+ process.exit(code)
107
326
  }
package/src/cli/new.ts CHANGED
@@ -15,7 +15,7 @@ export function scaffoldProject(targetDir: string, options: ScaffoldOptions = {}
15
15
  const root = resolve(targetDir)
16
16
  const name = basename(root).toLowerCase().replace(/[^a-z0-9-_]/g, '-') || 'kay-app'
17
17
  const template: ScaffoldTemplate = options.template ?? 'minimal'
18
- const kayVersion = options.kayVersion ?? '^2.0.0-alpha.8'
18
+ const kayVersion = options.kayVersion ?? '^2.0.0-beta.1'
19
19
 
20
20
  if (existsSync(root) && readdirSync(root).length > 0 && !options.force)
21
21
  throw new Error(`kay new: directory "${root}" is not empty (pass --force to overwrite)`)
@@ -169,6 +169,14 @@ const nameSchema: StandardSchemaV1<{ name: string }> = {
169
169
  export const greet = action(nameSchema, async ({ name }) => {
170
170
  return { message: \`Hello, \${name}!\` }
171
171
  })
172
+ `
173
+ files['src/styles/app.css'] += `
174
+ .greet-form {
175
+ margin-top: 1.5rem;
176
+ display: flex;
177
+ gap: 0.5rem;
178
+ align-items: center;
179
+ }
172
180
  `
173
181
  files['src/components/GreetForm.tsx'] = `import { signal } from 'kay'
174
182
  import { greet } from '../actions/greet'
@@ -184,7 +192,7 @@ export function GreetForm() {
184
192
  }
185
193
 
186
194
  return (
187
- <form action={greet.url} method="post" onSubmit={onSubmit} style="margin-top:1.5rem;display:flex;gap:.5rem;align-items:center">
195
+ <form class="greet-form" action={greet.url} method="post" onSubmit={onSubmit}>
188
196
  <input
189
197
  name="name"
190
198
  placeholder="Your name"
@@ -214,9 +222,20 @@ export default async function Home() {
214
222
  }
215
223
 
216
224
  else if (template === 'blog') {
217
- delete files['src/styles/app.css']
218
225
  delete files['src/components/Counter.tsx']
219
226
 
227
+ files['src/styles/app.css'] = `body { margin: 0; background: var(--ui-paper); color: var(--ui-ink); font-family: var(--ui-font-body); }
228
+ .wrap { max-width: 46rem; margin: 0 auto; padding: 2rem 1.25rem 4rem; }
229
+ .site-header { padding-bottom: 1.25rem; margin-bottom: 2rem; border-bottom: 1px solid var(--ui-line); }
230
+ .site-brand { font-family: var(--ui-font-display); font-size: 1.35rem; font-weight: 700; text-decoration: none; color: inherit; }
231
+ .site-rss { font-size: 0.9rem; color: var(--ui-muted); }
232
+ .page-title { margin: 0; font-family: var(--ui-font-display); }
233
+ .post-link { color: inherit; text-decoration: none; }
234
+ .post-desc { margin: 0; color: var(--ui-muted); }
235
+ .post-title { font-family: var(--ui-font-display); margin-bottom: 0.25rem; }
236
+ .post-meta { color: var(--ui-muted); margin-top: 0; }
237
+ `
238
+
220
239
  files['content/posts/welcome.md'] = `---
221
240
  title: Welcome to ${name}
222
241
  date: 2026-11-23
@@ -271,21 +290,18 @@ export default defineConfig({
271
290
  `
272
291
  files['src/routes/_layout.tsx'] = `import type { KayChild } from 'kay'
273
292
  import { Head } from 'kay'
293
+ import '../styles/app.css'
274
294
 
275
295
  export default function Layout({ children }: { children: KayChild }) {
276
296
  return (
277
297
  <>
278
298
  <Head>
279
299
  <title>${name}</title>
280
- <style>{\`
281
- body { margin: 0; background: var(--ui-paper); color: var(--ui-ink); font-family: var(--ui-font-body); }
282
- .wrap { max-width: 46rem; margin: 0 auto; padding: 2rem 1.25rem 4rem; }
283
- \`}</style>
284
300
  </Head>
285
301
  <div class="wrap">
286
- <header data-layout="split" style="padding-bottom:1.25rem;margin-bottom:2rem;border-bottom:1px solid var(--ui-line)">
287
- <a href="/" style="font-family:var(--ui-font-display);font-size:1.35rem;font-weight:700;text-decoration:none;color:inherit">${name}</a>
288
- <a href="/rss.xml" style="font-size:0.9rem;color:var(--ui-muted)">RSS</a>
302
+ <header data-layout="split" class="site-header">
303
+ <a href="/" class="site-brand">${name}</a>
304
+ <a href="/rss.xml" class="site-rss">RSS</a>
289
305
  </header>
290
306
  <main>{children}</main>
291
307
  </div>
@@ -301,15 +317,15 @@ export const prerender = true
301
317
  export default async function BlogIndex() {
302
318
  const list = posts.all()
303
319
  return (
304
- <Stack gap="1.5rem">
305
- <h1 style="margin:0;font-family:var(--ui-font-display)">Articles</h1>
320
+ <Stack gap="lg">
321
+ <h1 class="page-title">Articles</h1>
306
322
  {list.map(post => (
307
323
  <Card key={post.slug}>
308
324
  <CardHeader>
309
- <a href={\`/blog/\${post.slug}\`} style="color:inherit;text-decoration:none">{post.data.title}</a>
325
+ <a href={\`/blog/\${post.slug}\`} class="post-link">{post.data.title}</a>
310
326
  </CardHeader>
311
327
  <CardBody>
312
- <p style="margin:0;color:var(--ui-muted)">{post.data.description ?? ''}</p>
328
+ <p class="post-desc">{post.data.description ?? ''}</p>
313
329
  </CardBody>
314
330
  <CardFooter>
315
331
  <Cluster>
@@ -343,11 +359,11 @@ export async function load(ctx: RequestContext) {
343
359
  export default function PostPage({ data }: { data: { post: NonNullable<ReturnType<typeof posts.get>> } }) {
344
360
  const { post } = data
345
361
  return (
346
- <Stack gap="1.25rem">
362
+ <Stack gap="md">
347
363
  <Head><title>{post.data.title}</title></Head>
348
364
  <article>
349
- <h1 style="font-family:var(--ui-font-display);margin-bottom:0.25rem">{post.data.title}</h1>
350
- <p style="color:var(--ui-muted);margin-top:0">{post.data.date} · {post.readingMinutes} min read</p>
365
+ <h1 class="post-title">{post.data.title}</h1>
366
+ <p class="post-meta">{post.data.date} · {post.readingMinutes} min read</p>
351
367
  <div innerHTML={post.html} />
352
368
  </article>
353
369
  <div><Button href="/" variant="outline">← All posts</Button></div>
@@ -357,17 +373,36 @@ export default function PostPage({ data }: { data: { post: NonNullable<ReturnTyp
357
373
  `
358
374
  }
359
375
  else if (template === 'app') {
360
- delete files['src/styles/app.css']
361
376
  delete files['src/components/Counter.tsx']
362
377
 
363
- files['src/auth.ts'] = `import { createAuth } from '@kayjs/auth'
378
+ files['src/styles/app.css'] = `body { margin: 0; background: var(--ui-paper); color: var(--ui-ink); font-family: var(--ui-font-body); }
379
+ .wrap { max-width: 52rem; margin: 0 auto; padding: 1.5rem 1.25rem 4rem; }
380
+ .site-header { padding-bottom: 1.25rem; margin-bottom: 2rem; border-bottom: 1px solid var(--ui-line); }
381
+ .site-brand { font-family: var(--ui-font-display); font-size: 1.3rem; font-weight: 700; text-decoration: none; color: inherit; }
382
+ .page-title { margin: 0; font-family: var(--ui-font-display); }
383
+ .page-lead { margin: 0; color: var(--ui-muted); }
384
+ .m-0 { margin: 0; }
385
+ `
386
+
387
+ files['src/auth.ts'] = `import { join } from 'node:path'
388
+ import { createAuth } from '@kayjs/auth'
364
389
  import { sqliteAuthStore } from '@kayjs/auth/sqlite'
365
390
 
391
+ // Set AUTH_SECRET (at least 32 bytes) in production — see .env.example.
392
+ const defaultDb = import.meta.dir.startsWith('/$bunfs')
393
+ ? './data/auth.sqlite'
394
+ : join(import.meta.dir, '../data/auth.sqlite')
395
+
366
396
  export const auth = createAuth({
367
- store: sqliteAuthStore(process.env.AUTH_DB || ':memory:'),
368
- secret: process.env.AUTH_SECRET || 'dev-secret-change-in-production',
397
+ store: sqliteAuthStore(process.env.AUTH_DB || defaultDb),
398
+ secret: process.env.AUTH_SECRET || undefined,
369
399
  defaultRedirect: '/dashboard',
370
400
  })
401
+ `
402
+ files['.env.example'] = `# Generate a 32+ byte secret for production, e.g.:
403
+ # openssl rand -base64 32
404
+ AUTH_SECRET=
405
+ AUTH_DB=./data/auth.sqlite
371
406
  `
372
407
  files['kay.config.ts'] = `import { ui } from '@kayjs/ui/plugin'
373
408
  import { defineConfig } from 'kay/server'
@@ -385,6 +420,7 @@ export default defineConfig({
385
420
  import type { KayChild } from 'kay'
386
421
  import { Button, Cluster, Toaster } from '@kayjs/ui'
387
422
  import { Head } from 'kay'
423
+ import '../styles/app.css'
388
424
 
389
425
  export default function Layout({ children, locals }: { children: KayChild, locals?: { user?: PublicUser } }) {
390
426
  const user = locals?.user
@@ -392,14 +428,10 @@ export default function Layout({ children, locals }: { children: KayChild, local
392
428
  <>
393
429
  <Head>
394
430
  <title>${name}</title>
395
- <style>{\`
396
- body { margin: 0; background: var(--ui-paper); color: var(--ui-ink); font-family: var(--ui-font-body); }
397
- .wrap { max-width: 52rem; margin: 0 auto; padding: 1.5rem 1.25rem 4rem; }
398
- \`}</style>
399
431
  </Head>
400
432
  <div class="wrap">
401
- <header data-layout="split" style="padding-bottom:1.25rem;margin-bottom:2rem;border-bottom:1px solid var(--ui-line)">
402
- <a href="/" style="font-family:var(--ui-font-display);font-size:1.3rem;font-weight:700;text-decoration:none;color:inherit">${name}</a>
433
+ <header data-layout="split" class="site-header">
434
+ <a href="/" class="site-brand">${name}</a>
403
435
  {user
404
436
  ? (
405
437
  <Cluster>
@@ -422,10 +454,10 @@ export default function Layout({ children, locals }: { children: KayChild, local
422
454
 
423
455
  export default async function Home() {
424
456
  return (
425
- <Stack gap="1.25rem">
457
+ <Stack gap="md">
426
458
  <Cluster><Badge tone="accent">Kay v2</Badge><Badge>SQLite Auth</Badge></Cluster>
427
- <h1 style="margin:0;font-family:var(--ui-font-display)">Welcome to ${name}</h1>
428
- <p style="margin:0;color:var(--ui-muted)">Zero-dependency Argon2id auth, @kayjs/ui pure CSS grammar, and Bun speed.</p>
459
+ <h1 class="page-title">Welcome to ${name}</h1>
460
+ <p class="page-lead">Zero-dependency Argon2id auth, @kayjs/ui pure CSS grammar, and Bun speed.</p>
429
461
  <Cluster>
430
462
  <Button href="/login" tone="accent">Get started</Button>
431
463
  <Button href="/dashboard" variant="outline">Dashboard</Button>
@@ -438,12 +470,12 @@ export default async function Home() {
438
470
 
439
471
  export default function LoginPage() {
440
472
  return (
441
- <Grid min="18rem" gap="1.5rem">
473
+ <Grid min="md" gap="lg">
442
474
  <Card>
443
475
  <CardHeader>Sign in</CardHeader>
444
476
  <CardBody>
445
477
  <form action="/auth/signin" method="post">
446
- <Stack gap="0.9rem">
478
+ <Stack gap="sm">
447
479
  <input type="hidden" name="redirect" value="/dashboard" />
448
480
  <Field id="in-email" label="Email" required><input id="in-email" name="email" type="email" required /></Field>
449
481
  <Field id="in-pass" label="Password" required><input id="in-pass" name="password" type="password" required /></Field>
@@ -456,10 +488,10 @@ export default function LoginPage() {
456
488
  <CardHeader>Create account</CardHeader>
457
489
  <CardBody>
458
490
  <form action="/auth/signup" method="post">
459
- <Stack gap="0.9rem">
491
+ <Stack gap="sm">
460
492
  <input type="hidden" name="redirect" value="/dashboard" />
461
493
  <Field id="up-email" label="Email" required><input id="up-email" name="email" type="email" required /></Field>
462
- <Field id="up-pass" label="Password" hint="Min 8 characters" required><input id="up-pass" name="password" type="password" minlength="8" required /></Field>
494
+ <Field id="up-pass" label="Password" hint="Min 12 characters" required><input id="up-pass" name="password" type="password" minlength="12" required /></Field>
463
495
  <Button type="submit" tone="accent">Create account</Button>
464
496
  </Stack>
465
497
  </form>
@@ -481,7 +513,7 @@ export default async function DashboardPage({ locals }: { locals: { user?: Publi
481
513
  <Card>
482
514
  <CardHeader>Dashboard</CardHeader>
483
515
  <CardBody>
484
- <p style="margin:0">Signed in as <strong>{locals.user?.email}</strong>.</p>
516
+ <p class="m-0">Signed in as <strong>{locals.user?.email}</strong>.</p>
485
517
  </CardBody>
486
518
  </Card>
487
519
  )