@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.
- package/llms.txt +42 -0
- package/package.json +24 -13
- package/src/build/bundle.ts +11 -51
- package/src/build/client-plugin.ts +108 -0
- package/src/build/compile.ts +4 -2
- package/src/build/graph.ts +16 -3
- package/src/build/index.ts +23 -15
- package/src/build/islands.ts +28 -30
- package/src/build/manifest.ts +6 -3
- 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 +1 -1
- 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 +15 -23
- 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/context.ts +8 -6
- package/src/plugins/index.ts +2 -2
- package/src/plugins/load.ts +25 -2
- package/src/plugins/public.ts +6 -0
- package/src/plugins/services.ts +15 -3
- package/src/plugins/types.ts +7 -11
- package/src/server/action-registry.ts +10 -4
- package/src/server/action.ts +8 -2
- package/src/server/document.ts +13 -1
- package/src/server/errors.ts +7 -5
- package/src/server/index.ts +9 -10
- package/src/server/lifecycle.ts +22 -0
- package/src/server/plugin-host.ts +6 -8
- package/src/server/public.ts +15 -0
- package/src/server/request-scope.ts +22 -0
- package/src/server/stream.ts +4 -3
- 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 +4 -1
- 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
package/llms.txt
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
# Kay v2 Reference (for humans & coding agents)
|
|
2
|
+
|
|
3
|
+
> Kay v2 is a Bun-native TSX web framework with zero-directive automatic islands, `.value` fine-grained signals, flat-string SSR, unified Standard-Schema actions, single-binary `--compile`, and a composable `KayPlugin` API.
|
|
4
|
+
|
|
5
|
+
## Core Rules (everything fits on one page)
|
|
6
|
+
|
|
7
|
+
- **Imports**: `@kayjs/kay` (signals, `Head`, `Suspense`, contexts, `useAction`), `@kayjs/kay/server` (actions, `raw`, `esc`, route types, security helpers, `createServer({ root })` to run a built app inside another program), `@kayjs/kay/config` (`defineConfig`, `definePlugin`, plugin types), `@kayjs/kay/test`. A bare `kay` import fails the compile (`kay upgrade` rewrites them); `@kayjs/kay/internal/*` is compiler output, outside semver.
|
|
8
|
+
- **Standard TSX & compiler guardrails**: `.tsx` files with `jsxImportSource: "@kayjs/kay"`. Use `class` or `className` (never both). Standard `.map()` (with `key={...}`), `&&`, ternaries, `{...spread}`, SVG elements, style strings or objects (`style={{ color: 'red' }}`), and CSS / `*.module.css` imports work natively. Compiler/runtime refuse common React/Solid/Astro habits: `innerHTML={html}` takes a string or `raw(html)` (never `{ __html }`, never `dangerouslySetInnerHTML`, never on void elements or with children); events are camelCase DOM names (`onClick`, `onDblClick`, `onKeyDown` — never lowercase `onclick`, `on:click`, `onDoubleClick`, `*Capture`, string handlers, or render-time assignments); `ref` is always a callback `ref={el => ...}` (never `{ current }`); SVG attrs use kebab-case (`stroke-width`, `fill-opacity`); use `value`/`checked` (not `defaultValue`/`defaultChecked`) and boolean `{false}` (not `"false"`); no `client:*`/`use:*`/`class:list`/`set:html` directives; no Promises, functions, signals, or plain objects in JSX text/attrs. Spreads drop `on*`, `innerHTML`, `srcdoc`, and `javascript:`/`vbscript:` URLs.
|
|
9
|
+
- **Signals (`@kayjs/kay`)**: `const count = signal(0)` (`.value` read/write, `.peek()` untracked), `computed(() => ...)`, `effect(() => ...)` (return cleanup), `batch(() => ...)`, `untrack(() => ...)`, `root(dispose => ...)`, `onMount(() => ...)` (runs after DOM attach; return cleanup), `onCleanup(() => ...)`, `getOwner()`, `selector(() => id.value)` (O(1) selection), `store(obj)` + `snapshot(s)`. To let a child mutate parent state, pass the signal directly (`<Modal open={isOpen} />`).
|
|
10
|
+
- **Reactive props**: Destructuring props (`function Badge({ count = 0, ...rest }: Props)`) stays reactive in client components; server-rendered children inside islands are preserved via `<kay-slot>`.
|
|
11
|
+
- **Automatic islands**: Any component using reactive primitives (`signal`, `computed`, `effect`, `onMount`, `store`, `selector`), DOM `on*` handlers/`ref`, or imported reactive module state becomes an island automatically, decided per component: a static export beside an island stays static, a same-file helper or component that needs the browser makes each component calling or rendering it an island, and a primitive called at a file's top level makes every component of it one. Control hydration per call site with `$hydrate="load" | "visible" | "idle" | "interaction" | "media(...)" | "client"`, or the component file's default `export const hydrate = 'visible'` (unknown modes and `$hydrate` on non-islands fail compile). `<Head>`/`<Suspense>` in an island fail compile; an island reading a context provided outside it throws in SSR (pass the value as a prop); server children handed to an island render before it, in the page's scope. Island props crossing the server boundary must be serializable (JSON primitives + `Date`, `Map`, `Set`, `URL`, `RegExp` — functions and signals are refused). Islands cannot import server-only modules (`bun:sqlite`, `node:*`, `@kayjs/kay/server`) or read `process.env` other than `process.env.PUBLIC_*` (inlined at build time); action files are stubbed on the client (non-action exports from them cannot be imported by islands).
|
|
12
|
+
- **Routes (`src/routes/`)**:
|
|
13
|
+
- `export default async function Page({ params, locals, url })`: strictly server-only (`0 KB` JS; cannot use signals/handlers directly).
|
|
14
|
+
- Sync `export default function Page({ data, params, locals, url })`: static or auto-island; optional `export async function load(ctx)` runs server-only and returns data or a `Response` (e.g. `404` / redirect).
|
|
15
|
+
- Special files: `_layout.tsx` (nested outer→inner, receives `{ children, params, locals, url }`, server-only), `_middleware.ts` (`(ctx, next) => Response`, outer→inner), `_error.tsx` (receives `{ error }`, server-only, wrapped in root layout), `_404.tsx` (server-only, wrapped in root layout, also emitted as `404.html` in `--static`); each needs a default export. Any other file under `src/routes/` must export a page, a method handler or an action (guarded by its folder's `_middleware.ts`), else `kay build`/`kay check` fail: prefix helpers or their folder with `_`.
|
|
16
|
+
- Params: `[slug].tsx` → `params.slug`; `[...path].tsx` → `params.path`.
|
|
17
|
+
- API routes: `.ts` files exporting `GET`, `POST`, `PUT`, `PATCH`, `DELETE` receiving `RequestContext` (`request`, `url`, `params`, `cookies`, `locals`, `ip`, `json()`, `text()`, `redirect()`, `deny()`). Optional `export const csrf = false` opts out of origin checks (e.g. webhooks/bearer APIs).
|
|
18
|
+
- Prerendering: `export const prerender = true` (+ `export function paths() { return ['/posts/a'] }` required for dynamic routes; unlisted params return `404`). Skipped in `kay dev`.
|
|
19
|
+
- **Streaming & Head**: `<Head><title>...</title></Head>` (innermost `<title>` wins); `<Suspense fallback={<p>Loading</p>} error={<p>Failed</p>}><AsyncComp /></Suspense>` streams resolved HTML inline with 0 KB external JS (takes exactly one child; nested boundaries supported; times out after `streamTimeout`, default `30000` ms; errors also fire `onError`).
|
|
20
|
+
- **Actions (`@kayjs/kay/server`)**: `export const fn = action(standardSchema, async (input, ctx) => ..., options?)` or `action(async (ctx) => ...)` — must be a top-level named export so Kay can assign a URL. Works as zero-JS `<form action={fn} method="post">` (array fields auto-coerced from checkboxes/multi-selects; validation failures set an `HttpOnly` flash cookie readable via `getActionError(ctx.locals)` with sensitive fields stripped or `flashFields` allowlisted and `303` redirect to trusted Referer) and as typed island RPC `const res = await fn(data)` (always resolves to `{ ok: true, data }` or `{ ok: false, status, error, fieldErrors?, issues? }`; accepts `FormData` for files; redirects navigate the page). A route, `load()`, middleware or another action may also call it: it runs in that request, schema and folder `_middleware.ts` included, and resolves to the same result; called outside a request it throws. Server code is stripped from client bundles; CSRF `Origin`/`Sec-Fetch-Site` is checked before middleware and body parsing; folder `_middleware.ts` runs before the handler. `ctx` provides `redirect()` and `deny(status, message, fieldErrors?)`.
|
|
21
|
+
- **Config & Security (`kay.config.ts`, `@kayjs/kay/config`)**: `defineConfig({ lang, port, routesDir, outDir, publicDir, assetPrefix, security, trustedOrigins, trustProxy, maxRequestBodySize, streamTimeout, compress, onError, plugins })`. Default security headers (`security: false` to disable, or override `csp`, `hsts`, `frameOptions`, `referrerPolicy`, `contentTypeOptions`) attach strict `DEFAULT_CSP` (style attributes allowed) with automatic SHA-256 hashes for island/Suspense styles, the app's own `<style>` blocks and stream scripts, plus `HSTS` on HTTPS requests. `trustProxy: true | number` trusts that many right-most proxy hops for `X-Forwarded-*`. `maxRequestBodySize` defaults to `1 MiB`. `defineEnv(standardSchema)` validates env vars at startup; `nodeEnv()` reads `NODE_ENV` at runtime (safe in `--compile`).
|
|
22
|
+
- **Static files & CSS**: Files in `public/` are served at `/` with ETag/`304` (and `Cache-Control: no-cache` in `kay dev`; embedded in `--static` and `--compile`). Import `.css` or `*.module.css` directly from any component or layout.
|
|
23
|
+
- **CLI**: `kay new <dir> [--template minimal|fullstack|blog|app] [--force]` (its `AGENTS.md` points agents at this file, installed at `node_modules/@kayjs/kay/llms.txt`), `kay check [dir] [--no-typecheck]`, `kay dev [dir] [--port 3000] [--host [addr]]` (loopback `127.0.0.1` default; a `kay.config.ts` that fails to load stops it naming `kay.config.ts:<line>:<col>: <error>`), `kay build [dir] [--static] [--compile [out]] [--analyze] [--max-js <size>]` (`--analyze` lists each route's eager JS and its islands with why each is one; `--max-js 40kb` fails on a route whose gzipped eager JS is over it, naming its eager islands), `kay start [dir] [--port 3000] [--host [addr]]`, `kay upgrade [dir] [--no-install]` (moves an app from bare `kay` imports to `@kayjs/kay` and `icons` to `@kayjs/icons/plugin`, and registers stateful plugins as their handles), plus plugin commands (`kay ui-eject <grammar> [dest]`, `kay mcp-footprint`, `kay i18n-check`, `kay icons-find <words> [--set <prefix>] [--limit <n>]`). `kay --help`, `kay <command> --help` and `kay --completions fish|bash|zsh` come from `@kaynooo/cli-kit`; a typo'd command or option names the one meant. Exit codes: 0 done, 1 a finding or failure (`kay check` found an error, `kay upgrade` has steps left by hand, a build failed), 2 a usage error (unknown command or option, bad port or `--max-js`). Plugin commands are read from `kay.config.ts` only when the first word is no built-in, and take `--root <dir>` and `--help`; a config that fails to load leaves `kay --help` and the built-ins working, and a plugin command typed then names the error (exit 1).
|
|
24
|
+
- **Testing (`@kayjs/kay/test`)**: `const app = await testApp({ root, prebuilt? })` — in-process `app.get()`, `app.post()`, `app.import(path)` (the app's bundled copy of a route, action file or `kay.config.ts`), `app.submit(action | url, fields)`, `app.fetch()`, `app.cookies`, `app.clearCookies()` with persistent cookie jar and zero port binding. Islands: `const b = await testBrowser({ root, timeout?, browserPath? })` (needs `playwright-core` as a dev dependency and Chrome/Chromium; production build served on `b.origin`, a free 127.0.0.1 port) then `const page = await b.open(path)` (resolves once the page has loaded and its `load`/`client` islands have hydrated; `visible`, `idle` and `interaction` ones are the test's to trigger) with `page.click(sel)`, `page.fill(sel, value)`, `page.text(sel)`, `page.waitFor(sel | fn)`, `page.evaluate(fn)`, `page.errors` (page errors, console errors, 4xx/5xx responses), `page.close()`, and `await b.close()` at the end.
|
|
25
|
+
- **Plugins (`kay.config.ts`)**: `export default defineConfig({ plugins: [...] })` / `definePlugin(...)`.
|
|
26
|
+
- A stateful plugin's `createX()` returns the plugin and the app's handle in one object: `plugins: [auth, mail, rooms]`, with `auth.guard()`, `mail.send()`, `rooms.publish()` in routes. Stateless plugins are `x()`.
|
|
27
|
+
- Hooks: `server(api)` (`use`, `route(method, path, handler, { csrf?, trustedOrigins?, trustProxy? })` (responses get the security headers; an HTML one without its own CSP gets the app's, its `<style>` blocks hashed), `rewrite`, `provide(key, value)`/`inject(key)` typed by `serviceKey<T>(name)` from `@kayjs/kay/config`, `getBuildData`), `onError(info)`, `build(ctx)` (`emitAsset`, `emitPublic`, `addStyle`, `addRouteStyle`, `addHead`, `addRouteHead`, `provide`, `inject`, `setData`, `routes`), `afterPrerender(ctx)` (`routes`, `publicFiles`, `emitAsset`, `emitPublic`, `setData`), `transform`, `bunPlugins` (array or `({ root, assetPrefix, minify, target }) => [...]`), `css`, `head(head, ctx)`, `transformHtml`, `prerenderPaths`, `clientEntry`, `check(ctx)`, `watchPaths`, `commands`.
|
|
28
|
+
- Runtime state (timers, connections, caches) is created in `server(api)` and released in `api.onShutdown()`, never in the plugin factory (a throwing `onShutdown` or `onError` hook is logged with its plugin's name; the others still run): `kay dev` starts the next server on the same instance before shutting the last one down.
|
|
29
|
+
- First-party packages (13 total with `@kayjs/kay`):
|
|
30
|
+
- `@kayjs/ui`: Platform-first headless primitives (`Stack`, `Cluster`, `Grid`, `Sidebar`, `Split`, `Button`, `Card`, `Badge`, `Notice`, `Field`, `Switch`, `Checkbox`, `RadioGroup`, `Accordion`, `Popover`, `Dialog`, `Drawer`, `Tabs`, `Menu`, `Select`, `CommandPalette`, `DataTable`, `Toaster` + `toast()`) & pure CSS `@layer kui` Style Grammars (`orbit`, `editorial`, `workshop`, `console`, `soft`, `bare`); `kay ui-eject <grammar> [dest]`.
|
|
31
|
+
- `@kayjs/auth`: Argon2id passwords, hashed DB sessions, email verification (`requireEmailVerification: true` default), magic links (first claim drops prior password/sessions/OAuth links), OAuth 2.0 + PKCE (`github()`, `discord()`, `google()`, `oauthProvider()`), `auth.guard()`, `site` required off localhost, IP+email rate limiting (`trustProxy`), RGPD helpers (`listSessions`, `exportUser`, `deleteUser`, `pruneExpired`, `storeIp`, `storeUserAgent`), `memoryAuthStore()` & `sqliteAuthStore()` (`bun:sqlite`).
|
|
32
|
+
- `@kayjs/content`: Zero-dep `Bun.markdown` + `Bun.YAML` nested frontmatter + Standard Schema, lazy memoized Markdown rendering (`await entry.render()`) + O(1) `get(slug)`, `highlight(code, lang)` hook (Shiki-ready), MDX-lite embedded TSX `components`, `headingLinks`, auto-wired `@kayjs/images` optimization (`resolveImage: false` to opt out), localized collections (`localized: true`), TOC, and RSS feeds (`content({ feeds })`).
|
|
33
|
+
- `@kayjs/live`: Typed SSE rooms (`createRooms<TMessage, TMember>({ path, room, member, onJoin, onLeave, authorize })` mounts the stream at `path`; without `path`, a route calls `rooms.stream(ctx, ...)`), `publish(room, message, event?)`, microtask-coalesced broadcasts (`rooms.coalesce(build)`), `useLive(url, onMessage)` browser signal hook.
|
|
34
|
+
- `@kayjs/mcp`: Opt-in MCP Streamable HTTP (`2025-03-26`) plugin exposing typed `action()` handlers & compacted Standard JSON Schema tools (strips coercion branches, `x-*`, no-op bounds, folds homogeneous records) at `/mcp/tools` with bearer auth (`404` unconfigured, `401` invalid), `schemas`+`schemaRef` (`describe_schema`), `resources`, `format`/`formatResult`, `pruneEmpty`, `maxOutputChars`, `annotations`, `formatLines`/`formatTable`, `budget` warnings in dev/`kay check`, and `kay mcp-footprint` / `inspectMcpFootprint()`.
|
|
35
|
+
- `@kayjs/images`: Build-time AVIF/WebP pipeline + disk cache (`images()`, `image()`, `<Picture>`, `optimizeImageFile()`) + 1200×630 OG PNG `shareCard()`.
|
|
36
|
+
- `@kayjs/seo`: `titleTemplate`, localized `description`, multi-favicon, OG/Twitter/JSON-LD, `sitemap.xml` (`extraUrls`), redirects, self-hosted fonts (`@fontsource/*`).
|
|
37
|
+
- `@kayjs/i18n`: Locale URL rewriting (`ctx.locals.locale`/`t`/`localize`/`alternates`), `<html lang>` + internal link prefixing (`data-no-localize` opt-out), `prerenderPaths` expansion, `hreflang` alternates, `localizePath()`, `alternateLinks()`, `formatDate()`, `formatNumber()`, automatic `kay check` + `kay i18n-check`.
|
|
38
|
+
- `@kayjs/icons`: Virtual `~icons/<set>/<name>` inline SVG imports + `<Icon>` (islands too; takes SVG attributes, labelled by `aria-label`/`aria-labelledby` else `aria-hidden`); register `icons()` from `@kayjs/icons/plugin`, which also types `~icons/*` imports (a tsconfig leaving out `kay.config.ts` adds `/// <reference types="@kayjs/icons/ambient" />`). `.svg` files in `src/icons` are the set `local` (`~icons/local/logo`, each with a `viewBox` or `width`/`height`); `icons({ dirs: { brand: 'assets/brand' } })` adds folders, and naming `src/icons` there renames `local`. `kay icons-find <words>` prints the `~icons/...` specifiers matching the words, up to 10 per set (`--limit`), from the installed `@iconify-json/*` or `@iconify/json` sets, hoisted ones included, the `.svg` folders and `icons({ sets })` (`--set` picks one); run it before importing an icon rather than guessing its name. `kay check` and the build fail on an icon or set that does not exist, naming the file and the closest icons. It also matches a related word (`garbage` finds `trash`), a typo (`calnedar`), another form of a word (`searching`), a half-typed word (`shopp`) and two words typed apart (`sign out` finds `logout`); English only. `findIcons(set, query, { limit, offset })` from `@kayjs/icons/search` does the same for an app's own picker: names holding the query as whole words first (any word order), then related ones, those answering more query words first, then mid-word hits (`pin` in `spinner`) (throws on a negative or fractional `offset`/`limit`); `relatedWords(word)` gives `[word, strength]` pairs for an "also searched" list; it reads a ~1.7 MB word table on first call, so keep it server-side (an island importing it gets a build warning).
|
|
39
|
+
- `@kayjs/mail`: `createMailer({ from, transport, previewRoute, preview })`, `resend()` HTTP transport (auto-uses `RESEND_API_KEY`), custom transports; registered, it mounts the dev-only `/_kay/mail` (+ `.json`) outbox preview (never in production).
|
|
40
|
+
- `@kayjs/tailwind`: Tailwind v4 via `tailwind()` (auto-loads `bun-plugin-tailwind`, defaults `css: 'src/app.css'`).
|
|
41
|
+
- `@kayjs/spa`: Opt-in SPA navigation (`spa()`) with `[data-persist]` islands, `data-no-spa` opt-out, `[data-kay-prefetch]` hover prefetch, head/style diffing, and focus/live-region announcements.
|
|
42
|
+
- **Server builds & `--compile`**: Server `Bun.build` keeps npm dependencies external (`packages: 'external'`) while compiling `@kayjs/*` TSX packages; `kay build --compile` bundles everything + `public/` assets (`with { type: "file" }`) into one standalone Bun executable (`NODE_ENV` defaults to `production`). `kay start` and compiled binaries stop gracefully on `SIGTERM`/`SIGINT`/`SIGHUP`: no new connections, `api.onShutdown()` hooks run (`@kayjs/live` ends its streams), exit 0 once in-flight requests answer, exit 1 after 10 s.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kayjs/kay",
|
|
3
|
-
"version": "2.0.0-beta.
|
|
3
|
+
"version": "2.0.0-beta.4",
|
|
4
4
|
"description": "Bun-native TSX web framework with zero-directive automatic islands, fine-grained signals, and single-binary deploys",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"homepage": "https://kayjs.kaynooo.fr",
|
|
@@ -10,23 +10,25 @@
|
|
|
10
10
|
"kay": "./src/cli/index.ts"
|
|
11
11
|
},
|
|
12
12
|
"files": [
|
|
13
|
-
"src"
|
|
13
|
+
"src",
|
|
14
|
+
"templates",
|
|
15
|
+
"llms.txt"
|
|
14
16
|
],
|
|
15
17
|
"exports": {
|
|
16
18
|
".": "./src/index.ts",
|
|
17
|
-
"./
|
|
18
|
-
"./
|
|
19
|
-
"./dom-loop": "./src/dom/loop.ts",
|
|
20
|
-
"./action": "./src/dom/action.ts",
|
|
21
|
-
"./island": "./src/dom/island.ts",
|
|
22
|
-
"./ssr": "./src/ssr/index.ts",
|
|
23
|
-
"./server": "./src/server/index.ts",
|
|
24
|
-
"./compiler": "./src/compiler/index.ts",
|
|
25
|
-
"./build": "./src/build/index.ts",
|
|
26
|
-
"./dev": "./src/dev/index.ts",
|
|
19
|
+
"./server": "./src/server/public.ts",
|
|
20
|
+
"./config": "./src/plugins/public.ts",
|
|
27
21
|
"./test": "./src/test/index.ts",
|
|
22
|
+
"./build": "./src/build/index.ts",
|
|
28
23
|
"./jsx-runtime": "./src/jsx-runtime.ts",
|
|
29
|
-
"./jsx-dev-runtime": "./src/jsx-runtime.ts"
|
|
24
|
+
"./jsx-dev-runtime": "./src/jsx-runtime.ts",
|
|
25
|
+
"./internal/dom": "./src/dom/index.ts",
|
|
26
|
+
"./internal/dom-extras": "./src/dom/extras.ts",
|
|
27
|
+
"./internal/dom-loop": "./src/dom/loop.ts",
|
|
28
|
+
"./internal/action": "./src/dom/action.ts",
|
|
29
|
+
"./internal/island": "./src/dom/island.ts",
|
|
30
|
+
"./internal/ssr": "./src/ssr/index.ts",
|
|
31
|
+
"./internal/server": "./src/server/index.ts"
|
|
30
32
|
},
|
|
31
33
|
"engines": {
|
|
32
34
|
"bun": ">=1.4.0"
|
|
@@ -37,6 +39,15 @@
|
|
|
37
39
|
"directory": "packages/kay"
|
|
38
40
|
},
|
|
39
41
|
"dependencies": {
|
|
42
|
+
"@kaynooo/cli-kit": "^0.52.0",
|
|
40
43
|
"oxc-parser": "^0.155.0"
|
|
44
|
+
},
|
|
45
|
+
"peerDependencies": {
|
|
46
|
+
"playwright-core": "^1.64.0"
|
|
47
|
+
},
|
|
48
|
+
"peerDependenciesMeta": {
|
|
49
|
+
"playwright-core": {
|
|
50
|
+
"optional": true
|
|
51
|
+
}
|
|
41
52
|
}
|
|
42
53
|
}
|
package/src/build/bundle.ts
CHANGED
|
@@ -3,12 +3,14 @@
|
|
|
3
3
|
import type { BunPlugin } from 'bun'
|
|
4
4
|
import type { IslandBinding } from '../compiler/index'
|
|
5
5
|
import type { BuildPluginTarget, KayPlugin } from '../plugins/index'
|
|
6
|
+
import type { ClientTransforms } from './client-plugin'
|
|
6
7
|
import type { BuildCache, ModuleGraph } from './graph'
|
|
7
8
|
import type { ActionsByFile, IslandPlan } from './islands'
|
|
8
9
|
import { copyFileSync, existsSync, linkSync, mkdirSync, readdirSync, readFileSync, realpathSync, renameSync, writeFileSync } from 'node:fs'
|
|
9
10
|
import { dirname, isAbsolute, join, relative, resolve } from 'node:path'
|
|
10
|
-
import {
|
|
11
|
-
import { readsPrivateEnv
|
|
11
|
+
import { compileSsr } from '../compiler/index'
|
|
12
|
+
import { readsPrivateEnv } from '../compiler/server-only'
|
|
13
|
+
import { clientPlugin, KAY_SPECIFIER_FILTER, TS_FILTER } from './client-plugin'
|
|
12
14
|
import { formatBunBuildLogs, isOutsideRoot, isTsFile, relPosix } from './files'
|
|
13
15
|
import { stampFiles, stampsMatch } from './graph'
|
|
14
16
|
import { islandKey } from './islands'
|
|
@@ -64,11 +66,9 @@ function reuseDirFiles(srcDir: string, dstDir: string, relFiles?: readonly strin
|
|
|
64
66
|
return count > 0
|
|
65
67
|
}
|
|
66
68
|
|
|
67
|
-
const KAY_SPECIFIER_FILTER = /^(?:@kayjs\/)?kay(?:\/.*)?$/
|
|
68
|
-
const TS_FILTER = /\.(?:ts|tsx)$/
|
|
69
69
|
const KAY_SCOPE_RE = /^@kayjs\//
|
|
70
70
|
const LEADING_DOT_SLASH_RE = /^\.\//
|
|
71
|
-
const
|
|
71
|
+
const EXTERNAL_KAY_SPECIFIERS = new Set(['@kayjs/kay/build', '@kayjs/kay/test'])
|
|
72
72
|
|
|
73
73
|
export function pluginBunPlugins(env: Pick<BundleEnv, 'plugins' | 'root' | 'assetPrefix' | 'minify'>, target: BuildPluginTarget): BunPlugin[] {
|
|
74
74
|
const { root, assetPrefix, minify } = env
|
|
@@ -79,7 +79,7 @@ export function pluginBunPlugins(env: Pick<BundleEnv, 'plugins' | 'root' | 'asse
|
|
|
79
79
|
}
|
|
80
80
|
|
|
81
81
|
/** Plugin `transform` hooks, applied in order to every module the bundles load. */
|
|
82
|
-
function pluginTransforms(plugins: KayPlugin[]):
|
|
82
|
+
function pluginTransforms(plugins: KayPlugin[]): ClientTransforms {
|
|
83
83
|
const list = plugins.filter(p => typeof p.transform === 'function')
|
|
84
84
|
return {
|
|
85
85
|
active: list.length > 0,
|
|
@@ -226,8 +226,8 @@ export async function buildClient(env: BundleEnv, standaloneCss: string[]): Prom
|
|
|
226
226
|
if (islands.targets.size > 0 || pluginClientEntries.length > 0) {
|
|
227
227
|
const runtimeLines: string[] = []
|
|
228
228
|
if (islands.targets.size > 0) {
|
|
229
|
-
runtimeLines.push(`import { defineIslandElement } from 'kay/island';`)
|
|
230
|
-
runtimeLines.push(`export { hydrate${hasClientOnlyHydrate ? ', mount' : ''} } from 'kay/dom';`)
|
|
229
|
+
runtimeLines.push(`import { defineIslandElement } from '@kayjs/kay/internal/island';`)
|
|
230
|
+
runtimeLines.push(`export { hydrate${hasClientOnlyHydrate ? ', mount' : ''} } from '@kayjs/kay/internal/dom';`)
|
|
231
231
|
runtimeLines.push(`defineIslandElement();`)
|
|
232
232
|
}
|
|
233
233
|
for (const pe of pluginClientEntries)
|
|
@@ -251,47 +251,7 @@ export async function buildClient(env: BundleEnv, standaloneCss: string[]): Prom
|
|
|
251
251
|
|
|
252
252
|
const clientLeaks = new Set<string>()
|
|
253
253
|
const inlinedEnvKey = (key: string): boolean => key === 'NODE_ENV' || `process.env.${key}` in envDefines
|
|
254
|
-
const clientPlugin:
|
|
255
|
-
name: 'kay-v2-client',
|
|
256
|
-
setup(b) {
|
|
257
|
-
// Bun swaps node built-ins for empty shims in a browser build, so a server-only import would ship silently.
|
|
258
|
-
b.onResolve({ filter: SERVER_ONLY_FILTER }, (args) => {
|
|
259
|
-
if (!args.importer.includes('/node_modules/'))
|
|
260
|
-
clientLeaks.add(`${relPosix(root, args.importer)} imports server-only module "${args.path}"`)
|
|
261
|
-
return undefined
|
|
262
|
-
})
|
|
263
|
-
b.onResolve({ filter: KAY_SPECIFIER_FILTER }, (args) => {
|
|
264
|
-
const resolved = resolveKaySpecifier(args.path)
|
|
265
|
-
return resolved !== undefined ? { path: resolved } : undefined
|
|
266
|
-
})
|
|
267
|
-
b.onLoad({ filter: TS_FILTER }, (args) => {
|
|
268
|
-
const actions = actionsByFile.get(args.path)
|
|
269
|
-
if (actions !== undefined && !graph.analyses.get(args.path)?.isInteractive) {
|
|
270
|
-
const lines = [`import { actionStub } from 'kay/action';`]
|
|
271
|
-
for (const a of actions)
|
|
272
|
-
lines.push(`export const ${a.exportName} = actionStub(${JSON.stringify(a.url)});`)
|
|
273
|
-
return { contents: `${lines.join('\n')}\n`, loader: 'ts' }
|
|
274
|
-
}
|
|
275
|
-
|
|
276
|
-
if (!args.path.endsWith('.tsx')) {
|
|
277
|
-
if (!transforms.active || args.path.includes('/node_modules/'))
|
|
278
|
-
return undefined
|
|
279
|
-
const raw = graph.source(args.path)
|
|
280
|
-
const transformed = transforms.apply(raw, args.path, 'client')
|
|
281
|
-
return transformed !== raw ? { contents: transformed, loader: 'ts' } : undefined
|
|
282
|
-
}
|
|
283
|
-
|
|
284
|
-
const stamp = graph.stamp(args.path)
|
|
285
|
-
const cachedDom = stamp !== undefined ? cache?.domCompiled.get(args.path) : undefined
|
|
286
|
-
if (cachedDom !== undefined && cachedDom.mtimeMs === stamp!.mtimeMs && cachedDom.size === stamp!.size && (cachedDom.key ?? '') === transforms.key)
|
|
287
|
-
return { contents: cachedDom.code, loader: 'tsx' }
|
|
288
|
-
const compiled = transforms.apply(compileDom(args.path, graph.source(args.path), { analysis: graph.analyses.get(args.path) }).code, args.path, 'client')
|
|
289
|
-
if (cache !== undefined && stamp !== undefined)
|
|
290
|
-
cache.domCompiled.set(args.path, { mtimeMs: stamp.mtimeMs, size: stamp.size, key: transforms.key, code: compiled })
|
|
291
|
-
return { contents: compiled, loader: 'tsx' }
|
|
292
|
-
})
|
|
293
|
-
},
|
|
294
|
-
}
|
|
254
|
+
const plugin = clientPlugin({ root, graph, cache, actionsByFile, transforms, leaks: clientLeaks })
|
|
295
255
|
|
|
296
256
|
let clientResult: Awaited<ReturnType<typeof Bun.build>>
|
|
297
257
|
try {
|
|
@@ -310,7 +270,7 @@ export async function buildClient(env: BundleEnv, standaloneCss: string[]): Prom
|
|
|
310
270
|
'process.env.NODE_ENV': JSON.stringify(env.isDev ? 'development' : 'production'),
|
|
311
271
|
...envDefines,
|
|
312
272
|
},
|
|
313
|
-
plugins: [
|
|
273
|
+
plugins: [plugin, ...pluginBunPlugins(env, 'client')],
|
|
314
274
|
})
|
|
315
275
|
}
|
|
316
276
|
catch (err) {
|
|
@@ -484,7 +444,7 @@ export async function buildServer(env: BundleEnv, entries: string[], serverRoot:
|
|
|
484
444
|
const resolved = resolveKaySpecifier(args.path)
|
|
485
445
|
if (resolved === undefined)
|
|
486
446
|
return undefined
|
|
487
|
-
return
|
|
447
|
+
return EXTERNAL_KAY_SPECIFIERS.has(args.path) ? { path: resolved, external: true } : { path: resolved }
|
|
488
448
|
})
|
|
489
449
|
b.onResolve({ filter: KAY_SCOPE_RE }, (args) => {
|
|
490
450
|
try {
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
// The Bun plugin of the client build: kay specifiers, action stubs, compiled islands, and imports of the `@kayjs/kay` barrel pointed at the module holding each name.
|
|
2
|
+
|
|
3
|
+
import type { BunPlugin } from 'bun'
|
|
4
|
+
import type { BuildCache, ModuleGraph } from './graph'
|
|
5
|
+
import type { ActionsByFile } from './islands'
|
|
6
|
+
import { compileDom } from '../compiler/index'
|
|
7
|
+
import { SERVER_ONLY_FILTER } from '../compiler/server-only'
|
|
8
|
+
import { relPosix } from './files'
|
|
9
|
+
import { resolveKaySpecifier } from './resolve'
|
|
10
|
+
|
|
11
|
+
export const KAY_SPECIFIER_FILTER = /^@kayjs\/kay(?:\/.*)?$/
|
|
12
|
+
export const TS_FILTER = /\.(?:ts|tsx)$/
|
|
13
|
+
const BARREL_IMPORT_RE = /^([ \t]*)import\s*\{([^}]*)\}\s*from\s*(['"])@kayjs\/kay\3;?/gm
|
|
14
|
+
const SPECIFIER_RE = /^(type\s+)?([\w$]+)(?:\s+as\s+([\w$]+))?$/
|
|
15
|
+
|
|
16
|
+
export interface ClientTransforms {
|
|
17
|
+
active: boolean
|
|
18
|
+
key: string
|
|
19
|
+
apply: (code: string, id: string, target: 'server' | 'client') => string
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export interface ClientPluginEnv {
|
|
23
|
+
root: string
|
|
24
|
+
graph: ModuleGraph
|
|
25
|
+
cache: BuildCache | undefined
|
|
26
|
+
actionsByFile: ActionsByFile
|
|
27
|
+
transforms: ClientTransforms
|
|
28
|
+
/** Collects each server-only import a browser file makes, reported once the build ends. */
|
|
29
|
+
leaks: Set<string>
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Rewrites `import { a, b } from '@kayjs/kay'` to import each name from the module declaring it.
|
|
34
|
+
* Through the barrel every island reaches every module it re-exports, and Bun then places a module only some islands use (the action runtime) in the shared chunk in one build and in the island's own chunk in the next (#3598).
|
|
35
|
+
*/
|
|
36
|
+
export function directKayImports(code: string, graph: ModuleGraph): string {
|
|
37
|
+
if (!code.includes('@kayjs/kay'))
|
|
38
|
+
return code
|
|
39
|
+
const barrel = resolveKaySpecifier('@kayjs/kay')!
|
|
40
|
+
return code.replace(BARREL_IMPORT_RE, (statement, indent: string, list: string) => {
|
|
41
|
+
const byFile = new Map<string, string[]>()
|
|
42
|
+
const kept: string[] = []
|
|
43
|
+
for (const raw of list.split(',')) {
|
|
44
|
+
const spec = raw.trim()
|
|
45
|
+
if (spec === '')
|
|
46
|
+
continue
|
|
47
|
+
const match = SPECIFIER_RE.exec(spec)
|
|
48
|
+
const target = match !== null && match[1] === undefined ? graph.exportTarget(barrel, match[2]!) : undefined
|
|
49
|
+
if (target === undefined || target.file === barrel) {
|
|
50
|
+
kept.push(spec)
|
|
51
|
+
continue
|
|
52
|
+
}
|
|
53
|
+
const local = match![3] ?? match![2]!
|
|
54
|
+
const names = byFile.get(target.file) ?? []
|
|
55
|
+
names.push(target.exportName === local ? local : `${target.exportName} as ${local}`)
|
|
56
|
+
byFile.set(target.file, names)
|
|
57
|
+
}
|
|
58
|
+
const lines = [...byFile].map(([file, names]) => `import { ${names.join(', ')} } from ${JSON.stringify(file)};`)
|
|
59
|
+
if (kept.length > 0)
|
|
60
|
+
lines.push(`import { ${kept.join(', ')} } from '@kayjs/kay';`)
|
|
61
|
+
// Same line count, so later positions in the module stay where they were.
|
|
62
|
+
return `${indent}${lines.join(' ')}${'\n'.repeat(statement.split('\n').length - 1)}`
|
|
63
|
+
})
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export function clientPlugin(env: ClientPluginEnv): BunPlugin {
|
|
67
|
+
const { root, graph, cache, actionsByFile, transforms, leaks } = env
|
|
68
|
+
return {
|
|
69
|
+
name: 'kay-v2-client',
|
|
70
|
+
setup(b) {
|
|
71
|
+
// Bun swaps node built-ins for empty shims in a browser build, so a server-only import would ship silently.
|
|
72
|
+
b.onResolve({ filter: SERVER_ONLY_FILTER }, (args) => {
|
|
73
|
+
if (!args.importer.includes('/node_modules/'))
|
|
74
|
+
leaks.add(`${relPosix(root, args.importer)} imports server-only module "${args.path}"`)
|
|
75
|
+
return undefined
|
|
76
|
+
})
|
|
77
|
+
b.onResolve({ filter: KAY_SPECIFIER_FILTER }, (args) => {
|
|
78
|
+
const resolved = resolveKaySpecifier(args.path)
|
|
79
|
+
return resolved !== undefined ? { path: resolved } : undefined
|
|
80
|
+
})
|
|
81
|
+
b.onLoad({ filter: TS_FILTER }, (args) => {
|
|
82
|
+
const actions = actionsByFile.get(args.path)
|
|
83
|
+
if (actions !== undefined && !graph.analyses.get(args.path)?.isInteractive) {
|
|
84
|
+
const lines = [`import { actionStub } from '@kayjs/kay/internal/action';`]
|
|
85
|
+
for (const a of actions)
|
|
86
|
+
lines.push(`export const ${a.exportName} = actionStub(${JSON.stringify(a.url)});`)
|
|
87
|
+
return { contents: `${lines.join('\n')}\n`, loader: 'ts' }
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
if (!args.path.endsWith('.tsx')) {
|
|
91
|
+
const raw = graph.source(args.path)
|
|
92
|
+
const own = transforms.active && !args.path.includes('/node_modules/') ? transforms.apply(raw, args.path, 'client') : raw
|
|
93
|
+
const direct = directKayImports(own, graph)
|
|
94
|
+
return direct !== raw ? { contents: direct, loader: 'ts' } : undefined
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
const stamp = graph.stamp(args.path)
|
|
98
|
+
const cachedDom = stamp !== undefined ? cache?.domCompiled.get(args.path) : undefined
|
|
99
|
+
if (cachedDom !== undefined && cachedDom.mtimeMs === stamp!.mtimeMs && cachedDom.size === stamp!.size && (cachedDom.key ?? '') === transforms.key)
|
|
100
|
+
return { contents: cachedDom.code, loader: 'tsx' }
|
|
101
|
+
const compiled = directKayImports(transforms.apply(compileDom(args.path, graph.source(args.path), { analysis: graph.analyses.get(args.path) }).code, args.path, 'client'), graph)
|
|
102
|
+
if (cache !== undefined && stamp !== undefined)
|
|
103
|
+
cache.domCompiled.set(args.path, { mtimeMs: stamp.mtimeMs, size: stamp.size, key: transforms.key, code: compiled })
|
|
104
|
+
return { contents: compiled, loader: 'tsx' }
|
|
105
|
+
})
|
|
106
|
+
},
|
|
107
|
+
}
|
|
108
|
+
}
|
package/src/build/compile.ts
CHANGED
|
@@ -26,7 +26,8 @@ export async function compileExecutable(opts: CompileExecutableOptions): Promise
|
|
|
26
26
|
// Evaluated first via ESM static import order so `kay.config.ts` and route modules see NODE_ENV=production!
|
|
27
27
|
writeFileSync(prodEnvPath, `const _envKey = 'NODE_ENV';\nprocess.env[_envKey] ??= 'production';\n`)
|
|
28
28
|
const entryJs = join(outDir, 'server', SERVER_ENTRY_FILE)
|
|
29
|
-
const
|
|
29
|
+
const lifecycle = join(import.meta.dir, '../server/lifecycle.ts')
|
|
30
|
+
const imports: string[] = [`import ${JSON.stringify(prodEnvPath)};`, `import { createApp, kayConfig } from ${JSON.stringify(entryJs)};`, `import { handleSignals } from ${JSON.stringify(lifecycle)};`]
|
|
30
31
|
|
|
31
32
|
// Embed client assets and public files natively via `with { type: "file" }` (0 base64, 0 startup decode!)
|
|
32
33
|
const embeddedAssets: string[] = []
|
|
@@ -81,6 +82,7 @@ export async function compileExecutable(opts: CompileExecutableOptions): Promise
|
|
|
81
82
|
`if (Bun.argv.includes('--health')) { const probeHost = !hostname || hostname === '0.0.0.0' || hostname === '::' ? '127.0.0.1' : hostname; const r = await fetch(\`http://\${probeHost}:\${port}/\`).catch(() => null); process.exit(r && r.status < 500 ? 0 : 1); }`,
|
|
82
83
|
`const app = await createApp({ assetPrefix: ${JSON.stringify(assetPrefix)}, manifest, assets, publicAssets, publicEtags, prerenderedFiles });`,
|
|
83
84
|
`const server = app.serve(port, hostname);`,
|
|
85
|
+
`handleSignals(app, server);`,
|
|
84
86
|
`console.log(\`kay server listening on http://\${hostname ?? 'localhost'}:\${server.port}\`);`,
|
|
85
87
|
].join('\n')
|
|
86
88
|
|
|
@@ -89,7 +91,7 @@ export async function compileExecutable(opts: CompileExecutableOptions): Promise
|
|
|
89
91
|
const kayResolvePlugin: BunPlugin = {
|
|
90
92
|
name: 'kay-v2-compile-resolve',
|
|
91
93
|
setup(b) {
|
|
92
|
-
b.onResolve({ filter:
|
|
94
|
+
b.onResolve({ filter: /^@kayjs\/kay(?:\/.*)?$/ }, (args) => {
|
|
93
95
|
const resolved = resolveKaySpecifier(args.path)
|
|
94
96
|
return resolved !== undefined ? { path: resolved } : undefined
|
|
95
97
|
})
|
package/src/build/graph.ts
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
import type { ModuleAnalysis } from '../compiler/index'
|
|
4
4
|
import { existsSync, readFileSync, statSync } from 'node:fs'
|
|
5
5
|
import { analyzeModule } from '../compiler/index'
|
|
6
|
-
import { isTsFile } from './files'
|
|
6
|
+
import { isTsFile, relPosix } from './files'
|
|
7
7
|
import { resolveImportPath } from './resolve'
|
|
8
8
|
|
|
9
9
|
export interface FileStamp {
|
|
@@ -105,7 +105,8 @@ export class ModuleGraph {
|
|
|
105
105
|
private readonly resolved = new Map<string, string | undefined>()
|
|
106
106
|
private readonly deps = new Map<string, string[]>()
|
|
107
107
|
|
|
108
|
-
|
|
108
|
+
/** `root` is the app's folder, for the root-relative paths in errors. */
|
|
109
|
+
constructor(private readonly root: string, private readonly cache?: BuildCache) {}
|
|
109
110
|
|
|
110
111
|
/** The file's mtime and size; only tracked when a cache is in use. */
|
|
111
112
|
stamp(file: string): FileStamp | undefined {
|
|
@@ -174,7 +175,7 @@ export class ModuleGraph {
|
|
|
174
175
|
}
|
|
175
176
|
else {
|
|
176
177
|
const code = this.source(file)
|
|
177
|
-
analysis =
|
|
178
|
+
analysis = this.analyze(file, code)
|
|
178
179
|
if (this.cache !== undefined && stamp !== undefined)
|
|
179
180
|
this.cache.analyses.set(file, { mtimeMs: stamp.mtimeMs, size: stamp.size, code, analysis })
|
|
180
181
|
}
|
|
@@ -184,6 +185,18 @@ export class ModuleGraph {
|
|
|
184
185
|
return analysis
|
|
185
186
|
}
|
|
186
187
|
|
|
188
|
+
/** `analyzeModule`, its errors naming the file from the app's root. */
|
|
189
|
+
private analyze(file: string, code: string): ModuleAnalysis {
|
|
190
|
+
try {
|
|
191
|
+
return analyzeModule(file, code)
|
|
192
|
+
}
|
|
193
|
+
catch (err) {
|
|
194
|
+
if (err instanceof Error)
|
|
195
|
+
err.message = err.message.replaceAll(file, relPosix(this.root, file))
|
|
196
|
+
throw err
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
|
|
187
200
|
/** Follows `export { x } from './y'` and `export * from './y'` chains to the module that declares the export. */
|
|
188
201
|
exportTarget(file: string, exportName: string, depth = 0, seen = new Set<string>()): { file: string, exportName: string } {
|
|
189
202
|
if (depth > MAX_REEXPORT_DEPTH)
|
package/src/build/index.ts
CHANGED
|
@@ -21,17 +21,17 @@ import { planIslands } from './islands'
|
|
|
21
21
|
import { buildActionEntries, buildRouteEntries } from './manifest'
|
|
22
22
|
import { createPluginHost, createPublicFiles } from './plugin-host'
|
|
23
23
|
import { prerender } from './prerender'
|
|
24
|
-
import { formatBundleReport } from './report'
|
|
24
|
+
import { analyzeBundleWeights, checkJsBudget, formatBundleReport, islandOrigins } from './report'
|
|
25
25
|
import { SERVER_ENTRY_FILE, serverEntrySource } from './server-entry'
|
|
26
26
|
import { KAY_SRC_ROOT, resolveKaySpecifier } from './resolve'
|
|
27
|
-
import { assertNoRouteConflicts, hasRouteHandlerExport, routeExportProblem, SPECIAL_ROUTE_FILES } from './routes'
|
|
27
|
+
import { assertNoRouteConflicts, hasRouteHandlerExport, routeExportProblem, routeFileProblem, SPECIAL_ROUTE_FILES } from './routes'
|
|
28
28
|
import { exportStatic } from './static'
|
|
29
29
|
|
|
30
30
|
export type { BuildCache } from './graph'
|
|
31
31
|
export { createBuildCache } from './graph'
|
|
32
32
|
export type { ActionManifestEntry, BuildManifest, RouteManifestEntry } from './manifest'
|
|
33
|
-
export { analyzeBundleWeights, formatBundleReport } from './report'
|
|
34
|
-
export type { RouteBundleMetrics } from './report'
|
|
33
|
+
export { analyzeBundleWeights, checkJsBudget, formatBundleReport } from './report'
|
|
34
|
+
export type { BundleReport, RouteBundleMetrics, RouteIsland } from './report'
|
|
35
35
|
export { resolveKaySpecifier } from './resolve'
|
|
36
36
|
|
|
37
37
|
export interface BuildOptions {
|
|
@@ -47,6 +47,8 @@ export interface BuildOptions {
|
|
|
47
47
|
cache?: BuildCache | undefined
|
|
48
48
|
/** Print a per-route JS/CSS bundle weight report using Bun.build's metafile. */
|
|
49
49
|
analyze?: boolean | undefined
|
|
50
|
+
/** Fail the build when a route's eager JS, gzipped, is over this many bytes, naming the route and its islands. */
|
|
51
|
+
maxJs?: number | undefined
|
|
50
52
|
/** Export a static site directly into outDir (dist/) with no server/ folder left behind. */
|
|
51
53
|
static?: boolean | undefined
|
|
52
54
|
/** Run build-time prerendering for routes exporting `prerender = true` (default: true; disabled in `kay dev`). */
|
|
@@ -159,7 +161,7 @@ async function runBuild(run: BuildRun): Promise<BuildManifest> {
|
|
|
159
161
|
|
|
160
162
|
const allRouteFiles = walkRoutes(routesDir).sort()
|
|
161
163
|
const specialFiles = allRouteFiles.filter(f => SPECIAL_ROUTE_FILES.has(basename(f)))
|
|
162
|
-
const
|
|
164
|
+
const candidateFiles = allRouteFiles.filter(f => !basename(f).startsWith('_'))
|
|
163
165
|
const rootLayoutSrc = join(routesDir, '_layout.tsx')
|
|
164
166
|
const errorSrc = join(routesDir, '_error.tsx')
|
|
165
167
|
const notFoundSrc = join(routesDir, '_404.tsx')
|
|
@@ -171,21 +173,23 @@ async function runBuild(run: BuildRun): Promise<BuildManifest> {
|
|
|
171
173
|
// kay.config.ts enters the graph too, so an action or component reached only from it is analyzed and gets its URL.
|
|
172
174
|
const configSrc = join(root, 'kay.config.ts')
|
|
173
175
|
const hasConfigFile = existsSync(configSrc)
|
|
174
|
-
const graph = new ModuleGraph(options.cache)
|
|
175
|
-
for (const f of [...specialFiles, ...
|
|
176
|
+
const graph = new ModuleGraph(root, options.cache)
|
|
177
|
+
for (const f of [...specialFiles, ...candidateFiles, ...(hasConfigFile ? [configSrc] : [])])
|
|
176
178
|
graph.load(f)
|
|
177
179
|
for (const analysis of graph.analyses.values()) {
|
|
178
180
|
for (const warning of analysis.warnings)
|
|
179
181
|
console.warn(warning)
|
|
180
182
|
}
|
|
181
183
|
|
|
182
|
-
|
|
183
|
-
for (const f of
|
|
184
|
-
const
|
|
184
|
+
const routesRel = relPosix(root, routesDir)
|
|
185
|
+
for (const f of [...specialFiles, ...candidateFiles]) {
|
|
186
|
+
const analysis = graph.analyses.get(f)!
|
|
187
|
+
const problem = routeFileProblem(analysis, relPosix(root, f), routesRel) ?? routeExportProblem(analysis, relPosix(root, f))
|
|
185
188
|
if (problem !== undefined)
|
|
186
189
|
throw new Error(`kay build: ${problem}`)
|
|
187
190
|
}
|
|
188
|
-
|
|
191
|
+
// A file exporting only actions stays in routes/ for its folder's middleware.
|
|
192
|
+
const pageFiles = candidateFiles.filter(f => hasRouteHandlerExport(graph.analyses.get(f)!))
|
|
189
193
|
assertNoRouteConflicts(root, routesDir, pageFiles)
|
|
190
194
|
|
|
191
195
|
// Server actions, keyed by source file
|
|
@@ -209,7 +213,7 @@ async function runBuild(run: BuildRun): Promise<BuildManifest> {
|
|
|
209
213
|
.flatMap(p => p.css ?? [])
|
|
210
214
|
.map(c => resolve(root, c))
|
|
211
215
|
.filter(c => existsSync(c))
|
|
212
|
-
const env = { root, outDir, clientDir, serverDir, assetPrefix, minify: run.minify, isDev, analyze: options.analyze === true, graph, cache: options.cache, plugins, actionsByFile, islands }
|
|
216
|
+
const env = { root, outDir, clientDir, serverDir, assetPrefix, minify: run.minify, isDev, analyze: options.analyze === true || options.maxJs !== undefined, graph, cache: options.cache, plugins, actionsByFile, islands }
|
|
213
217
|
|
|
214
218
|
const routeEntryFiles = new Set([...specialFiles, ...pageFiles])
|
|
215
219
|
const standaloneActionFiles = [...actionsByFile.keys()].filter(f => !routeEntryFiles.has(f))
|
|
@@ -351,6 +355,13 @@ async function runBuild(run: BuildRun): Promise<BuildManifest> {
|
|
|
351
355
|
}
|
|
352
356
|
const writeManifest = (): void => writeFileSync(join(outDir, 'manifest.json'), JSON.stringify(manifest, null, 2))
|
|
353
357
|
writeManifest()
|
|
358
|
+
if (options.analyze === true || options.maxJs !== undefined) {
|
|
359
|
+
const report = analyzeBundleWeights(manifest, clientDir, assetPrefix, client.metafile, islandOrigins(islands, client.islandChunks, graph, root))
|
|
360
|
+
if (options.analyze === true)
|
|
361
|
+
console.log(formatBundleReport(report))
|
|
362
|
+
if (options.maxJs !== undefined)
|
|
363
|
+
checkJsBudget(report, options.maxJs)
|
|
364
|
+
}
|
|
354
365
|
|
|
355
366
|
// Hybrid prerendering / static export (skipped in `kay dev`, where routes render on-demand)
|
|
356
367
|
const prerenderRoutes = options.prerender !== false || isStatic ? routes.filter(r => r.prerender) : []
|
|
@@ -401,8 +412,5 @@ async function runBuild(run: BuildRun): Promise<BuildManifest> {
|
|
|
401
412
|
})
|
|
402
413
|
}
|
|
403
414
|
|
|
404
|
-
if (options.analyze)
|
|
405
|
-
console.log(formatBundleReport(manifest, clientDir, assetPrefix, client.metafile))
|
|
406
|
-
|
|
407
415
|
return manifest
|
|
408
416
|
}
|
package/src/build/islands.ts
CHANGED
|
@@ -3,6 +3,8 @@
|
|
|
3
3
|
import type { ModuleGraph } from './graph'
|
|
4
4
|
import { basename, extname } from 'node:path'
|
|
5
5
|
import { asyncInteractiveError } from '../compiler/analyze'
|
|
6
|
+
import { withStateReads } from '../compiler/interactivity'
|
|
7
|
+
import { serverOnlyTagError } from '../compiler/mistakes'
|
|
6
8
|
import { isTsFile, relPosix } from './files'
|
|
7
9
|
|
|
8
10
|
export interface IslandTarget {
|
|
@@ -55,40 +57,36 @@ export function planIslands(graph: ModuleGraph, root: string, pageFiles: string[
|
|
|
55
57
|
|
|
56
58
|
// A component reading reactive state another module exports runs in the browser too. The promoted analysis lives in this build's map only, so the cached one still reflects the file alone.
|
|
57
59
|
for (const [file, analysis] of analyses) {
|
|
58
|
-
if (!file.endsWith('.tsx')
|
|
60
|
+
if (!file.endsWith('.tsx'))
|
|
59
61
|
continue
|
|
60
|
-
|
|
62
|
+
const promoted = withStateReads(analysis, (imp, imported) => {
|
|
61
63
|
const resolved = graph.resolve(file, imp.source)
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
break
|
|
78
|
-
}
|
|
79
|
-
}
|
|
64
|
+
if (resolved === undefined || !isTsFile(resolved))
|
|
65
|
+
return false
|
|
66
|
+
if (imported === '*')
|
|
67
|
+
return graph.load(resolved).stateExports.length > 0
|
|
68
|
+
const target = graph.exportTarget(resolved, imported)
|
|
69
|
+
return graph.load(target.file).stateExports.includes(target.exportName)
|
|
70
|
+
})
|
|
71
|
+
if (promoted === undefined)
|
|
72
|
+
continue
|
|
73
|
+
const page = promoted.exports.get('default')
|
|
74
|
+
if (analysis.hasAsyncDefault && page?.interactive === true)
|
|
75
|
+
throw asyncInteractiveError(file, page.reason)
|
|
76
|
+
if (promoted.serverOnly !== undefined)
|
|
77
|
+
throw serverOnlyTagError(relPosix(root, file), promoted.serverOnly)
|
|
78
|
+
analyses.set(file, { ...analysis, ...promoted })
|
|
80
79
|
}
|
|
81
80
|
|
|
82
81
|
for (const [file, analysis] of analyses) {
|
|
83
82
|
if (!file.endsWith('.tsx'))
|
|
84
83
|
continue
|
|
85
|
-
if (analysis.
|
|
86
|
-
|
|
87
|
-
registerIsland(file, 'default')
|
|
84
|
+
if (analysis.exports.get('default')?.interactive === true && pageSet.has(file)) {
|
|
85
|
+
registerIsland(file, 'default')
|
|
88
86
|
continue
|
|
89
87
|
}
|
|
90
88
|
|
|
91
|
-
// Only names rendered as tags become islands: `<Counter />`, or `<UI.Counter />` through a namespace import.
|
|
89
|
+
// Only names rendered as tags from server-side code become islands: `<Counter />`, or `<UI.Counter />` through a namespace import.
|
|
92
90
|
const bindings = new Map<string, IslandTarget>()
|
|
93
91
|
for (const imp of analysis.imports) {
|
|
94
92
|
const resolved = graph.resolve(file, imp.source)
|
|
@@ -96,11 +94,11 @@ export function planIslands(graph: ModuleGraph, root: string, pageFiles: string[
|
|
|
96
94
|
continue
|
|
97
95
|
for (const spec of imp.specifiers) {
|
|
98
96
|
const tags = spec.imported === '*'
|
|
99
|
-
? [...analysis.
|
|
100
|
-
: analysis.
|
|
97
|
+
? [...analysis.staticJsxTags].filter(tag => tag.startsWith(`${spec.local}.`) && !tag.slice(spec.local.length + 1).includes('.')).map(tag => [tag, tag.slice(spec.local.length + 1)] as const)
|
|
98
|
+
: analysis.staticJsxTags.has(spec.local) ? [[spec.local, spec.imported] as const] : []
|
|
101
99
|
for (const [tag, exportName] of tags) {
|
|
102
100
|
const target = graph.exportTarget(resolved, exportName)
|
|
103
|
-
if (target.file.endsWith('.tsx') && graph.load(target.file).
|
|
101
|
+
if (target.file.endsWith('.tsx') && graph.load(target.file).exports.get(target.exportName)?.interactive === true)
|
|
104
102
|
bindings.set(tag, registerIsland(target.file, target.exportName))
|
|
105
103
|
}
|
|
106
104
|
}
|
|
@@ -134,10 +132,10 @@ export function planIslands(graph: ModuleGraph, root: string, pageFiles: string[
|
|
|
134
132
|
|
|
135
133
|
// A layout, error or 404 page renders on the server only, so interactivity written in it would never run.
|
|
136
134
|
for (const file of specialFiles) {
|
|
137
|
-
const
|
|
138
|
-
if (
|
|
135
|
+
const page = analyses.get(file)?.exports.get('default')
|
|
136
|
+
if (page?.interactive === true) {
|
|
139
137
|
const rel = relPosix(root, file)
|
|
140
|
-
throw new Error(`kay build: ${rel} uses browser interactivity (${
|
|
138
|
+
throw new Error(`kay build: ${rel} uses browser interactivity (${page.reason}), but it renders on the server only. Move the interactive part into a component and render that component from ${rel}.`)
|
|
141
139
|
}
|
|
142
140
|
}
|
|
143
141
|
|