sordo 0.3.0 → 0.5.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 +22 -0
- package/README.md +81 -0
- package/package.json +1 -1
- package/src/adapters/edge.ts +38 -1
- package/src/adapters/types.ts +4 -0
- package/src/agents-md/render.ts +1 -0
- package/src/build/css.ts +27 -1
- package/src/build/index.ts +35 -6
- package/src/build/macros/inline-assets.macro.ts +14 -8
- package/src/build/server-entry.ts +2 -2
- package/src/cli/build.ts +11 -0
- package/src/config/schema.ts +8 -1
- package/src/index.ts +1 -0
- package/src/middleware/index.ts +37 -1
- package/src/router/filesystem.ts +2 -2
- package/src/router/index.ts +32 -10
- package/src/router/pattern.ts +20 -4
- package/src/server/inline-assets.ts +23 -5
- package/src/types.ts +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,27 @@
|
|
|
1
1
|
# sordo
|
|
2
2
|
|
|
3
|
+
## 0.5.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- 9d53d86: Routing: handler files with a content extension (`sitemap.xml.ts`, `robots.txt.ts`, `llms.txt.ts`) now work anywhere under `app/routes/`, and `app/routes/_404.tsx` renders a custom 404 page (status 404) for unknown paths. Handlers can call `ctx.notFound()` to respond with it.
|
|
8
|
+
|
|
9
|
+
### Patch Changes
|
|
10
|
+
|
|
11
|
+
- 5a49288: Fix the gaps found verifying the Cloudflare recipe. The UI starter now installs `tailwindcss`, and `--deploy cloudflare` on edge adds `@sordo/deploy-cloudflare` plus a `plugins` entry to `sordo.config.ts`. Edge builds in the default inline mode now serve `public/` files at `/_sordo/assets/<name>`. Build failures report the bundler's logs instead of a bare "Bundle failed", and a css build that cannot resolve a package names it. The generated edge `fetch` is typed so it passes a strict tsconfig. The README augments `SordoBindings` through `sordo/middleware` and no longer claims the scaffold's `build` script generates CSS.
|
|
12
|
+
|
|
13
|
+
## 0.4.0
|
|
14
|
+
|
|
15
|
+
### Minor Changes
|
|
16
|
+
|
|
17
|
+
- 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.
|
|
18
|
+
|
|
19
|
+
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.
|
|
20
|
+
|
|
21
|
+
### Patch Changes
|
|
22
|
+
|
|
23
|
+
- 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.
|
|
24
|
+
|
|
3
25
|
## 0.3.0
|
|
4
26
|
|
|
5
27
|
### Minor Changes
|
package/README.md
CHANGED
|
@@ -72,6 +72,87 @@ 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 # runs `sordo 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 compile Tailwind CSS through the `css` entry in `sordo.config.ts`, so
|
|
116
|
+
`bun run build` and `sordo build` are equivalent.
|
|
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/middleware" {
|
|
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. Files from `app/public/` are inlined
|
|
149
|
+
too and served at `/_sordo/assets/<name>` (not at `/<name>`), with
|
|
150
|
+
`must-revalidate` caching since their names are not content-hashed; they count
|
|
151
|
+
toward the worker's size, so keep large files out of `public/`. With
|
|
152
|
+
`adapter.edge.assets: "external"` also set `assets.directory`, and the same
|
|
153
|
+
files are served from there instead. Only `config.env.public` values are
|
|
154
|
+
inlined at build; secrets never are.
|
|
155
|
+
|
|
75
156
|
UI components (upstream shadcn/ui, local paths, or registries):
|
|
76
157
|
|
|
77
158
|
```sh
|
package/package.json
CHANGED
package/src/adapters/edge.ts
CHANGED
|
@@ -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
|
|
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
|
+
}
|
package/src/adapters/types.ts
CHANGED
|
@@ -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 {
|
package/src/agents-md/render.ts
CHANGED
|
@@ -16,6 +16,7 @@ export function render(data: CollectedData): string {
|
|
|
16
16
|
} else {
|
|
17
17
|
out.push("| File | URL | Methods |", "|---|---|---|");
|
|
18
18
|
const rows = data.routes
|
|
19
|
+
.filter((r) => r.kind !== "notFound")
|
|
19
20
|
.map((r) => ({
|
|
20
21
|
file: relPath(r.filePath),
|
|
21
22
|
pattern: r.bunPattern,
|
package/src/build/css.ts
CHANGED
|
@@ -22,6 +22,28 @@ export interface CssBuildInput {
|
|
|
22
22
|
|
|
23
23
|
const TAILWIND_RE = /@import\s+(?:url\(\s*)?["']tailwindcss["']|@tailwind\s/;
|
|
24
24
|
|
|
25
|
+
// Bun logs an unresolvable import as `Could not resolve: "pkg"`, and
|
|
26
|
+
// bun-plugin-tailwind as `Can't resolve 'pkg' in '<dir>'`.
|
|
27
|
+
export function missingPackageHint(msgs: string): string {
|
|
28
|
+
const pkgs = new Set<string>();
|
|
29
|
+
for (const m of msgs.matchAll(
|
|
30
|
+
/(?:resolve|find)[^"'`\n]*["'`]([^"'`]+)["'`]/gi,
|
|
31
|
+
)) {
|
|
32
|
+
const spec = m[1] as string;
|
|
33
|
+
if (spec.startsWith(".") || spec.startsWith("/")) continue;
|
|
34
|
+
// Aliases, builtins and file-like specifiers (a missing url() asset)
|
|
35
|
+
// are not installable packages.
|
|
36
|
+
if (/^(@\/|~|node:|bun:)/.test(spec)) continue;
|
|
37
|
+
if (/\.(?:[a-z0-9]{1,5})$/i.test(spec) && spec.includes("/")) continue;
|
|
38
|
+
const parts = spec.split("/");
|
|
39
|
+
pkgs.add(
|
|
40
|
+
spec.startsWith("@") ? parts.slice(0, 2).join("/") : (parts[0] as string),
|
|
41
|
+
);
|
|
42
|
+
}
|
|
43
|
+
if (pkgs.size === 0) return "";
|
|
44
|
+
return `\nMissing package${pkgs.size > 1 ? "s" : ""}: ${[...pkgs].join(", ")}. Run \`bun add -d ${[...pkgs].join(" ")}\`.`;
|
|
45
|
+
}
|
|
46
|
+
|
|
25
47
|
const TAILWIND_MISSING =
|
|
26
48
|
'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
49
|
|
|
@@ -75,10 +97,14 @@ export async function buildCss(input: CssBuildInput): Promise<CssBuildOutput> {
|
|
|
75
97
|
naming: "[name]-[hash].[ext]",
|
|
76
98
|
minify: input.mode === "production",
|
|
77
99
|
plugins,
|
|
100
|
+
// Default is to reject with a bare "Bundle failed"; we want the logs.
|
|
101
|
+
throw: false,
|
|
78
102
|
});
|
|
79
103
|
if (!result.success) {
|
|
80
104
|
const msgs = result.logs.map((l) => l.message ?? String(l)).join("\n");
|
|
81
|
-
throw new Error(
|
|
105
|
+
throw new Error(
|
|
106
|
+
`sordo build: css build failed\n${msgs}${missingPackageHint(msgs)}`,
|
|
107
|
+
);
|
|
82
108
|
}
|
|
83
109
|
|
|
84
110
|
const files = result.outputs.map((o) => ({
|
package/src/build/index.ts
CHANGED
|
@@ -70,6 +70,9 @@ export interface BuildOptions {
|
|
|
70
70
|
hydrate?: HydrateDefault;
|
|
71
71
|
// Stylesheet entry (`config.css`). Relative paths resolve against cwd.
|
|
72
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";
|
|
73
76
|
}
|
|
74
77
|
|
|
75
78
|
const PUBLIC_PREFIX = "/_sordo/client/";
|
|
@@ -178,6 +181,7 @@ export async function build(options: BuildOptions): Promise<BuildResult> {
|
|
|
178
181
|
// React picks its dev or prod build from NODE_ENV; without this the
|
|
179
182
|
// browser bundle ships React's development build in production.
|
|
180
183
|
define: { "process.env.NODE_ENV": JSON.stringify(mode) },
|
|
184
|
+
throw: false,
|
|
181
185
|
plugins: [
|
|
182
186
|
stripServerExportsPlugin(hydratedPages.map((p) => p.entry.filePath)),
|
|
183
187
|
],
|
|
@@ -215,15 +219,41 @@ export async function build(options: BuildOptions): Promise<BuildResult> {
|
|
|
215
219
|
manifest.css = cssOut.href;
|
|
216
220
|
}
|
|
217
221
|
|
|
222
|
+
// Listed once here: the inline list below and adapter.emit both read it.
|
|
223
|
+
const assets = await copyAssets(appDir, outDir, { write: !compile });
|
|
224
|
+
|
|
218
225
|
// Non-compiled servers (bun + edge) serve every client output (island and
|
|
219
226
|
// page chunks, the CSS sheet and its assets) from bytes inlined at build
|
|
220
227
|
// time; compile mode embeds client/ into the binary instead.
|
|
221
228
|
let inlineAssetsPath: string | undefined;
|
|
222
|
-
|
|
223
|
-
|
|
229
|
+
const externalAssets = target === "edge" && options.edgeAssets === "external";
|
|
230
|
+
if (!compile && !externalAssets) {
|
|
231
|
+
const clientFiles: Array<{
|
|
232
|
+
url: string;
|
|
233
|
+
path: string;
|
|
234
|
+
mutable?: boolean;
|
|
235
|
+
etag?: string;
|
|
236
|
+
}> = (await collectClientChunks(clientOutDir)).map((c) => ({
|
|
224
237
|
url: c.url,
|
|
225
238
|
path: c.src,
|
|
226
239
|
}));
|
|
240
|
+
// Edge has no filesystem at runtime, so public/ is inlined too, served
|
|
241
|
+
// at /_sordo/assets/<name> like the external layout. Requests arrive
|
|
242
|
+
// percent-encoded, so the key must be too.
|
|
243
|
+
if (target === "edge") {
|
|
244
|
+
for (const a of assets) {
|
|
245
|
+
clientFiles.push({
|
|
246
|
+
// Round-trip through URL so the key matches `new URL(req.url).pathname`.
|
|
247
|
+
url: new URL(
|
|
248
|
+
a.publicPath.split("/").map(encodeURIComponent).join("/"),
|
|
249
|
+
"http://x",
|
|
250
|
+
).pathname,
|
|
251
|
+
path: a.src,
|
|
252
|
+
mutable: true,
|
|
253
|
+
etag: a.hash,
|
|
254
|
+
});
|
|
255
|
+
}
|
|
256
|
+
}
|
|
227
257
|
if (clientFiles.length > 0) {
|
|
228
258
|
inlineAssetsPath = `${outDir}/inline-assets.json`;
|
|
229
259
|
await Bun.write(inlineAssetsPath, JSON.stringify(clientFiles, null, 2));
|
|
@@ -299,6 +329,7 @@ export async function build(options: BuildOptions): Promise<BuildResult> {
|
|
|
299
329
|
target: adapter.buildTarget,
|
|
300
330
|
outdir: serverOutDir,
|
|
301
331
|
minify: false,
|
|
332
|
+
throw: false,
|
|
302
333
|
});
|
|
303
334
|
|
|
304
335
|
if (!serverResult.success) {
|
|
@@ -316,11 +347,9 @@ export async function build(options: BuildOptions): Promise<BuildResult> {
|
|
|
316
347
|
: `${serverOutDir}/server-entry.js`;
|
|
317
348
|
}
|
|
318
349
|
|
|
319
|
-
const assets = await copyAssets(appDir, outDir, { write: !compile });
|
|
320
|
-
|
|
321
350
|
const emitted = await adapter.emit(
|
|
322
|
-
{ serverEntryOut, serverEntrySrc: serverEntryPath, assets },
|
|
323
|
-
{ appDir, outDir, mode, compile },
|
|
351
|
+
{ serverEntryOut, serverEntrySrc: serverEntryPath, assets, clientOutDir },
|
|
352
|
+
{ appDir, outDir, mode, compile, edgeAssets: options.edgeAssets },
|
|
324
353
|
);
|
|
325
354
|
|
|
326
355
|
const result: BuildResult = {
|
|
@@ -11,18 +11,24 @@ export async function INLINE_ASSETS(
|
|
|
11
11
|
const list = (await Bun.file(listPath).json()) as Array<{
|
|
12
12
|
url: string;
|
|
13
13
|
path: string;
|
|
14
|
+
mutable?: boolean;
|
|
15
|
+
etag?: string;
|
|
14
16
|
}>;
|
|
15
17
|
const out: Record<string, InlineAsset> = {};
|
|
16
|
-
for (const { url, path } of list) {
|
|
18
|
+
for (const { url, path, mutable, etag } of list) {
|
|
17
19
|
const file = Bun.file(path);
|
|
18
20
|
const type = file.type || "application/octet-stream";
|
|
19
|
-
out[url] =
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
21
|
+
out[url] = {
|
|
22
|
+
...(type.startsWith("text/")
|
|
23
|
+
? { type, body: await file.text(), base64: false }
|
|
24
|
+
: {
|
|
25
|
+
type,
|
|
26
|
+
body: Buffer.from(await file.arrayBuffer()).toString("base64"),
|
|
27
|
+
base64: true,
|
|
28
|
+
}),
|
|
29
|
+
...(mutable ? { mutable } : {}),
|
|
30
|
+
...(etag ? { etag } : {}),
|
|
31
|
+
};
|
|
26
32
|
}
|
|
27
33
|
return out;
|
|
28
34
|
}
|
|
@@ -203,10 +203,10 @@ export { server }
|
|
|
203
203
|
${triggerWire}
|
|
204
204
|
const __compiled = compilePatterns(router.routes)
|
|
205
205
|
export default {
|
|
206
|
-
async fetch(req, env, execCtx) {${inline ? "\n const asset = matchInlineAsset(INLINE_ASSET_DATA, req)\n if (asset) return asset" : ""}
|
|
206
|
+
async fetch(req: Request, env: Record<string, unknown>, execCtx: { waitUntil(p: Promise<unknown>): void }) {${inline ? "\n const asset = matchInlineAsset(INLINE_ASSET_DATA, req)\n if (asset) return asset" : ""}
|
|
207
207
|
const hit = await dispatch(router.routes, req, { env, execCtx }, __compiled)
|
|
208
208
|
if (hit) return hit
|
|
209
|
-
return router.fallback(req)
|
|
209
|
+
return router.fallback(Object.assign(req, { env, execCtx }))
|
|
210
210
|
}
|
|
211
211
|
}
|
|
212
212
|
`.trim();
|
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 {
|
|
@@ -66,6 +69,7 @@ export async function runBuild(
|
|
|
66
69
|
plugins,
|
|
67
70
|
hydrate: config.render.hydrate,
|
|
68
71
|
css: config.css,
|
|
72
|
+
edgeAssets: config.adapter.edge.assets,
|
|
69
73
|
});
|
|
70
74
|
} catch (err) {
|
|
71
75
|
failure = err as Error;
|
|
@@ -127,6 +131,13 @@ async function printSummary(
|
|
|
127
131
|
log.dim(
|
|
128
132
|
` serverEntry: ${result.serverEntry} (${formatBytes(serverSize)} gz)`,
|
|
129
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
|
+
}
|
|
130
141
|
if (result.assets.length > 0) {
|
|
131
142
|
log.dim(` assets:`);
|
|
132
143
|
for (const a of result.assets) {
|
package/src/config/schema.ts
CHANGED
|
@@ -92,8 +92,15 @@ export const SordoConfigSchema = z.object({
|
|
|
92
92
|
compile: z.boolean().default(false),
|
|
93
93
|
})
|
|
94
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" }),
|
|
95
102
|
})
|
|
96
|
-
.default({ bun: { compile: false } }),
|
|
103
|
+
.default({ bun: { compile: false }, edge: { assets: "inline" } }),
|
|
97
104
|
// Generated agent-manifest target(s). Defaults to "CLAUDE.md" so the
|
|
98
105
|
// manifest lands in the same file Claude already reads. The CLI splices
|
|
99
106
|
// the manifest between fenced markers so any human-written content
|
package/src/index.ts
CHANGED
package/src/middleware/index.ts
CHANGED
|
@@ -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/middleware" { 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>;
|
|
@@ -23,6 +33,8 @@ export interface SordoContext {
|
|
|
23
33
|
json(body: unknown, init?: ResponseInit): Response;
|
|
24
34
|
html(body: string | ReadableStream, init?: ResponseInit): Response;
|
|
25
35
|
redirect(to: string, status?: 301 | 302 | 303 | 307 | 308): Response;
|
|
36
|
+
// Responds 404 with the app's `app/routes/_404.tsx` page, or plain text if none.
|
|
37
|
+
notFound(): Response | Promise<Response>;
|
|
26
38
|
}
|
|
27
39
|
|
|
28
40
|
export type Handler = (
|
|
@@ -59,10 +71,21 @@ export function compose(middlewares: Middleware[], handler: Handler): Handler {
|
|
|
59
71
|
export function makeContext(
|
|
60
72
|
req: Request,
|
|
61
73
|
params: Record<string, string> = {},
|
|
74
|
+
renderNotFound?: (req: Request, ctx: SordoContext) => Promise<Response>,
|
|
62
75
|
): SordoContext {
|
|
63
76
|
let urlCache: URL | null = null;
|
|
64
77
|
let cookiesCache: unknown;
|
|
65
|
-
const env =
|
|
78
|
+
const { env: workerEnv, execCtx } = req as unknown as {
|
|
79
|
+
env?: unknown;
|
|
80
|
+
execCtx?: { waitUntil?: (p: Promise<unknown>) => void };
|
|
81
|
+
};
|
|
82
|
+
const bindings = (
|
|
83
|
+
workerEnv && typeof workerEnv === "object" ? workerEnv : {}
|
|
84
|
+
) as SordoBindings;
|
|
85
|
+
const env = { ...runtimeEnv() };
|
|
86
|
+
for (const [k, v] of Object.entries(bindings)) {
|
|
87
|
+
if (typeof v === "string") env[k] = v;
|
|
88
|
+
}
|
|
66
89
|
|
|
67
90
|
const ctx: SordoContext = {
|
|
68
91
|
params,
|
|
@@ -84,6 +107,14 @@ export function makeContext(
|
|
|
84
107
|
return cookiesCache;
|
|
85
108
|
},
|
|
86
109
|
env,
|
|
110
|
+
bindings,
|
|
111
|
+
waitUntil(p) {
|
|
112
|
+
if (typeof execCtx?.waitUntil === "function") {
|
|
113
|
+
execCtx.waitUntil(p);
|
|
114
|
+
} else {
|
|
115
|
+
p.catch(() => {});
|
|
116
|
+
}
|
|
117
|
+
},
|
|
87
118
|
vars: {},
|
|
88
119
|
get url() {
|
|
89
120
|
if (!urlCache) urlCache = new URL(req.url);
|
|
@@ -92,6 +123,11 @@ export function makeContext(
|
|
|
92
123
|
json: jsonResponse,
|
|
93
124
|
html: htmlResponse,
|
|
94
125
|
redirect: redirectResponse,
|
|
126
|
+
notFound() {
|
|
127
|
+
return renderNotFound
|
|
128
|
+
? renderNotFound(req, ctx)
|
|
129
|
+
: new Response("Not Found", { status: 404 });
|
|
130
|
+
},
|
|
95
131
|
};
|
|
96
132
|
return ctx;
|
|
97
133
|
}
|
package/src/router/filesystem.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { RouteEntry } from "../types.ts";
|
|
2
2
|
import { assertNoConflicts } from "./conflict.ts";
|
|
3
|
-
import { compareRoutes, parseRouteFile } from "./pattern.ts";
|
|
3
|
+
import { compareRoutes, NOT_FOUND_FILE, parseRouteFile } from "./pattern.ts";
|
|
4
4
|
|
|
5
5
|
const TEST_FILE_RE = /\.test\.tsx?$/;
|
|
6
6
|
|
|
@@ -13,7 +13,7 @@ export async function scanRoutes(appDir: string): Promise<RouteEntry[]> {
|
|
|
13
13
|
try {
|
|
14
14
|
for await (const rel of glob.scan({ cwd: routesDir, onlyFiles: true })) {
|
|
15
15
|
const base = rel.split("/").pop() ?? rel;
|
|
16
|
-
if (base.startsWith("_")) continue;
|
|
16
|
+
if (base.startsWith("_") && rel !== NOT_FOUND_FILE) continue;
|
|
17
17
|
if (TEST_FILE_RE.test(base)) continue;
|
|
18
18
|
|
|
19
19
|
const parsed = parseRouteFile(rel);
|
package/src/router/index.ts
CHANGED
|
@@ -8,7 +8,13 @@ import {
|
|
|
8
8
|
type PluginServer,
|
|
9
9
|
} from "../plugin/index.ts";
|
|
10
10
|
import type { Renderer } from "../render/index.tsx";
|
|
11
|
-
import type {
|
|
11
|
+
import type {
|
|
12
|
+
BunRoutes,
|
|
13
|
+
Handler,
|
|
14
|
+
HTTPMethod,
|
|
15
|
+
RouteEntry,
|
|
16
|
+
SordoContext,
|
|
17
|
+
} from "../types.ts";
|
|
12
18
|
import { HTTP_METHODS } from "../types.ts";
|
|
13
19
|
|
|
14
20
|
export interface RouterOptions {
|
|
@@ -120,11 +126,29 @@ export async function createCompiledRouter(
|
|
|
120
126
|
const preloadedModules = options.modules;
|
|
121
127
|
const routes: BunRoutes = {};
|
|
122
128
|
|
|
129
|
+
const notFoundEntry = entries.find((e) => e.kind === "notFound");
|
|
130
|
+
const renderNotFound = notFoundEntry
|
|
131
|
+
? async (req: Request, ctx: SordoContext): Promise<Response> => {
|
|
132
|
+
const res = await renderer.renderPage(notFoundEntry, req, ctx);
|
|
133
|
+
return new Response(res.body, {
|
|
134
|
+
status: 404,
|
|
135
|
+
statusText: "Not Found",
|
|
136
|
+
headers: res.headers,
|
|
137
|
+
});
|
|
138
|
+
}
|
|
139
|
+
: undefined;
|
|
140
|
+
|
|
123
141
|
for (const entry of entries) {
|
|
142
|
+
if (entry.kind === "notFound") continue;
|
|
124
143
|
if (entry.kind === "page") {
|
|
125
144
|
const handler: Handler = (req, ctx) =>
|
|
126
145
|
renderer.renderPage(entry, req, ctx);
|
|
127
|
-
attach(
|
|
146
|
+
attach(
|
|
147
|
+
routes,
|
|
148
|
+
entry.bunPattern,
|
|
149
|
+
{ GET: wrap(handler, middlewareChain) },
|
|
150
|
+
renderNotFound,
|
|
151
|
+
);
|
|
128
152
|
} else {
|
|
129
153
|
const mod = (preloadedModules?.[entry.filePath] ??
|
|
130
154
|
(await import(entry.filePath))) as Record<string, unknown>;
|
|
@@ -149,7 +173,7 @@ export async function createCompiledRouter(
|
|
|
149
173
|
`(GET/POST/PUT/DELETE/PATCH/OPTIONS/HEAD).`,
|
|
150
174
|
);
|
|
151
175
|
}
|
|
152
|
-
attach(routes, entry.bunPattern, methodMap);
|
|
176
|
+
attach(routes, entry.bunPattern, methodMap, renderNotFound);
|
|
153
177
|
}
|
|
154
178
|
}
|
|
155
179
|
|
|
@@ -161,19 +185,16 @@ export async function createCompiledRouter(
|
|
|
161
185
|
][]) {
|
|
162
186
|
wrapped[m] = wrap(h, middlewareChain);
|
|
163
187
|
}
|
|
164
|
-
attach(routes, pr.pattern, wrapped);
|
|
188
|
+
attach(routes, pr.pattern, wrapped, renderNotFound);
|
|
165
189
|
}
|
|
166
190
|
|
|
167
|
-
const fallback = wrap(
|
|
168
|
-
() => new Response("Not Found", { status: 404 }),
|
|
169
|
-
middlewareChain,
|
|
170
|
-
);
|
|
191
|
+
const fallback = wrap((_req, ctx) => ctx.notFound(), middlewareChain);
|
|
171
192
|
|
|
172
193
|
return {
|
|
173
194
|
routes,
|
|
174
195
|
fallback: async (req: Request) => {
|
|
175
196
|
const startMs = now();
|
|
176
|
-
const ctx = makeContext(req);
|
|
197
|
+
const ctx = makeContext(req, {}, renderNotFound);
|
|
177
198
|
const res = await fallback(req, ctx);
|
|
178
199
|
return finalizeResponse(res, ctx, { startMs });
|
|
179
200
|
},
|
|
@@ -185,6 +206,7 @@ function attach(
|
|
|
185
206
|
routes: BunRoutes,
|
|
186
207
|
pattern: string,
|
|
187
208
|
methodMap: Partial<Record<HTTPMethod, Handler>>,
|
|
209
|
+
renderNotFound?: (req: Request, ctx: SordoContext) => Promise<Response>,
|
|
188
210
|
): void {
|
|
189
211
|
const existing = routes[pattern];
|
|
190
212
|
const bunWrapped: Record<
|
|
@@ -196,7 +218,7 @@ function attach(
|
|
|
196
218
|
bunWrapped[m] = (req) => {
|
|
197
219
|
const startMs = now();
|
|
198
220
|
const params = req.params ?? {};
|
|
199
|
-
const ctx = makeContext(req, params);
|
|
221
|
+
const ctx = makeContext(req, params, renderNotFound);
|
|
200
222
|
return Promise.resolve(h(req, ctx)).then((res) =>
|
|
201
223
|
finalizeResponse(res, ctx, { startMs }),
|
|
202
224
|
);
|
package/src/router/pattern.ts
CHANGED
|
@@ -3,7 +3,7 @@ import type { Segment } from "../types.ts";
|
|
|
3
3
|
export interface ParsedFile {
|
|
4
4
|
bunPattern: string;
|
|
5
5
|
segments: Segment[];
|
|
6
|
-
kind: "page" | "api";
|
|
6
|
+
kind: "page" | "api" | "notFound";
|
|
7
7
|
}
|
|
8
8
|
|
|
9
9
|
const CATCHALL_RE = /^\[\.\.\.([^\]]+)\]$/;
|
|
@@ -11,7 +11,16 @@ const PARAM_RE = /^\[([^\]]+)\]$/;
|
|
|
11
11
|
|
|
12
12
|
// relPath is path under app/routes/, e.g. "index.tsx", "hotels/[city].tsx",
|
|
13
13
|
// "api/revenue.ts", "files/[...rest].tsx".
|
|
14
|
+
export const NOT_FOUND_FILE = "_404.tsx";
|
|
15
|
+
|
|
16
|
+
// A `.ts` file outside api/ is a handler route only when its name carries a
|
|
17
|
+
// content extension before `.ts` (sitemap.xml.ts, robots.txt.ts, llms.txt.ts).
|
|
18
|
+
const CONTENT_EXT_RE = /\.[A-Za-z0-9]+\.ts$/;
|
|
19
|
+
|
|
14
20
|
export function parseRouteFile(relPath: string): ParsedFile {
|
|
21
|
+
if (relPath === NOT_FOUND_FILE) {
|
|
22
|
+
return { bunPattern: "/_404", segments: [], kind: "notFound" };
|
|
23
|
+
}
|
|
15
24
|
const isApi = relPath === "api" || relPath.startsWith("api/");
|
|
16
25
|
const ext = relPath.endsWith(".tsx")
|
|
17
26
|
? ".tsx"
|
|
@@ -23,10 +32,13 @@ export function parseRouteFile(relPath: string): ParsedFile {
|
|
|
23
32
|
if (isApi && ext === ".tsx") {
|
|
24
33
|
throw new Error(`API route must be .ts, not .tsx: ${relPath}`);
|
|
25
34
|
}
|
|
26
|
-
|
|
35
|
+
const isContentHandler =
|
|
36
|
+
!isApi && ext === ".ts" && CONTENT_EXT_RE.test(relPath);
|
|
37
|
+
if (!isApi && ext === ".ts" && !isContentHandler) {
|
|
27
38
|
throw new Error(
|
|
28
39
|
`Non-API route must be .tsx (pages) - got .ts: ${relPath}. ` +
|
|
29
|
-
`Move it under app/routes/api
|
|
40
|
+
`Move it under app/routes/api/, or name it with a content extension ` +
|
|
41
|
+
`(e.g. sitemap.xml.ts) for a handler route.`,
|
|
30
42
|
);
|
|
31
43
|
}
|
|
32
44
|
|
|
@@ -61,7 +73,11 @@ export function parseRouteFile(relPath: string): ParsedFile {
|
|
|
61
73
|
bunPattern = bunPattern.slice(0, -1);
|
|
62
74
|
}
|
|
63
75
|
|
|
64
|
-
return {
|
|
76
|
+
return {
|
|
77
|
+
bunPattern,
|
|
78
|
+
segments,
|
|
79
|
+
kind: isApi || isContentHandler ? "api" : "page",
|
|
80
|
+
};
|
|
65
81
|
}
|
|
66
82
|
|
|
67
83
|
// Sort so that more-specific patterns come first:
|
|
@@ -5,18 +5,36 @@ export interface InlineAsset {
|
|
|
5
5
|
type: string;
|
|
6
6
|
body: string;
|
|
7
7
|
base64: boolean;
|
|
8
|
+
// public/ files keep their names, so they must not be cached as immutable.
|
|
9
|
+
mutable?: boolean;
|
|
10
|
+
// Content hash; lets revalidating clients get a 304 instead of the body.
|
|
11
|
+
etag?: string;
|
|
8
12
|
}
|
|
9
13
|
|
|
10
14
|
// URLs carry a content hash, so a cached copy never goes stale.
|
|
11
15
|
const IMMUTABLE = "public, max-age=31536000, immutable";
|
|
16
|
+
const REVALIDATE = "public, max-age=0, must-revalidate";
|
|
12
17
|
|
|
13
|
-
export function inlineAssetResponse(
|
|
18
|
+
export function inlineAssetResponse(
|
|
19
|
+
asset: InlineAsset,
|
|
20
|
+
req?: Request,
|
|
21
|
+
): Response {
|
|
22
|
+
const headers: Record<string, string> = {
|
|
23
|
+
"content-type": asset.type,
|
|
24
|
+
"cache-control": asset.mutable ? REVALIDATE : IMMUTABLE,
|
|
25
|
+
};
|
|
26
|
+
if (asset.etag) {
|
|
27
|
+
const etag = `"${asset.etag}"`;
|
|
28
|
+
headers.etag = etag;
|
|
29
|
+
const inm = req?.headers.get("if-none-match");
|
|
30
|
+
if (inm?.split(",").some((t) => t.trim().replace(/^W\//, "") === etag)) {
|
|
31
|
+
return new Response(null, { status: 304, headers });
|
|
32
|
+
}
|
|
33
|
+
}
|
|
14
34
|
const body = asset.base64
|
|
15
35
|
? Uint8Array.from(atob(asset.body), (c) => c.charCodeAt(0))
|
|
16
36
|
: asset.body;
|
|
17
|
-
return new Response(body, {
|
|
18
|
-
headers: { "content-type": asset.type, "cache-control": IMMUTABLE },
|
|
19
|
-
});
|
|
37
|
+
return new Response(body, { headers });
|
|
20
38
|
}
|
|
21
39
|
|
|
22
40
|
export function inlineAssetRoutes(
|
|
@@ -35,5 +53,5 @@ export function matchInlineAsset(
|
|
|
35
53
|
): Response | null {
|
|
36
54
|
if (req.method !== "GET" && req.method !== "HEAD") return null;
|
|
37
55
|
const asset = assets[new URL(req.url).pathname];
|
|
38
|
-
return asset ? inlineAssetResponse(asset) : null;
|
|
56
|
+
return asset ? inlineAssetResponse(asset, req) : null;
|
|
39
57
|
}
|