Skip to content

Commit

Permalink
enable ssr, improve server
Browse files Browse the repository at this point in the history
  • Loading branch information
inetol committed Aug 17, 2024
1 parent ed3f42a commit d59e64f
Show file tree
Hide file tree
Showing 6 changed files with 47 additions and 39 deletions.
Binary file modified bun.lockb
Binary file not shown.
7 changes: 4 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@
"postbuild:compress": "bun run ./scripts/compress.ts",
"start": "bun run start:server",
"start:dev": "bun vite",
"start:server": "bun run build:standalone && NODE_ENV=production bun run --cwd=./dist/ ./server/index.js"
"start:force": "bun run build && bun run start:server",
"start:server": "NODE_ENV=production bun run --cwd=./dist/ ./server/index.js"
},
"dependencies": {
"@swc/core": "~1.7.11",
Expand All @@ -44,13 +45,13 @@
"typescript": "~5.5.4",
"vike": "~0.4.184",
"vike-node": "~0.1.14",
"vike-react": "~0.5.2",
"vike-react": "~0.5.3",
"vite": "~5.4.1",
"zustand": "~4.5.5"
},
"devDependencies": {
"@biomejs/biome": "~1.8.3",
"lefthook": "~1.7.12",
"lefthook": "~1.7.13",
"sort-package-json": "~2.10.0"
},
"trustedDependencies": [
Expand Down
4 changes: 3 additions & 1 deletion src/components/modals/settings/Settings.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import ThemeSection from '@x-component/modals/settings/ThemeSection';
import { themeStore } from '@x-util/store';
import { clientOnly } from 'vike-react/clientOnly';

const ThemeSection = clientOnly(() => import('@x-component/modals/settings/ThemeSection'));

export default function () {
const { getTheme } = themeStore();
Expand Down
2 changes: 1 addition & 1 deletion src/pages/(editor)/+config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,5 @@ export default {
title: siteManifest.siteTitle,
description: siteManifest.description,
clientRouting: false,
ssr: false
ssr: true
} satisfies Config;
70 changes: 37 additions & 33 deletions src/server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,69 +4,73 @@ import { renderPage } from 'vike/server';
import { logger } from './logger.ts';
import { loadMemory, memory } from './memory.ts';

const encodings = {
br: '.br',
zstd: '.zst',
gzip: '.gz'
type Encoding = 'br' | 'zstd' | 'gzip';

const encodings: Record<Encoding, { extension: string; weight: number }> = {
br: { extension: '.br', weight: 0 },
zstd: { extension: '.zst', weight: 1 },
gzip: { extension: '.gz', weight: 2 }
};

const port = process.env.PORT ? Number.parseInt(process.env.PORT, 10) : 3000;

logger.set(2);

const staticDirectory = 'client/';
const staticDirectory = ['client/'];

logger.info(`Preloading memory from: "${staticDirectory}"`);
await loadMemory(staticDirectory);
for (const directory of staticDirectory) {
logger.info(`Preloading memory from: "${directory}"`);
await loadMemory(directory);
}

logger.info(`Listening on http://localhost:${port}`);

// TODO: 103 Early Hints -> https://github.com/oven-sh/bun/issues/8690
export default {
async fetch(req) {
const url = new URL(req.url);
const reqURL = new URL(req.url);

// Static files
if (Object.hasOwn(memory, url.pathname)) {
const acceptEncoding = req.headers.get('Accept-Encoding');
let selectedEncoding: keyof typeof encodings | undefined;

if (acceptEncoding) {
for (const encoding of acceptEncoding.split(',').map((encoding) => encoding.trim())) {
for (const [availableEncoding, extension] of Object.entries(encodings)) {
if (availableEncoding !== encoding) continue;

if (Object.hasOwn(memory, url.pathname + extension)) {
selectedEncoding = availableEncoding as keyof typeof encodings;
break;
}
}
}
}

if (Object.hasOwn(memory, reqURL.pathname)) {
const headers: HeadersInit = {
'Content-Type': mime.getType(url.pathname) || 'application/octet-stream'
'Content-Type': mime.getType(reqURL.pathname) || 'application/octet-stream'
};

if (selectedEncoding) {
headers['Content-Encoding'] = selectedEncoding;
const acceptEncodings =
req.headers
.get('Accept-Encoding')
?.split(',')
.map((encoding) => encoding.trim())
.filter((encoding): encoding is Encoding => Object.hasOwn(encodings, encoding))
.sort((a, b) => encodings[a].weight - encodings[b].weight) || [];

for (const acceptEncoding of acceptEncodings) {
if (!Object.hasOwn(encodings, acceptEncoding)) continue;

const extension = encodings[acceptEncoding as keyof typeof encodings].extension;

if (Object.hasOwn(memory, reqURL.pathname + extension)) {
headers['Content-Encoding'] = acceptEncoding;
reqURL.pathname += extension;
break;
}
}

if (url.pathname.startsWith('/assets/')) {
if (reqURL.pathname.startsWith('/assets/')) {
headers['Cache-Control'] = 'public, max-age=31536000, immutable';
} else {
headers['Cache-Control'] = 'public, max-age=3600, no-transform';
}

logger.debug(req.method, url.pathname + (selectedEncoding ? encodings[selectedEncoding] : ''));
logger.debug(req.method, reqURL.pathname);

return new Response(memory[url.pathname + (selectedEncoding ? encodings[selectedEncoding] : '')], {
return new Response(memory[reqURL.pathname], {
headers: headers
});
}

// Dynamic pages
const pageContext = await renderPage({ urlOriginal: url.href });
const pageContext = await renderPage({ urlOriginal: reqURL.href });
const response = pageContext.httpResponse;

if (!response) {
Expand All @@ -77,7 +81,7 @@ export default {

response.pipe(writable);

logger.debug(req.method, url.pathname);
logger.debug(req.method, reqURL.pathname);

return new Response(readable, {
status: response.statusCode,
Expand Down
3 changes: 2 additions & 1 deletion vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@ export default {
target: 'es2022',
rollupOptions: {
external: ['bun']
}
},
reportCompressedSize: false
},
resolve: {
alias: {
Expand Down

0 comments on commit d59e64f

Please sign in to comment.