@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.
- package/llms.txt +42 -0
- package/package.json +24 -13
- package/src/build/bundle.ts +15 -53
- package/src/build/client-plugin.ts +108 -0
- package/src/build/compile.ts +9 -44
- package/src/build/graph.ts +16 -3
- package/src/build/index.ts +45 -25
- package/src/build/islands.ts +28 -30
- package/src/build/manifest.ts +9 -4
- package/src/build/prerender.ts +15 -7
- package/src/build/report.ts +82 -13
- package/src/build/resolve.ts +6 -7
- package/src/build/routes.ts +12 -21
- package/src/build/server-entry.ts +38 -0
- package/src/cli/check.ts +49 -43
- package/src/cli/commands.ts +224 -0
- package/src/cli/index.ts +46 -302
- package/src/cli/new.ts +15 -509
- package/src/cli/upgrade-plugins.ts +168 -0
- package/src/cli/upgrade.ts +220 -0
- package/src/compiler/analyze.ts +319 -565
- package/src/compiler/ast.ts +39 -0
- package/src/compiler/data-keys.ts +233 -0
- package/src/compiler/dom.ts +18 -15
- package/src/compiler/interactivity.ts +174 -0
- package/src/compiler/mistakes.ts +19 -1
- package/src/compiler/server-only.ts +4 -1
- package/src/compiler/shared.ts +1 -1
- package/src/compiler/ssr.ts +28 -28
- package/src/context.ts +1 -1
- package/src/dev/index.ts +19 -46
- package/src/dom/extras.ts +43 -12
- package/src/dom/index.ts +25 -1
- package/src/index.ts +0 -13
- package/src/jsx-runtime.ts +1 -1
- package/src/plugins/config.ts +49 -0
- package/src/plugins/context.ts +8 -28
- package/src/plugins/index.ts +10 -385
- package/src/plugins/load.ts +61 -0
- package/src/plugins/order.ts +107 -0
- package/src/plugins/public.ts +6 -0
- package/src/plugins/services.ts +35 -0
- package/src/plugins/types.ts +193 -0
- package/src/server/action-registry.ts +78 -0
- package/src/server/action.ts +8 -2
- package/src/server/app-entry.ts +23 -0
- package/src/server/assets.ts +182 -0
- package/src/server/document.ts +204 -0
- package/src/server/errors.ts +125 -0
- package/src/server/http.ts +14 -0
- package/src/server/index.ts +66 -766
- package/src/server/lifecycle.ts +22 -0
- package/src/server/loader.ts +60 -85
- package/src/server/page.ts +107 -0
- package/src/server/plugin-host.ts +165 -0
- package/src/server/public.ts +15 -0
- package/src/server/request-scope.ts +22 -0
- package/src/server/security.ts +40 -1
- package/src/server/static-dir.ts +22 -3
- package/src/server/stream.ts +95 -0
- package/src/ssr/context.ts +25 -0
- package/src/ssr/index.ts +10 -7
- package/src/test/browser.ts +180 -0
- package/src/test/index.ts +25 -6
- package/templates/_shared/AGENTS.md +5 -0
- package/templates/_shared/CLAUDE.md +1 -0
- package/templates/_shared/public/robots.txt +2 -0
- package/templates/_shared/tsconfig.json +19 -0
- package/templates/app/.env.example +4 -0
- package/templates/app/kay.config.ts +11 -0
- package/templates/app/package.json +20 -0
- package/templates/app/src/auth.ts +14 -0
- package/templates/app/src/routes/_layout.tsx +32 -0
- package/templates/app/src/routes/dashboard/_middleware.ts +3 -0
- package/templates/app/src/routes/dashboard/index.tsx +13 -0
- package/templates/app/src/routes/index.tsx +15 -0
- package/templates/app/src/routes/login.tsx +34 -0
- package/templates/app/src/styles/app.css +7 -0
- package/templates/blog/content/posts/welcome.md +9 -0
- package/templates/blog/kay.config.ts +23 -0
- package/templates/blog/package.json +21 -0
- package/templates/blog/src/posts.ts +26 -0
- package/templates/blog/src/routes/_layout.tsx +20 -0
- package/templates/blog/src/routes/blog/[slug].tsx +31 -0
- package/templates/blog/src/routes/index.tsx +29 -0
- package/templates/blog/src/styles/app.css +10 -0
- package/templates/fullstack/kay.config.ts +6 -0
- package/templates/fullstack/package.json +18 -0
- package/templates/fullstack/src/actions/greet.ts +19 -0
- package/templates/fullstack/src/components/Counter.tsx +10 -0
- package/templates/fullstack/src/components/GreetForm.tsx +26 -0
- package/templates/fullstack/src/routes/_layout.tsx +14 -0
- package/templates/fullstack/src/routes/api/health.ts +5 -0
- package/templates/fullstack/src/routes/index.tsx +13 -0
- package/templates/fullstack/src/styles/app.css +29 -0
- package/templates/minimal/kay.config.ts +6 -0
- package/templates/minimal/package.json +18 -0
- package/templates/minimal/src/components/Counter.tsx +10 -0
- package/templates/minimal/src/routes/_layout.tsx +14 -0
- package/templates/minimal/src/routes/index.tsx +11 -0
- package/templates/minimal/src/styles/app.css +22 -0
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
// A page with pending `<Suspense>` boundaries: its document flushes first, then each boundary as a script once it resolves or times out.
|
|
2
|
+
|
|
3
|
+
import type { PendingChunk, RenderContext, SettledChunk } from '../ssr/context'
|
|
4
|
+
import { streamChunkScript } from '../ssr/context'
|
|
5
|
+
|
|
6
|
+
const textEncoder = new TextEncoder()
|
|
7
|
+
// Where a streamed page's document splits: everything before it flushes first, resolved boundaries go in between.
|
|
8
|
+
export const STREAM_TAIL_MARK = '<!--kay:stream-tail-->'
|
|
9
|
+
|
|
10
|
+
/** `streamTimeout` is only named in the error: the page's boundaries share one `deadlineMs`. */
|
|
11
|
+
async function settleWithin(chunk: PendingChunk, deadlineMs: number, streamTimeout: number, signal: AbortSignal): Promise<SettledChunk | undefined> {
|
|
12
|
+
if (signal.aborted)
|
|
13
|
+
return undefined
|
|
14
|
+
const remaining = Math.max(0, deadlineMs - Date.now())
|
|
15
|
+
let timer: ReturnType<typeof setTimeout> | undefined
|
|
16
|
+
const abortedOrTimedOut = new Promise<SettledChunk | undefined>((resolve) => {
|
|
17
|
+
const onAbort = () => resolve(undefined)
|
|
18
|
+
signal.addEventListener('abort', onAbort, { once: true })
|
|
19
|
+
timer = setTimeout(() => {
|
|
20
|
+
signal.removeEventListener('abort', onAbort)
|
|
21
|
+
const error = new Error(`<Suspense> boundary ${chunk.id} did not resolve within ${streamTimeout} ms`)
|
|
22
|
+
resolve({ html: chunk.renderError(error), error })
|
|
23
|
+
}, remaining)
|
|
24
|
+
})
|
|
25
|
+
try {
|
|
26
|
+
return await Promise.race([chunk.settled, abortedOrTimedOut])
|
|
27
|
+
}
|
|
28
|
+
finally {
|
|
29
|
+
clearTimeout(timer)
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** Streams `shell` (a document holding `STREAM_TAIL_MARK`), with every boundary of `rctx` flushed before its tail. */
|
|
34
|
+
export function streamDocument(shell: string, rctx: RenderContext, streamTimeout: number, onBoundaryError: (error: unknown) => void): ReadableStream<Uint8Array> {
|
|
35
|
+
let splitAt = shell.lastIndexOf(STREAM_TAIL_MARK)
|
|
36
|
+
let tailOffset = STREAM_TAIL_MARK.length
|
|
37
|
+
if (splitAt === -1) {
|
|
38
|
+
splitAt = shell.lastIndexOf('</body>')
|
|
39
|
+
tailOffset = 0
|
|
40
|
+
}
|
|
41
|
+
const openingHtml = splitAt === -1 ? shell : shell.slice(0, splitAt)
|
|
42
|
+
const tailHtml = splitAt === -1 ? '' : shell.slice(splitAt + tailOffset)
|
|
43
|
+
|
|
44
|
+
const abortCtrl = new AbortController()
|
|
45
|
+
let closed = false
|
|
46
|
+
const deadline = Date.now() + streamTimeout
|
|
47
|
+
|
|
48
|
+
const safeEnqueue = (controller: ReadableStreamDefaultController<Uint8Array>, data: Uint8Array): void => {
|
|
49
|
+
if (closed || abortCtrl.signal.aborted)
|
|
50
|
+
return
|
|
51
|
+
try {
|
|
52
|
+
controller.enqueue(data)
|
|
53
|
+
}
|
|
54
|
+
catch {
|
|
55
|
+
closed = true
|
|
56
|
+
abortCtrl.abort()
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
return new ReadableStream<Uint8Array>({
|
|
61
|
+
async start(controller) {
|
|
62
|
+
safeEnqueue(controller, textEncoder.encode(openingHtml))
|
|
63
|
+
// A resolved boundary can render boundaries of its own, so each flush also drains the ones it added.
|
|
64
|
+
let flushed = 0
|
|
65
|
+
const flushPending = async (): Promise<void> => {
|
|
66
|
+
if (closed || abortCtrl.signal.aborted)
|
|
67
|
+
return
|
|
68
|
+
const chunks = rctx.pending.slice(flushed)
|
|
69
|
+
flushed = rctx.pending.length
|
|
70
|
+
await Promise.all(chunks.map(async (chunk) => {
|
|
71
|
+
const settled = await settleWithin(chunk, deadline, streamTimeout, abortCtrl.signal)
|
|
72
|
+
if (settled === undefined || closed || abortCtrl.signal.aborted)
|
|
73
|
+
return
|
|
74
|
+
if ('error' in settled)
|
|
75
|
+
onBoundaryError(settled.error)
|
|
76
|
+
safeEnqueue(controller, textEncoder.encode(streamChunkScript(chunk.id, settled.html)))
|
|
77
|
+
await flushPending()
|
|
78
|
+
}))
|
|
79
|
+
}
|
|
80
|
+
await flushPending()
|
|
81
|
+
if (!closed && !abortCtrl.signal.aborted) {
|
|
82
|
+
safeEnqueue(controller, textEncoder.encode(tailHtml))
|
|
83
|
+
closed = true
|
|
84
|
+
try {
|
|
85
|
+
controller.close()
|
|
86
|
+
}
|
|
87
|
+
catch {}
|
|
88
|
+
}
|
|
89
|
+
},
|
|
90
|
+
cancel() {
|
|
91
|
+
closed = true
|
|
92
|
+
abortCtrl.abort()
|
|
93
|
+
},
|
|
94
|
+
})
|
|
95
|
+
}
|
package/src/ssr/context.ts
CHANGED
|
@@ -28,6 +28,10 @@ export interface RenderContext {
|
|
|
28
28
|
idPrefix: string
|
|
29
29
|
idSeq: number
|
|
30
30
|
contexts: Map<symbol, unknown>
|
|
31
|
+
/** While an island renders, the contexts provided outside it, which the browser never sees. */
|
|
32
|
+
outerContexts: Map<symbol, unknown> | undefined
|
|
33
|
+
/** The island rendering, as its tag. */
|
|
34
|
+
island: string | undefined
|
|
31
35
|
/** Maps island chunk URL -> eager (true if hydrate is undefined/'load'). */
|
|
32
36
|
renderedIslands: Map<string, boolean>
|
|
33
37
|
hasIslands: boolean
|
|
@@ -42,6 +46,8 @@ registerServerContextBridge({
|
|
|
42
46
|
const ctx = renderStorage.getStore()
|
|
43
47
|
if (ctx !== undefined && ctx.contexts.has(key))
|
|
44
48
|
return { found: true, value: ctx.contexts.get(key) }
|
|
49
|
+
if (ctx?.outerContexts?.has(key) === true)
|
|
50
|
+
throw new Error(`kay: <${ctx.island}> reads a context provided outside the island, which the browser never sees; pass its value as a prop.`)
|
|
45
51
|
return undefined
|
|
46
52
|
},
|
|
47
53
|
runWithContext<T>(key: symbol, value: unknown, fn: () => T): T {
|
|
@@ -86,12 +92,31 @@ export function createRenderContext(): RenderContext {
|
|
|
86
92
|
idPrefix: '',
|
|
87
93
|
idSeq: 0,
|
|
88
94
|
contexts: new Map(),
|
|
95
|
+
outerContexts: undefined,
|
|
96
|
+
island: undefined,
|
|
89
97
|
renderedIslands: new Map(),
|
|
90
98
|
hasIslands: false,
|
|
91
99
|
htmlAttrs: {},
|
|
92
100
|
}
|
|
93
101
|
}
|
|
94
102
|
|
|
103
|
+
// An island sees only the contexts provided inside it, as in the browser.
|
|
104
|
+
export function renderIsland(ctx: RenderContext, name: string, render: () => string): string {
|
|
105
|
+
const outer = ctx.contexts
|
|
106
|
+
ctx.contexts = new Map()
|
|
107
|
+
ctx.outerContexts = outer
|
|
108
|
+
ctx.island = name
|
|
109
|
+
try {
|
|
110
|
+
return render()
|
|
111
|
+
}
|
|
112
|
+
finally {
|
|
113
|
+
ctx.contexts = outer
|
|
114
|
+
ctx.outerContexts = undefined
|
|
115
|
+
ctx.island = undefined
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
|
|
95
120
|
export function runWithRenderContext<T>(ctx: RenderContext, fn: () => T): T {
|
|
96
121
|
return renderStorage.run(ctx, fn)
|
|
97
122
|
}
|
package/src/ssr/index.ts
CHANGED
|
@@ -4,7 +4,7 @@ import type { Html, HydrateStrategy, KayChild } from '../jsx-runtime'
|
|
|
4
4
|
import { isBlockedAttr, isStringBoolAttr, isUnsafeUrlAttr } from '../attrs'
|
|
5
5
|
import { styleText } from '../style'
|
|
6
6
|
import { assertRenderable } from '../unrenderable'
|
|
7
|
-
import { currentRenderContext, KAY_STREAM_SCRIPT } from './context'
|
|
7
|
+
import { currentRenderContext, KAY_STREAM_SCRIPT, renderIsland } from './context'
|
|
8
8
|
|
|
9
9
|
export const KAY_ISLAND_STYLE = 'kay-island,kay-slot{display:contents}'
|
|
10
10
|
export const KAY_SUSPENSE_STYLE = 'kay-s{display:contents}'
|
|
@@ -213,14 +213,14 @@ export function recordRenderedIsland(chunk: string, hydrate?: HydrateStrategy):
|
|
|
213
213
|
ctx.renderedIslands.set(chunk, false)
|
|
214
214
|
}
|
|
215
215
|
|
|
216
|
-
export function ssrInIsland(render: () => string, chunk?: string, hydrate?: HydrateStrategy): string {
|
|
216
|
+
export function ssrInIsland(render: () => string, chunk?: string, hydrate?: HydrateStrategy, name = 'island'): string {
|
|
217
217
|
const ctx = currentRenderContext()
|
|
218
218
|
if (ctx !== undefined) {
|
|
219
219
|
if (chunk !== undefined && ctx.islandDepth === 0)
|
|
220
220
|
recordRenderedIsland(chunk, hydrate)
|
|
221
221
|
ctx.islandDepth++
|
|
222
222
|
try {
|
|
223
|
-
return render()
|
|
223
|
+
return ctx.islandDepth === 1 ? renderIsland(ctx, name, render) : render()
|
|
224
224
|
}
|
|
225
225
|
finally {
|
|
226
226
|
ctx.islandDepth--
|
|
@@ -235,6 +235,7 @@ export function ssrInIsland(render: () => string, chunk?: string, hydrate?: Hydr
|
|
|
235
235
|
}
|
|
236
236
|
}
|
|
237
237
|
|
|
238
|
+
|
|
238
239
|
/** Lazily evaluates non-async component children on first read inside the component's dynamic context, memoizing the result. */
|
|
239
240
|
export function ssrChildProp<P extends Record<string, unknown>>(props: P, fn: () => Html): P {
|
|
240
241
|
let cached: Html | undefined
|
|
@@ -257,6 +258,7 @@ export function ssrIslandStatic(
|
|
|
257
258
|
openTag: string,
|
|
258
259
|
render: (() => string) | undefined,
|
|
259
260
|
hydrate?: HydrateStrategy,
|
|
261
|
+
name?: string,
|
|
260
262
|
): string {
|
|
261
263
|
if (getIslandDepth() > 0)
|
|
262
264
|
return render !== undefined ? render() : ''
|
|
@@ -275,7 +277,7 @@ export function ssrIslandStatic(
|
|
|
275
277
|
ctx.idPrefix = islandPrefix
|
|
276
278
|
ctx.idSeq = 0
|
|
277
279
|
try {
|
|
278
|
-
inner = ssrInIsland(render)
|
|
280
|
+
inner = ssrInIsland(render, undefined, undefined, name)
|
|
279
281
|
if (ctx.idSeq > 0)
|
|
280
282
|
idAttr = ` i="${islandPrefix}"`
|
|
281
283
|
}
|
|
@@ -285,7 +287,7 @@ export function ssrIslandStatic(
|
|
|
285
287
|
}
|
|
286
288
|
}
|
|
287
289
|
else {
|
|
288
|
-
inner = ssrInIsland(render)
|
|
290
|
+
inner = ssrInIsland(render, undefined, undefined, name)
|
|
289
291
|
}
|
|
290
292
|
}
|
|
291
293
|
|
|
@@ -303,6 +305,7 @@ export function ssrIsland(
|
|
|
303
305
|
props: Record<string, unknown>,
|
|
304
306
|
hydrate?: HydrateStrategy,
|
|
305
307
|
scriptProps = false,
|
|
308
|
+
name?: string,
|
|
306
309
|
): string {
|
|
307
310
|
if (getIslandDepth() > 0)
|
|
308
311
|
return render()
|
|
@@ -334,7 +337,7 @@ export function ssrIsland(
|
|
|
334
337
|
ctx.idPrefix = islandPrefix
|
|
335
338
|
ctx.idSeq = 0
|
|
336
339
|
try {
|
|
337
|
-
inner = ssrInIsland(render)
|
|
340
|
+
inner = ssrInIsland(render, undefined, undefined, name)
|
|
338
341
|
if (ctx.idSeq > 0)
|
|
339
342
|
idAttr = ` i="${islandPrefix}"`
|
|
340
343
|
}
|
|
@@ -344,7 +347,7 @@ export function ssrIsland(
|
|
|
344
347
|
}
|
|
345
348
|
}
|
|
346
349
|
else {
|
|
347
|
-
inner = ssrInIsland(render)
|
|
350
|
+
inner = ssrInIsland(render, undefined, undefined, name)
|
|
348
351
|
}
|
|
349
352
|
}
|
|
350
353
|
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
// @kayjs/kay/test browser tests: the built app served on a loopback port of its own, its pages opened in Chromium with islands hydrated.
|
|
2
|
+
|
|
3
|
+
import type { TestApp, TestAppOptions } from './index'
|
|
4
|
+
import { existsSync } from 'node:fs'
|
|
5
|
+
import { testApp } from './index'
|
|
6
|
+
|
|
7
|
+
export interface BrowserTestOptions extends TestAppOptions {
|
|
8
|
+
/** Chrome or Chromium executable; defaults to `BUN_CHROME_PATH`, Playwright's own, then the system's. */
|
|
9
|
+
browserPath?: string | undefined
|
|
10
|
+
/** Milliseconds `open`, `waitFor` and `click` wait before they throw. Default 10000. */
|
|
11
|
+
timeout?: number | undefined
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export interface BrowserPage {
|
|
15
|
+
readonly url: string
|
|
16
|
+
/** Page errors, `console.error` messages and failed requests (status 400 and up, but the favicon) seen since the page opened. */
|
|
17
|
+
readonly errors: string[]
|
|
18
|
+
/** Runs `fn` (or the expression string) in the page and returns its JSON-serializable result. */
|
|
19
|
+
evaluate<T>(fn: string | (() => T | Promise<T>)): Promise<T>
|
|
20
|
+
/** Waits for a CSS selector to match, or for `fn` to return a truthy value in the page. */
|
|
21
|
+
waitFor(selectorOrFn: string | (() => unknown)): Promise<void>
|
|
22
|
+
click(selector: string): Promise<void>
|
|
23
|
+
fill(selector: string, value: string): Promise<void>
|
|
24
|
+
/** The text content of the first element matching `selector`. */
|
|
25
|
+
text(selector: string): Promise<string>
|
|
26
|
+
close(): Promise<void>
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export interface BrowserTest {
|
|
30
|
+
/** The built app, for requests that need no browser. */
|
|
31
|
+
readonly app: TestApp
|
|
32
|
+
/** `http://127.0.0.1:<port>`, a port the test owns. */
|
|
33
|
+
readonly origin: string
|
|
34
|
+
/** Opens `path` and resolves once the page has loaded and the islands that hydrate on load have hydrated. */
|
|
35
|
+
open(path: string): Promise<BrowserPage>
|
|
36
|
+
/** Closes the browser and the server. */
|
|
37
|
+
close(): Promise<void>
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
const DEFAULT_TIMEOUT_MS = 10_000
|
|
41
|
+
|
|
42
|
+
// The few playwright-core types used here, so an app's typecheck never needs playwright-core installed.
|
|
43
|
+
interface Page {
|
|
44
|
+
on(event: 'pageerror', listener: (error: Error) => void): void
|
|
45
|
+
on(event: 'response', listener: (response: { status: () => number, url: () => string }) => void): void
|
|
46
|
+
on(event: 'console', listener: (message: { type: () => string, text: () => string }) => void): void
|
|
47
|
+
goto(url: string, options: { waitUntil: 'load', timeout: number }): Promise<unknown>
|
|
48
|
+
evaluate<T>(fn: string | (() => T | Promise<T>)): Promise<T>
|
|
49
|
+
waitForSelector(selector: string, options: { timeout: number }): Promise<unknown>
|
|
50
|
+
waitForFunction(fn: string | (() => unknown), arg: undefined, options: { timeout: number }): Promise<unknown>
|
|
51
|
+
click(selector: string, options: { timeout: number }): Promise<void>
|
|
52
|
+
fill(selector: string, value: string, options: { timeout: number }): Promise<void>
|
|
53
|
+
locator(selector: string): { first: () => { innerText: (options: { timeout: number }) => Promise<string> } }
|
|
54
|
+
}
|
|
55
|
+
interface BrowserContext {
|
|
56
|
+
newPage(): Promise<Page>
|
|
57
|
+
close(): Promise<void>
|
|
58
|
+
}
|
|
59
|
+
interface Browser {
|
|
60
|
+
newContext(): Promise<BrowserContext>
|
|
61
|
+
close(): Promise<void>
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
// True once every island that hydrates on load has hydrated; the ones waiting to be seen, idle or touched are left to the test.
|
|
65
|
+
const ISLANDS_HYDRATED = `[...document.querySelectorAll('kay-island')].every(e => ['visible', 'idle', 'interaction'].includes(e.getAttribute('h')) || e._d !== undefined)`
|
|
66
|
+
|
|
67
|
+
interface PlaywrightCore {
|
|
68
|
+
chromium: { launch: (options: { headless: boolean, executablePath: string }) => Promise<Browser>, executablePath: () => string }
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
async function loadPlaywright(): Promise<PlaywrightCore> {
|
|
72
|
+
try {
|
|
73
|
+
return await import('playwright-core') as unknown as PlaywrightCore
|
|
74
|
+
}
|
|
75
|
+
catch {
|
|
76
|
+
throw new Error('kay: browser tests need playwright-core, and it is not installed: run `bun add -d playwright-core`.')
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function findBrowser(playwright: PlaywrightCore, given: string | undefined): string {
|
|
81
|
+
if (given !== undefined) {
|
|
82
|
+
if (!existsSync(given))
|
|
83
|
+
throw new Error(`kay: no browser at ${given}: give the path of Chrome or Chromium as \`browserPath\`, or set BUN_CHROME_PATH.`)
|
|
84
|
+
return given
|
|
85
|
+
}
|
|
86
|
+
const found = [process.env.BUN_CHROME_PATH, playwright.chromium.executablePath(), '/usr/bin/chromium', '/usr/bin/google-chrome']
|
|
87
|
+
.find((path): path is string => typeof path === 'string' && path.length > 0 && existsSync(path))
|
|
88
|
+
if (found === undefined)
|
|
89
|
+
throw new Error('kay: browser tests found no Chrome or Chromium: install one, run `bunx playwright install chromium`, or give its path as `browserPath` or BUN_CHROME_PATH.')
|
|
90
|
+
return found
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function wrapPage(page: Page, context: BrowserContext, timeout: number, url: string): BrowserPage {
|
|
94
|
+
const errors: string[] = []
|
|
95
|
+
page.on('pageerror', error => errors.push(error.message))
|
|
96
|
+
// A failed load logs a console error without its URL, so the response names it instead; the favicon browsers ask for unprompted is no mistake of the app.
|
|
97
|
+
page.on('response', (response) => {
|
|
98
|
+
if (response.status() >= 400 && !response.url().endsWith('/favicon.ico'))
|
|
99
|
+
errors.push(`${response.status()} ${response.url()}`)
|
|
100
|
+
})
|
|
101
|
+
page.on('console', (message) => {
|
|
102
|
+
if (message.type() === 'error' && !message.text().startsWith('Failed to load resource'))
|
|
103
|
+
errors.push(message.text())
|
|
104
|
+
})
|
|
105
|
+
return {
|
|
106
|
+
url,
|
|
107
|
+
errors,
|
|
108
|
+
async evaluate(fn) {
|
|
109
|
+
return await page.evaluate(fn as () => never)
|
|
110
|
+
},
|
|
111
|
+
async waitFor(selectorOrFn) {
|
|
112
|
+
if (typeof selectorOrFn === 'string')
|
|
113
|
+
await page.waitForSelector(selectorOrFn, { timeout })
|
|
114
|
+
else
|
|
115
|
+
await page.waitForFunction(selectorOrFn, undefined, { timeout })
|
|
116
|
+
},
|
|
117
|
+
async click(selector) {
|
|
118
|
+
await page.click(selector, { timeout })
|
|
119
|
+
},
|
|
120
|
+
async fill(selector, value) {
|
|
121
|
+
await page.fill(selector, value, { timeout })
|
|
122
|
+
},
|
|
123
|
+
async text(selector) {
|
|
124
|
+
return await page.locator(selector).first().innerText({ timeout })
|
|
125
|
+
},
|
|
126
|
+
async close() {
|
|
127
|
+
await context.close()
|
|
128
|
+
},
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** Builds the app for production, serves it on 127.0.0.1 on a free port and opens its pages in Chromium. */
|
|
133
|
+
export async function testBrowser(options: BrowserTestOptions): Promise<BrowserTest> {
|
|
134
|
+
const playwright = await loadPlaywright()
|
|
135
|
+
const executablePath = findBrowser(playwright, options.browserPath)
|
|
136
|
+
const timeout = options.timeout ?? DEFAULT_TIMEOUT_MS
|
|
137
|
+
const app = await testApp({ ...options, minify: options.minify ?? true })
|
|
138
|
+
const server = app.app.serve(0, '127.0.0.1')
|
|
139
|
+
const origin = `http://127.0.0.1:${server.port}`
|
|
140
|
+
const stop = async () => {
|
|
141
|
+
server.stop(true)
|
|
142
|
+
await app.app.dispose?.()
|
|
143
|
+
}
|
|
144
|
+
let browser: Browser
|
|
145
|
+
try {
|
|
146
|
+
browser = await playwright.chromium.launch({ headless: true, executablePath })
|
|
147
|
+
}
|
|
148
|
+
catch (error) {
|
|
149
|
+
await stop()
|
|
150
|
+
throw error
|
|
151
|
+
}
|
|
152
|
+
return {
|
|
153
|
+
app,
|
|
154
|
+
origin,
|
|
155
|
+
async open(path) {
|
|
156
|
+
const context = await browser.newContext()
|
|
157
|
+
const page = await context.newPage()
|
|
158
|
+
const url = new URL(path, origin).href
|
|
159
|
+
const wrapped = wrapPage(page, context, timeout, url)
|
|
160
|
+
// Not `networkidle`: a page that polls or streams never goes idle.
|
|
161
|
+
await page.goto(url, { waitUntil: 'load', timeout })
|
|
162
|
+
try {
|
|
163
|
+
await page.waitForFunction(ISLANDS_HYDRATED, undefined, { timeout })
|
|
164
|
+
}
|
|
165
|
+
catch (error) {
|
|
166
|
+
const seen = wrapped.errors.length > 0 ? `; the page reported: ${wrapped.errors.join('; ')}` : ''
|
|
167
|
+
throw new Error(`kay: the islands of ${url} did not hydrate within ${timeout} ms${seen}.`, { cause: error })
|
|
168
|
+
}
|
|
169
|
+
return wrapped
|
|
170
|
+
},
|
|
171
|
+
async close() {
|
|
172
|
+
try {
|
|
173
|
+
await browser.close()
|
|
174
|
+
}
|
|
175
|
+
finally {
|
|
176
|
+
await stop()
|
|
177
|
+
}
|
|
178
|
+
},
|
|
179
|
+
}
|
|
180
|
+
}
|
package/src/test/index.ts
CHANGED
|
@@ -1,9 +1,12 @@
|
|
|
1
|
-
// kay/test: in-process testing for pages, middleware, cookies, and actions — zero port binding.
|
|
1
|
+
// @kayjs/kay/test: in-process testing for pages, middleware, cookies, and actions — zero port binding.
|
|
2
2
|
|
|
3
3
|
import type { BuildManifest, BuildOptions } from '../build/index'
|
|
4
|
-
import type { KayApp, ServerRuntimeConfig } from '../server/index'
|
|
4
|
+
import type { KayApp, ServerAction, ServerRuntimeConfig } from '../server/index'
|
|
5
|
+
import { resolve } from 'node:path'
|
|
5
6
|
import { build } from '../build/index'
|
|
6
|
-
import {
|
|
7
|
+
import { relPosix } from '../build/files'
|
|
8
|
+
import { resolveServerConfig } from '../server/index'
|
|
9
|
+
import { startBuiltApp } from '../server/loader'
|
|
7
10
|
|
|
8
11
|
export interface TestAppOptions extends Omit<BuildOptions, 'compile' | 'static'>, Partial<ServerRuntimeConfig> {
|
|
9
12
|
prebuilt?: boolean | undefined
|
|
@@ -16,7 +19,10 @@ export interface TestApp {
|
|
|
16
19
|
fetch(pathOrReq: string | Request, init?: RequestInit): Promise<Response>
|
|
17
20
|
get(path: string, headers?: HeadersInit): Promise<Response>
|
|
18
21
|
post(path: string, body?: unknown, headers?: HeadersInit): Promise<Response>
|
|
19
|
-
|
|
22
|
+
/** The app's own bundled copy of a route, layout, middleware, action file or `kay.config.ts`, by path from the root. */
|
|
23
|
+
import(path: string): Promise<Record<string, unknown>>
|
|
24
|
+
/** Posts `fields` as a form to an action, given as one from `import()` or as its URL. */
|
|
25
|
+
submit(action: ServerAction<never, unknown> | string, fields: Record<string, string>, headers?: HeadersInit): Promise<Response>
|
|
20
26
|
clearCookies(): void
|
|
21
27
|
}
|
|
22
28
|
|
|
@@ -31,7 +37,7 @@ export async function testApp(options: TestAppOptions): Promise<TestApp> {
|
|
|
31
37
|
plugins: options.plugins,
|
|
32
38
|
})
|
|
33
39
|
|
|
34
|
-
const app = await
|
|
40
|
+
const { app, entry } = await startBuiltApp({
|
|
35
41
|
root: options.root,
|
|
36
42
|
outDir: options.outDir,
|
|
37
43
|
...resolveServerConfig(undefined, options),
|
|
@@ -101,7 +107,17 @@ export async function testApp(options: TestAppOptions): Promise<TestApp> {
|
|
|
101
107
|
headers: h,
|
|
102
108
|
})
|
|
103
109
|
},
|
|
104
|
-
|
|
110
|
+
async import(path) {
|
|
111
|
+
const source = relPosix(options.root, resolve(options.root, path))
|
|
112
|
+
const mod = entry?.sources[source]
|
|
113
|
+
if (mod === undefined)
|
|
114
|
+
throw new Error(`kay: testApp().import('${path}') found no bundled module. Only routes, layouts, middlewares, action files and kay.config.ts are bundled entries; reach ${source} through one of them.`)
|
|
115
|
+
return mod
|
|
116
|
+
},
|
|
117
|
+
submit(action, fields, headers) {
|
|
118
|
+
const actionUrl = typeof action === 'string' ? action : action.url
|
|
119
|
+
if (actionUrl === '')
|
|
120
|
+
throw new Error('kay: testApp().submit() got an action with no URL. Pass one from `await app.import(path)`, not one the test file imported itself.')
|
|
105
121
|
const fd = new FormData()
|
|
106
122
|
for (const [k, v] of Object.entries(fields))
|
|
107
123
|
fd.append(k, v)
|
|
@@ -115,3 +131,6 @@ export async function testApp(options: TestAppOptions): Promise<TestApp> {
|
|
|
115
131
|
},
|
|
116
132
|
}
|
|
117
133
|
}
|
|
134
|
+
|
|
135
|
+
export { testBrowser } from './browser'
|
|
136
|
+
export type { BrowserPage, BrowserTest, BrowserTestOptions } from './browser'
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
@AGENTS.md
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
{
|
|
2
|
+
"compilerOptions": {
|
|
3
|
+
"target": "ESNext",
|
|
4
|
+
"module": "ESNext",
|
|
5
|
+
"moduleResolution": "bundler",
|
|
6
|
+
"jsx": "react-jsx",
|
|
7
|
+
"jsxImportSource": "@kayjs/kay",
|
|
8
|
+
"strict": true,
|
|
9
|
+
"noEmit": true,
|
|
10
|
+
"skipLibCheck": true,
|
|
11
|
+
"types": [
|
|
12
|
+
"bun"
|
|
13
|
+
]
|
|
14
|
+
},
|
|
15
|
+
"include": [
|
|
16
|
+
"src",
|
|
17
|
+
"kay.config.ts"
|
|
18
|
+
]
|
|
19
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "__APP_NAME__",
|
|
3
|
+
"private": true,
|
|
4
|
+
"type": "module",
|
|
5
|
+
"scripts": {
|
|
6
|
+
"dev": "kay dev",
|
|
7
|
+
"build": "kay build",
|
|
8
|
+
"start": "kay start",
|
|
9
|
+
"check": "kay check"
|
|
10
|
+
},
|
|
11
|
+
"dependencies": {
|
|
12
|
+
"@kayjs/kay": "__KAY_VERSION__",
|
|
13
|
+
"@kayjs/auth": "__KAY_VERSION__",
|
|
14
|
+
"@kayjs/ui": "__KAY_VERSION__"
|
|
15
|
+
},
|
|
16
|
+
"devDependencies": {
|
|
17
|
+
"@types/bun": "latest",
|
|
18
|
+
"typescript": "^6.0.3"
|
|
19
|
+
}
|
|
20
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { join } from 'node:path'
|
|
2
|
+
import { createAuth } from '@kayjs/auth'
|
|
3
|
+
import { sqliteAuthStore } from '@kayjs/auth/sqlite'
|
|
4
|
+
|
|
5
|
+
// Set AUTH_SECRET (at least 32 bytes) in production — see .env.example.
|
|
6
|
+
const defaultDb = import.meta.dir.startsWith('/$bunfs')
|
|
7
|
+
? './data/auth.sqlite'
|
|
8
|
+
: join(import.meta.dir, '../data/auth.sqlite')
|
|
9
|
+
|
|
10
|
+
export const auth = createAuth({
|
|
11
|
+
store: sqliteAuthStore(process.env.AUTH_DB || defaultDb),
|
|
12
|
+
secret: process.env.AUTH_SECRET || undefined,
|
|
13
|
+
defaultRedirect: '/dashboard',
|
|
14
|
+
})
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import type { LayoutProps } from '@kayjs/kay'
|
|
2
|
+
import { Button, Cluster, Toaster } from '@kayjs/ui'
|
|
3
|
+
import { Head } from '@kayjs/kay'
|
|
4
|
+
import '../styles/app.css'
|
|
5
|
+
|
|
6
|
+
export default function Layout({ children, locals }: LayoutProps) {
|
|
7
|
+
const user = locals.user
|
|
8
|
+
return (
|
|
9
|
+
<>
|
|
10
|
+
<Head>
|
|
11
|
+
<title>__APP_NAME__</title>
|
|
12
|
+
</Head>
|
|
13
|
+
<div class="wrap">
|
|
14
|
+
<header data-layout="split" class="site-header">
|
|
15
|
+
<a href="/" class="site-brand">__APP_NAME__</a>
|
|
16
|
+
{user
|
|
17
|
+
? (
|
|
18
|
+
<Cluster>
|
|
19
|
+
<Button href="/dashboard" variant="ghost" size="sm">{user.email}</Button>
|
|
20
|
+
<form action="/auth/signout" method="post">
|
|
21
|
+
<Button type="submit" variant="outline" size="sm">Sign out</Button>
|
|
22
|
+
</form>
|
|
23
|
+
</Cluster>
|
|
24
|
+
)
|
|
25
|
+
: <Button href="/login" variant="outline" size="sm">Sign in</Button>}
|
|
26
|
+
</header>
|
|
27
|
+
<main>{children}</main>
|
|
28
|
+
</div>
|
|
29
|
+
<Toaster />
|
|
30
|
+
</>
|
|
31
|
+
)
|
|
32
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { PageProps } from '@kayjs/kay'
|
|
2
|
+
import { Card, CardBody, CardHeader } from '@kayjs/ui'
|
|
3
|
+
|
|
4
|
+
export default async function DashboardPage({ locals }: PageProps) {
|
|
5
|
+
return (
|
|
6
|
+
<Card>
|
|
7
|
+
<CardHeader>Dashboard</CardHeader>
|
|
8
|
+
<CardBody>
|
|
9
|
+
<p class="m-0">Signed in as <strong>{locals.user?.email}</strong>.</p>
|
|
10
|
+
</CardBody>
|
|
11
|
+
</Card>
|
|
12
|
+
)
|
|
13
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { Badge, Button, Cluster, Stack } from '@kayjs/ui'
|
|
2
|
+
|
|
3
|
+
export default async function Home() {
|
|
4
|
+
return (
|
|
5
|
+
<Stack gap="md">
|
|
6
|
+
<Cluster><Badge tone="accent">Kay v2</Badge><Badge>SQLite Auth</Badge></Cluster>
|
|
7
|
+
<h1 class="page-title">Welcome to __APP_NAME__</h1>
|
|
8
|
+
<p class="page-lead">Zero-dependency Argon2id auth, @kayjs/ui pure CSS grammar, and Bun speed.</p>
|
|
9
|
+
<Cluster>
|
|
10
|
+
<Button href="/login" tone="accent">Get started</Button>
|
|
11
|
+
<Button href="/dashboard" variant="outline">Dashboard</Button>
|
|
12
|
+
</Cluster>
|
|
13
|
+
</Stack>
|
|
14
|
+
)
|
|
15
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { Button, Card, CardBody, CardHeader, Field, Grid, Stack } from '@kayjs/ui'
|
|
2
|
+
|
|
3
|
+
export default function LoginPage() {
|
|
4
|
+
return (
|
|
5
|
+
<Grid min="md" gap="lg">
|
|
6
|
+
<Card>
|
|
7
|
+
<CardHeader>Sign in</CardHeader>
|
|
8
|
+
<CardBody>
|
|
9
|
+
<form action="/auth/signin" method="post">
|
|
10
|
+
<Stack gap="sm">
|
|
11
|
+
<input type="hidden" name="redirect" value="/dashboard" />
|
|
12
|
+
<Field id="in-email" label="Email" required><input id="in-email" name="email" type="email" required /></Field>
|
|
13
|
+
<Field id="in-pass" label="Password" required><input id="in-pass" name="password" type="password" required /></Field>
|
|
14
|
+
<Button type="submit" tone="accent">Sign in</Button>
|
|
15
|
+
</Stack>
|
|
16
|
+
</form>
|
|
17
|
+
</CardBody>
|
|
18
|
+
</Card>
|
|
19
|
+
<Card>
|
|
20
|
+
<CardHeader>Create account</CardHeader>
|
|
21
|
+
<CardBody>
|
|
22
|
+
<form action="/auth/signup" method="post">
|
|
23
|
+
<Stack gap="sm">
|
|
24
|
+
<input type="hidden" name="redirect" value="/dashboard" />
|
|
25
|
+
<Field id="up-email" label="Email" required><input id="up-email" name="email" type="email" required /></Field>
|
|
26
|
+
<Field id="up-pass" label="Password" hint="Min 12 characters" required><input id="up-pass" name="password" type="password" minlength="12" required /></Field>
|
|
27
|
+
<Button type="submit" tone="accent">Create account</Button>
|
|
28
|
+
</Stack>
|
|
29
|
+
</form>
|
|
30
|
+
</CardBody>
|
|
31
|
+
</Card>
|
|
32
|
+
</Grid>
|
|
33
|
+
)
|
|
34
|
+
}
|