Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: misc perf improvements #2

Merged
merged 2 commits into from
Jan 21, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file modified bun.lockb
Binary file not shown.
3 changes: 1 addition & 2 deletions src/decorators.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { HTMLTemplateString } from "./html";
import { Route, RouteResponse } from "./route";

export function cache(component?: "head" | "body") {
Expand All @@ -8,7 +7,7 @@ export function cache(component?: "head" | "body") {
super(...args);

// TODO: this.data() support?
let head: HTMLTemplateString, body: RouteResponse;
let head: string, body: RouteResponse;

if (this.head && (!component || component == "head")) {
head = this.head({});
Expand Down
3 changes: 1 addition & 2 deletions src/exports.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { Server } from "bun";
export { default as html } from "./html";
export type { HTMLTemplateString } from "./html";
export { html, meta } from "./html";
export * from "./route";
export * from "./error";
export * from "./ws";
Expand Down
49 changes: 36 additions & 13 deletions src/html.ts
Original file line number Diff line number Diff line change
@@ -1,25 +1,30 @@
export type HTMLTemplateString = {
value: string;
export type MetaParams = {
title: string;
description?: string;
imageURL?: string;
omitDefaultTags?: boolean; // omit UTF-8 & viewport tags
};

const defaultTags = html`
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
`;

// prettier-ignore
const _ws = '<script>let ws;let _b=1000;let _r=false;let _c=[];function _ws(){ws=new WebSocket("ws"+window.location.href.slice(4),_r?"reconnect":undefined);_r=true;if(_c.length>0){_c.forEach(e=>ws.addEventListener(...e))}ws.onopen=function(){_b=1000};ws.onmessage=function(e){if(e.data=="reload"){+`${new Date("3")}`[8]?window.location.reload():window.location.href=window.location.href}};ws.onclose=function(){setTimeout(()=>{_b*=2;_ws()},_b)}}_ws();const b=ws.addEventListener;ws.addEventListener=function(x,y,z){_c.push([x,y,z]);b.call(ws,x,y,z)}</script>';

export function page(head: HTMLTemplateString, body: HTMLTemplateString, ws: boolean): string {
return `<!DOCTYPE html><html lang="en"><head>${head.value}</head><body>${ws ? _ws : ""}${body.value}</body></html>`;
export function page(head: string, body: string, ws: boolean): string {
return `<!DOCTYPE html><html lang="en"><head>${head}</head><body>${ws ? _ws : ""}${body}</body></html>`;
}

export default function (strings: TemplateStringsArray, ...values: unknown[]): HTMLTemplateString {
export function html(strings: TemplateStringsArray, ...values: unknown[]): string {
let html = "";
for (let i = 0; i < strings.length; i++) {
if (i > 0) {
let value = values[i - 1];
let asHTML = value as HTMLTemplateString;

if (asHTML.value) {
html += asHTML.value;
} else if (value instanceof Array) {
html += value.map((e) => e.value).join("");
if (value instanceof Array) {
html += value.join("");
} else {
html += value;
}
Expand All @@ -28,7 +33,25 @@ export default function (strings: TemplateStringsArray, ...values: unknown[]): H
html += strings[i];
}

return {
value: html,
};
return html;
}

export function meta(params: MetaParams) {
const description = params.description || "";
const imageURL = params.imageURL || "";

return html`
${!params.omitDefaultTags ? defaultTags : ""}
<title>${params.title}</title>
<meta name="title" content="${params.title}" />
<meta name="description" content="${description}" />
<meta property="og:type" content="website" />
<meta property="og:title" content="${params.title}" />
<meta property="og:description" content="${description}" />
<meta property="og:image" content="${imageURL}" />
<meta property="twitter:card" content="summary_large_image" />
<meta property="twitter:title" content="${params.title}" />
<meta property="twitter:description" content="${description}" />
<meta property="twitter:image" content="${imageURL}" />
`;
}
48 changes: 15 additions & 33 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { watch } from "fs";
import path from "path";
import { ZodError } from "zod";
import { RouteError, ZodErrorWithMessage } from "./error";
import html, { HTMLTemplateString, page } from "./html";
import { page } from "./html";
import { Route } from "./route";
import { generateFile, parseBoolean, walk } from "./utils";
import { MatchedRoute, Server, ServerWebSocket } from "bun";
Expand Down Expand Up @@ -77,10 +77,6 @@ if (env == "dev") {
}

const notFound = pages.get("404.ts");
const defaultHead = html`
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
`;

type Ctx = {
match: MatchedRoute | null;
Expand Down Expand Up @@ -204,20 +200,13 @@ async function request(req: Request, ctx: Ctx): Promise<Response> {
return body;
}

let head = ctx.route.head ? ctx.route.head(data, err) : null;

return new Response(
page(
head ? html`${defaultHead.value}${head.value}` : defaultHead,
body,
ctx.route.ws != undefined || env == "dev"
),
{
headers: {
"Content-Type": "text/html; charset=utf-8",
},
}
);
let head = ctx.route.head ? ctx.route.head(data, err) : "";

return new Response(page(head, body, ctx.route.ws != undefined || env == "dev"), {
headers: {
"Content-Type": "text/html; charset=utf-8",
},
});
} catch (err: any) {
if (err instanceof RouteError && err.redirect) {
console.error(`❌ [${err.name}] ${ctx.pathname} ${err.message}`);
Expand Down Expand Up @@ -246,24 +235,17 @@ async function request(req: Request, ctx: Ctx): Promise<Response> {
}

if (notFound && notFound.body) {
const head = notFound.head ? notFound.head(null) : null;
const head = notFound.head ? notFound.head(null) : "";
const body = notFound.body(null);

if (body instanceof Response) return body;

return new Response(
page(
head ? html`${defaultHead.value}${head.value}` : defaultHead,
body as unknown as HTMLTemplateString,
notFound.ws != undefined || env == "dev"
),
{
headers: {
"Content-Type": "text/html; charset=utf-8",
},
status: 404,
}
);
return new Response(page(head, body as string, notFound.ws != undefined || env == "dev"), {
headers: {
"Content-Type": "text/html; charset=utf-8",
},
status: 404,
});
} else {
return new Response("", {
status: 404,
Expand Down
5 changes: 2 additions & 3 deletions src/route.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
import { MatchedRoute, ServerWebSocket } from "bun";
import { HTMLTemplateString } from "./html";
import { z } from "zod";
import { WebSocketContext } from "./ws";

export type Resolved<T> = T extends Promise<infer R> ? R : T;
// @ts-ignore
export type Data<T extends Route> = Resolved<ReturnType<T["data"]>>;
export type RouteResponse = HTMLTemplateString | Response;
export type RouteResponse = string | Response;

export interface RouteWebSocket {
open?: (ws: ServerWebSocket<WebSocketContext>) => void | Promise<void>;
Expand All @@ -17,7 +16,7 @@ export interface RouteWebSocket {
export interface Route {
data?(req: Request, route: MatchedRoute): any;
ws?(): RouteWebSocket;
head?<T extends Route>(data: Data<T>, err?: Error): HTMLTemplateString;
head?<T extends Route>(data: Data<T>, err?: Error): string;
body?<T extends Route>(data: Data<T>, err?: Error): RouteResponse;
}

Expand Down
6 changes: 3 additions & 3 deletions tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
"allowJs": true,
"noEmit": true,
"types": [
"bun-types" // add Bun global
]
}
"bun-types", // add Bun global
],
},
}