sordo 0.2.0 → 0.3.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 +10 -0
- package/CLAUDE.md +2 -2
- package/package.json +12 -3
- package/src/build/css.ts +102 -0
- package/src/build/index.ts +40 -1
- package/src/build/macros/inline-assets.macro.ts +28 -0
- package/src/build/server-entry.ts +22 -3
- package/src/cli/build.ts +1 -0
- package/src/cli/commands/ui/init.ts +3 -0
- package/src/cli/index.ts +5 -0
- package/src/cli/start.ts +99 -0
- package/src/config/load.ts +5 -0
- package/src/config/schema.ts +18 -0
- package/src/dev/client.ts +20 -5
- package/src/render/index.tsx +8 -0
- package/src/server/inline-assets.ts +39 -0
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,15 @@
|
|
|
1
1
|
# sordo
|
|
2
2
|
|
|
3
|
+
## 0.3.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- 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.
|
|
8
|
+
|
|
9
|
+
### Patch Changes
|
|
10
|
+
|
|
11
|
+
- 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`.
|
|
12
|
+
|
|
3
13
|
## 0.2.0
|
|
4
14
|
|
|
5
15
|
### 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/package.json
CHANGED
|
@@ -1,8 +1,13 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "sordo",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"type": "module",
|
|
3
|
+
"version": "0.3.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": {
|
package/src/build/css.ts
ADDED
|
@@ -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
|
+
}
|
package/src/build/index.ts
CHANGED
|
@@ -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,8 @@ 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;
|
|
68
73
|
}
|
|
69
74
|
|
|
70
75
|
const PUBLIC_PREFIX = "/_sordo/client/";
|
|
@@ -101,7 +106,7 @@ export async function build(options: BuildOptions): Promise<BuildResult> {
|
|
|
101
106
|
const serverOutDir = `${outDir}/server`;
|
|
102
107
|
// Hashed chunk names change per edit; without this, stale chunks pile up
|
|
103
108
|
// and get globbed into compiled binaries.
|
|
104
|
-
await Bun.$`rm -rf ${clientOutDir} ${serverOutDir}`.quiet();
|
|
109
|
+
await Bun.$`rm -rf ${clientOutDir} ${serverOutDir} ${`${outDir}/inline-assets.json`}`.quiet();
|
|
105
110
|
|
|
106
111
|
const islands = await scanIslands(appDir);
|
|
107
112
|
const entries = await scanRoutes(appDir);
|
|
@@ -195,6 +200,36 @@ export async function build(options: BuildOptions): Promise<BuildResult> {
|
|
|
195
200
|
clientBytes = await measurePageBytes(manifest.pages, clientOutDir);
|
|
196
201
|
}
|
|
197
202
|
|
|
203
|
+
if (options.css !== undefined) {
|
|
204
|
+
const css =
|
|
205
|
+
typeof options.css === "string"
|
|
206
|
+
? absolutize(options.css)
|
|
207
|
+
: { ...options.css, entry: absolutize(options.css.entry) };
|
|
208
|
+
const cssOut = await buildCss({
|
|
209
|
+
css,
|
|
210
|
+
appDir,
|
|
211
|
+
clientOutDir,
|
|
212
|
+
publicPrefix: PUBLIC_PREFIX,
|
|
213
|
+
mode,
|
|
214
|
+
});
|
|
215
|
+
manifest.css = cssOut.href;
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
// Non-compiled servers (bun + edge) serve every client output (island and
|
|
219
|
+
// page chunks, the CSS sheet and its assets) from bytes inlined at build
|
|
220
|
+
// time; compile mode embeds client/ into the binary instead.
|
|
221
|
+
let inlineAssetsPath: string | undefined;
|
|
222
|
+
if (!compile) {
|
|
223
|
+
const clientFiles = (await collectClientChunks(clientOutDir)).map((c) => ({
|
|
224
|
+
url: c.url,
|
|
225
|
+
path: c.src,
|
|
226
|
+
}));
|
|
227
|
+
if (clientFiles.length > 0) {
|
|
228
|
+
inlineAssetsPath = `${outDir}/inline-assets.json`;
|
|
229
|
+
await Bun.write(inlineAssetsPath, JSON.stringify(clientFiles, null, 2));
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
|
|
198
233
|
// Manifest must hit disk before the server entry is generated — the server
|
|
199
234
|
// entry pulls it back in via the MANIFEST macro, which reads from this path
|
|
200
235
|
// at bundle time.
|
|
@@ -206,6 +241,7 @@ export async function build(options: BuildOptions): Promise<BuildResult> {
|
|
|
206
241
|
const manifestMacroPath = `${frameworkRoot}/build/macros/manifest.macro.ts`;
|
|
207
242
|
const agentsHashMacroPath = `${frameworkRoot}/build/macros/agents-hash.macro.ts`;
|
|
208
243
|
const agentsMacroPath = `${frameworkRoot}/build/macros/agents.macro.ts`;
|
|
244
|
+
const inlineAssetsMacroPath = `${frameworkRoot}/build/macros/inline-assets.macro.ts`;
|
|
209
245
|
|
|
210
246
|
const serverEntrySource = generateServerEntry({
|
|
211
247
|
appDir,
|
|
@@ -221,6 +257,9 @@ export async function build(options: BuildOptions): Promise<BuildResult> {
|
|
|
221
257
|
agentsHashMacroPath,
|
|
222
258
|
agentsMacroPath,
|
|
223
259
|
manifestPath,
|
|
260
|
+
inlineAssets: inlineAssetsPath
|
|
261
|
+
? { macroPath: inlineAssetsMacroPath, listPath: inlineAssetsPath }
|
|
262
|
+
: undefined,
|
|
224
263
|
target,
|
|
225
264
|
port: options.port,
|
|
226
265
|
compile,
|
|
@@ -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,${
|
|
197
|
+
fallback: router.fallback,${staticRoutesExpr ? `\n staticRoutes: ${staticRoutesExpr},` : ""}
|
|
180
198
|
})
|
|
181
199
|
export { server }
|
|
182
200
|
`.trim();
|
|
@@ -185,7 +203,7 @@ 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
209
|
return router.fallback(req)
|
|
@@ -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
|
@@ -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.
|
package/src/cli/start.ts
ADDED
|
@@ -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
|
+
}
|
package/src/config/load.ts
CHANGED
|
@@ -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
|
}
|
package/src/config/schema.ts
CHANGED
|
@@ -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"),
|
|
@@ -101,6 +117,8 @@ export const SordoConfigSchema = z.object({
|
|
|
101
117
|
.default({ hydrate: "off" }),
|
|
102
118
|
// Optional, no default: absent must behave exactly as today (conventions only).
|
|
103
119
|
ui: UiConfigSchema.optional(),
|
|
120
|
+
// Relative paths resolve against the project root (where the config lives).
|
|
121
|
+
css: CssConfigSchema.optional(),
|
|
104
122
|
// Per-task input/output declarations consumed by `sordo run` (the cache
|
|
105
123
|
// layer). Absent ⇒ `sordo run <task>` falls back to per-task defaults.
|
|
106
124
|
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
|
|
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
|
|
90
|
-
async function
|
|
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/render/index.tsx
CHANGED
|
@@ -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
|
+
}
|