Skip to content

Commit

Permalink
feat: harmonize print address infos util api
Browse files Browse the repository at this point in the history
  • Loading branch information
JulianCataldo committed Aug 6, 2024
1 parent 74e9673 commit 315ed00
Show file tree
Hide file tree
Showing 8 changed files with 34 additions and 93 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@
<link rel="icon" type="image/svg" href="/favicon.svg" />

<title>Gracile Contact</title>
<script type="module" crossorigin src="/assets/index-Bo3GL0oc.js"></script>
<script type="module" crossorigin src="/assets/index-CzX5SsJy.js"></script>
<link rel="modulepreload" crossorigin href="/assets/document.client-Cca60DWw.js">
<link rel="stylesheet" crossorigin href="/assets/document-aADsc6DG.css">
</head>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,7 @@ const routeAssets = new Map([
],
[
"/contact/",
"\t<script type=\"module\" crossorigin src=\"/assets/index-Bo3GL0oc.js\"></script>\n\n\t<link rel=\"modulepreload\" crossorigin href=\"/assets/document.client-Cca60DWw.js\">\n\n\t<link rel=\"stylesheet\" crossorigin href=\"/assets/document-aADsc6DG.css\">\n"
"\t<script type=\"module\" crossorigin src=\"/assets/index-CzX5SsJy.js\"></script>\n\n\t<link rel=\"modulepreload\" crossorigin href=\"/assets/document.client-Cca60DWw.js\">\n\n\t<link rel=\"stylesheet\" crossorigin href=\"/assets/document-aADsc6DG.css\">\n"
],
[
"/foo/bar/",
Expand All @@ -184,7 +184,7 @@ const routeAssets = new Map([
],
[
"/throws/",
"\t<script type=\"module\" crossorigin src=\"/assets/index-CzX5SsJy.js\"></script>\n\n\t<link rel=\"modulepreload\" crossorigin href=\"/assets/document.client-Cca60DWw.js\">\n\n\t<link rel=\"stylesheet\" crossorigin href=\"/assets/document-aADsc6DG.css\">\n"
"\t<script type=\"module\" crossorigin src=\"/assets/index-Bo3GL0oc.js\"></script>\n\n\t<link rel=\"modulepreload\" crossorigin href=\"/assets/document.client-Cca60DWw.js\">\n\n\t<link rel=\"stylesheet\" crossorigin href=\"/assets/document-aADsc6DG.css\">\n"
]
]);

Expand Down
4 changes: 3 additions & 1 deletion integration/__fixtures__/server-express/express.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ app.use((_req, res, next) => {

app.use(gracile.nodeAdapter(handler));

const server = app.listen(9874, () => gracile.printAddressInfos({ server }));
const server = app.listen(9874, () =>
gracile.printAddressInfos(server.address()),
);

export { server };
4 changes: 2 additions & 2 deletions integration/__fixtures__/server-express/hono.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,6 @@ app.use((c, next) => {

app.use(gracile.honoAdapter(handler));

serve({ fetch: app.fetch, port: 9874, hostname: 'localhost' }, (server) =>
gracile.printAddressInfos(server),
serve({ fetch: app.fetch, port: 9874, hostname: 'localhost' }, (address) =>
gracile.printAddressInfos(address),
);
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@
<link rel="icon" type="image/svg" href="/favicon.svg" />

<title>Gracile Contact</title>
<script type="module" crossorigin src="/assets/index-Bo3GL0oc.js"></script>
<script type="module" crossorigin src="/assets/index-CzX5SsJy.js"></script>
<link
rel="modulepreload"
crossorigin
Expand Down
10 changes: 10 additions & 0 deletions integration/src/env.d.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,13 @@
/// <reference types="@gracile/gracile/ambient" />
/// <reference types="@gracile/markdown/ambient" />
/// <reference types="@gracile/svg/ambient" />

declare namespace Gracile {
interface Locals {
requestId: import('node:crypto').UUID;
userEmail: string | null;
}
}
declare namespace Express {
interface Locals extends Gracile.Locals {}
}
5 changes: 4 additions & 1 deletion integration/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,14 @@
//
"./src/**/*.ts",
"./src/env.d.ts",
"./__fixtures__/**/*.ts"
"./__fixtures__/**/*.d.ts",
"./__fixtures__/**/*.ts",
"./__fixtures__/**/*.js"
],
"compilerOptions": {
"noEmit": true,

// "checkJs": true,
"experimentalDecorators": true,
"useDefineForClassFields": false
}
Expand Down
96 changes: 11 additions & 85 deletions packages/engine/src/server/utils.ts
Original file line number Diff line number Diff line change
@@ -1,111 +1,37 @@
// NOTE: Util. to pretty print for user provided server.

import type { IncomingMessage, Server, ServerResponse } from 'node:http';
import type { AddressInfo } from 'node:net';

// import type { AddressInfo } from 'node:net';
import { logger } from '@gracile/internal-utils/logger';
import { DEV } from 'esm-env';
import c from 'picocolors';

import { IP_EXPOSED } from './env.js';

export function printAddressInfos(options: {
server?: Server;
address?: string;
port?: number;
}) {
export function printAddressInfos(server: string | AddressInfo | null) {
let address: null | string = null;

if (options.server) {
const infos = options.server.address();

if (typeof infos === 'object' && infos && infos.port && infos.address) {
address = `http://${infos.address}:${infos.port}/`;
}
} else if (options.address) {
address = `http://${options.address}${options.port ? `:${String(options.port)}` : ''}`;
if (!server) throw new Error('Incorrect address infos');
if (typeof server === 'string') {
address = server;
} else {
address = `http://${server.address}${server.port ? `:${String(server.port)}` : ''}`;
}
if (!address) throw new Error('Incorrect options');

logger.info(c.green(`${DEV ? 'development' : 'production'} server started`), {
timestamp: true,
});

if (address?.includes(IP_EXPOSED))
if (address.includes(IP_EXPOSED))
logger.info(
`${
address?.includes(IP_EXPOSED)
? `\n${c.dim('┃')} Network ${c.cyan(address)}`
address.includes(IP_EXPOSED)
? `\n${c.dim('┃')} Network ${c.cyan(address)}\n`
: ''
}`,
);
else
logger.info(
`
${c.dim('┃')} Local ${c.cyan(address.replace(/::1?/, 'localhost'))}`,
${c.dim('┃')} Local ${c.cyan(address.replace(/::1?/, 'localhost'))}\n`,
);
}

// NOTE: UNUSED (keep?)
function sendHtml(res: ServerResponse, payload: unknown) {
res.setHeader('content/type', 'text/html');
res.end(payload);
}
function fallback404(res: ServerResponse) {
return sendHtml(res, '404 — Not found!');
}
export function notFoundHandler(req: IncomingMessage, res: ServerResponse) {
const host = req.headers.host;
if (!host) {
fallback404(res);
return;
}

const url = new URL('/404/', `http://${host}`);

fetch(url)
.then((t) => t.text())
.then((r) => sendHtml(res, r))
.catch(() => fallback404(res));
}

export type LocalMiddlewareContext = {
request: Request;
response: ResponseInit;
};

// NOTE: NOT EXPOSED FOR NOW. Maybe just put in docs.
export type BasicAuthUser = { userName: string | null };

/**
* @param context
* @returns
*/
export const authenticateBasic = (
context: LocalMiddlewareContext,
validate: (user: { name: string; pass: string }) => boolean,
): BasicAuthUser => {
const b64 = context.request.headers.get('authorization')?.split(' ')?.[1];

if (b64) {
const [name, pass] = Buffer.from(b64, 'base64').toString().split(':');
if (name && pass) {
validate({ name, pass });

return { userName: name };
}
}

/**
* Authentication failed
*/
context.response.headers = new Headers({
...context.response.headers,
'WWW-Authenticate': 'Basic',
});

context.response.status = 401;
context.response.statusText = 'You are not authenticated!';

return { userName: null };
};

0 comments on commit 315ed00

Please sign in to comment.