@kiln-js/server 0.1.3 → 0.1.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +45 -0
- package/dist/app.d.ts +2 -1
- package/dist/index.d.ts +2 -0
- package/dist/index.js +233 -132
- package/dist/types.d.ts +15 -0
- package/package.json +2 -2
package/README.md
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
# @kiln-js/server
|
|
2
|
+
|
|
3
|
+
[](https://www.npmjs.com/package/@kiln-js/server)
|
|
4
|
+
[](LICENSE)
|
|
5
|
+
|
|
6
|
+
Part of the Kiln framework.
|
|
7
|
+
|
|
8
|
+
Part of [Kiln](https://github.com/kiln-js/kiln), a file-based server-side rendering framework for React and Vite.
|
|
9
|
+
|
|
10
|
+
## Install
|
|
11
|
+
|
|
12
|
+
```bash
|
|
13
|
+
bun add @kiln-js/server
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
## Usage
|
|
17
|
+
|
|
18
|
+
```ts
|
|
19
|
+
import { createAppHandler, type KilnAssets } from "@kiln-js/server";
|
|
20
|
+
|
|
21
|
+
export function createHandler(assets: KilnAssets) {
|
|
22
|
+
return createAppHandler({
|
|
23
|
+
assets,
|
|
24
|
+
defaultTitle: "My app",
|
|
25
|
+
notFound: "<h1>Page not found</h1>",
|
|
26
|
+
});
|
|
27
|
+
}
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
## Runtime
|
|
31
|
+
|
|
32
|
+
Handlers use standard `Request` and `Response` objects, so the same code runs on Bun, Node, and edge runtimes.
|
|
33
|
+
The route table is provided by `@kiln-js/vite-plugin`.
|
|
34
|
+
|
|
35
|
+
## Documentation
|
|
36
|
+
|
|
37
|
+
See the [Kiln repository](https://github.com/kiln-js/kiln) for the full API reference and guides.
|
|
38
|
+
|
|
39
|
+
## Development
|
|
40
|
+
|
|
41
|
+
This repository is generated from the Kiln monorepo. Make changes there, then run `scripts/publish-repo.ps1` to publish them here. Report issues in this repository, and send pull requests to the monorepo.
|
|
42
|
+
|
|
43
|
+
## License
|
|
44
|
+
|
|
45
|
+
MIT
|
package/dist/app.d.ts
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
|
-
import type { ApiRoute, KilnAssets, RouteEntry } from "./types";
|
|
1
|
+
import type { ApiRoute, KilnAssets, RouteEntry, Specials } from "./types";
|
|
2
2
|
export interface AppOptions {
|
|
3
3
|
routes?: RouteEntry[];
|
|
4
4
|
api?: ApiRoute[];
|
|
5
|
+
specials?: Specials;
|
|
5
6
|
assets: KilnAssets;
|
|
6
7
|
template?: string;
|
|
7
8
|
notFound?: string;
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
export { createHandler } from "./render";
|
|
2
2
|
export { createAppHandler, type AppOptions } from "./app";
|
|
3
3
|
export { defaultTemplate } from "./template";
|
|
4
|
+
export { HttpError, notFound, forbidden, redirect, island, defer, Await } from "@kiln-js/core";
|
|
5
|
+
export type { Deferred } from "@kiln-js/core";
|
|
4
6
|
export type * from "./types";
|
package/dist/index.js
CHANGED
|
@@ -1,153 +1,245 @@
|
|
|
1
|
-
//
|
|
2
|
-
// src/render.tsx
|
|
1
|
+
// packages/server/src/render.tsx
|
|
3
2
|
import { renderToString } from "react-dom/server";
|
|
3
|
+
import { renderToReadableStream } from "react-dom/server.browser";
|
|
4
|
+
import {
|
|
5
|
+
compose,
|
|
6
|
+
HeadProvider,
|
|
7
|
+
HttpError,
|
|
8
|
+
IslandContext,
|
|
9
|
+
matchRoute as matchRoute2,
|
|
10
|
+
RouteProvider
|
|
11
|
+
} from "@kiln-js/core";
|
|
4
12
|
|
|
5
|
-
//
|
|
6
|
-
import {
|
|
7
|
-
import { createContext, useContext } from "react";
|
|
8
|
-
import { jsx as jsx2 } from "react/jsx-runtime";
|
|
9
|
-
import { createContext as createContext2, useContext as useContext2, useEffect, useLayoutEffect } from "react";
|
|
10
|
-
import { jsx as jsx3 } from "react/jsx-runtime";
|
|
11
|
-
function matchRoute(routes, pathname) {
|
|
12
|
-
const parts = pathname.split("/").filter(Boolean);
|
|
13
|
-
for (const route of routes) {
|
|
14
|
-
const segs = route.pattern.split("/").filter(Boolean);
|
|
15
|
-
const params = {};
|
|
16
|
-
let ok = true;
|
|
17
|
-
let i = 0;
|
|
18
|
-
for (const seg of segs) {
|
|
19
|
-
if (seg.startsWith("*")) {
|
|
20
|
-
params[seg.slice(1)] = parts.slice(i).map(decodeURIComponent).join("/");
|
|
21
|
-
i = parts.length;
|
|
22
|
-
break;
|
|
23
|
-
}
|
|
24
|
-
if (i >= parts.length) {
|
|
25
|
-
ok = false;
|
|
26
|
-
break;
|
|
27
|
-
}
|
|
28
|
-
if (seg.startsWith(":"))
|
|
29
|
-
params[seg.slice(1)] = decodeURIComponent(parts[i]);
|
|
30
|
-
else if (seg !== parts[i]) {
|
|
31
|
-
ok = false;
|
|
32
|
-
break;
|
|
33
|
-
}
|
|
34
|
-
i++;
|
|
35
|
-
}
|
|
36
|
-
if (ok && i === parts.length)
|
|
37
|
-
return { route, params };
|
|
38
|
-
}
|
|
39
|
-
return null;
|
|
40
|
-
}
|
|
41
|
-
function compose(page, layouts) {
|
|
42
|
-
let tree = page;
|
|
43
|
-
for (const Layout of [...layouts].reverse())
|
|
44
|
-
tree = /* @__PURE__ */ jsx(Layout, {
|
|
45
|
-
children: tree
|
|
46
|
-
});
|
|
47
|
-
return tree;
|
|
48
|
-
}
|
|
49
|
-
var RouteContext = createContext({ pathname: "/", params: {} });
|
|
50
|
-
function RouteProvider({ value, children }) {
|
|
51
|
-
return /* @__PURE__ */ jsx2(RouteContext.Provider, {
|
|
52
|
-
value,
|
|
53
|
-
children
|
|
54
|
-
});
|
|
55
|
-
}
|
|
56
|
-
var HeadContext = createContext2(null);
|
|
57
|
-
function HeadProvider({ value, children }) {
|
|
58
|
-
return /* @__PURE__ */ jsx3(HeadContext.Provider, {
|
|
59
|
-
value,
|
|
60
|
-
children
|
|
61
|
-
});
|
|
62
|
-
}
|
|
63
|
-
|
|
64
|
-
// src/api.ts
|
|
13
|
+
// packages/server/src/api.ts
|
|
14
|
+
import { matchRoute } from "@kiln-js/core";
|
|
65
15
|
var METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"];
|
|
66
16
|
async function handleApi(request, pathname, routes) {
|
|
67
17
|
const match = matchRoute(routes, pathname);
|
|
68
|
-
if (!match)
|
|
69
|
-
return null;
|
|
18
|
+
if (!match) return null;
|
|
70
19
|
const mod = await match.route.load();
|
|
71
20
|
const method = request.method.toUpperCase();
|
|
72
21
|
let handler = mod[method];
|
|
73
|
-
if (!handler && method === "HEAD")
|
|
74
|
-
handler = mod.GET;
|
|
22
|
+
if (!handler && method === "HEAD") handler = mod.GET;
|
|
75
23
|
if (typeof handler !== "function") {
|
|
76
24
|
const allow = METHODS.filter((m) => typeof mod[m] === "function");
|
|
77
|
-
return Response.json(
|
|
25
|
+
return Response.json(
|
|
26
|
+
{ error: `Method ${method} not allowed` },
|
|
27
|
+
{ status: 405, headers: { allow: allow.join(", ") } }
|
|
28
|
+
);
|
|
78
29
|
}
|
|
79
30
|
const ctx = { params: match.params, request };
|
|
80
31
|
const result = await handler(ctx);
|
|
81
|
-
if (result instanceof Response)
|
|
82
|
-
|
|
83
|
-
if (result === undefined)
|
|
84
|
-
return new Response(null, { status: 204 });
|
|
32
|
+
if (result instanceof Response) return result;
|
|
33
|
+
if (result === void 0) return new Response(null, { status: 204 });
|
|
85
34
|
return Response.json(result);
|
|
86
35
|
}
|
|
87
36
|
|
|
88
|
-
// src/render.tsx
|
|
89
|
-
import { jsx
|
|
90
|
-
var
|
|
37
|
+
// packages/server/src/render.tsx
|
|
38
|
+
import { jsx } from "react/jsx-runtime";
|
|
39
|
+
var DATA_PATH = "/__kiln/data";
|
|
40
|
+
var HTML = "text/html; charset=utf-8";
|
|
41
|
+
var MARK_APP = "%%KILN_APP%%";
|
|
42
|
+
var MARK_TAIL = "%%KILN_TAIL%%";
|
|
91
43
|
var serialize = (v) => JSON.stringify(v).replace(/</g, "\\u003c");
|
|
92
44
|
var escapeHtml = (s) => s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
return /<title>[\s\S]*?<\/title>/i.test(template) ? template.replace(/<title>[\s\S]*?<\/title>/i, () => tag) : template.replace("</head>", () => `${tag}
|
|
96
|
-
</head>`);
|
|
97
|
-
}
|
|
45
|
+
var wantsJson = (request) => (request.headers.get("accept") ?? "").includes("application/json");
|
|
46
|
+
var isDev = () => globalThis.__KILN_DEV__ === true;
|
|
98
47
|
function createHandler(ctx) {
|
|
99
48
|
return async function handle(request) {
|
|
100
49
|
const url = new URL(request.url);
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
if (
|
|
105
|
-
|
|
106
|
-
const mod = await match.route.load();
|
|
107
|
-
const data = mod.loader ? await mod.loader({ params: match.params, request }) : null;
|
|
108
|
-
return Response.json(data ?? null);
|
|
109
|
-
}
|
|
110
|
-
if (ctx.api) {
|
|
111
|
-
const apiResponse = await handleApi(request, url.pathname, await ctx.api());
|
|
112
|
-
if (apiResponse)
|
|
113
|
-
return apiResponse;
|
|
50
|
+
try {
|
|
51
|
+
return await dispatch(request, url, ctx);
|
|
52
|
+
} catch (err) {
|
|
53
|
+
if (err instanceof HttpError) return httpErrorResponse(err, request, url, ctx);
|
|
54
|
+
throw err;
|
|
114
55
|
}
|
|
115
|
-
const match = matchRoute(routes, url.pathname);
|
|
116
|
-
if (!match) {
|
|
117
|
-
return new Response(await ctx.notFound(), { status: 404, headers: htmlHeaders });
|
|
118
|
-
}
|
|
119
|
-
const page = await renderRoute(match.route, match.params, request, url.pathname, ctx);
|
|
120
|
-
return new Response(page, { status: 200, headers: htmlHeaders });
|
|
121
56
|
};
|
|
122
57
|
}
|
|
123
|
-
async function
|
|
124
|
-
const
|
|
58
|
+
async function dispatch(request, url, ctx) {
|
|
59
|
+
const routes = await ctx.manifest();
|
|
60
|
+
const specials = await loadSpecials(ctx);
|
|
61
|
+
if (url.pathname === DATA_PATH) return dataResponse(request, url, routes);
|
|
62
|
+
if (ctx.api) {
|
|
63
|
+
const apiResponse = await handleApi(request, url.pathname, await ctx.api());
|
|
64
|
+
if (apiResponse) return apiResponse;
|
|
65
|
+
}
|
|
66
|
+
const match = matchRoute2(routes, url.pathname);
|
|
67
|
+
if (!match) return notFoundResponse(request, url, ctx, specials);
|
|
68
|
+
const mod = match.route.load ? await match.route.load() : null;
|
|
69
|
+
if (request.method === "POST") return actionResponse(request, url, match.params, mod);
|
|
70
|
+
if (request.method !== "GET" && request.method !== "HEAD") {
|
|
71
|
+
return new Response("Method Not Allowed", { status: 405, headers: { allow: "GET, HEAD, POST" } });
|
|
72
|
+
}
|
|
73
|
+
try {
|
|
74
|
+
return await pageResponse(match.route, match.params, request, url, ctx, mod);
|
|
75
|
+
} catch (err) {
|
|
76
|
+
return errorPageOr(err, request, url, ctx, specials);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
async function loadSpecials(ctx) {
|
|
80
|
+
return ctx.specials ? ctx.specials() : { errors: [], notFounds: [] };
|
|
81
|
+
}
|
|
82
|
+
function pickSpecial(list, pathname) {
|
|
83
|
+
return matchRoute2(list, pathname)?.route ?? null;
|
|
84
|
+
}
|
|
85
|
+
async function dataResponse(request, url, routes) {
|
|
86
|
+
const target = new URL(url.searchParams.get("path") ?? "/", url.origin);
|
|
87
|
+
const match = matchRoute2(routes, target.pathname);
|
|
88
|
+
if (!match?.route.load) return Response.json(null);
|
|
89
|
+
const mod = await match.route.load();
|
|
90
|
+
if (!mod.loader) return Response.json(null);
|
|
91
|
+
const targetRequest = new Request(target, { method: "GET", headers: request.headers });
|
|
92
|
+
const data = await mod.loader({ params: match.params, request: targetRequest });
|
|
93
|
+
if (data instanceof Response) {
|
|
94
|
+
const location = data.headers.get("location");
|
|
95
|
+
if (location && data.status >= 300 && data.status < 400) return Response.json({ redirect: location });
|
|
96
|
+
return data;
|
|
97
|
+
}
|
|
98
|
+
return Response.json(data ?? null);
|
|
99
|
+
}
|
|
100
|
+
async function pageResponse(route, params, request, url, ctx, mod) {
|
|
125
101
|
const data = mod?.loader ? await mod.loader({ params, request }) : null;
|
|
102
|
+
if (data instanceof Response) return data;
|
|
103
|
+
const [template, assets] = await Promise.all([ctx.template(), ctx.assets()]);
|
|
126
104
|
const head = {};
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
appHtml = renderToString(/* @__PURE__ */ jsx4(HeadProvider, {
|
|
132
|
-
value: head,
|
|
133
|
-
children: /* @__PURE__ */ jsx4(RouteProvider, {
|
|
134
|
-
value: { pathname, params },
|
|
135
|
-
children: compose(/* @__PURE__ */ jsx4(Page, {
|
|
136
|
-
params,
|
|
137
|
-
data
|
|
138
|
-
}), layouts)
|
|
139
|
-
})
|
|
140
|
-
}));
|
|
105
|
+
const islands = /* @__PURE__ */ new Set();
|
|
106
|
+
const fallbackTitle = ctx.defaultTitle ?? "Kiln App";
|
|
107
|
+
if (route.mode === "server" && mod) {
|
|
108
|
+
return streamPage({ route, mod, params, data, request, url, head, islands, template, assets, fallbackTitle });
|
|
141
109
|
}
|
|
142
|
-
const
|
|
143
|
-
const
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
110
|
+
const appHtml = route.mode !== "client" && mod ? renderToString(await buildTree(route, mod, params, data, url, head, islands)) : "";
|
|
111
|
+
const page = assemble(template, assets, {
|
|
112
|
+
appHtml,
|
|
113
|
+
title: head.title ?? fallbackTitle,
|
|
114
|
+
tail: hydrationTail(route, data, islands.size > 0, assets)
|
|
115
|
+
});
|
|
116
|
+
const headers = new Headers({ "content-type": HTML });
|
|
117
|
+
applyCachePolicy(headers, mod, request);
|
|
118
|
+
return new Response(request.method === "HEAD" ? null : page, { status: 200, headers });
|
|
119
|
+
}
|
|
120
|
+
async function buildTree(route, mod, params, data, url, head, islands) {
|
|
121
|
+
const layouts = await Promise.all(route.layouts.map((l) => l().then((m) => m.default)));
|
|
122
|
+
const Page = mod.default;
|
|
123
|
+
return /* @__PURE__ */ jsx(IslandContext.Provider, { value: islands, children: /* @__PURE__ */ jsx(HeadProvider, { value: head, children: /* @__PURE__ */ jsx(RouteProvider, { value: { pathname: url.pathname, params }, children: compose(/* @__PURE__ */ jsx(Page, { params, data }), layouts) }) }) });
|
|
124
|
+
}
|
|
125
|
+
async function streamPage(p) {
|
|
126
|
+
const shell = await renderToReadableStream(
|
|
127
|
+
await buildTree(p.route, p.mod, p.params, p.data, p.url, p.head, p.islands),
|
|
128
|
+
{ onError: (err) => console.error("[kiln] streaming error", err) }
|
|
129
|
+
);
|
|
130
|
+
const doc = assemble(p.template, p.assets, {
|
|
131
|
+
appHtml: MARK_APP,
|
|
132
|
+
title: p.head.title ?? p.fallbackTitle,
|
|
133
|
+
tail: MARK_TAIL
|
|
134
|
+
});
|
|
135
|
+
const [before, after] = doc.split(MARK_APP);
|
|
136
|
+
const encoder = new TextEncoder();
|
|
137
|
+
const body = new ReadableStream({
|
|
138
|
+
async start(controller) {
|
|
139
|
+
try {
|
|
140
|
+
controller.enqueue(encoder.encode(before));
|
|
141
|
+
const reader = shell.getReader();
|
|
142
|
+
for (; ; ) {
|
|
143
|
+
const { done, value } = await reader.read();
|
|
144
|
+
if (done) break;
|
|
145
|
+
controller.enqueue(value);
|
|
146
|
+
}
|
|
147
|
+
const tail = hydrationTail(p.route, p.data, p.islands.size > 0, p.assets);
|
|
148
|
+
controller.enqueue(encoder.encode(after.replace(MARK_TAIL, () => tail)));
|
|
149
|
+
controller.close();
|
|
150
|
+
} catch (err) {
|
|
151
|
+
controller.error(err);
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
});
|
|
155
|
+
const headers = new Headers({ "content-type": HTML });
|
|
156
|
+
applyCachePolicy(headers, p.mod, p.request);
|
|
157
|
+
return new Response(body, { status: 200, headers });
|
|
158
|
+
}
|
|
159
|
+
function assemble(template, assets, parts) {
|
|
160
|
+
const withHead = template.replace("<!--kiln-head-->", () => assets.head);
|
|
161
|
+
const withApp = withHead.replace("<!--kiln-app-->", () => parts.appHtml);
|
|
162
|
+
const withTail = withApp.replace("<!--kiln-data-->", () => parts.tail);
|
|
163
|
+
return setTitle(withTail, parts.title);
|
|
164
|
+
}
|
|
165
|
+
function setTitle(template, title) {
|
|
166
|
+
const tag = `<title>${escapeHtml(title)}</title>`;
|
|
167
|
+
return /<title>[\s\S]*?<\/title>/i.test(template) ? template.replace(/<title>[\s\S]*?<\/title>/i, () => tag) : template.replace("</head>", () => `${tag}
|
|
168
|
+
</head>`);
|
|
169
|
+
}
|
|
170
|
+
function hydrationTail(route, data, islands, assets) {
|
|
171
|
+
if (route.mode === "server" && !islands) return "";
|
|
172
|
+
const payload = {
|
|
173
|
+
mode: route.mode,
|
|
174
|
+
pattern: route.pattern,
|
|
175
|
+
data: route.mode === "universal" ? data : null,
|
|
176
|
+
islands
|
|
177
|
+
};
|
|
178
|
+
return `<script>window.__KILN__ = ${serialize(payload)};</script><script type="module" src="${assets.entry}"></script>`;
|
|
179
|
+
}
|
|
180
|
+
function applyCachePolicy(headers, mod, request) {
|
|
181
|
+
if (!mod || typeof mod.revalidate !== "number") return;
|
|
182
|
+
headers.set("vary", "Cookie");
|
|
183
|
+
if (request.headers.has("cookie")) {
|
|
184
|
+
headers.set("cache-control", "private, no-store");
|
|
185
|
+
return;
|
|
186
|
+
}
|
|
187
|
+
const seconds = Math.max(0, Math.floor(mod.revalidate));
|
|
188
|
+
headers.set("cache-control", `public, s-maxage=${seconds}, stale-while-revalidate=${seconds * 10}`);
|
|
189
|
+
}
|
|
190
|
+
async function actionResponse(request, url, params, mod) {
|
|
191
|
+
if (!mod?.action) return new Response("Method Not Allowed", { status: 405, headers: { allow: "GET, HEAD" } });
|
|
192
|
+
const origin = request.headers.get("origin");
|
|
193
|
+
if (origin && origin !== url.origin) return new Response("Forbidden", { status: 403 });
|
|
194
|
+
const result = await mod.action({ params, request });
|
|
195
|
+
if (result instanceof Response) return result;
|
|
196
|
+
if (wantsJson(request)) return Response.json(result ?? { ok: true });
|
|
197
|
+
return new Response(null, { status: 303, headers: { location: url.pathname } });
|
|
198
|
+
}
|
|
199
|
+
async function renderSpecial(special, props, status, request, url, ctx) {
|
|
200
|
+
const mod = await special.load();
|
|
201
|
+
const layouts = await Promise.all(special.layouts.map((l) => l().then((m) => m.default)));
|
|
202
|
+
const head = {};
|
|
203
|
+
const Page = mod.default;
|
|
204
|
+
const appHtml = renderToString(
|
|
205
|
+
/* @__PURE__ */ jsx(HeadProvider, { value: head, children: /* @__PURE__ */ jsx(RouteProvider, { value: { pathname: url.pathname, params: {} }, children: compose(/* @__PURE__ */ jsx(Page, { ...props }), layouts) }) })
|
|
206
|
+
);
|
|
207
|
+
const page = assemble(await ctx.template(), await ctx.assets(), {
|
|
208
|
+
appHtml,
|
|
209
|
+
title: head.title ?? ctx.defaultTitle ?? "Kiln App",
|
|
210
|
+
tail: ""
|
|
211
|
+
});
|
|
212
|
+
return new Response(request.method === "HEAD" ? null : page, {
|
|
213
|
+
status,
|
|
214
|
+
headers: { "content-type": HTML, "cache-control": "no-store" }
|
|
215
|
+
});
|
|
216
|
+
}
|
|
217
|
+
async function notFoundResponse(request, url, ctx, specials) {
|
|
218
|
+
const special = pickSpecial(specials.notFounds, url.pathname);
|
|
219
|
+
if (special) return renderSpecial(special, {}, 404, request, url, ctx);
|
|
220
|
+
return new Response(await ctx.notFound(), { status: 404, headers: { "content-type": HTML } });
|
|
221
|
+
}
|
|
222
|
+
async function errorPageOr(err, request, url, ctx, specials) {
|
|
223
|
+
if (err instanceof HttpError || isDev()) throw err;
|
|
224
|
+
const special = pickSpecial(specials.errors, url.pathname);
|
|
225
|
+
if (!special) throw err;
|
|
226
|
+
const requestId = Math.random().toString(36).slice(2, 10);
|
|
227
|
+
console.error(`[kiln] ${request.method} ${url.pathname} [${requestId}]`, err);
|
|
228
|
+
return renderSpecial(special, { status: 500, error: { message: "Internal Server Error", requestId } }, 500, request, url, ctx);
|
|
229
|
+
}
|
|
230
|
+
async function httpErrorResponse(err, request, url, ctx) {
|
|
231
|
+
if (url.pathname.startsWith("/api/") || wantsJson(request)) {
|
|
232
|
+
return Response.json({ error: err.message }, { status: err.status });
|
|
233
|
+
}
|
|
234
|
+
if (err.status === 404) return notFoundResponse(request, url, ctx, await loadSpecials(ctx));
|
|
235
|
+
const body = `<!doctype html><meta charset="utf-8"><title>${err.status}</title><h1>${err.status}</h1><p>${escapeHtml(err.message)}</p>`;
|
|
236
|
+
return new Response(request.method === "HEAD" ? null : body, {
|
|
237
|
+
status: err.status,
|
|
238
|
+
headers: { "content-type": HTML, "cache-control": "no-store" }
|
|
239
|
+
});
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
// packages/server/src/template.ts
|
|
151
243
|
var defaultTemplate = `<!doctype html>
|
|
152
244
|
<html lang="en">
|
|
153
245
|
<head>
|
|
@@ -162,28 +254,37 @@ var defaultTemplate = `<!doctype html>
|
|
|
162
254
|
</body>
|
|
163
255
|
</html>`;
|
|
164
256
|
|
|
165
|
-
// src/app.ts
|
|
166
|
-
|
|
167
|
-
|
|
257
|
+
// packages/server/src/app.ts
|
|
258
|
+
var injected = (key) => globalThis[key];
|
|
259
|
+
function createAppHandler(options) {
|
|
260
|
+
const routes = options.routes ?? injected("__KILN_ROUTES__");
|
|
168
261
|
if (!routes) {
|
|
169
262
|
throw new Error("No routes found. Pass createAppHandler({ routes, assets }) or run through the Kiln plugin.");
|
|
170
263
|
}
|
|
171
|
-
|
|
172
|
-
}
|
|
173
|
-
function createAppHandler(options) {
|
|
174
|
-
const routes = options.routes ?? injectedRoutes();
|
|
175
|
-
const api = options.api ?? globalThis.__KILN_API__ ?? [];
|
|
264
|
+
const api = options.api ?? injected("__KILN_API__") ?? [];
|
|
265
|
+
const specials = options.specials ?? injected("__KILN_SPECIALS__") ?? { errors: [], notFounds: [] };
|
|
176
266
|
return createHandler({
|
|
177
267
|
manifest: async () => routes,
|
|
178
268
|
api: async () => api,
|
|
269
|
+
specials: async () => specials,
|
|
179
270
|
template: async () => options.template ?? defaultTemplate,
|
|
180
271
|
assets: async () => options.assets,
|
|
181
272
|
notFound: async () => options.notFound ?? "<h1>404: Not found</h1>",
|
|
182
273
|
defaultTitle: options.defaultTitle ?? "Kiln App"
|
|
183
274
|
});
|
|
184
275
|
}
|
|
276
|
+
|
|
277
|
+
// packages/server/src/index.ts
|
|
278
|
+
import { HttpError as HttpError2, notFound, forbidden, redirect, island, defer, Await } from "@kiln-js/core";
|
|
185
279
|
export {
|
|
280
|
+
Await,
|
|
281
|
+
HttpError2 as HttpError,
|
|
186
282
|
createAppHandler,
|
|
187
283
|
createHandler,
|
|
188
|
-
defaultTemplate
|
|
284
|
+
defaultTemplate,
|
|
285
|
+
defer,
|
|
286
|
+
forbidden,
|
|
287
|
+
island,
|
|
288
|
+
notFound,
|
|
289
|
+
redirect
|
|
189
290
|
};
|
package/dist/types.d.ts
CHANGED
|
@@ -4,9 +4,12 @@ export interface LoaderContext {
|
|
|
4
4
|
params: Record<string, string>;
|
|
5
5
|
request: Request;
|
|
6
6
|
}
|
|
7
|
+
export type ActionContext = LoaderContext;
|
|
7
8
|
export interface PageModule {
|
|
8
9
|
default: ComponentType<any>;
|
|
9
10
|
loader?: (ctx: LoaderContext) => unknown;
|
|
11
|
+
action?: (ctx: ActionContext) => unknown;
|
|
12
|
+
revalidate?: number;
|
|
10
13
|
}
|
|
11
14
|
export interface LayoutModule {
|
|
12
15
|
default: ComponentType<any>;
|
|
@@ -17,6 +20,17 @@ export interface RouteEntry {
|
|
|
17
20
|
load: (() => Promise<PageModule>) | null;
|
|
18
21
|
layouts: (() => Promise<LayoutModule>)[];
|
|
19
22
|
}
|
|
23
|
+
export interface SpecialRoute {
|
|
24
|
+
pattern: string;
|
|
25
|
+
load: () => Promise<{
|
|
26
|
+
default: ComponentType<any>;
|
|
27
|
+
}>;
|
|
28
|
+
layouts: (() => Promise<LayoutModule>)[];
|
|
29
|
+
}
|
|
30
|
+
export interface Specials {
|
|
31
|
+
errors: SpecialRoute[];
|
|
32
|
+
notFounds: SpecialRoute[];
|
|
33
|
+
}
|
|
20
34
|
export interface ApiContext {
|
|
21
35
|
params: Record<string, string>;
|
|
22
36
|
request: Request;
|
|
@@ -35,6 +49,7 @@ export interface KilnAssets {
|
|
|
35
49
|
export interface KilnContext {
|
|
36
50
|
manifest(): Promise<RouteEntry[]>;
|
|
37
51
|
api?(): Promise<ApiRoute[]>;
|
|
52
|
+
specials?(): Promise<Specials>;
|
|
38
53
|
template(): Promise<string>;
|
|
39
54
|
assets(): Promise<KilnAssets>;
|
|
40
55
|
notFound(): Promise<string>;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kiln-js/server",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.4",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"exports": {
|
|
6
6
|
".": {
|
|
@@ -17,7 +17,7 @@
|
|
|
17
17
|
"typecheck": "tsc -p tsconfig.json --noEmit"
|
|
18
18
|
},
|
|
19
19
|
"dependencies": {
|
|
20
|
-
"@kiln-js/core": "^0.1.
|
|
20
|
+
"@kiln-js/core": "^0.1.5"
|
|
21
21
|
},
|
|
22
22
|
"peerDependencies": {
|
|
23
23
|
"react": "\u003e=18",
|