sordo 0.2.0 → 0.4.0

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/CHANGELOG.md CHANGED
@@ -1,5 +1,27 @@
1
1
  # sordo
2
2
 
3
+ ## 0.4.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 5ebcc79: Edge: expose Worker bindings and `waitUntil` on `SordoContext` (`ctx.bindings`, typed via the augmentable `SordoBindings`), merge Worker string vars into `ctx.env`, and add `adapter.edge.assets: "external"` to emit client assets to `worker-assets/` instead of inlining them. `sordo build` warns when `worker.js` nears Cloudflare's size limit.
8
+
9
+ Document the manual Cloudflare Workers deploy recipe (`wrangler deploy` against `worker.js`) in the README, and note in the `sordo deploy` hint that `@sordo/deploy-cloudflare` is not yet published.
10
+
11
+ ### Patch Changes
12
+
13
+ - b266211: New `@sordo/deploy-cloudflare` deploy plugin: `sordo deploy --target edge` runs `wrangler deploy` against the edge build, generating a minimal Wrangler config when the project has none. The README now documents the plugin and the manual Wrangler path (`.sordo/worker.js`, `bun run build`, external assets served under `/_sordo/assets/`), and the `sordo deploy` hint no longer calls the plugin unpublished.
14
+
15
+ ## 0.3.0
16
+
17
+ ### Minor Changes
18
+
19
+ - 0f36821: Add an optional `css` build entry. Set `css: "app/styles/app.css"` (or `{ entry, tailwind }`) in `sordo.config.ts` and `sordo build` / the dev client compile it with `Bun.build` into a content-hashed sheet under `/_sordo/client/`, record it as `manifest.css`, and link it from every rendered page. The bun and edge servers serve the sheet from the bundle. Entries that `@import "tailwindcss"` load `bun-plugin-tailwind` (an optional peer dependency: `bun add -D bun-plugin-tailwind`). Apps without the option build exactly as before.
20
+
21
+ ### Patch Changes
22
+
23
+ - 62a3969: Production servers now serve the app's client code. A non-compiled `bun` build and the `edge` worker serve every `/_sordo/client/*` output (island and page chunks, the CSS sheet and its assets) from bytes inlined at build time, so islands and hydrated pages hydrate in production. Before, only `--compile` builds served them, and every other build returned 404. Adds `sordo start`, which runs the last build's server (the compiled binary when there is one) and accepts `--port` / `--out`; scaffolded apps' `bun run start` already calls it. The built bun server now honours `PORT`.
24
+
3
25
  ## 0.2.0
4
26
 
5
27
  ### Minor Changes
package/CLAUDE.md CHANGED
@@ -12,7 +12,7 @@ below are specific to working inside this package.
12
12
  - `src/router/` — filesystem route scan + compile to Bun route patterns
13
13
  - `src/render/` — React SSR (`renderToReadableStream`) + dev error overlay + island marker emission
14
14
  - `src/client/` — browser hydration runtime: scans `[data-island]` markers; `page.ts` boots whole-tree hydrated pages (`export const hydrate = true`) and drives client-side navigation (`Link` / `navigate`) from the `__sordo_bootstrap` payload (framework specs 28/29)
15
- - `src/build/` — route + island scan, client/server entry generation, `Bun.build` pipeline. Hydrated pages get a generated per-route entry (`page-entry.ts`) bundled in the same split build as islands; `loader`/`serialize` are stripped from client bundles via `Bun.Transpiler` export elimination. `adapter.bun.compile` (production) runs `bun build --compile` against the generated server-entry SOURCE and embeds app/public + client chunks via `with { type: "file" }` / `Bun.embeddedFiles`; `--compile` with `--target edge` is a config-time error
15
+ - `src/build/` — route + island scan, client/server entry generation, `Bun.build` pipeline. Hydrated pages get a generated per-route entry (`page-entry.ts`) bundled in the same split build as islands; `loader`/`serialize` are stripped from client bundles via `Bun.Transpiler` export elimination. `adapter.bun.compile` (production) runs `bun build --compile` against the generated server-entry SOURCE and embeds app/public + client chunks via `with { type: "file" }` / `Bun.embeddedFiles`; `--compile` with `--target edge` is a config-time error. An optional `css` config entry is built by `css.ts` into a hashed sheet under `client/`, recorded as `manifest.css` (the renderer links it), and inlined into the bun/edge server bundle via `inline-assets.macro.ts`; Tailwind entries load `bun-plugin-tailwind` (optional peer) by dynamic import
16
16
  - `src/middleware/` — composition, `SordoContext`. `request-id.ts` mints `ctx.requestId` (echoed as `X-Request-Id`, inbound junk ignored); the router finalizer folds in the cookie flush and dev-only `Server-Timing`
17
17
  - `src/dev/` — `bun --hot` / `bun --watch` integration, HMR WebSocket, `setupDevClient` (bundles islands in dev and serves `/_sordo/client/*`)
18
18
  - `src/server/` — `startServer` / `createServer` around `Bun.serve`
@@ -30,7 +30,7 @@ Declared in `package.json#exports`:
30
30
  `sordo/build`, `sordo/dev`, `sordo/config`, `sordo/middleware`,
31
31
  `sordo/server`, `sordo/ai`, `sordo/agents-md`, `sordo/plugin`.
32
32
 
33
- CLI at `bin/sordo.ts` → `src/cli/index.ts` (`dev` / `build` / `run` / `deploy` / `secret` / `doctor` / `add` / `ui` / `view` / `update` / `upgrade` / `migrate`). `run` is the opt-in monorepo task orchestrator: `sordo run <task>` wraps each workspace `(package, task)` unit with a content-addressed output cache + affected detection (`src/cli/run.ts` + `src/cli/run/`, framework spec 27). Its cache is 100% Bun builtins (`Bun.CryptoHasher` sha256 key, `Bun.Glob`, `Bun.Archive` tarballs, `bun:sqlite` WAL index, `Bun.$` git, `Bun.spawn`); per-task `inputs`/`outputs`/`env`/`cache` come from a `tasks` block in `sordo.config.ts`. `sordo add <component>` stamps UI source (upstream shadcn/ui via `@shadcn/<name>`) into `app/components/ui/` (it also resolves local paths, https URLs, and `@ns/<name>` namespaced registries); `ui init` scaffolds tokens + helpers, `ui build` emits a fetchable registry, `view`/`update` preview-then-stamp, and `migrate` codemods radix imports / RTL logical props. See `src/cli/commands/` and `.claude/rules/ui-catalog.md`. `upgrade` bumps the project's `sordo` dependency to the newest release on its channel (stable→`latest`, prerelease→its pre tag); the CLI also prints a cached, channel-aware "update available" banner on startup (`src/cli/update-check.ts`, opt out with `--no-update-check` / `NO_UPDATE_NOTIFIER`). `doctor` aggregates read-only project-hygiene checks (toolchain probes, `bun audit` / `bun outdated`, lockfile sync, config + biome validity, and monorepo single-React / catalog invariants) into one aligned report with a remedy per finding and a CI exit code (`src/cli/doctor.ts` + `src/cli/doctor/`, cli spec 20); Phase 1 is report-only — no `--fix`. Width-aware output utilities live in `src/cli/ansi.ts` (`Bun.stringWidth` / `stripANSI` / `wrapAnsi`).
33
+ CLI at `bin/sordo.ts` → `src/cli/index.ts` (`dev` / `build` / `start` / `run` / `deploy` / `secret` / `doctor` / `add` / `ui` / `view` / `update` / `upgrade` / `migrate`). `run` is the opt-in monorepo task orchestrator: `sordo run <task>` wraps each workspace `(package, task)` unit with a content-addressed output cache + affected detection (`src/cli/run.ts` + `src/cli/run/`, framework spec 27). Its cache is 100% Bun builtins (`Bun.CryptoHasher` sha256 key, `Bun.Glob`, `Bun.Archive` tarballs, `bun:sqlite` WAL index, `Bun.$` git, `Bun.spawn`); per-task `inputs`/`outputs`/`env`/`cache` come from a `tasks` block in `sordo.config.ts`. `sordo add <component>` stamps UI source (upstream shadcn/ui via `@shadcn/<name>`) into `app/components/ui/` (it also resolves local paths, https URLs, and `@ns/<name>` namespaced registries); `ui init` scaffolds tokens + helpers, `ui build` emits a fetchable registry, `view`/`update` preview-then-stamp, and `migrate` codemods radix imports / RTL logical props. See `src/cli/commands/` and `.claude/rules/ui-catalog.md`. `upgrade` bumps the project's `sordo` dependency to the newest release on its channel (stable→`latest`, prerelease→its pre tag); the CLI also prints a cached, channel-aware "update available" banner on startup (`src/cli/update-check.ts`, opt out with `--no-update-check` / `NO_UPDATE_NOTIFIER`). `doctor` aggregates read-only project-hygiene checks (toolchain probes, `bun audit` / `bun outdated`, lockfile sync, config + biome validity, and monorepo single-React / catalog invariants) into one aligned report with a remedy per finding and a CI exit code (`src/cli/doctor.ts` + `src/cli/doctor/`, cli spec 20); Phase 1 is report-only — no `--fix`. Width-aware output utilities live in `src/cli/ansi.ts` (`Bun.stringWidth` / `stripANSI` / `wrapAnsi`).
34
34
 
35
35
  ## Dev mode wiring
36
36
 
package/README.md CHANGED
@@ -72,6 +72,84 @@ sordo deploy # build then dispatch to an installed deploy plugin
72
72
  sordo secret # manage dev-time secrets in the OS keychain
73
73
  ```
74
74
 
75
+ On `--target edge`, client chunks and CSS are inlined into `dist/worker.js` by
76
+ default. Set `adapter: { edge: { assets: "external" } }` to write them (and
77
+ `public/`) to `dist/worker-assets/` instead — URL paths mirror the directory,
78
+ with a `_headers` file and `manifest.json` — and upload that directory as
79
+ Workers static assets. `sordo build` warns when `worker.js` nears the 3 MB gz
80
+ free-plan limit.
81
+
82
+ ### Deploying to Cloudflare Workers
83
+
84
+ Install the deploy plugin and let `sordo deploy` build and ship the Worker:
85
+
86
+ ```sh
87
+ bun add -d @sordo/deploy-cloudflare
88
+ ```
89
+
90
+ ```ts
91
+ // sordo.config.ts
92
+ import { defineConfig } from "sordo/config";
93
+ import { cloudflare } from "@sordo/deploy-cloudflare";
94
+
95
+ export default defineConfig({
96
+ target: "edge",
97
+ plugins: [cloudflare({ name: "my-site" })],
98
+ });
99
+ ```
100
+
101
+ ```sh
102
+ bunx wrangler login
103
+ bun run build # scaffolded apps generate CSS first, then build
104
+ sordo deploy --target edge
105
+ ```
106
+
107
+ With no `wrangler.jsonc`/`wrangler.toml` in the project the plugin generates
108
+ `.sordo/wrangler.generated.jsonc`; add your own to control bindings, routes or
109
+ vars. See the plugin README for options (`wranglerEnv`, `dryRun`, `args`).
110
+
111
+ #### Manual path (no plugin)
112
+
113
+ Sordo emits no `wrangler.jsonc` — you own it. `sordo build --target edge` writes
114
+ `.sordo/worker.js` (default `outDir` is `./.sordo`, not `dist/`). Scaffolded
115
+ apps generate Tailwind CSS in their `build` script, so use `bun run build`
116
+ rather than calling `sordo build` directly.
117
+
118
+ ```sh
119
+ bun run build
120
+ bunx wrangler deploy # reads wrangler.jsonc
121
+ ```
122
+
123
+ ```jsonc
124
+ // wrangler.jsonc
125
+ {
126
+ "name": "my-site",
127
+ "main": ".sordo/worker.js",
128
+ "compatibility_date": "2026-01-01",
129
+ "services": [{ "binding": "CMS", "service": "my-cms-worker" }]
130
+ // only with adapter.edge.assets: "external":
131
+ // "assets": { "directory": ".sordo/worker-assets" }
132
+ }
133
+ ```
134
+
135
+ Secrets: `bunx wrangler secret put NAME`. Handlers read them as `ctx.env.NAME`
136
+ and read bindings (service, KV, R2, D1) from `ctx.bindings`; `ctx.waitUntil(p)`
137
+ extends the request. Type bindings by augmenting the interface:
138
+
139
+ ```ts
140
+ declare module "sordo" {
141
+ interface SordoBindings {
142
+ CMS: { fetch: typeof fetch };
143
+ }
144
+ }
145
+ ```
146
+
147
+ By default `worker.js` is self-contained (client chunks and CSS are inlined), so
148
+ `main` is the only file Wrangler needs. With `adapter.edge.assets: "external"`
149
+ also set `assets.directory`; files from `app/public/` are then served at
150
+ `/_sordo/assets/<name>` (not at `/<name>`). Only `config.env.public` values are
151
+ inlined at build; secrets never are.
152
+
75
153
  UI components (upstream shadcn/ui, local paths, or registries):
76
154
 
77
155
  ```sh
package/package.json CHANGED
@@ -1,8 +1,13 @@
1
1
  {
2
2
  "name": "sordo",
3
- "version": "0.2.0",
4
- "type": "module",
3
+ "version": "0.4.0",
5
4
  "description": "Bun-native full-stack meta-framework with React rendering",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "git+https://github.com/bihaviour/sordo.git",
8
+ "directory": "packages/sordo"
9
+ },
10
+ "type": "module",
6
11
  "license": "MIT",
7
12
  "exports": {
8
13
  ".": "./src/index.ts",
@@ -38,11 +43,15 @@
38
43
  "peerDependencies": {
39
44
  "react": "^19.0.0",
40
45
  "react-dom": "^19.0.0",
41
- "@anthropic-ai/sdk": "^0.30.0"
46
+ "@anthropic-ai/sdk": "^0.30.0",
47
+ "bun-plugin-tailwind": ">=0.1.0"
42
48
  },
43
49
  "peerDependenciesMeta": {
44
50
  "@anthropic-ai/sdk": {
45
51
  "optional": true
52
+ },
53
+ "bun-plugin-tailwind": {
54
+ "optional": true
46
55
  }
47
56
  },
48
57
  "dependencies": {
@@ -1,3 +1,5 @@
1
+ import { collectClientChunks } from "../build/embedded.ts";
2
+ import { xxh64 } from "../build/hash.ts";
1
3
  import type {
2
4
  Adapter,
3
5
  AdapterBuildInput,
@@ -29,10 +31,45 @@ export const edgeAdapter: Adapter = {
29
31
  }
30
32
  const bytes = await Bun.file(input.serverEntryOut).bytes();
31
33
  await Bun.write(workerPath, bytes);
34
+ const extraFiles = [workerPath];
35
+ if (ctx.edgeAssets === "external") {
36
+ extraFiles.push(
37
+ await writeExternalAssets(input, `${ctx.outDir}/worker-assets`),
38
+ );
39
+ }
32
40
  return {
33
41
  serverEntry: workerPath,
34
42
  assets: input.assets,
35
- extraFiles: [workerPath],
43
+ extraFiles,
36
44
  };
37
45
  },
38
46
  };
47
+
48
+ // Lays files out so the directory root maps 1:1 to URL paths — point Workers
49
+ // static assets (`assets.directory`) at it. Client chunks are content-hashed by
50
+ // the client build; public/ files keep their names, the manifest records hashes.
51
+ async function writeExternalAssets(
52
+ input: AdapterBuildInput,
53
+ dir: string,
54
+ ): Promise<string> {
55
+ await Bun.$`rm -rf ${dir}`.quiet();
56
+ const manifest: Record<string, { hash: string; bytes: number }> = {};
57
+ const files: { url: string; src: string }[] = [
58
+ ...(input.clientOutDir
59
+ ? await collectClientChunks(input.clientOutDir)
60
+ : []),
61
+ ...input.assets.map((a) => ({ url: a.publicPath, src: a.src })),
62
+ ];
63
+ for (const { url, src } of files) {
64
+ const bytes = await Bun.file(src).bytes();
65
+ await Bun.write(`${dir}${url}`, bytes);
66
+ manifest[url] = { hash: xxh64(bytes), bytes: bytes.byteLength };
67
+ }
68
+ // Workers static assets reads `_headers`; client URLs carry a content hash.
69
+ await Bun.write(
70
+ `${dir}/_headers`,
71
+ "/_sordo/client/*\n Cache-Control: public, max-age=31536000, immutable\n",
72
+ );
73
+ await Bun.write(`${dir}/manifest.json`, JSON.stringify(manifest, null, 2));
74
+ return dir;
75
+ }
@@ -7,6 +7,8 @@ export interface AdapterContext {
7
7
  mode: "development" | "production";
8
8
  config?: SordoConfig;
9
9
  compile?: boolean;
10
+ /** edge only: where client chunks + public assets are served from. */
11
+ edgeAssets?: "inline" | "external";
10
12
  }
11
13
 
12
14
  export interface AdapterBuildInput {
@@ -17,6 +19,8 @@ export interface AdapterBuildInput {
17
19
  /** Absolute path to the generated server-entry.ts SOURCE (for --compile). */
18
20
  serverEntrySrc: string;
19
21
  assets: BuiltAsset[];
22
+ /** Absolute path to the built client output dir (chunks, CSS). */
23
+ clientOutDir?: string;
20
24
  }
21
25
 
22
26
  export interface EmittedArtifacts {
@@ -0,0 +1,102 @@
1
+ import type { BunPlugin } from "bun";
2
+ import type { CssConfig } from "../config/schema.ts";
3
+
4
+ export type CssOption = CssConfig;
5
+
6
+ export interface CssBuildOutput {
7
+ // Public URL of the hashed stylesheet; what the renderer links.
8
+ href: string;
9
+ // Every file the CSS build emitted (the sheet plus any url() assets too
10
+ // large to inline), as public URL → absolute path on disk.
11
+ files: Array<{ url: string; path: string }>;
12
+ }
13
+
14
+ export interface CssBuildInput {
15
+ css: CssOption;
16
+ appDir: string;
17
+ clientOutDir: string;
18
+ publicPrefix: string;
19
+ mode: "development" | "production";
20
+ loadTailwind?: (fromDir: string) => Promise<BunPlugin>;
21
+ }
22
+
23
+ const TAILWIND_RE = /@import\s+(?:url\(\s*)?["']tailwindcss["']|@tailwind\s/;
24
+
25
+ const TAILWIND_MISSING =
26
+ 'sordo build: the css entry imports Tailwind but "bun-plugin-tailwind" is not installed. Run `bun add -D bun-plugin-tailwind`, or set `css: { entry, tailwind: false }` to build it as plain CSS.';
27
+
28
+ export function usesTailwind(source: string): boolean {
29
+ return TAILWIND_RE.test(source);
30
+ }
31
+
32
+ // Resolved from the app (not the framework) so a linked or hoisted sordo
33
+ // still finds the plugin the user installed next to their project.
34
+ export async function loadTailwindPlugin(
35
+ fromDir: string,
36
+ deps: {
37
+ resolve?: (id: string, from: string) => string;
38
+ importModule?: (path: string) => Promise<unknown>;
39
+ } = {},
40
+ ): Promise<BunPlugin> {
41
+ const resolve = deps.resolve ?? Bun.resolveSync;
42
+ const importModule = deps.importModule ?? ((p: string) => import(p));
43
+ let path: string;
44
+ try {
45
+ path = resolve("bun-plugin-tailwind", fromDir);
46
+ } catch {
47
+ throw new Error(TAILWIND_MISSING);
48
+ }
49
+ const mod = (await importModule(path)) as { default?: unknown };
50
+ const plugin = (mod.default ?? mod) as Partial<BunPlugin>;
51
+ if (typeof plugin?.setup !== "function") {
52
+ throw new Error(
53
+ `sordo build: "bun-plugin-tailwind" at ${path} does not export a Bun plugin`,
54
+ );
55
+ }
56
+ return plugin as BunPlugin;
57
+ }
58
+
59
+ export async function buildCss(input: CssBuildInput): Promise<CssBuildOutput> {
60
+ const opt =
61
+ typeof input.css === "string" ? { entry: input.css } : { ...input.css };
62
+ const entry = opt.entry;
63
+ const file = Bun.file(entry);
64
+ if (!(await file.exists())) {
65
+ throw new Error(`sordo build: css entry not found: ${entry}`);
66
+ }
67
+ const tailwind = opt.tailwind ?? usesTailwind(await file.text());
68
+ const plugins: BunPlugin[] = tailwind
69
+ ? [await (input.loadTailwind ?? loadTailwindPlugin)(input.appDir)]
70
+ : [];
71
+
72
+ const result = await Bun.build({
73
+ entrypoints: [entry],
74
+ outdir: input.clientOutDir,
75
+ naming: "[name]-[hash].[ext]",
76
+ minify: input.mode === "production",
77
+ plugins,
78
+ });
79
+ if (!result.success) {
80
+ const msgs = result.logs.map((l) => l.message ?? String(l)).join("\n");
81
+ throw new Error(`sordo build: css build failed\n${msgs}`);
82
+ }
83
+
84
+ const files = result.outputs.map((o) => ({
85
+ url: input.publicPrefix + relativeTo(o.path, input.clientOutDir),
86
+ path: o.path,
87
+ }));
88
+ const sheet = files.find((f) => f.path.endsWith(".css"));
89
+ if (!sheet) {
90
+ throw new Error(
91
+ `sordo build: css build emitted no stylesheet for ${entry}`,
92
+ );
93
+ }
94
+ return { href: sheet.url, files };
95
+ }
96
+
97
+ function relativeTo(abs: string, dir: string): string {
98
+ const rel = abs.startsWith(dir)
99
+ ? abs.slice(dir.length)
100
+ : (abs.split("/").pop() ?? "");
101
+ return rel.replace(/^\/+/, "");
102
+ }
@@ -6,6 +6,7 @@ import type { JobSummary, Plugin } from "../plugin/index.ts";
6
6
  import { scanRoutes } from "../router/filesystem.ts";
7
7
  import { type BuiltAsset, copyAssets } from "./assets.ts";
8
8
  import { generateClientEntry } from "./client-entry.ts";
9
+ import { buildCss, type CssOption } from "./css.ts";
9
10
  import {
10
11
  collectClientChunks,
11
12
  type EmbeddedEntry,
@@ -28,6 +29,8 @@ export interface ClientManifest {
28
29
  islands: Record<string, string>;
29
30
  // Whole-tree hydrated routes: bunPattern → page entry chunk URL.
30
31
  pages: Record<string, string>;
32
+ // Hashed stylesheet URL. Present only when `css` is configured.
33
+ css?: string;
31
34
  }
32
35
 
33
36
  export interface BuildCounts {
@@ -65,6 +68,11 @@ export interface BuildOptions {
65
68
  // `render.hydrate` from config: "pages" hydrates every route unless it
66
69
  // exports `hydrate = false`. Default "off".
67
70
  hydrate?: HydrateDefault;
71
+ // Stylesheet entry (`config.css`). Relative paths resolve against cwd.
72
+ css?: CssOption;
73
+ // `adapter.edge.assets`: with "external" the edge build writes client
74
+ // outputs + public/ to <outDir>/worker-assets instead of inlining them.
75
+ edgeAssets?: "inline" | "external";
68
76
  }
69
77
 
70
78
  const PUBLIC_PREFIX = "/_sordo/client/";
@@ -101,7 +109,7 @@ export async function build(options: BuildOptions): Promise<BuildResult> {
101
109
  const serverOutDir = `${outDir}/server`;
102
110
  // Hashed chunk names change per edit; without this, stale chunks pile up
103
111
  // and get globbed into compiled binaries.
104
- await Bun.$`rm -rf ${clientOutDir} ${serverOutDir}`.quiet();
112
+ await Bun.$`rm -rf ${clientOutDir} ${serverOutDir} ${`${outDir}/inline-assets.json`}`.quiet();
105
113
 
106
114
  const islands = await scanIslands(appDir);
107
115
  const entries = await scanRoutes(appDir);
@@ -195,6 +203,37 @@ export async function build(options: BuildOptions): Promise<BuildResult> {
195
203
  clientBytes = await measurePageBytes(manifest.pages, clientOutDir);
196
204
  }
197
205
 
206
+ if (options.css !== undefined) {
207
+ const css =
208
+ typeof options.css === "string"
209
+ ? absolutize(options.css)
210
+ : { ...options.css, entry: absolutize(options.css.entry) };
211
+ const cssOut = await buildCss({
212
+ css,
213
+ appDir,
214
+ clientOutDir,
215
+ publicPrefix: PUBLIC_PREFIX,
216
+ mode,
217
+ });
218
+ manifest.css = cssOut.href;
219
+ }
220
+
221
+ // Non-compiled servers (bun + edge) serve every client output (island and
222
+ // page chunks, the CSS sheet and its assets) from bytes inlined at build
223
+ // time; compile mode embeds client/ into the binary instead.
224
+ let inlineAssetsPath: string | undefined;
225
+ const externalAssets = target === "edge" && options.edgeAssets === "external";
226
+ if (!compile && !externalAssets) {
227
+ const clientFiles = (await collectClientChunks(clientOutDir)).map((c) => ({
228
+ url: c.url,
229
+ path: c.src,
230
+ }));
231
+ if (clientFiles.length > 0) {
232
+ inlineAssetsPath = `${outDir}/inline-assets.json`;
233
+ await Bun.write(inlineAssetsPath, JSON.stringify(clientFiles, null, 2));
234
+ }
235
+ }
236
+
198
237
  // Manifest must hit disk before the server entry is generated — the server
199
238
  // entry pulls it back in via the MANIFEST macro, which reads from this path
200
239
  // at bundle time.
@@ -206,6 +245,7 @@ export async function build(options: BuildOptions): Promise<BuildResult> {
206
245
  const manifestMacroPath = `${frameworkRoot}/build/macros/manifest.macro.ts`;
207
246
  const agentsHashMacroPath = `${frameworkRoot}/build/macros/agents-hash.macro.ts`;
208
247
  const agentsMacroPath = `${frameworkRoot}/build/macros/agents.macro.ts`;
248
+ const inlineAssetsMacroPath = `${frameworkRoot}/build/macros/inline-assets.macro.ts`;
209
249
 
210
250
  const serverEntrySource = generateServerEntry({
211
251
  appDir,
@@ -221,6 +261,9 @@ export async function build(options: BuildOptions): Promise<BuildResult> {
221
261
  agentsHashMacroPath,
222
262
  agentsMacroPath,
223
263
  manifestPath,
264
+ inlineAssets: inlineAssetsPath
265
+ ? { macroPath: inlineAssetsMacroPath, listPath: inlineAssetsPath }
266
+ : undefined,
224
267
  target,
225
268
  port: options.port,
226
269
  compile,
@@ -280,8 +323,8 @@ export async function build(options: BuildOptions): Promise<BuildResult> {
280
323
  const assets = await copyAssets(appDir, outDir, { write: !compile });
281
324
 
282
325
  const emitted = await adapter.emit(
283
- { serverEntryOut, serverEntrySrc: serverEntryPath, assets },
284
- { appDir, outDir, mode, compile },
326
+ { serverEntryOut, serverEntrySrc: serverEntryPath, assets, clientOutDir },
327
+ { appDir, outDir, mode, compile, edgeAssets: options.edgeAssets },
285
328
  );
286
329
 
287
330
  const result: BuildResult = {
@@ -0,0 +1,28 @@
1
+ import type { InlineAsset } from "../../server/inline-assets.ts";
2
+
3
+ // Bun macro: reads the build's client outputs (listed in a JSON file the build
4
+ // writes) and inlines their bytes into the server bundle, so the bun and edge
5
+ // servers serve them with no filesystem access at runtime.
6
+ // import { INLINE_ASSETS } from "...inline-assets.macro.ts" with { type: "macro" }
7
+ // const A = await INLINE_ASSETS("/abs/out/inline-assets.json")
8
+ export async function INLINE_ASSETS(
9
+ listPath: string,
10
+ ): Promise<Record<string, InlineAsset>> {
11
+ const list = (await Bun.file(listPath).json()) as Array<{
12
+ url: string;
13
+ path: string;
14
+ }>;
15
+ const out: Record<string, InlineAsset> = {};
16
+ for (const { url, path } of list) {
17
+ const file = Bun.file(path);
18
+ const type = file.type || "application/octet-stream";
19
+ out[url] = type.startsWith("text/")
20
+ ? { type, body: await file.text(), base64: false }
21
+ : {
22
+ type,
23
+ body: Buffer.from(await file.arrayBuffer()).toString("base64"),
24
+ base64: true,
25
+ };
26
+ }
27
+ return out;
28
+ }
@@ -15,6 +15,10 @@ export interface ServerEntryInput {
15
15
  agentsHashMacroPath: string; // absolute path to agents-hash.macro.ts
16
16
  agentsMacroPath?: string; // absolute path to agents.macro.ts
17
17
  manifestPath: string; // absolute path to the on-disk manifest.json
18
+ // Client outputs (island/page chunks, the CSS sheet and its assets) inlined
19
+ // via macro and served from memory. Absent in compile mode and when the
20
+ // build produced no client files.
21
+ inlineAssets?: { macroPath: string; listPath: string };
18
22
  target: "bun" | "edge";
19
23
  port?: number;
20
24
  /** Emit Bun.embeddedFiles static-map wiring (bun + --compile only). */
@@ -67,6 +71,20 @@ for (const [route, id] of Object.entries(EMBEDDED_ASSET_PATHS)) {
67
71
 
68
72
  const fwImport = (sub: string) => JSON.stringify(`${frameworkRoot}/${sub}`);
69
73
 
74
+ const inline = input.inlineAssets;
75
+ const inlineImports = inline
76
+ ? `import { INLINE_ASSETS } from ${JSON.stringify(inline.macroPath)} with { type: "macro" }
77
+ import { inlineAssetRoutes, matchInlineAsset } from ${fwImport("server/inline-assets.ts")}
78
+ const INLINE_ASSET_DATA = await INLINE_ASSETS(${JSON.stringify(inline.listPath)})`
79
+ : "";
80
+ // Compile mode embeds client/ in the binary, so the build only passes
81
+ // `inlineAssets` for non-compiled servers.
82
+ const staticRoutesExpr = emitEmbedded
83
+ ? "__staticMap"
84
+ : inline
85
+ ? "inlineAssetRoutes(INLINE_ASSET_DATA)"
86
+ : null;
87
+
70
88
  // Workaround: Bun.build can fail to resolve a `.tsx` import when a sibling
71
89
  // `.ts` import with a shared path prefix is encountered first. Emit the
72
90
  // import statements with `.tsx` files first; ROUTE_TABLE keeps the canonical
@@ -174,9 +192,9 @@ ${triggerWire}
174
192
  ${cronWire}
175
193
  ${staticMapSetup}
176
194
  const server = startServer({
177
- port: ${port ?? 3000},
195
+ port: Number(Bun.env.PORT) || ${port ?? 3000},
178
196
  routes: router.routes,
179
- fallback: router.fallback,${emitEmbedded ? "\n staticRoutes: __staticMap," : ""}
197
+ fallback: router.fallback,${staticRoutesExpr ? `\n staticRoutes: ${staticRoutesExpr},` : ""}
180
198
  })
181
199
  export { server }
182
200
  `.trim();
@@ -185,10 +203,10 @@ export { server }
185
203
  ${triggerWire}
186
204
  const __compiled = compilePatterns(router.routes)
187
205
  export default {
188
- async fetch(req, env, execCtx) {
206
+ async fetch(req, env, execCtx) {${inline ? "\n const asset = matchInlineAsset(INLINE_ASSET_DATA, req)\n if (asset) return asset" : ""}
189
207
  const hit = await dispatch(router.routes, req, { env, execCtx }, __compiled)
190
208
  if (hit) return hit
191
- return router.fallback(req)
209
+ return router.fallback(Object.assign(req, { env, execCtx }))
192
210
  }
193
211
  }
194
212
  `.trim();
@@ -210,6 +228,7 @@ import { createRenderer } from ${fwImport("render/index.tsx")}
210
228
  import { startServer } from ${fwImport("server/index.ts")}
211
229
  import { compilePatterns, dispatch } from ${fwImport("router/match.ts")}
212
230
  ${embeddedImport}
231
+ ${inlineImports}
213
232
 
214
233
  const ROUTE_TABLE = await ROUTES(${appDirLiteral})
215
234
  const PUBLIC_ENV_VALUES = PUBLIC_ENV()
package/src/cli/build.ts CHANGED
@@ -8,6 +8,9 @@ import { assertPluginCompat, type Plugin } from "../plugin/index.ts";
8
8
  import type { CliContext } from "./index.ts";
9
9
  import { EXIT, formatError, log } from "./log.ts";
10
10
 
11
+ // 80% of the 3 MB gzipped free-plan Worker script limit.
12
+ const WORKER_WARN_BYTES = 0.8 * 3 * 1024 * 1024;
13
+
11
14
  const FRAMEWORK_VERSION = (pkg as { version: string }).version;
12
15
 
13
16
  export interface BuildArgs {
@@ -65,6 +68,8 @@ export async function runBuild(
65
68
  compile,
66
69
  plugins,
67
70
  hydrate: config.render.hydrate,
71
+ css: config.css,
72
+ edgeAssets: config.adapter.edge.assets,
68
73
  });
69
74
  } catch (err) {
70
75
  failure = err as Error;
@@ -126,6 +131,13 @@ async function printSummary(
126
131
  log.dim(
127
132
  ` serverEntry: ${result.serverEntry} (${formatBytes(serverSize)} gz)`,
128
133
  );
134
+ if (ctx.target === "edge") {
135
+ if (serverSize >= WORKER_WARN_BYTES) {
136
+ log.warn(
137
+ `worker.js is ${formatBytes(serverSize)} gz — Cloudflare caps a Worker at 3 MB gz (free) / 10 MB gz (paid). Set adapter.edge.assets: "external" to move client assets out of the script.`,
138
+ );
139
+ }
140
+ }
129
141
  if (result.assets.length > 0) {
130
142
  log.dim(` assets:`);
131
143
  for (const a of result.assets) {
@@ -123,6 +123,9 @@ function printWiring(tokensFile: string): void {
123
123
  log.dim(` @import "tailwindcss";`);
124
124
  log.dim(` @import "${relTokensImport(tokensFile)}";`);
125
125
  log.dim(` @theme inline { /* map --color-* to the tokens */ }`);
126
+ log.info(" build have sordo compile and link it:");
127
+ log.dim(` css: "app/styles/app.css" (sordo.config.ts)`);
128
+ log.dim(" bun add -D bun-plugin-tailwind");
126
129
  }
127
130
 
128
131
  function relTokensImport(tokensFile: string): string {
package/src/cli/index.ts CHANGED
@@ -59,6 +59,10 @@ export async function main(argv: string[]): Promise<number | null> {
59
59
  return runDev(rest, ctx);
60
60
  case "build":
61
61
  return runBuild(rest, ctx);
62
+ case "start": {
63
+ const { runStart } = await import("./start.ts");
64
+ return runStart(rest, ctx);
65
+ }
62
66
  case "run":
63
67
  return runRun(rest, ctx);
64
68
  case "deploy":
@@ -140,6 +144,7 @@ Usage:
140
144
  Commands:
141
145
  dev Start the dev server (bun --hot by default).
142
146
  build Produce a production bundle for the configured target.
147
+ start Run the production server from the last build (bun target).
143
148
  run Run a workspace task with output caching + affected detection.
144
149
  deploy Build then dispatch to an installed deploy plugin.
145
150
  secret Manage dev-time secrets in the OS keychain.
@@ -0,0 +1,99 @@
1
+ import { resolve } from "node:path";
2
+ import { loadConfig } from "../config/load.ts";
3
+ import type { CliContext } from "./index.ts";
4
+ import { EXIT, log } from "./log.ts";
5
+
6
+ export interface StartArgs {
7
+ port?: number;
8
+ outDir?: string;
9
+ }
10
+
11
+ // Runs the production server from the last `sordo build`: the compiled binary
12
+ // when the build used --compile, otherwise the bundled server entry.
13
+ export async function runStart(
14
+ argv: string[],
15
+ ctx: CliContext = { cwd: process.cwd(), verbose: false },
16
+ ): Promise<number> {
17
+ let args: StartArgs;
18
+ try {
19
+ args = parseStartArgs(argv, ctx.cwd);
20
+ } catch (err) {
21
+ log.error((err as Error).message);
22
+ return EXIT.USAGE;
23
+ }
24
+
25
+ let config: Awaited<ReturnType<typeof loadConfig>>["config"];
26
+ try {
27
+ ({ config } = await loadConfig({
28
+ cwd: ctx.cwd,
29
+ configPath: ctx.configPath,
30
+ }));
31
+ } catch (err) {
32
+ log.error((err as Error)?.message ?? String(err));
33
+ return EXIT.ERROR;
34
+ }
35
+
36
+ if (config.target === "edge") {
37
+ log.error(
38
+ "sordo start runs the bun target. An edge build (.sordo/worker.js) runs on its platform: e.g. `wrangler dev` with main = the built worker.js.",
39
+ );
40
+ return EXIT.USAGE;
41
+ }
42
+
43
+ const outDir = args.outDir ?? config.outDir;
44
+ const cmd = await resolveServerCommand(outDir);
45
+ if (!cmd) {
46
+ log.error(
47
+ `sordo start: no build found in ${outDir}. Run \`sordo build\` first.`,
48
+ );
49
+ return EXIT.ERROR;
50
+ }
51
+
52
+ const env: Record<string, string | undefined> = {
53
+ ...process.env,
54
+ NODE_ENV: process.env.NODE_ENV ?? "production",
55
+ };
56
+ if (args.port !== undefined) env.PORT = String(args.port);
57
+
58
+ const proc = Bun.spawn(cmd, {
59
+ cwd: ctx.cwd,
60
+ env,
61
+ stdio: ["inherit", "inherit", "inherit"],
62
+ });
63
+ const forward = (sig: NodeJS.Signals) => () => proc.kill(sig);
64
+ process.on("SIGINT", forward("SIGINT"));
65
+ process.on("SIGTERM", forward("SIGTERM"));
66
+ return await proc.exited;
67
+ }
68
+
69
+ export async function resolveServerCommand(
70
+ outDir: string,
71
+ ): Promise<string[] | null> {
72
+ const bin = `${outDir}/server-bin`;
73
+ if (await Bun.file(bin).exists()) return [bin];
74
+ const entry = `${outDir}/server/server-entry.js`;
75
+ if (await Bun.file(entry).exists()) return [process.execPath, entry];
76
+ return null;
77
+ }
78
+
79
+ export function parseStartArgs(argv: string[], cwd: string): StartArgs {
80
+ const out: StartArgs = {};
81
+ for (let i = 0; i < argv.length; i++) {
82
+ const a = argv[i];
83
+ if (a === undefined) continue;
84
+ let port: string | undefined;
85
+ if (a === "--port" || a === "-p") port = argv[++i];
86
+ else if (a.startsWith("--port=")) port = a.slice(7);
87
+ else if (a === "--out") out.outDir = resolve(cwd, String(argv[++i]));
88
+ else if (a.startsWith("--out=")) out.outDir = resolve(cwd, a.slice(6));
89
+ else throw new Error(`sordo start: unknown flag ${a}`);
90
+ if (port !== undefined) {
91
+ const n = Number(port);
92
+ if (!Number.isInteger(n) || n < 0 || n > 65535) {
93
+ throw new Error(`sordo start: invalid --port ${port}`);
94
+ }
95
+ out.port = n;
96
+ }
97
+ }
98
+ return out;
99
+ }
@@ -61,6 +61,11 @@ export async function loadConfig(
61
61
 
62
62
  parsed.appDir = absolutize(parsed.appDir, cwd);
63
63
  parsed.outDir = absolutize(parsed.outDir, cwd);
64
+ if (typeof parsed.css === "string") {
65
+ parsed.css = absolutize(parsed.css, cwd);
66
+ } else if (parsed.css) {
67
+ parsed.css = { ...parsed.css, entry: absolutize(parsed.css.entry, cwd) };
68
+ }
64
69
 
65
70
  return { config: parsed, path: found };
66
71
  }
@@ -49,6 +49,22 @@ export const TasksConfigSchema = z.record(z.string(), TaskConfigSchema);
49
49
 
50
50
  export type TasksConfig = z.infer<typeof TasksConfigSchema>;
51
51
 
52
+ // Optional stylesheet entry built by `sordo build` / the dev client into a
53
+ // content-hashed asset the renderer links. A string is shorthand for
54
+ // `{ entry }`. `tailwind` defaults to detecting `@import "tailwindcss"` in the
55
+ // entry; Tailwind needs `bun-plugin-tailwind` installed in the app.
56
+ export const CssConfigSchema = z.union([
57
+ z.string().min(1),
58
+ z
59
+ .object({
60
+ entry: z.string().min(1),
61
+ tailwind: z.boolean().optional(),
62
+ })
63
+ .strict(),
64
+ ]);
65
+
66
+ export type CssConfig = z.infer<typeof CssConfigSchema>;
67
+
52
68
  export const SordoConfigSchema = z.object({
53
69
  target: z.enum(["bun", "edge"]).default("bun"),
54
70
  appDir: z.string().default("./app"),
@@ -76,8 +92,15 @@ export const SordoConfigSchema = z.object({
76
92
  compile: z.boolean().default(false),
77
93
  })
78
94
  .default({ compile: false }),
95
+ edge: z
96
+ .object({
97
+ // "inline" bakes client chunks + CSS into worker.js; "external" writes
98
+ // them to <outDir>/worker-assets for Workers static assets.
99
+ assets: z.enum(["inline", "external"]).default("inline"),
100
+ })
101
+ .default({ assets: "inline" }),
79
102
  })
80
- .default({ bun: { compile: false } }),
103
+ .default({ bun: { compile: false }, edge: { assets: "inline" } }),
81
104
  // Generated agent-manifest target(s). Defaults to "CLAUDE.md" so the
82
105
  // manifest lands in the same file Claude already reads. The CLI splices
83
106
  // the manifest between fenced markers so any human-written content
@@ -101,6 +124,8 @@ export const SordoConfigSchema = z.object({
101
124
  .default({ hydrate: "off" }),
102
125
  // Optional, no default: absent must behave exactly as today (conventions only).
103
126
  ui: UiConfigSchema.optional(),
127
+ // Relative paths resolve against the project root (where the config lives).
128
+ css: CssConfigSchema.optional(),
104
129
  // Per-task input/output declarations consumed by `sordo run` (the cache
105
130
  // layer). Absent ⇒ `sordo run <task>` falls back to per-task defaults.
106
131
  tasks: TasksConfigSchema.optional(),
package/src/dev/client.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import type { CssOption } from "../build/css.ts";
1
2
  import { build, type ClientManifest } from "../build/index.ts";
2
3
  import type { HydrateDefault } from "../build/page-entry.ts";
3
4
  import { loadConfig } from "../config/load.ts";
@@ -9,6 +10,8 @@ export interface SetupDevClientOptions {
9
10
  outDir?: string;
10
11
  /** Whole-tree hydration default. Defaults to `render.hydrate` from config. */
11
12
  hydrate?: HydrateDefault;
13
+ /** Stylesheet entry. Defaults to `css` from config; `null` disables it. */
14
+ css?: CssOption | null;
12
15
  }
13
16
 
14
17
  export interface DevClient {
@@ -32,7 +35,13 @@ export async function setupDevClient(
32
35
  const clientOutDir = `${outDir}/client`;
33
36
 
34
37
  const manifest: ClientManifest = { entry: null, islands: {}, pages: {} };
35
- const hydrate = options.hydrate ?? (await configuredHydrate());
38
+ const configured =
39
+ options.hydrate === undefined || options.css === undefined
40
+ ? await configuredDefaults()
41
+ : undefined;
42
+ const hydrate = options.hydrate ?? configured?.hydrate ?? "off";
43
+ const css =
44
+ options.css === undefined ? configured?.css : (options.css ?? undefined);
36
45
 
37
46
  const rebuild = async (): Promise<void> => {
38
47
  const result = await build({
@@ -40,8 +49,11 @@ export async function setupDevClient(
40
49
  outDir,
41
50
  mode: "development",
42
51
  hydrate,
52
+ css,
43
53
  });
44
54
  manifest.entry = result.clientManifest.entry;
55
+ if (result.clientManifest.css) manifest.css = result.clientManifest.css;
56
+ else delete manifest.css;
45
57
  // Replace keys so removed islands/pages disappear from the manifest.
46
58
  replaceRecord(manifest.islands, result.clientManifest.islands);
47
59
  replaceRecord(manifest.pages, result.clientManifest.pages);
@@ -86,12 +98,15 @@ function replaceRecord(
86
98
  }
87
99
 
88
100
  // `sordo dev` runs from the project root, so the config there is the app's.
89
- // A missing or invalid config falls back to "off" — the dev client must boot.
90
- async function configuredHydrate(): Promise<HydrateDefault> {
101
+ // A missing or invalid config falls back to defaults — the dev client must boot.
102
+ async function configuredDefaults(): Promise<{
103
+ hydrate: HydrateDefault;
104
+ css?: CssOption;
105
+ }> {
91
106
  try {
92
107
  const { config } = await loadConfig(process.cwd());
93
- return config.render.hydrate;
108
+ return { hydrate: config.render.hydrate, css: config.css };
94
109
  } catch {
95
- return "off";
110
+ return { hydrate: "off" };
96
111
  }
97
112
  }
package/src/index.ts CHANGED
@@ -27,6 +27,7 @@ export { loadSecrets } from "./config/secrets.ts";
27
27
  export type {
28
28
  Handler,
29
29
  Middleware,
30
+ SordoBindings,
30
31
  SordoContext,
31
32
  } from "./middleware/index.ts";
32
33
  export { compose, defineMiddleware, makeContext } from "./middleware/index.ts";
@@ -9,13 +9,23 @@ import {
9
9
  redirectResponse,
10
10
  } from "./response-helpers.ts";
11
11
 
12
+ // Apps augment this to type their Worker bindings on the edge target:
13
+ // declare module "sordo" { interface SordoBindings { CMS: Fetcher } }
14
+ // biome-ignore lint/suspicious/noEmptyInterface: declaration-merging seam
15
+ export interface SordoBindings {}
16
+
12
17
  export interface SordoContext {
13
18
  params: Record<string, string>;
14
19
  // Framework-generated correlation id, populated before user middleware runs.
15
20
  // User middleware/plugins read it; they MUST NOT re-generate it.
16
21
  requestId: string;
17
22
  cookies: unknown;
23
+ // Process env merged with the string vars/secrets from the Worker env on edge.
18
24
  env: Record<string, string | undefined>;
25
+ // Raw Worker env (KV/R2/D1/service bindings) on edge; empty object on bun.
26
+ bindings: SordoBindings;
27
+ // Extends the request lifetime on edge; awaits nothing and swallows nothing on bun.
28
+ waitUntil(p: Promise<unknown>): void;
19
29
  aiContext?: AiContext;
20
30
  csrf?: { token(): string; verify(t: string | null): boolean };
21
31
  vars: Record<string, unknown>;
@@ -62,7 +72,17 @@ export function makeContext(
62
72
  ): SordoContext {
63
73
  let urlCache: URL | null = null;
64
74
  let cookiesCache: unknown;
65
- const env = runtimeEnv();
75
+ const { env: workerEnv, execCtx } = req as unknown as {
76
+ env?: unknown;
77
+ execCtx?: { waitUntil?: (p: Promise<unknown>) => void };
78
+ };
79
+ const bindings = (
80
+ workerEnv && typeof workerEnv === "object" ? workerEnv : {}
81
+ ) as SordoBindings;
82
+ const env = { ...runtimeEnv() };
83
+ for (const [k, v] of Object.entries(bindings)) {
84
+ if (typeof v === "string") env[k] = v;
85
+ }
66
86
 
67
87
  const ctx: SordoContext = {
68
88
  params,
@@ -84,6 +104,14 @@ export function makeContext(
84
104
  return cookiesCache;
85
105
  },
86
106
  env,
107
+ bindings,
108
+ waitUntil(p) {
109
+ if (typeof execCtx?.waitUntil === "function") {
110
+ execCtx.waitUntil(p);
111
+ } else {
112
+ p.catch(() => {});
113
+ }
114
+ },
87
115
  vars: {},
88
116
  get url() {
89
117
  if (!urlCache) urlCache = new URL(req.url);
@@ -26,6 +26,8 @@ export interface ClientManifest {
26
26
  // Whole-tree hydrated routes: page-route bunPattern → page entry chunk URL.
27
27
  // Presence here is what marks a route as hydrated at request time.
28
28
  pages?: Record<string, string>;
29
+ // Hashed stylesheet URL from the `css` build entry; linked on every page.
30
+ css?: string;
29
31
  }
30
32
 
31
33
  // The page-module surface the renderer reads. Everything is optional except
@@ -140,6 +142,12 @@ export function createRenderer(options: RenderOptions = {}): Renderer {
140
142
  />,
141
143
  );
142
144
  }
145
+ // Before the page's own head() so its tags can override the sheet.
146
+ if (manifest?.css) {
147
+ headNodes.push(
148
+ <link key="sordo-css" rel="stylesheet" href={manifest.css} />,
149
+ );
150
+ }
143
151
  if (mod.head) {
144
152
  headNodes.push(
145
153
  <React.Fragment key="user-head">{mod.head()}</React.Fragment>,
@@ -0,0 +1,39 @@
1
+ // Build-time-inlined client outputs: hashed island/page chunks, the CSS sheet
2
+ // and its url() assets.
3
+ // Kept free of Bun APIs: the edge worker imports this too.
4
+ export interface InlineAsset {
5
+ type: string;
6
+ body: string;
7
+ base64: boolean;
8
+ }
9
+
10
+ // URLs carry a content hash, so a cached copy never goes stale.
11
+ const IMMUTABLE = "public, max-age=31536000, immutable";
12
+
13
+ export function inlineAssetResponse(asset: InlineAsset): Response {
14
+ const body = asset.base64
15
+ ? Uint8Array.from(atob(asset.body), (c) => c.charCodeAt(0))
16
+ : asset.body;
17
+ return new Response(body, {
18
+ headers: { "content-type": asset.type, "cache-control": IMMUTABLE },
19
+ });
20
+ }
21
+
22
+ export function inlineAssetRoutes(
23
+ assets: Record<string, InlineAsset>,
24
+ ): Record<string, Response> {
25
+ const out: Record<string, Response> = {};
26
+ for (const [url, asset] of Object.entries(assets)) {
27
+ out[url] = inlineAssetResponse(asset);
28
+ }
29
+ return out;
30
+ }
31
+
32
+ export function matchInlineAsset(
33
+ assets: Record<string, InlineAsset>,
34
+ req: Request,
35
+ ): Response | null {
36
+ if (req.method !== "GET" && req.method !== "HEAD") return null;
37
+ const asset = assets[new URL(req.url).pathname];
38
+ return asset ? inlineAssetResponse(asset) : null;
39
+ }