@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
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) {
|
|
@@ -425,7 +385,8 @@ export async function buildClient(env: BundleEnv, standaloneCss: string[]): Prom
|
|
|
425
385
|
return result
|
|
426
386
|
}
|
|
427
387
|
|
|
428
|
-
|
|
388
|
+
/** `entry` is the generated `_entry.js`, an in-memory file bundled beside `entries` so it shares their chunks. */
|
|
389
|
+
export async function buildServer(env: BundleEnv, entries: string[], serverRoot: string, islandChunks: Map<string, string>, entry: { file: string, source: string }): Promise<void> {
|
|
429
390
|
const { root, outDir, serverDir, graph, cache, islands } = env
|
|
430
391
|
const transforms = pluginTransforms(env.plugins)
|
|
431
392
|
const externalOutDir = isOutsideRoot(root, outDir)
|
|
@@ -483,7 +444,7 @@ export async function buildServer(env: BundleEnv, entries: string[], serverRoot:
|
|
|
483
444
|
const resolved = resolveKaySpecifier(args.path)
|
|
484
445
|
if (resolved === undefined)
|
|
485
446
|
return undefined
|
|
486
|
-
return
|
|
447
|
+
return EXTERNAL_KAY_SPECIFIERS.has(args.path) ? { path: resolved, external: true } : { path: resolved }
|
|
487
448
|
})
|
|
488
449
|
b.onResolve({ filter: KAY_SCOPE_RE }, (args) => {
|
|
489
450
|
try {
|
|
@@ -567,7 +528,8 @@ export async function buildServer(env: BundleEnv, entries: string[], serverRoot:
|
|
|
567
528
|
let serverResult: Awaited<ReturnType<typeof Bun.build>>
|
|
568
529
|
try {
|
|
569
530
|
serverResult = await Bun.build({
|
|
570
|
-
entrypoints: entries,
|
|
531
|
+
entrypoints: [...entries, entry.file],
|
|
532
|
+
files: { [entry.file]: entry.source },
|
|
571
533
|
outdir: serverDir,
|
|
572
534
|
root: serverRoot,
|
|
573
535
|
target: 'bun',
|
|
@@ -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
|
@@ -6,6 +6,7 @@ import type { BuildManifest } from './index'
|
|
|
6
6
|
import { existsSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
|
|
7
7
|
import { join } from 'node:path'
|
|
8
8
|
import { formatBunBuildLogs } from './files'
|
|
9
|
+
import { SERVER_ENTRY_FILE } from './server-entry'
|
|
9
10
|
|
|
10
11
|
export interface CompileExecutableOptions {
|
|
11
12
|
root: string
|
|
@@ -14,50 +15,19 @@ export interface CompileExecutableOptions {
|
|
|
14
15
|
manifest: BuildManifest
|
|
15
16
|
assetPrefix: string
|
|
16
17
|
outfile: string
|
|
17
|
-
kaySrcRoot: string
|
|
18
18
|
resolveKaySpecifier: (specifier: string) => string | undefined
|
|
19
19
|
bunPlugins?: BunPlugin[] | undefined
|
|
20
20
|
}
|
|
21
21
|
|
|
22
22
|
export async function compileExecutable(opts: CompileExecutableOptions): Promise<void> {
|
|
23
|
-
const { root, outDir, clientDir, manifest, assetPrefix, outfile,
|
|
23
|
+
const { root, outDir, clientDir, manifest, assetPrefix, outfile, resolveKaySpecifier, bunPlugins = [] } = opts
|
|
24
24
|
const entryPath = join(outDir, '__compile_entry.ts')
|
|
25
25
|
const prodEnvPath = join(outDir, '__compile_prod_env.ts')
|
|
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
|
-
const
|
|
29
|
-
const
|
|
30
|
-
const
|
|
31
|
-
let idx = 0
|
|
32
|
-
|
|
33
|
-
const addMod = (rel: string) => {
|
|
34
|
-
if (seenFiles.has(rel))
|
|
35
|
-
return
|
|
36
|
-
seenFiles.add(rel)
|
|
37
|
-
const v = `_m${idx++}`
|
|
38
|
-
imports.push(`import * as ${v} from ${JSON.stringify(join(outDir, rel))};`)
|
|
39
|
-
modEntries.push(`${JSON.stringify(rel)}: ${v}`)
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
for (const r of manifest.routes) {
|
|
43
|
-
addMod(r.file)
|
|
44
|
-
for (const l of r.layouts) addMod(l)
|
|
45
|
-
for (const m of r.middlewares) addMod(m)
|
|
46
|
-
}
|
|
47
|
-
if (manifest.rootLayoutFile) addMod(manifest.rootLayoutFile)
|
|
48
|
-
if (manifest.errorFile) addMod(manifest.errorFile)
|
|
49
|
-
if (manifest.notFoundFile) addMod(manifest.notFoundFile)
|
|
50
|
-
for (const a of manifest.actions) {
|
|
51
|
-
addMod(a.file)
|
|
52
|
-
for (const m of a.middlewares) addMod(m)
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
const configPath = manifest.configFile !== undefined
|
|
56
|
-
? join(outDir, manifest.configFile)
|
|
57
|
-
: join(root, 'kay.config.ts')
|
|
58
|
-
const hasConfig = existsSync(configPath)
|
|
59
|
-
if (hasConfig)
|
|
60
|
-
imports.push(`import _kayConfig from ${JSON.stringify(configPath)};`)
|
|
28
|
+
const entryJs = join(outDir, 'server', SERVER_ENTRY_FILE)
|
|
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)};`]
|
|
61
31
|
|
|
62
32
|
// Embed client assets and public files natively via `with { type: "file" }` (0 base64, 0 startup decode!)
|
|
63
33
|
const embeddedAssets: string[] = []
|
|
@@ -100,24 +70,19 @@ export async function compileExecutable(opts: CompileExecutableOptions): Promise
|
|
|
100
70
|
}
|
|
101
71
|
}
|
|
102
72
|
|
|
103
|
-
const cfgExpr = hasConfig
|
|
104
|
-
? `resolveServerConfig(_kayConfig, { assetPrefix: ${JSON.stringify(assetPrefix)} })`
|
|
105
|
-
: `{ assetPrefix: ${JSON.stringify(assetPrefix)} }`
|
|
106
|
-
|
|
107
73
|
const code = [
|
|
108
74
|
...imports,
|
|
109
|
-
`import { createServerFromEmbedded, resolveServerConfig } from ${JSON.stringify(join(kaySrcRoot, 'server/index.ts'))};`,
|
|
110
75
|
`const manifest = ${JSON.stringify(manifest)};`,
|
|
111
|
-
`const modules = { ${modEntries.join(', ')} };`,
|
|
112
76
|
`const assets = { ${embeddedAssets.join(', ')} };`,
|
|
113
77
|
`const publicAssets = { ${embeddedPublic.join(', ')} };`,
|
|
114
78
|
`const publicEtags = { ${embeddedPublicEtags.join(', ')} };`,
|
|
115
79
|
`const prerenderedFiles = { ${embeddedPrerenderedFiles.join(', ')} };`,
|
|
116
|
-
`const port = Number(process.env.PORT ||
|
|
80
|
+
`const port = Number(process.env.PORT || kayConfig.port || 3000);`,
|
|
117
81
|
`const hostname = process.env.HOST || undefined;`,
|
|
118
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); }`,
|
|
119
|
-
`const app = await
|
|
83
|
+
`const app = await createApp({ assetPrefix: ${JSON.stringify(assetPrefix)}, manifest, assets, publicAssets, publicEtags, prerenderedFiles });`,
|
|
120
84
|
`const server = app.serve(port, hostname);`,
|
|
85
|
+
`handleSignals(app, server);`,
|
|
121
86
|
`console.log(\`kay server listening on http://\${hostname ?? 'localhost'}:\${server.port}\`);`,
|
|
122
87
|
].join('\n')
|
|
123
88
|
|
|
@@ -126,7 +91,7 @@ export async function compileExecutable(opts: CompileExecutableOptions): Promise
|
|
|
126
91
|
const kayResolvePlugin: BunPlugin = {
|
|
127
92
|
name: 'kay-v2-compile-resolve',
|
|
128
93
|
setup(b) {
|
|
129
|
-
b.onResolve({ filter:
|
|
94
|
+
b.onResolve({ filter: /^@kayjs\/kay(?:\/.*)?$/ }, (args) => {
|
|
130
95
|
const resolved = resolveKaySpecifier(args.path)
|
|
131
96
|
return resolved !== undefined ? { path: resolved } : undefined
|
|
132
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)
|