sordo 0.4.0 → 1.0.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 +6 -116
- package/README.md +8 -175
- package/bin/sordo.ts +1 -4
- package/package.json +17 -41
- package/src/agents-md.ts +1 -0
- package/src/ai.ts +1 -0
- package/src/build.ts +1 -0
- package/src/client.ts +1 -0
- package/src/config.ts +1 -0
- package/src/dev.ts +1 -0
- package/src/index.ts +1 -55
- package/src/middleware.ts +1 -0
- package/src/plugin.ts +1 -0
- package/src/render.ts +1 -0
- package/src/router.ts +1 -0
- package/src/server.ts +1 -0
- package/CLAUDE.md +0 -124
- package/src/adapters/bun.ts +0 -59
- package/src/adapters/edge.ts +0 -75
- package/src/adapters/types.ts +0 -43
- package/src/agents-md/collect.ts +0 -113
- package/src/agents-md/generate.ts +0 -44
- package/src/agents-md/index.ts +0 -9
- package/src/agents-md/render.ts +0 -150
- package/src/agents-md/subprocess-entry.ts +0 -92
- package/src/agents-md/subprocess-runner.ts +0 -111
- package/src/agents-md/write.ts +0 -38
- package/src/agents-md/zod-to-json-schema.ts +0 -18
- package/src/ai/context.ts +0 -72
- package/src/ai/define.ts +0 -15
- package/src/ai/errors.ts +0 -51
- package/src/ai/index.ts +0 -36
- package/src/ai/middleware.ts +0 -21
- package/src/ai/registry.ts +0 -96
- package/src/ai/run.ts +0 -185
- package/src/ai/scan.ts +0 -42
- package/src/ai/stream.ts +0 -71
- package/src/ai/triggers.ts +0 -124
- package/src/ai/types.ts +0 -67
- package/src/ai/validate.ts +0 -82
- package/src/build/assets.ts +0 -48
- package/src/build/client-entry.ts +0 -43
- package/src/build/css.ts +0 -102
- package/src/build/embedded.ts +0 -66
- package/src/build/hash.ts +0 -21
- package/src/build/index.ts +0 -480
- package/src/build/macros/agents-hash.macro.ts +0 -9
- package/src/build/macros/agents.macro.ts +0 -21
- package/src/build/macros/env.macro.ts +0 -25
- package/src/build/macros/inline-assets.macro.ts +0 -28
- package/src/build/macros/manifest.macro.ts +0 -8
- package/src/build/macros/routes.macro.ts +0 -10
- package/src/build/page-entry.ts +0 -136
- package/src/build/scan-islands.ts +0 -39
- package/src/build/server-entry.ts +0 -256
- package/src/cli/ansi.ts +0 -41
- package/src/cli/build.ts +0 -195
- package/src/cli/commands/add/apply.ts +0 -31
- package/src/cli/commands/add/component-diff.ts +0 -116
- package/src/cli/commands/add/diff.ts +0 -153
- package/src/cli/commands/add/internal.ts +0 -41
- package/src/cli/commands/add/load-catalog.ts +0 -22
- package/src/cli/commands/add/peer-deps.ts +0 -115
- package/src/cli/commands/add/registry-fetch.ts +0 -122
- package/src/cli/commands/add/shadcn.ts +0 -285
- package/src/cli/commands/add/source.ts +0 -273
- package/src/cli/commands/add/stamper.ts +0 -73
- package/src/cli/commands/add/tokens.ts +0 -81
- package/src/cli/commands/add/ui-paths.ts +0 -113
- package/src/cli/commands/add.ts +0 -427
- package/src/cli/commands/deploy.ts +0 -143
- package/src/cli/commands/migrate.ts +0 -149
- package/src/cli/commands/secret.ts +0 -316
- package/src/cli/commands/ui/build.ts +0 -111
- package/src/cli/commands/ui/init.ts +0 -135
- package/src/cli/commands/ui/migrate/git-guard.ts +0 -19
- package/src/cli/commands/ui/migrate/radix.ts +0 -67
- package/src/cli/commands/ui/migrate/rtl.ts +0 -148
- package/src/cli/commands/ui/shadcn.ts +0 -82
- package/src/cli/commands/ui/view.ts +0 -63
- package/src/cli/commands/ui.ts +0 -86
- package/src/cli/commands/update.ts +0 -134
- package/src/cli/commands/upgrade.ts +0 -53
- package/src/cli/commands/view.ts +0 -34
- package/src/cli/dev.ts +0 -393
- package/src/cli/doctor/config-checks.ts +0 -63
- package/src/cli/doctor/deps.ts +0 -295
- package/src/cli/doctor/hydrate.ts +0 -65
- package/src/cli/doctor/monorepo.ts +0 -158
- package/src/cli/doctor/probes.ts +0 -16
- package/src/cli/doctor/report.ts +0 -72
- package/src/cli/doctor/toolchain.ts +0 -95
- package/src/cli/doctor/types.ts +0 -36
- package/src/cli/doctor.ts +0 -127
- package/src/cli/index.ts +0 -168
- package/src/cli/log.ts +0 -135
- package/src/cli/run/affected.ts +0 -79
- package/src/cli/run/cache-key.ts +0 -177
- package/src/cli/run/cache-store.ts +0 -0
- package/src/cli/run/files.ts +0 -96
- package/src/cli/run/git.ts +0 -13
- package/src/cli/run/runner.ts +0 -189
- package/src/cli/run/workspace.ts +0 -216
- package/src/cli/run.ts +0 -184
- package/src/cli/start.ts +0 -99
- package/src/cli/update-check.ts +0 -157
- package/src/client/index.ts +0 -65
- package/src/client/link.tsx +0 -61
- package/src/client/page.ts +0 -250
- package/src/config/define.ts +0 -5
- package/src/config/env.ts +0 -36
- package/src/config/load.ts +0 -152
- package/src/config/schema.ts +0 -135
- package/src/config/secrets.ts +0 -108
- package/src/dev/client.ts +0 -112
- package/src/dev/hot.ts +0 -24
- package/src/dev/index.ts +0 -4
- package/src/dev/tree.ts +0 -95
- package/src/dev/watcher.ts +0 -95
- package/src/internal/hmr-client.ts +0 -52
- package/src/internal/open-in-editor.ts +0 -23
- package/src/internal/runtime.ts +0 -30
- package/src/middleware/cookie-jar.ts +0 -135
- package/src/middleware/cookies.ts +0 -60
- package/src/middleware/index.ts +0 -127
- package/src/middleware/request-id.ts +0 -22
- package/src/middleware/response-helpers.ts +0 -25
- package/src/plugin/index.ts +0 -109
- package/src/render/bootstrap.ts +0 -44
- package/src/render/dev-error.tsx +0 -73
- package/src/render/index.tsx +0 -261
- package/src/render/island.tsx +0 -33
- package/src/render/meta.tsx +0 -48
- package/src/render/shell.tsx +0 -41
- package/src/router/conflict.ts +0 -20
- package/src/router/filesystem.ts +0 -37
- package/src/router/index.ts +0 -247
- package/src/router/match.ts +0 -91
- package/src/router/pattern.ts +0 -88
- package/src/server/index.ts +0 -250
- package/src/server/inline-assets.ts +0 -39
- package/src/types.ts +0 -53
- package/src/ui/schema.ts +0 -68
- package/src/ui/types.ts +0 -10
- package/templates/_internal/cn.ts +0 -6
- package/templates/_internal/slot.ts +0 -50
- package/templates/_internal/variants.ts +0 -1
- package/templates/themes/neutral/tokens.css +0 -46
- package/templates/themes/slate/tokens.css +0 -46
- package/templates/themes/stone/tokens.css +0 -46
- package/templates/themes/zinc/tokens.css +0 -46
- package/templates/tokens.css +0 -46
package/src/render/meta.tsx
DELETED
|
@@ -1,48 +0,0 @@
|
|
|
1
|
-
import type * as React from "react";
|
|
2
|
-
|
|
3
|
-
export interface MetaInput {
|
|
4
|
-
title?: string;
|
|
5
|
-
description?: string;
|
|
6
|
-
[key: string]: string | undefined;
|
|
7
|
-
}
|
|
8
|
-
|
|
9
|
-
export function renderMetaTags(meta: MetaInput | undefined): React.ReactNode[] {
|
|
10
|
-
if (!meta) return [];
|
|
11
|
-
const nodes: React.ReactNode[] = [];
|
|
12
|
-
let key = 0;
|
|
13
|
-
if (meta.title) nodes.push(<title key={`meta-${key++}`}>{meta.title}</title>);
|
|
14
|
-
for (const [name, value] of Object.entries(meta)) {
|
|
15
|
-
if (name === "title" || value == null) continue;
|
|
16
|
-
if (name === "description") {
|
|
17
|
-
nodes.push(
|
|
18
|
-
<meta key={`meta-${key++}`} name="description" content={value} />,
|
|
19
|
-
);
|
|
20
|
-
continue;
|
|
21
|
-
}
|
|
22
|
-
// OpenGraph and Twitter use property/name conventions; default to name.
|
|
23
|
-
const attr =
|
|
24
|
-
name.startsWith("og:") || name.startsWith("article:")
|
|
25
|
-
? "property"
|
|
26
|
-
: "name";
|
|
27
|
-
nodes.push(
|
|
28
|
-
attr === "property" ? (
|
|
29
|
-
<meta key={`meta-${key++}`} property={name} content={value} />
|
|
30
|
-
) : (
|
|
31
|
-
<meta key={`meta-${key++}`} name={name} content={value} />
|
|
32
|
-
),
|
|
33
|
-
);
|
|
34
|
-
}
|
|
35
|
-
return nodes;
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
export function defaultHead(urlPath: string): React.ReactNode[] {
|
|
39
|
-
return [
|
|
40
|
-
<meta key="charset" charSet="utf-8" />,
|
|
41
|
-
<meta
|
|
42
|
-
key="viewport"
|
|
43
|
-
name="viewport"
|
|
44
|
-
content="width=device-width, initial-scale=1"
|
|
45
|
-
/>,
|
|
46
|
-
<title key="default-title">{urlPath || "/"}</title>,
|
|
47
|
-
];
|
|
48
|
-
}
|
package/src/render/shell.tsx
DELETED
|
@@ -1,41 +0,0 @@
|
|
|
1
|
-
import type * as React from "react";
|
|
2
|
-
import { BOOTSTRAP_ID } from "./bootstrap.ts";
|
|
3
|
-
|
|
4
|
-
export interface ShellProps {
|
|
5
|
-
headNodes: React.ReactNode[];
|
|
6
|
-
children: React.ReactNode;
|
|
7
|
-
clientScriptUrl?: string;
|
|
8
|
-
// Serialized `{ params, data }` for whole-tree hydrated pages. Rendered
|
|
9
|
-
// outside `#root` so the client's `hydrateRoot` never sees it.
|
|
10
|
-
bootstrap?: string;
|
|
11
|
-
}
|
|
12
|
-
|
|
13
|
-
// The HMR client <script> tag is injected post-render as a raw string by
|
|
14
|
-
// render/index.tsx — it's a fixed framework snippet and is appended to the
|
|
15
|
-
// stream after React finishes. Keeping it out of the React tree avoids
|
|
16
|
-
// React's escape hatch APIs entirely.
|
|
17
|
-
export function Shell({
|
|
18
|
-
headNodes,
|
|
19
|
-
children,
|
|
20
|
-
clientScriptUrl,
|
|
21
|
-
bootstrap,
|
|
22
|
-
}: ShellProps) {
|
|
23
|
-
return (
|
|
24
|
-
<html lang="en">
|
|
25
|
-
<head>{headNodes}</head>
|
|
26
|
-
<body>
|
|
27
|
-
<div id="root">{children}</div>
|
|
28
|
-
{bootstrap !== undefined ? (
|
|
29
|
-
// React emits <script> text raw and rewrites `</script` to
|
|
30
|
-
// `</script`, which stays valid JSON — no manual escaping needed.
|
|
31
|
-
<script type="application/json" id={BOOTSTRAP_ID}>
|
|
32
|
-
{bootstrap}
|
|
33
|
-
</script>
|
|
34
|
-
) : null}
|
|
35
|
-
{clientScriptUrl ? (
|
|
36
|
-
<script type="module" src={clientScriptUrl} />
|
|
37
|
-
) : null}
|
|
38
|
-
</body>
|
|
39
|
-
</html>
|
|
40
|
-
);
|
|
41
|
-
}
|
package/src/router/conflict.ts
DELETED
|
@@ -1,20 +0,0 @@
|
|
|
1
|
-
import type { RouteEntry } from "../types.ts";
|
|
2
|
-
|
|
3
|
-
export function assertNoConflicts(entries: RouteEntry[]): void {
|
|
4
|
-
const byPattern = new Map<string, string[]>();
|
|
5
|
-
for (const e of entries) {
|
|
6
|
-
const existing = byPattern.get(e.bunPattern);
|
|
7
|
-
if (existing) {
|
|
8
|
-
existing.push(e.filePath);
|
|
9
|
-
} else {
|
|
10
|
-
byPattern.set(e.bunPattern, [e.filePath]);
|
|
11
|
-
}
|
|
12
|
-
}
|
|
13
|
-
for (const [pattern, files] of byPattern) {
|
|
14
|
-
if (files.length > 1) {
|
|
15
|
-
throw new Error(
|
|
16
|
-
`Route conflict at pattern "${pattern}": ${files.join(", ")}`,
|
|
17
|
-
);
|
|
18
|
-
}
|
|
19
|
-
}
|
|
20
|
-
}
|
package/src/router/filesystem.ts
DELETED
|
@@ -1,37 +0,0 @@
|
|
|
1
|
-
import type { RouteEntry } from "../types.ts";
|
|
2
|
-
import { assertNoConflicts } from "./conflict.ts";
|
|
3
|
-
import { compareRoutes, parseRouteFile } from "./pattern.ts";
|
|
4
|
-
|
|
5
|
-
const TEST_FILE_RE = /\.test\.tsx?$/;
|
|
6
|
-
|
|
7
|
-
export async function scanRoutes(appDir: string): Promise<RouteEntry[]> {
|
|
8
|
-
const routesDir = `${appDir.replace(/\/+$/, "")}/routes`;
|
|
9
|
-
|
|
10
|
-
const glob = new Bun.Glob("**/*.{ts,tsx}");
|
|
11
|
-
const entries: RouteEntry[] = [];
|
|
12
|
-
|
|
13
|
-
try {
|
|
14
|
-
for await (const rel of glob.scan({ cwd: routesDir, onlyFiles: true })) {
|
|
15
|
-
const base = rel.split("/").pop() ?? rel;
|
|
16
|
-
if (base.startsWith("_")) continue;
|
|
17
|
-
if (TEST_FILE_RE.test(base)) continue;
|
|
18
|
-
|
|
19
|
-
const parsed = parseRouteFile(rel);
|
|
20
|
-
entries.push({
|
|
21
|
-
filePath: `${routesDir}/${rel}`,
|
|
22
|
-
bunPattern: parsed.bunPattern,
|
|
23
|
-
kind: parsed.kind,
|
|
24
|
-
segments: parsed.segments,
|
|
25
|
-
});
|
|
26
|
-
}
|
|
27
|
-
} catch (err) {
|
|
28
|
-
// Missing routes/ dir: treat as no routes.
|
|
29
|
-
const msg = (err as Error)?.message ?? "";
|
|
30
|
-
if (/ENOENT|no such file/i.test(msg)) return [];
|
|
31
|
-
throw err;
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
assertNoConflicts(entries);
|
|
35
|
-
entries.sort(compareRoutes);
|
|
36
|
-
return entries;
|
|
37
|
-
}
|
package/src/router/index.ts
DELETED
|
@@ -1,247 +0,0 @@
|
|
|
1
|
-
import { runtimeCwd } from "../internal/runtime.ts";
|
|
2
|
-
import { finalizeResponse, now } from "../middleware/cookies.ts";
|
|
3
|
-
import { compose, type Middleware, makeContext } from "../middleware/index.ts";
|
|
4
|
-
import {
|
|
5
|
-
assertPluginCompat,
|
|
6
|
-
type Plugin,
|
|
7
|
-
type PluginContext,
|
|
8
|
-
type PluginServer,
|
|
9
|
-
} from "../plugin/index.ts";
|
|
10
|
-
import type { Renderer } from "../render/index.tsx";
|
|
11
|
-
import type { BunRoutes, Handler, HTTPMethod, RouteEntry } from "../types.ts";
|
|
12
|
-
import { HTTP_METHODS } from "../types.ts";
|
|
13
|
-
|
|
14
|
-
export interface RouterOptions {
|
|
15
|
-
appDir: string;
|
|
16
|
-
middleware?: Middleware;
|
|
17
|
-
plugins?: Plugin[];
|
|
18
|
-
pluginContext?: PluginContext;
|
|
19
|
-
frameworkVersion?: string;
|
|
20
|
-
renderer: Renderer;
|
|
21
|
-
// Pre-scanned route table. When provided, skips runtime scanRoutes().
|
|
22
|
-
entries?: RouteEntry[];
|
|
23
|
-
// Pre-imported route modules keyed by entry.filePath. When provided, used instead of `await import(entry.filePath)`.
|
|
24
|
-
modules?: Record<string, unknown>;
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
export interface CompiledRouter {
|
|
28
|
-
routes: BunRoutes;
|
|
29
|
-
fallback: (req: Request) => Promise<Response>;
|
|
30
|
-
entries: RouteEntry[];
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
export async function createRouter(
|
|
34
|
-
options: RouterOptions,
|
|
35
|
-
): Promise<CompiledRouter> {
|
|
36
|
-
const { appDir } = options;
|
|
37
|
-
|
|
38
|
-
const userMiddleware =
|
|
39
|
-
options.middleware ?? (await loadAppMiddleware(appDir));
|
|
40
|
-
|
|
41
|
-
let entries = options.entries;
|
|
42
|
-
if (!entries) {
|
|
43
|
-
// Static import — fine for dev paths. The build pipeline (which always
|
|
44
|
-
// pre-scans) bypasses this function entirely via createCompiledRouter().
|
|
45
|
-
const { scanRoutes } = await import("./filesystem.ts");
|
|
46
|
-
entries = await scanRoutes(appDir);
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
return createCompiledRouter({
|
|
50
|
-
entries,
|
|
51
|
-
middleware: userMiddleware,
|
|
52
|
-
plugins: options.plugins,
|
|
53
|
-
pluginContext: options.pluginContext,
|
|
54
|
-
frameworkVersion: options.frameworkVersion,
|
|
55
|
-
renderer: options.renderer,
|
|
56
|
-
modules: options.modules,
|
|
57
|
-
});
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
export interface CompiledRouterOptions {
|
|
61
|
-
entries: RouteEntry[];
|
|
62
|
-
middleware?: Middleware;
|
|
63
|
-
plugins?: Plugin[];
|
|
64
|
-
pluginContext?: PluginContext;
|
|
65
|
-
frameworkVersion?: string;
|
|
66
|
-
renderer: Renderer;
|
|
67
|
-
modules?: Record<string, unknown>;
|
|
68
|
-
}
|
|
69
|
-
|
|
70
|
-
interface PendingRoute {
|
|
71
|
-
pattern: string;
|
|
72
|
-
methods: Partial<Record<HTTPMethod, Handler>>;
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
// Pure routing assembly — no filesystem access. The build module's generated
|
|
76
|
-
// server entry imports this directly so `Bun.Glob` / `scanRoutes` never enter
|
|
77
|
-
// the production bundle.
|
|
78
|
-
export async function createCompiledRouter(
|
|
79
|
-
options: CompiledRouterOptions,
|
|
80
|
-
): Promise<CompiledRouter> {
|
|
81
|
-
const { entries, renderer } = options;
|
|
82
|
-
const plugins = options.plugins ?? [];
|
|
83
|
-
const userMw = options.middleware;
|
|
84
|
-
const pluginMiddleware: Middleware[] = [];
|
|
85
|
-
const pendingRoutes: PendingRoute[] = [];
|
|
86
|
-
|
|
87
|
-
for (const p of plugins) {
|
|
88
|
-
try {
|
|
89
|
-
if (options.frameworkVersion) {
|
|
90
|
-
assertPluginCompat(options.frameworkVersion, p);
|
|
91
|
-
}
|
|
92
|
-
} catch (err) {
|
|
93
|
-
throw wrapPluginError(p.name, err);
|
|
94
|
-
}
|
|
95
|
-
if (!p.setup) continue;
|
|
96
|
-
const server: PluginServer = {
|
|
97
|
-
route(pattern, methods) {
|
|
98
|
-
pendingRoutes.push({ pattern, methods });
|
|
99
|
-
},
|
|
100
|
-
use(mw) {
|
|
101
|
-
pluginMiddleware.push(mw);
|
|
102
|
-
},
|
|
103
|
-
};
|
|
104
|
-
const ctx: PluginContext = options.pluginContext ?? {
|
|
105
|
-
config: {},
|
|
106
|
-
root: runtimeCwd(),
|
|
107
|
-
logger: console,
|
|
108
|
-
};
|
|
109
|
-
try {
|
|
110
|
-
await p.setup(server, ctx);
|
|
111
|
-
} catch (err) {
|
|
112
|
-
throw wrapPluginError(p.name, err);
|
|
113
|
-
}
|
|
114
|
-
}
|
|
115
|
-
|
|
116
|
-
const middlewareChain: Middleware[] = [];
|
|
117
|
-
if (userMw) middlewareChain.push(userMw);
|
|
118
|
-
for (const mw of pluginMiddleware) middlewareChain.push(mw);
|
|
119
|
-
|
|
120
|
-
const preloadedModules = options.modules;
|
|
121
|
-
const routes: BunRoutes = {};
|
|
122
|
-
|
|
123
|
-
for (const entry of entries) {
|
|
124
|
-
if (entry.kind === "page") {
|
|
125
|
-
const handler: Handler = (req, ctx) =>
|
|
126
|
-
renderer.renderPage(entry, req, ctx);
|
|
127
|
-
attach(routes, entry.bunPattern, { GET: wrap(handler, middlewareChain) });
|
|
128
|
-
} else {
|
|
129
|
-
const mod = (preloadedModules?.[entry.filePath] ??
|
|
130
|
-
(await import(entry.filePath))) as Record<string, unknown>;
|
|
131
|
-
if (typeof mod.default === "function") {
|
|
132
|
-
throw new Error(
|
|
133
|
-
`API route ${entry.filePath} must not default-export a handler. ` +
|
|
134
|
-
`Export named GET/POST/PUT/DELETE/PATCH/OPTIONS/HEAD instead.`,
|
|
135
|
-
);
|
|
136
|
-
}
|
|
137
|
-
const methodMap: Partial<Record<HTTPMethod, Handler>> = {};
|
|
138
|
-
let found = 0;
|
|
139
|
-
for (const m of HTTP_METHODS) {
|
|
140
|
-
const fn = mod[m];
|
|
141
|
-
if (typeof fn === "function") {
|
|
142
|
-
methodMap[m] = wrap(fn as Handler, middlewareChain);
|
|
143
|
-
found++;
|
|
144
|
-
}
|
|
145
|
-
}
|
|
146
|
-
if (found === 0) {
|
|
147
|
-
throw new Error(
|
|
148
|
-
`API route ${entry.filePath} exports no HTTP-method handlers ` +
|
|
149
|
-
`(GET/POST/PUT/DELETE/PATCH/OPTIONS/HEAD).`,
|
|
150
|
-
);
|
|
151
|
-
}
|
|
152
|
-
attach(routes, entry.bunPattern, methodMap);
|
|
153
|
-
}
|
|
154
|
-
}
|
|
155
|
-
|
|
156
|
-
for (const pr of pendingRoutes) {
|
|
157
|
-
const wrapped: Partial<Record<HTTPMethod, Handler>> = {};
|
|
158
|
-
for (const [m, h] of Object.entries(pr.methods) as [
|
|
159
|
-
HTTPMethod,
|
|
160
|
-
Handler,
|
|
161
|
-
][]) {
|
|
162
|
-
wrapped[m] = wrap(h, middlewareChain);
|
|
163
|
-
}
|
|
164
|
-
attach(routes, pr.pattern, wrapped);
|
|
165
|
-
}
|
|
166
|
-
|
|
167
|
-
const fallback = wrap(
|
|
168
|
-
() => new Response("Not Found", { status: 404 }),
|
|
169
|
-
middlewareChain,
|
|
170
|
-
);
|
|
171
|
-
|
|
172
|
-
return {
|
|
173
|
-
routes,
|
|
174
|
-
fallback: async (req: Request) => {
|
|
175
|
-
const startMs = now();
|
|
176
|
-
const ctx = makeContext(req);
|
|
177
|
-
const res = await fallback(req, ctx);
|
|
178
|
-
return finalizeResponse(res, ctx, { startMs });
|
|
179
|
-
},
|
|
180
|
-
entries,
|
|
181
|
-
};
|
|
182
|
-
}
|
|
183
|
-
|
|
184
|
-
function attach(
|
|
185
|
-
routes: BunRoutes,
|
|
186
|
-
pattern: string,
|
|
187
|
-
methodMap: Partial<Record<HTTPMethod, Handler>>,
|
|
188
|
-
): void {
|
|
189
|
-
const existing = routes[pattern];
|
|
190
|
-
const bunWrapped: Record<
|
|
191
|
-
string,
|
|
192
|
-
(req: Request & { params: Record<string, string> }) => Promise<Response>
|
|
193
|
-
> = {};
|
|
194
|
-
for (const [m, h] of Object.entries(methodMap)) {
|
|
195
|
-
if (!h) continue;
|
|
196
|
-
bunWrapped[m] = (req) => {
|
|
197
|
-
const startMs = now();
|
|
198
|
-
const params = req.params ?? {};
|
|
199
|
-
const ctx = makeContext(req, params);
|
|
200
|
-
return Promise.resolve(h(req, ctx)).then((res) =>
|
|
201
|
-
finalizeResponse(res, ctx, { startMs }),
|
|
202
|
-
);
|
|
203
|
-
};
|
|
204
|
-
}
|
|
205
|
-
if (
|
|
206
|
-
existing &&
|
|
207
|
-
typeof existing === "object" &&
|
|
208
|
-
!(existing instanceof Response)
|
|
209
|
-
) {
|
|
210
|
-
routes[pattern] = {
|
|
211
|
-
...(existing as object),
|
|
212
|
-
...bunWrapped,
|
|
213
|
-
} as (typeof routes)[string];
|
|
214
|
-
} else {
|
|
215
|
-
routes[pattern] = bunWrapped as (typeof routes)[string];
|
|
216
|
-
}
|
|
217
|
-
}
|
|
218
|
-
|
|
219
|
-
function wrap(handler: Handler, mws: Middleware[]): Handler {
|
|
220
|
-
if (mws.length === 0) return handler;
|
|
221
|
-
return compose(mws, handler);
|
|
222
|
-
}
|
|
223
|
-
|
|
224
|
-
function wrapPluginError(name: string, err: unknown): Error {
|
|
225
|
-
const msg = (err as Error)?.message ?? String(err);
|
|
226
|
-
if (msg.startsWith(`[plugin ${name}]`)) return err as Error;
|
|
227
|
-
const wrapped = new Error(`[plugin ${name}] ${msg}`);
|
|
228
|
-
(wrapped as Error & { cause?: unknown }).cause = err;
|
|
229
|
-
return wrapped;
|
|
230
|
-
}
|
|
231
|
-
|
|
232
|
-
async function loadAppMiddleware(
|
|
233
|
-
appDir: string,
|
|
234
|
-
): Promise<Middleware | undefined> {
|
|
235
|
-
const path = `${appDir.replace(/\/+$/, "")}/middleware.ts`;
|
|
236
|
-
const exists = await Bun.file(path).exists();
|
|
237
|
-
if (!exists) return undefined;
|
|
238
|
-
const mod = (await import(path)) as { default?: unknown };
|
|
239
|
-
const fn = mod.default;
|
|
240
|
-
if (fn === undefined) return undefined;
|
|
241
|
-
if (typeof fn !== "function") {
|
|
242
|
-
throw new Error(
|
|
243
|
-
`${path}: default export must be a Middleware function (got ${typeof fn}).`,
|
|
244
|
-
);
|
|
245
|
-
}
|
|
246
|
-
return fn as Middleware;
|
|
247
|
-
}
|
package/src/router/match.ts
DELETED
|
@@ -1,91 +0,0 @@
|
|
|
1
|
-
import type { BunRoutes } from "../types.ts";
|
|
2
|
-
|
|
3
|
-
// Shared route matcher. Implements the same `:param` / `*` catch-all semantics
|
|
4
|
-
// as Bun.serve's native router so the in-process `createServer` and the
|
|
5
|
-
// edge-target's generated worker boot dispatch identically.
|
|
6
|
-
|
|
7
|
-
export interface Compiled {
|
|
8
|
-
pattern: string;
|
|
9
|
-
match: (path: string) => Record<string, string> | null;
|
|
10
|
-
}
|
|
11
|
-
|
|
12
|
-
export function makeMatcher(
|
|
13
|
-
pattern: string,
|
|
14
|
-
): (path: string) => Record<string, string> | null {
|
|
15
|
-
const segs = pattern.split("/").filter(Boolean);
|
|
16
|
-
return (path) => {
|
|
17
|
-
const parts = path.split("/").filter(Boolean);
|
|
18
|
-
const params: Record<string, string> = {};
|
|
19
|
-
let i = 0;
|
|
20
|
-
for (; i < segs.length; i++) {
|
|
21
|
-
const s = segs[i];
|
|
22
|
-
if (s === undefined) return null;
|
|
23
|
-
if (s === "*") {
|
|
24
|
-
params["*"] = parts.slice(i).join("/");
|
|
25
|
-
return params;
|
|
26
|
-
}
|
|
27
|
-
const p = parts[i];
|
|
28
|
-
if (p === undefined) return null;
|
|
29
|
-
if (s.startsWith(":")) {
|
|
30
|
-
params[s.slice(1)] = decodeURIComponent(p);
|
|
31
|
-
continue;
|
|
32
|
-
}
|
|
33
|
-
if (s !== p) return null;
|
|
34
|
-
}
|
|
35
|
-
if (i !== parts.length) return null;
|
|
36
|
-
return params;
|
|
37
|
-
};
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
export function compilePatterns(routes: BunRoutes): Compiled[] {
|
|
41
|
-
return Object.keys(routes).map((pattern) => ({
|
|
42
|
-
pattern,
|
|
43
|
-
match: makeMatcher(pattern),
|
|
44
|
-
}));
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
export interface DispatchExtras {
|
|
48
|
-
env?: unknown;
|
|
49
|
-
execCtx?: unknown;
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
// Returns a Response on hit; null on miss so the caller can apply a fallback.
|
|
53
|
-
// `compiled` is optional — pass a pre-compiled list to avoid re-walking the
|
|
54
|
-
// route map on every request when the route table is stable.
|
|
55
|
-
export async function dispatch(
|
|
56
|
-
routes: BunRoutes,
|
|
57
|
-
req: Request,
|
|
58
|
-
extras: DispatchExtras = {},
|
|
59
|
-
compiled?: Compiled[],
|
|
60
|
-
): Promise<Response | null> {
|
|
61
|
-
const url = new URL(req.url);
|
|
62
|
-
const list = compiled ?? compilePatterns(routes);
|
|
63
|
-
for (const c of list) {
|
|
64
|
-
const params = c.match(url.pathname);
|
|
65
|
-
if (!params) continue;
|
|
66
|
-
const value = routes[c.pattern];
|
|
67
|
-
if (value instanceof Response) return value.clone();
|
|
68
|
-
const augmented = Object.assign(req, {
|
|
69
|
-
params,
|
|
70
|
-
env: extras.env,
|
|
71
|
-
execCtx: extras.execCtx,
|
|
72
|
-
});
|
|
73
|
-
if (typeof value === "function") {
|
|
74
|
-
return await (
|
|
75
|
-
value as (
|
|
76
|
-
r: Request & { params: Record<string, string> },
|
|
77
|
-
) => Response | Promise<Response>
|
|
78
|
-
)(augmented);
|
|
79
|
-
}
|
|
80
|
-
const methodHandler = (value as Record<string, unknown>)[req.method];
|
|
81
|
-
if (typeof methodHandler === "function") {
|
|
82
|
-
return await (
|
|
83
|
-
methodHandler as (
|
|
84
|
-
r: Request & { params: Record<string, string> },
|
|
85
|
-
) => Response | Promise<Response>
|
|
86
|
-
)(augmented);
|
|
87
|
-
}
|
|
88
|
-
return new Response("Method Not Allowed", { status: 405 });
|
|
89
|
-
}
|
|
90
|
-
return null;
|
|
91
|
-
}
|
package/src/router/pattern.ts
DELETED
|
@@ -1,88 +0,0 @@
|
|
|
1
|
-
import type { Segment } from "../types.ts";
|
|
2
|
-
|
|
3
|
-
export interface ParsedFile {
|
|
4
|
-
bunPattern: string;
|
|
5
|
-
segments: Segment[];
|
|
6
|
-
kind: "page" | "api";
|
|
7
|
-
}
|
|
8
|
-
|
|
9
|
-
const CATCHALL_RE = /^\[\.\.\.([^\]]+)\]$/;
|
|
10
|
-
const PARAM_RE = /^\[([^\]]+)\]$/;
|
|
11
|
-
|
|
12
|
-
// relPath is path under app/routes/, e.g. "index.tsx", "hotels/[city].tsx",
|
|
13
|
-
// "api/revenue.ts", "files/[...rest].tsx".
|
|
14
|
-
export function parseRouteFile(relPath: string): ParsedFile {
|
|
15
|
-
const isApi = relPath === "api" || relPath.startsWith("api/");
|
|
16
|
-
const ext = relPath.endsWith(".tsx")
|
|
17
|
-
? ".tsx"
|
|
18
|
-
: relPath.endsWith(".ts")
|
|
19
|
-
? ".ts"
|
|
20
|
-
: "";
|
|
21
|
-
if (!ext) throw new Error(`Unsupported route extension: ${relPath}`);
|
|
22
|
-
|
|
23
|
-
if (isApi && ext === ".tsx") {
|
|
24
|
-
throw new Error(`API route must be .ts, not .tsx: ${relPath}`);
|
|
25
|
-
}
|
|
26
|
-
if (!isApi && ext === ".ts") {
|
|
27
|
-
throw new Error(
|
|
28
|
-
`Non-API route must be .tsx (pages) - got .ts: ${relPath}. ` +
|
|
29
|
-
`Move it under app/routes/api/ for an API route.`,
|
|
30
|
-
);
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
const noExt = relPath.slice(0, -ext.length);
|
|
34
|
-
const parts = noExt.split("/");
|
|
35
|
-
const segments: Segment[] = [];
|
|
36
|
-
|
|
37
|
-
for (const part of parts) {
|
|
38
|
-
if (part === "" || part === "index") continue;
|
|
39
|
-
|
|
40
|
-
const catchall = part.match(CATCHALL_RE);
|
|
41
|
-
if (catchall) {
|
|
42
|
-
segments.push({ raw: part, kind: "catchall", name: catchall[1] });
|
|
43
|
-
continue;
|
|
44
|
-
}
|
|
45
|
-
const param = part.match(PARAM_RE);
|
|
46
|
-
if (param) {
|
|
47
|
-
segments.push({ raw: part, kind: "param", name: param[1] });
|
|
48
|
-
continue;
|
|
49
|
-
}
|
|
50
|
-
segments.push({ raw: part, kind: "static" });
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
const pieces = segments.map((s) => {
|
|
54
|
-
if (s.kind === "static") return s.raw;
|
|
55
|
-
if (s.kind === "param") return `:${s.name}`;
|
|
56
|
-
return "*";
|
|
57
|
-
});
|
|
58
|
-
let bunPattern = `/${pieces.join("/")}`;
|
|
59
|
-
bunPattern = bunPattern.replace(/\/+/g, "/");
|
|
60
|
-
if (bunPattern.length > 1 && bunPattern.endsWith("/")) {
|
|
61
|
-
bunPattern = bunPattern.slice(0, -1);
|
|
62
|
-
}
|
|
63
|
-
|
|
64
|
-
return { bunPattern, segments, kind: isApi ? "api" : "page" };
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
// Sort so that more-specific patterns come first:
|
|
68
|
-
// - more static segments outrank fewer
|
|
69
|
-
// - non-catchall outranks catchall
|
|
70
|
-
// - shorter patterns outrank longer (when static count is equal)
|
|
71
|
-
// - lexicographic tie-break for determinism
|
|
72
|
-
export function compareRoutes(
|
|
73
|
-
a: { segments: Segment[]; bunPattern: string },
|
|
74
|
-
b: { segments: Segment[]; bunPattern: string },
|
|
75
|
-
): number {
|
|
76
|
-
const aStatic = a.segments.filter((s) => s.kind === "static").length;
|
|
77
|
-
const bStatic = b.segments.filter((s) => s.kind === "static").length;
|
|
78
|
-
if (aStatic !== bStatic) return bStatic - aStatic;
|
|
79
|
-
|
|
80
|
-
const aCatch = a.segments.some((s) => s.kind === "catchall") ? 1 : 0;
|
|
81
|
-
const bCatch = b.segments.some((s) => s.kind === "catchall") ? 1 : 0;
|
|
82
|
-
if (aCatch !== bCatch) return aCatch - bCatch;
|
|
83
|
-
|
|
84
|
-
if (a.segments.length !== b.segments.length)
|
|
85
|
-
return a.segments.length - b.segments.length;
|
|
86
|
-
|
|
87
|
-
return a.bunPattern.localeCompare(b.bunPattern);
|
|
88
|
-
}
|