@@ -1,58 +0,0 @@
|
||||
export const snapshot = {};
|
||||
|
||||
snapshot[`createCodeFrame markers 1`] = `
|
||||
"
|
||||
1 | foo
|
||||
> 2 | bar
|
||||
| ^
|
||||
3 | baz
|
||||
"
|
||||
`;
|
||||
|
||||
snapshot[`createCodeFrame markers 2`] = `
|
||||
"
|
||||
> 1 | foo
|
||||
| ^
|
||||
2 | bar
|
||||
3 | baz
|
||||
"
|
||||
`;
|
||||
|
||||
snapshot[`createCodeFrame markers 3`] = `
|
||||
"
|
||||
1 | foo
|
||||
2 | bar
|
||||
> 3 | baz
|
||||
| ^
|
||||
"
|
||||
`;
|
||||
|
||||
snapshot[`createCodeFrame markers 4`] = `
|
||||
"
|
||||
7 |
|
||||
8 |
|
||||
> 9 | bar
|
||||
| ^
|
||||
10 |
|
||||
11 |
|
||||
12 | bar
|
||||
"
|
||||
`;
|
||||
|
||||
snapshot[`createCodeFrame with indentation 1`] = `
|
||||
"
|
||||
1 | foo
|
||||
> 2 | bar
|
||||
| ^
|
||||
3 | baz
|
||||
"
|
||||
`;
|
||||
|
||||
snapshot[`createCodeFrame with indentation 2`] = `
|
||||
"
|
||||
1 | foo
|
||||
> 2 | bar
|
||||
| ^
|
||||
3 | baz
|
||||
"
|
||||
`;
|
||||
@@ -1,31 +0,0 @@
|
||||
export const snapshot = {};
|
||||
|
||||
snapshot[`serializer - primitives & plain objects 1`] = `'{"v":{"a":1,"b":"2","c":true,"d":null,"f":[1,2,3],"g":{"a":1,"b":2,"c":3}}}'`;
|
||||
|
||||
snapshot[`serializer - bigint 1`] = `'{"v":{"a":{"_f":"b","d":"999999999999999999"}}}'`;
|
||||
|
||||
snapshot[`serializer - Uint8Array 1`] = `'{"v":{"a":{"_f":"u8a","d":"AQID"}}}'`;
|
||||
|
||||
snapshot[`serializer - signals 1`] = `'{"v":{"a":1,"b":{"_f":"s","v":2}}}'`;
|
||||
|
||||
snapshot[`serializer - @preact/signals-core 1.2.3 1`] = `'{"v":{"a":1,"b":{"_f":"s","v":2}}}'`;
|
||||
|
||||
snapshot[`serializer - @preact/signals-core 1.3.0 1`] = `'{"v":{"a":1,"b":{"_f":"s","v":2}}}'`;
|
||||
|
||||
snapshot[`serializer - multiple versions of @preact/signals-core 1`] = `'{"v":{"a":1,"b":{"_f":"s","v":2},"c":{"_f":"s","v":2},"d":{"_f":"s","v":2}}}'`;
|
||||
|
||||
snapshot[`serializer - magic key 1`] = `'{"v":{"_f":"l","k":"f","v":{"a":1}}}'`;
|
||||
|
||||
snapshot[`serializer - circular reference objects 1`] = `'{"v":{"a":1,"b":0},"r":[[[],["b"]]]}'`;
|
||||
|
||||
snapshot[`serializer - circular reference nested objects 1`] = `'{"v":{"a":1,"b":{"c":2,"d":0}},"r":[[[],["b","d"]]]}'`;
|
||||
|
||||
snapshot[`serializer - circular reference array 1`] = `'{"v":[1,2,3,0],"r":[[[],["3"]]]}'`;
|
||||
|
||||
snapshot[`serializer - multiple reference 1`] = `'{"v":{"a":1,"b":{"c":2},"d":0},"r":[[["b"],["d"]]]}'`;
|
||||
|
||||
snapshot[`serializer - multiple reference signals 1`] = `'{"v":{"inner":{"_f":"l","k":"x","v":{"x":1,"y":0}},"a":{"_f":"s","v":0},"b":{"c":0}},"r":[[["inner"],["inner",null,"y"],["a","value"]],[["a"],["b","c"]]]}'`;
|
||||
|
||||
snapshot[`serializer - multiple reference in magic key 1`] = `'{"v":{"literal":{"_f":"l","k":"x","v":{"inner":{"foo":"bar"}}},"inner":0},"r":[[["literal",null,"inner"],["inner"]]]}'`;
|
||||
|
||||
snapshot[`serializer - multiple reference in signal 1`] = `'{"v":{"s":{"_f":"s","v":{"foo":"bar"}},"inner":0},"r":[[["s","value"],["inner"]]]}'`;
|
||||
@@ -1,125 +0,0 @@
|
||||
import { DENO_DEPLOYMENT_ID } from "./build_id.ts";
|
||||
import { colors } from "./deps.ts";
|
||||
import { ServeHandler } from "./types.ts";
|
||||
|
||||
const defaultOnListenFor = <T>(getAddress: (params: T) => string) => {
|
||||
return (params: T) => {
|
||||
const address = colors.cyan(
|
||||
getAddress(params),
|
||||
);
|
||||
const localLabel = colors.bold("Local:");
|
||||
|
||||
// Print more concise output for deploy logs
|
||||
if (DENO_DEPLOYMENT_ID) {
|
||||
console.log(
|
||||
colors.bgRgb8(colors.rgb8(" 🍋 Fresh ready ", 0), 121),
|
||||
`${localLabel} ${address}`,
|
||||
);
|
||||
} else {
|
||||
console.log();
|
||||
console.log(
|
||||
colors.bgRgb8(colors.rgb8(" 🍋 Fresh ready ", 0), 121),
|
||||
);
|
||||
console.log(` ${localLabel} ${address}\n`);
|
||||
}
|
||||
};
|
||||
};
|
||||
export async function startUnixServer(
|
||||
handler: Deno.ServeUnixHandler,
|
||||
opts: Deno.ServeUnixOptions,
|
||||
) {
|
||||
if (!opts.onListen) {
|
||||
opts.onListen = defaultOnListenFor((params) => {
|
||||
return `socket://${params.path}`;
|
||||
});
|
||||
// @ts-ignore Ignore type error when type checking with Deno versions
|
||||
if (typeof Deno.serve === "function") {
|
||||
await Deno.serve(
|
||||
opts,
|
||||
handler,
|
||||
).finished;
|
||||
}
|
||||
throw new Error(
|
||||
`unix domain sockets are not supported in your current deno version.`,
|
||||
);
|
||||
}
|
||||
}
|
||||
export async function startServer(
|
||||
handler: Deno.ServeHandler,
|
||||
opts: Partial<Deno.ServeTlsOptions> & { basePath: string },
|
||||
) {
|
||||
if (!opts.onListen) {
|
||||
opts.onListen = defaultOnListenFor((params) => {
|
||||
const pathname = opts.basePath + "/";
|
||||
const https = !!(opts.key && opts.cert);
|
||||
const protocol = https ? "https:" : "http:";
|
||||
return `${protocol}//localhost:${params.port}${pathname}`;
|
||||
});
|
||||
}
|
||||
|
||||
const portEnv = Deno.env.get("PORT");
|
||||
if (portEnv !== undefined) {
|
||||
opts.port ??= parseInt(portEnv, 10);
|
||||
}
|
||||
|
||||
if (opts.port) {
|
||||
await bootServer(handler, opts);
|
||||
} else {
|
||||
// No port specified, check for a free port. Instead of picking just
|
||||
// any port we'll check if the next one is free for UX reasons.
|
||||
// That way the user only needs to increment a number when running
|
||||
// multiple apps vs having to remember completely different ports.
|
||||
let firstError;
|
||||
for (let port = 8000; port < 8020; port++) {
|
||||
try {
|
||||
await bootServer(handler, { ...opts, port });
|
||||
firstError = undefined;
|
||||
break;
|
||||
} catch (err) {
|
||||
if (err instanceof Deno.errors.AddrInUse) {
|
||||
// Throw first EADDRINUSE error
|
||||
// if no port is free
|
||||
if (!firstError) {
|
||||
firstError = err;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
if (firstError) {
|
||||
throw firstError;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function bootServer(
|
||||
handler: ServeHandler,
|
||||
opts: Partial<Deno.ServeTlsOptions>,
|
||||
) {
|
||||
// @ts-ignore Ignore type error when type checking with Deno versions
|
||||
if (typeof Deno.serve === "function") {
|
||||
// @ts-ignore Ignore type error when type checking with Deno versions
|
||||
await Deno.serve(
|
||||
opts,
|
||||
(r, info) =>
|
||||
handler(
|
||||
r,
|
||||
{
|
||||
...info,
|
||||
remoteAddr: info.remoteAddr,
|
||||
localAddr: {
|
||||
transport: "tcp",
|
||||
hostname: opts.hostname ?? "localhost",
|
||||
port: opts.port,
|
||||
} as Deno.NetAddr,
|
||||
},
|
||||
),
|
||||
).finished;
|
||||
} else {
|
||||
// @ts-ignore Deprecated std serve way
|
||||
await serve(handler, opts);
|
||||
}
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
import { encodeHex } from "./deps.ts";
|
||||
|
||||
export const DENO_DEPLOYMENT_ID = Deno.env.get("DENO_DEPLOYMENT_ID");
|
||||
const deploymentId = DENO_DEPLOYMENT_ID ||
|
||||
// For CI
|
||||
Deno.env.get("GITHUB_SHA") ||
|
||||
crypto.randomUUID();
|
||||
const buildIdHash = await crypto.subtle.digest(
|
||||
"SHA-1",
|
||||
new TextEncoder().encode(deploymentId),
|
||||
);
|
||||
|
||||
export let BUILD_ID = encodeHex(buildIdHash);
|
||||
|
||||
export function setBuildId(buildId: string) {
|
||||
BUILD_ID = buildId;
|
||||
}
|
||||
@@ -1,127 +0,0 @@
|
||||
import { colors, fromFileUrl } from "./deps.ts";
|
||||
|
||||
function tabs2Spaces(str: string) {
|
||||
return str.replace(/^\t+/, (tabs) => " ".repeat(tabs.length));
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate an excerpt of the location in the source around the
|
||||
* specified position.
|
||||
*/
|
||||
export function createCodeFrame(
|
||||
text: string,
|
||||
lineNum: number,
|
||||
columnNum: number,
|
||||
): string | undefined {
|
||||
// Default settings
|
||||
const before = 2;
|
||||
const after = 3;
|
||||
|
||||
const lines = text.split("\n");
|
||||
|
||||
// Check if specified range is valid
|
||||
if (lines.length <= lineNum || lines[lineNum].length < columnNum) {
|
||||
return;
|
||||
}
|
||||
|
||||
const start = Math.max(0, lineNum - before);
|
||||
const end = Math.min(lines.length, lineNum + after + 1);
|
||||
|
||||
// Maximum space needed for line numbering in the current range.
|
||||
// Necessary when the amount of digits of the line numbering grows:
|
||||
// 999 | asdf
|
||||
// 1000 | asdjadfjsa
|
||||
const maxLineNum = String(end).length;
|
||||
const padding = " ".repeat(maxLineNum);
|
||||
|
||||
// Normalize all indentation (=tabs) to use 2 spaces. We need to
|
||||
// apply the difference to the marker position to move it back in
|
||||
// place.
|
||||
const spaceLines: string[] = [];
|
||||
let maxLineLen = 0;
|
||||
for (let i = start; i < end; i++) {
|
||||
const line = tabs2Spaces(lines[i]);
|
||||
spaceLines.push(line);
|
||||
|
||||
if (line.length > maxLineLen) maxLineLen = line.length;
|
||||
}
|
||||
|
||||
const activeLine = spaceLines[lineNum - start];
|
||||
// Move marker into correct place by taking the amount of
|
||||
// normalized tabs into account
|
||||
const count = Math.max(
|
||||
0,
|
||||
activeLine.length - lines[lineNum].length + columnNum,
|
||||
);
|
||||
|
||||
const sep = colors.dim("|");
|
||||
let out = "";
|
||||
|
||||
for (let i = 0; i < spaceLines.length; i++) {
|
||||
const line = spaceLines[i];
|
||||
const currentLine = colors.dim(
|
||||
(padding + (i + start + 1)).slice(-maxLineNum),
|
||||
);
|
||||
|
||||
// Line where the error occurred
|
||||
if (i === lineNum - start) {
|
||||
out += colors.red(">") +
|
||||
` ${currentLine} ${sep} ${line}\n`;
|
||||
|
||||
const columnMarker = colors.bold(colors.red("^"));
|
||||
out += ` ${padding} ${sep} ${" ".repeat(count)}${columnMarker}\n`;
|
||||
} else {
|
||||
out += ` ${currentLine} ${sep} ${line}\n`;
|
||||
}
|
||||
}
|
||||
|
||||
return out;
|
||||
}
|
||||
|
||||
const STACK_FRAME = /^\s*at\s+(?:(.*)\s+)?\((.*):(\d+):(\d+)\)$/;
|
||||
export interface StackFrame {
|
||||
fnName: string;
|
||||
file: string;
|
||||
line: number;
|
||||
column: number;
|
||||
}
|
||||
export function getFirstUserFile(stack: string): StackFrame | undefined {
|
||||
const lines = stack.split("\n");
|
||||
for (let i = 0; i < lines.length; i++) {
|
||||
const match = lines[i].match(STACK_FRAME);
|
||||
if (match && match) {
|
||||
const fnName = match[1] ?? "";
|
||||
const file = match[2];
|
||||
const line = +match[3];
|
||||
const column = +match[4];
|
||||
|
||||
if (file.startsWith("file://")) {
|
||||
return {
|
||||
fnName,
|
||||
file,
|
||||
line,
|
||||
column,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export async function getCodeFrame(error: Error) {
|
||||
if (!error.stack) return;
|
||||
|
||||
const file = getFirstUserFile(error.stack);
|
||||
if (file) {
|
||||
try {
|
||||
const filePath = fromFileUrl(file.file);
|
||||
const text = await Deno.readTextFile(filePath);
|
||||
return createCodeFrame(
|
||||
text,
|
||||
file.line - 1,
|
||||
file.column - 1,
|
||||
);
|
||||
} catch {
|
||||
// Ignore
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,57 +0,0 @@
|
||||
import { createCodeFrame, getFirstUserFile } from "./code_frame.ts";
|
||||
import { assertEquals, assertSnapshot, colors } from "./deps.ts";
|
||||
|
||||
function testCodeFrame(text: string, line: number, column: number) {
|
||||
const codeFrame = createCodeFrame(text, line, column);
|
||||
if (codeFrame !== undefined) {
|
||||
return "\n" + colors.stripColor(codeFrame);
|
||||
}
|
||||
return codeFrame;
|
||||
}
|
||||
|
||||
const FILE = `file://example.com/foo.js`;
|
||||
|
||||
Deno.test("getFirstUserFile", () => {
|
||||
let stack = `Some message
|
||||
at asdf.foo (https://example.com/foo.js:8:20)
|
||||
at asdf.foo (${FILE}:8:20)
|
||||
`;
|
||||
assertEquals(getFirstUserFile(stack), {
|
||||
fnName: "asdf.foo",
|
||||
file: FILE,
|
||||
column: 20,
|
||||
line: 8,
|
||||
});
|
||||
|
||||
stack = `Some message
|
||||
at asdf.foo (https://example.com/foo.js:8:20)
|
||||
at (${FILE}:8:20)
|
||||
`;
|
||||
assertEquals(getFirstUserFile(stack), {
|
||||
fnName: "",
|
||||
file: FILE,
|
||||
column: 20,
|
||||
line: 8,
|
||||
});
|
||||
});
|
||||
|
||||
Deno.test("createCodeFrame invalid ranges", () => {
|
||||
assertEquals(createCodeFrame("", 2, 10), undefined);
|
||||
assertEquals(createCodeFrame("asdf", 2, 10), undefined);
|
||||
assertEquals(createCodeFrame("asdf", 1, 10), undefined);
|
||||
});
|
||||
|
||||
Deno.test("createCodeFrame markers", async (t) => {
|
||||
await assertSnapshot(t, testCodeFrame("foo\nbar\nbaz", 1, 2));
|
||||
await assertSnapshot(t, testCodeFrame("foo\nbar\nbaz", 0, 0));
|
||||
await assertSnapshot(t, testCodeFrame("foo\nbar\nbaz", 2, 2));
|
||||
await assertSnapshot(
|
||||
t,
|
||||
testCodeFrame("foo\n\n\n\n\n\n\n\nbar\n\n\nbar", 8, 0),
|
||||
);
|
||||
});
|
||||
|
||||
Deno.test("createCodeFrame with indentation", async (t) => {
|
||||
await assertSnapshot(t, testCodeFrame("foo\n bar\nbaz", 1, 6));
|
||||
await assertSnapshot(t, testCodeFrame("foo\n\t\tbar\nbaz", 1, 2));
|
||||
});
|
||||
@@ -1,126 +0,0 @@
|
||||
import { SEPARATOR } from "./deps.ts";
|
||||
import { ErrorHandler, FinalHandler, RouteResult, withBase } from "./router.ts";
|
||||
import {
|
||||
BaseRoute,
|
||||
FreshContext,
|
||||
MiddlewareRoute,
|
||||
UnknownRenderFunction,
|
||||
} from "./types.ts";
|
||||
|
||||
export const ROOT_BASE_ROUTE = toBaseRoute("/");
|
||||
|
||||
export function toBaseRoute(input: string): BaseRoute {
|
||||
input = input.replaceAll(SEPARATOR, "/");
|
||||
|
||||
if (input.endsWith("_layout")) {
|
||||
input = input.slice(0, -"_layout".length);
|
||||
} else if (input.endsWith("_middleware")) {
|
||||
input = input.slice(0, -"_middleware".length);
|
||||
} else if (input.endsWith("index")) {
|
||||
input = input.slice(0, -"index".length);
|
||||
}
|
||||
|
||||
if (input.endsWith("/")) {
|
||||
input = input.slice(0, -1);
|
||||
}
|
||||
|
||||
const suffix = !input.startsWith("/") ? "/" : "";
|
||||
return (suffix + input) as BaseRoute;
|
||||
}
|
||||
|
||||
export function selectSharedRoutes<T extends { baseRoute: BaseRoute }>(
|
||||
curBaseRoute: BaseRoute,
|
||||
items: T[],
|
||||
): T[] {
|
||||
const selected: T[] = [];
|
||||
|
||||
for (const item of items) {
|
||||
const { baseRoute } = item;
|
||||
const res = curBaseRoute === baseRoute ||
|
||||
curBaseRoute.startsWith(
|
||||
baseRoute.length > 1 ? baseRoute + "/" : baseRoute,
|
||||
);
|
||||
if (res) {
|
||||
selected.push(item);
|
||||
}
|
||||
}
|
||||
|
||||
return selected;
|
||||
}
|
||||
|
||||
/**
|
||||
* Identify which middlewares should be applied for a request,
|
||||
* chain them and return a handler response
|
||||
*/
|
||||
export function composeMiddlewares(
|
||||
middlewares: MiddlewareRoute[],
|
||||
errorHandler: ErrorHandler,
|
||||
paramsAndRoute: (
|
||||
url: URL,
|
||||
) => RouteResult,
|
||||
renderNotFound: UnknownRenderFunction,
|
||||
basePath: string,
|
||||
) {
|
||||
return (
|
||||
req: Request,
|
||||
ctx: FreshContext,
|
||||
inner: FinalHandler,
|
||||
) => {
|
||||
const handlers: (() => Response | Promise<Response>)[] = [];
|
||||
const paramsAndRouteResult = paramsAndRoute(ctx.url);
|
||||
ctx.params = paramsAndRouteResult.params;
|
||||
|
||||
// identify middlewares to apply, if any.
|
||||
// middlewares should be already sorted from deepest to shallow layer
|
||||
const mws = selectSharedRoutes(
|
||||
paramsAndRouteResult.route?.baseRoute ??
|
||||
toBaseRoute(withBase(ROOT_BASE_ROUTE, basePath)),
|
||||
middlewares,
|
||||
);
|
||||
|
||||
if (paramsAndRouteResult.route) {
|
||||
ctx.route = paramsAndRouteResult.route.originalPattern;
|
||||
}
|
||||
|
||||
ctx.next = () => {
|
||||
const handler = handlers.shift()!;
|
||||
try {
|
||||
// As the `handler` can be either sync or async, depending on the user's code,
|
||||
// the current shape of our wrapper, that is `() => handler(req, middlewareCtx)`,
|
||||
// doesn't guarantee that all possible errors will be captured.
|
||||
// `Promise.resolve` accept the value that should be returned to the promise
|
||||
// chain, however, if that value is produced by the external function call,
|
||||
// the possible `Error`, will *not* be caught by any `.catch()` attached to that chain.
|
||||
// Because of that, we need to make sure that the produced value is pushed
|
||||
// through the pipeline only if function was called successfully, and handle
|
||||
// the error case manually, by returning the `Error` as rejected promise.
|
||||
return Promise.resolve(handler());
|
||||
} catch (e) {
|
||||
if (e instanceof Deno.errors.NotFound) {
|
||||
return renderNotFound(req, ctx);
|
||||
}
|
||||
return Promise.reject(e);
|
||||
}
|
||||
};
|
||||
|
||||
for (const { module } of mws) {
|
||||
if (module.handler instanceof Array) {
|
||||
for (const handler of module.handler) {
|
||||
handlers.push(() => handler(req, ctx));
|
||||
}
|
||||
} else {
|
||||
const handler = module.handler;
|
||||
handlers.push(() => handler(req, ctx));
|
||||
}
|
||||
}
|
||||
|
||||
const { destination, handler } = inner(
|
||||
req,
|
||||
ctx,
|
||||
paramsAndRouteResult.route,
|
||||
);
|
||||
handlers.push(handler);
|
||||
ctx.destination = destination;
|
||||
return ctx.next().catch((e) => errorHandler(req, ctx, e));
|
||||
};
|
||||
}
|
||||
@@ -1,143 +0,0 @@
|
||||
import { dirname, fromFileUrl, isAbsolute, join, JSONC } from "./deps.ts";
|
||||
import { FromManifestConfig, Manifest } from "./mod.ts";
|
||||
import { DEFAULT_RENDER_FN } from "./render.ts";
|
||||
import {
|
||||
DenoConfig,
|
||||
InternalFreshState,
|
||||
ResolvedFreshConfig,
|
||||
} from "./types.ts";
|
||||
|
||||
export async function readDenoConfig(
|
||||
directory: string,
|
||||
): Promise<{ config: DenoConfig; path: string }> {
|
||||
let dir = directory;
|
||||
while (true) {
|
||||
for (const name of ["deno.json", "deno.jsonc"]) {
|
||||
const path = join(dir, name);
|
||||
try {
|
||||
const file = await Deno.readTextFile(path);
|
||||
if (name.endsWith(".jsonc")) {
|
||||
return { config: JSONC.parse(file) as DenoConfig, path };
|
||||
} else {
|
||||
return { config: JSON.parse(file), path };
|
||||
}
|
||||
} catch (err) {
|
||||
if (!(err instanceof Deno.errors.NotFound)) {
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
}
|
||||
const parent = dirname(dir);
|
||||
if (parent === dir) {
|
||||
throw new Error(
|
||||
`Could not find a deno.json file in the current directory or any parent directory.`,
|
||||
);
|
||||
}
|
||||
dir = parent;
|
||||
}
|
||||
}
|
||||
|
||||
function isObject(value: unknown) {
|
||||
return value !== null && typeof value === "object" &&
|
||||
!Array.isArray(value);
|
||||
}
|
||||
|
||||
export async function getInternalFreshState(
|
||||
manifest: Manifest,
|
||||
config: FromManifestConfig,
|
||||
): Promise<InternalFreshState> {
|
||||
const base = dirname(fromFileUrl(manifest.baseUrl));
|
||||
const { config: denoJson, path: denoJsonPath } = await readDenoConfig(base);
|
||||
|
||||
if (typeof denoJson.importMap !== "string" && !isObject(denoJson.imports)) {
|
||||
throw new Error(
|
||||
"deno.json must contain an 'importMap' or 'imports' property.",
|
||||
);
|
||||
}
|
||||
|
||||
const isLegacyDev = Deno.env.get("__FRSH_LEGACY_DEV") === "true";
|
||||
|
||||
/**
|
||||
* assume a basePath is declared like this:
|
||||
* basePath: "/foo/bar"
|
||||
* it must start with a slash, and not have a trailing slash
|
||||
*/
|
||||
|
||||
let basePath = "";
|
||||
if (config.router?.basePath) {
|
||||
basePath = config.router?.basePath;
|
||||
if (!basePath.startsWith("/")) {
|
||||
throw new TypeError(
|
||||
`"basePath" option must start with "/". Received: "${basePath}"`,
|
||||
);
|
||||
}
|
||||
if (basePath.endsWith("/")) {
|
||||
throw new TypeError(
|
||||
`"basePath" option must not end with "/". Received: "${basePath}"`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const internalConfig: ResolvedFreshConfig = {
|
||||
dev: isLegacyDev || Boolean(config.dev),
|
||||
build: {
|
||||
outDir: config.build?.outDir
|
||||
? parseFileOrUrl(config.build.outDir, base)
|
||||
: join(base, "_fresh"),
|
||||
target: config.build?.target ?? ["chrome99", "firefox99", "safari15"],
|
||||
},
|
||||
plugins: config.plugins ?? [],
|
||||
staticDir: config.staticDir
|
||||
? parseFileOrUrl(config.staticDir, base)
|
||||
: join(base, "static"),
|
||||
render: config.render ?? DEFAULT_RENDER_FN,
|
||||
router: config.router,
|
||||
server: config.server ?? {},
|
||||
basePath,
|
||||
};
|
||||
|
||||
if (config.cert) {
|
||||
internalConfig.server.cert = config.cert;
|
||||
}
|
||||
if (config.hostname) {
|
||||
internalConfig.server.hostname = config.hostname;
|
||||
}
|
||||
if (config.key) {
|
||||
internalConfig.server.key = config.key;
|
||||
}
|
||||
if (config.onError) {
|
||||
internalConfig.server.onError = config.onError;
|
||||
}
|
||||
if (config.onListen) {
|
||||
internalConfig.server.onListen = config.onListen;
|
||||
}
|
||||
if (config.port) {
|
||||
internalConfig.server.port = config.port;
|
||||
}
|
||||
if (config.reusePort) {
|
||||
internalConfig.server.reusePort = config.reusePort;
|
||||
}
|
||||
if (config.signal) {
|
||||
internalConfig.server.signal = config.signal;
|
||||
}
|
||||
|
||||
return {
|
||||
config: internalConfig,
|
||||
manifest,
|
||||
loadSnapshot: !isLegacyDev && !config.dev,
|
||||
didLoadSnapshot: false,
|
||||
denoJsonPath,
|
||||
denoJson,
|
||||
build: false,
|
||||
};
|
||||
}
|
||||
|
||||
function parseFileOrUrl(input: string, base: string) {
|
||||
if (input.startsWith("file://")) {
|
||||
return fromFileUrl(input);
|
||||
} else if (!isAbsolute(input)) {
|
||||
return join(base, input);
|
||||
}
|
||||
|
||||
return input;
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
import { INTERNAL_PREFIX } from "../runtime/utils.ts";
|
||||
import { BUILD_ID } from "./build_id.ts";
|
||||
|
||||
export const DEV_CLIENT_URL = `${INTERNAL_PREFIX}/fresh_dev_client.js`;
|
||||
export const DEV_ERROR_OVERLAY_URL = `${INTERNAL_PREFIX}/error_overlay`;
|
||||
export const ALIVE_URL = `${INTERNAL_PREFIX}/alive`;
|
||||
export const JS_PREFIX = `/js`;
|
||||
export const DEBUG = !Deno.env.get("DENO_DEPLOYMENT_ID");
|
||||
|
||||
export function bundleAssetUrl(path: string) {
|
||||
return `${INTERNAL_PREFIX}${JS_PREFIX}/${BUILD_ID}${path}`;
|
||||
}
|
||||
@@ -1,831 +0,0 @@
|
||||
import { contentType, extname, SEPARATOR, STATUS_CODE } from "./deps.ts";
|
||||
import * as router from "./router.ts";
|
||||
import { FreshConfig, FreshContext, Manifest } from "./mod.ts";
|
||||
import {
|
||||
ALIVE_URL,
|
||||
DEV_CLIENT_URL,
|
||||
DEV_ERROR_OVERLAY_URL,
|
||||
JS_PREFIX,
|
||||
} from "./constants.ts";
|
||||
import { BUILD_ID, DENO_DEPLOYMENT_ID } from "./build_id.ts";
|
||||
|
||||
import {
|
||||
ErrorPage,
|
||||
Handler,
|
||||
InternalFreshState,
|
||||
Island,
|
||||
Plugin,
|
||||
RenderFunction,
|
||||
RenderOptions,
|
||||
Route,
|
||||
ServeHandlerInfo,
|
||||
UnknownPage,
|
||||
UnknownRenderFunction,
|
||||
} from "./types.ts";
|
||||
import { render as internalRender } from "./render.ts";
|
||||
import {
|
||||
ContentSecurityPolicy,
|
||||
ContentSecurityPolicyDirectives,
|
||||
SELF,
|
||||
} from "../runtime/csp.ts";
|
||||
import { ASSET_CACHE_BUST_KEY, INTERNAL_PREFIX } from "../runtime/utils.ts";
|
||||
import { Builder, BuildSnapshot, EsbuildBuilder } from "../build/mod.ts";
|
||||
import { setAllIslands } from "./rendering/preact_hooks.ts";
|
||||
import { getCodeFrame } from "./code_frame.ts";
|
||||
import { getInternalFreshState } from "./config.ts";
|
||||
import {
|
||||
composeMiddlewares,
|
||||
ROOT_BASE_ROUTE,
|
||||
selectSharedRoutes,
|
||||
toBaseRoute,
|
||||
} from "./compose.ts";
|
||||
import { extractRoutes, FsExtractResult } from "./fs_extract.ts";
|
||||
import { loadAotSnapshot } from "../build/aot_snapshot.ts";
|
||||
import { ErrorOverlay } from "./error_overlay.tsx";
|
||||
import { withBase } from "./router.ts";
|
||||
import { PARTIAL_SEARCH_PARAM } from "../constants.ts";
|
||||
import TailwindErrorPage from "./tailwind_aot_error_page.tsx";
|
||||
|
||||
// TODO: Completed type clashes in older Deno versions
|
||||
// deno-lint-ignore no-explicit-any
|
||||
const DEFAULT_CONN_INFO: any = {
|
||||
localAddr: { transport: "tcp", hostname: "localhost", port: 8080 },
|
||||
remoteAddr: { transport: "tcp", hostname: "localhost", port: 1234 },
|
||||
};
|
||||
|
||||
// deno-lint-ignore no-explicit-any
|
||||
const NOOP_COMPONENT = () => null as any;
|
||||
const NOOP_NEXT = () => Promise.resolve(new Response(null, { status: 500 }));
|
||||
|
||||
/**
|
||||
* @deprecated Use {@linkcode FromManifestConfig} instead
|
||||
*/
|
||||
export type FromManifestOptions = FromManifestConfig;
|
||||
|
||||
export type FromManifestConfig = FreshConfig & {
|
||||
dev?: boolean;
|
||||
};
|
||||
|
||||
export async function getServerContext(state: InternalFreshState) {
|
||||
const { config, denoJson, denoJsonPath: configPath } = state;
|
||||
|
||||
if (config.dev) {
|
||||
// Ensure that debugging hooks are set up for SSR rendering
|
||||
await import("preact/debug");
|
||||
}
|
||||
|
||||
// Plugins are already instantiated in build mode
|
||||
if (!state.build) {
|
||||
await Promise.all(
|
||||
config.plugins.map((plugin) => plugin.configResolved?.(state.config)),
|
||||
);
|
||||
}
|
||||
|
||||
const extractResult = await extractRoutes(state);
|
||||
|
||||
// Restore snapshot if available
|
||||
let snapshot: Builder | BuildSnapshot | Promise<BuildSnapshot> | null = null;
|
||||
if (state.loadSnapshot) {
|
||||
const loadedSnapshot = await loadAotSnapshot(config);
|
||||
if (loadedSnapshot !== null) {
|
||||
snapshot = loadedSnapshot;
|
||||
state.didLoadSnapshot = true;
|
||||
}
|
||||
}
|
||||
|
||||
const finalSnapshot = snapshot ?? new EsbuildBuilder({
|
||||
buildID: BUILD_ID,
|
||||
entrypoints: collectEntrypoints(
|
||||
config.dev,
|
||||
extractResult.islands,
|
||||
config.plugins,
|
||||
),
|
||||
configPath,
|
||||
dev: config.dev,
|
||||
jsx: denoJson.compilerOptions?.jsx,
|
||||
jsxImportSource: denoJson.compilerOptions?.jsxImportSource,
|
||||
target: state.config.build.target,
|
||||
absoluteWorkingDir: Deno.cwd(),
|
||||
basePath: state.config.basePath,
|
||||
});
|
||||
|
||||
return new ServerContext(
|
||||
state,
|
||||
extractResult,
|
||||
finalSnapshot,
|
||||
);
|
||||
}
|
||||
|
||||
export class ServerContext {
|
||||
#renderFn: RenderFunction;
|
||||
#plugins: Plugin[];
|
||||
#builder: Builder | Promise<BuildSnapshot> | BuildSnapshot;
|
||||
#state: InternalFreshState;
|
||||
#extractResult: FsExtractResult;
|
||||
#dev: boolean;
|
||||
#revision = 0;
|
||||
|
||||
constructor(
|
||||
state: InternalFreshState,
|
||||
extractResult: FsExtractResult,
|
||||
snapshot: Builder | BuildSnapshot | Promise<BuildSnapshot>,
|
||||
) {
|
||||
this.#state = state;
|
||||
this.#extractResult = extractResult;
|
||||
this.#renderFn = state.config.render;
|
||||
this.#plugins = state.config.plugins;
|
||||
this.#dev = state.config.dev;
|
||||
this.#builder = snapshot;
|
||||
}
|
||||
|
||||
/**
|
||||
* Process the manifest into individual components and pages.
|
||||
*/
|
||||
static async fromManifest(
|
||||
manifest: Manifest,
|
||||
config: FromManifestConfig,
|
||||
): Promise<ServerContext> {
|
||||
const configWithDefaults = await getInternalFreshState(
|
||||
manifest,
|
||||
config,
|
||||
);
|
||||
return getServerContext(configWithDefaults);
|
||||
}
|
||||
|
||||
/**
|
||||
* This functions returns a request handler that handles all routes required
|
||||
* by Fresh, including static files.
|
||||
*/
|
||||
handler(): (req: Request, connInfo?: ServeHandlerInfo) => Promise<Response> {
|
||||
const basePath = this.#state.config.basePath;
|
||||
const renderNotFound = createRenderNotFound(
|
||||
this.#extractResult,
|
||||
this.#dev,
|
||||
this.#plugins,
|
||||
this.#renderFn,
|
||||
this.#maybeBuildSnapshot(),
|
||||
);
|
||||
const handlers = this.#handlers(renderNotFound);
|
||||
const inner = router.router(handlers);
|
||||
const withMiddlewares = composeMiddlewares(
|
||||
this.#extractResult.middlewares,
|
||||
handlers.errorHandler,
|
||||
router.getParamsAndRoute(handlers),
|
||||
renderNotFound,
|
||||
basePath,
|
||||
);
|
||||
const trailingSlashEnabled = this.#state.config.router?.trailingSlash;
|
||||
const isDev = this.#dev;
|
||||
|
||||
if (this.#dev) {
|
||||
this.#revision = Date.now();
|
||||
}
|
||||
|
||||
// deno-lint-ignore no-this-alias
|
||||
const _self = this;
|
||||
|
||||
return async function handler(
|
||||
req: Request,
|
||||
connInfo: ServeHandlerInfo = DEFAULT_CONN_INFO,
|
||||
) {
|
||||
const url = new URL(req.url);
|
||||
// Syntactically having double slashes in the pathname is valid per
|
||||
// spec, but there is no behavior defined for that. Practically all
|
||||
// servers normalize the pathname of a URL to not include double
|
||||
// forward slashes.
|
||||
url.pathname = url.pathname.replaceAll(/\/+/g, "/");
|
||||
|
||||
const aliveUrl = basePath + ALIVE_URL;
|
||||
|
||||
if (isDev) {
|
||||
// Live reload: Send updates to browser
|
||||
if (url.pathname === aliveUrl) {
|
||||
if (req.headers.get("upgrade") !== "websocket") {
|
||||
return new Response(null, { status: 501 });
|
||||
}
|
||||
|
||||
// TODO: When a change is made the Deno server restarts,
|
||||
// so for now the WebSocket connection is only used for
|
||||
// the client to know when the server is back up. Once we
|
||||
// have HMR we'll actively start sending messages back
|
||||
// and forth.
|
||||
const { response, socket } = Deno.upgradeWebSocket(req);
|
||||
|
||||
socket.addEventListener("open", () => {
|
||||
socket.send(
|
||||
JSON.stringify({
|
||||
type: "initial-state",
|
||||
revision: _self.#revision,
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
return response;
|
||||
} else if (
|
||||
url.pathname === withBase(DEV_CLIENT_URL, basePath) ||
|
||||
url.pathname === withBase(`${DEV_CLIENT_URL}.map`, basePath)
|
||||
) {
|
||||
const bundlePath = (url.pathname.endsWith(".map"))
|
||||
? "fresh_dev_client.js.map"
|
||||
: "fresh_dev_client.js";
|
||||
|
||||
return _self.#bundleAssetRoute(bundlePath);
|
||||
}
|
||||
}
|
||||
|
||||
// Redirect requests that end with a trailing slash to their non-trailing
|
||||
// slash counterpart.
|
||||
// Ex: /about/ -> /about
|
||||
if (
|
||||
url.pathname.length > 1 && url.pathname.endsWith("/") &&
|
||||
!trailingSlashEnabled
|
||||
) {
|
||||
// Remove trailing slashes
|
||||
const path = url.pathname.replace(/\/+$/, "");
|
||||
const location = `${path}${url.search}`;
|
||||
return new Response(null, {
|
||||
status: STATUS_CODE.TemporaryRedirect,
|
||||
headers: { location },
|
||||
});
|
||||
} else if (trailingSlashEnabled && !url.pathname.endsWith("/")) {
|
||||
// If the last element of the path has a "." it's a file
|
||||
const isFile = url.pathname.split("/").at(-1)?.includes(".");
|
||||
|
||||
// If the path uses the internal prefix, don't redirect it
|
||||
const isInternal = url.pathname.startsWith(INTERNAL_PREFIX);
|
||||
|
||||
if (!isFile && !isInternal) {
|
||||
url.pathname += "/";
|
||||
return Response.redirect(url, STATUS_CODE.PermanentRedirect);
|
||||
}
|
||||
}
|
||||
|
||||
// Redirect to base path if not present in url
|
||||
if (basePath && !url.pathname.startsWith(basePath)) {
|
||||
const to = new URL(basePath + url.pathname, url.origin);
|
||||
return Response.redirect(to, 302);
|
||||
}
|
||||
|
||||
const ctx: FreshContext = {
|
||||
url,
|
||||
params: {},
|
||||
config: _self.#state.config,
|
||||
basePath: _self.#state.config.basePath,
|
||||
localAddr: connInfo.localAddr,
|
||||
remoteAddr: connInfo.remoteAddr,
|
||||
state: {},
|
||||
isPartial: url.searchParams.has(PARTIAL_SEARCH_PARAM),
|
||||
destination: "route",
|
||||
error: undefined,
|
||||
codeFrame: undefined,
|
||||
Component: NOOP_COMPONENT,
|
||||
next: NOOP_NEXT,
|
||||
render: NOOP_NEXT,
|
||||
renderNotFound: async (data) => {
|
||||
ctx.data = data;
|
||||
return await renderNotFound(req, ctx);
|
||||
},
|
||||
route: "",
|
||||
get pattern() {
|
||||
return ctx.route;
|
||||
},
|
||||
data: undefined,
|
||||
};
|
||||
|
||||
return await withMiddlewares(req, ctx, inner);
|
||||
};
|
||||
}
|
||||
|
||||
#maybeBuildSnapshot(): BuildSnapshot | null {
|
||||
if ("build" in this.#builder || this.#builder instanceof Promise) {
|
||||
return null;
|
||||
}
|
||||
return this.#builder;
|
||||
}
|
||||
|
||||
async buildSnapshot() {
|
||||
if ("build" in this.#builder) {
|
||||
const builder = this.#builder;
|
||||
this.#builder = builder.build();
|
||||
try {
|
||||
const snapshot = await this.#builder;
|
||||
this.#builder = snapshot;
|
||||
} catch (err) {
|
||||
this.#builder = builder;
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
return this.#builder;
|
||||
}
|
||||
|
||||
/**
|
||||
* This function returns all routes required by Fresh as an extended
|
||||
* path-to-regex, to handler mapping.
|
||||
*/
|
||||
#handlers(
|
||||
renderNotFound: UnknownRenderFunction,
|
||||
): {
|
||||
internalRoutes: router.Routes;
|
||||
staticRoutes: router.Routes;
|
||||
routes: router.Routes;
|
||||
|
||||
otherHandler: router.Handler;
|
||||
errorHandler: router.ErrorHandler;
|
||||
} {
|
||||
const internalRoutes: router.Routes = {};
|
||||
const staticRoutes: router.Routes = {};
|
||||
let routes: router.Routes = {};
|
||||
|
||||
const assetRoute = withBase(
|
||||
`${INTERNAL_PREFIX}${JS_PREFIX}/${BUILD_ID}/:path*`,
|
||||
this.#state.config.basePath,
|
||||
);
|
||||
internalRoutes[assetRoute] = {
|
||||
baseRoute: toBaseRoute(assetRoute),
|
||||
methods: {
|
||||
default: (_req, ctx) => this.#bundleAssetRoute(ctx.params.path),
|
||||
},
|
||||
};
|
||||
|
||||
// Add the static file routes.
|
||||
// each files has 2 static routes:
|
||||
// - one serving the file at its location without a "cache bursting" mechanism
|
||||
// - one containing the BUILD_ID in the path that can be cached
|
||||
for (
|
||||
const { localUrl, path, size, contentType, etag } of this.#extractResult
|
||||
.staticFiles
|
||||
) {
|
||||
staticRoutes[path.replaceAll(SEPARATOR, "/")] = {
|
||||
baseRoute: toBaseRoute(path),
|
||||
methods: {
|
||||
"HEAD": this.#staticFileHandler(
|
||||
localUrl,
|
||||
size,
|
||||
contentType,
|
||||
etag,
|
||||
),
|
||||
"GET": this.#staticFileHandler(
|
||||
localUrl,
|
||||
size,
|
||||
contentType,
|
||||
etag,
|
||||
),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// Tell renderer about all globally available islands
|
||||
setAllIslands(this.#extractResult.islands);
|
||||
|
||||
const dependenciesFn = (path: string) => {
|
||||
const snapshot = this.#maybeBuildSnapshot();
|
||||
return snapshot?.dependencies(path) ?? [];
|
||||
};
|
||||
|
||||
const genRender = <Data = undefined>(
|
||||
route: Route<Data> | UnknownPage | ErrorPage,
|
||||
status: number,
|
||||
) => {
|
||||
const imports: string[] = [];
|
||||
if (this.#dev) imports.push(this.#state.config.basePath + DEV_CLIENT_URL);
|
||||
return (
|
||||
req: Request,
|
||||
ctx: FreshContext,
|
||||
error?: unknown,
|
||||
codeFrame?: string,
|
||||
) => {
|
||||
return async (data?: Data, options?: RenderOptions) => {
|
||||
if (route.component === undefined) {
|
||||
throw new Error("This page does not have a component to render.");
|
||||
}
|
||||
const layouts = selectSharedRoutes(
|
||||
route.baseRoute,
|
||||
this.#extractResult.layouts,
|
||||
);
|
||||
|
||||
ctx.error = error;
|
||||
ctx.data = data;
|
||||
const resp = await internalRender({
|
||||
request: req,
|
||||
context: ctx,
|
||||
route,
|
||||
plugins: this.#plugins,
|
||||
app: this.#extractResult.app,
|
||||
layouts,
|
||||
imports,
|
||||
dependenciesFn,
|
||||
renderFn: this.#renderFn,
|
||||
codeFrame,
|
||||
});
|
||||
|
||||
if (resp instanceof Response) {
|
||||
return resp;
|
||||
}
|
||||
|
||||
return sendResponse(resp, {
|
||||
status: options?.status ?? status,
|
||||
statusText: options?.statusText,
|
||||
headers: options?.headers,
|
||||
isDev: this.#dev,
|
||||
});
|
||||
};
|
||||
};
|
||||
};
|
||||
|
||||
for (const route of this.#extractResult.routes) {
|
||||
if (
|
||||
this.#state.config.router?.trailingSlash && route.pattern != "/"
|
||||
) {
|
||||
route.pattern += "/";
|
||||
}
|
||||
const createRender = genRender(route, STATUS_CODE.OK);
|
||||
if (typeof route.handler === "function") {
|
||||
routes[route.pattern] = {
|
||||
baseRoute: route.baseRoute,
|
||||
methods: {
|
||||
default: (req, ctx) => {
|
||||
ctx.render = createRender(req, ctx);
|
||||
return (route.handler as Handler)(req, ctx);
|
||||
},
|
||||
},
|
||||
};
|
||||
} else {
|
||||
routes[route.pattern] = {
|
||||
baseRoute: route.baseRoute,
|
||||
methods: {},
|
||||
};
|
||||
for (const [method, handler] of Object.entries(route.handler)) {
|
||||
routes[route.pattern].methods[method as router.KnownMethod] = (
|
||||
req,
|
||||
ctx,
|
||||
) => {
|
||||
ctx.render = createRender(req, ctx);
|
||||
return handler(req, ctx);
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let otherHandler: router.Handler = (req, ctx) => {
|
||||
ctx.render = (data) => {
|
||||
ctx.data = data;
|
||||
return renderNotFound(req, ctx);
|
||||
};
|
||||
return this.#extractResult.notFound.handler(req, ctx);
|
||||
};
|
||||
|
||||
const errorHandlerRender = genRender(
|
||||
this.#extractResult.error,
|
||||
STATUS_CODE.InternalServerError,
|
||||
);
|
||||
const errorHandler: router.ErrorHandler = async (
|
||||
req,
|
||||
ctx,
|
||||
error,
|
||||
) => {
|
||||
console.error(
|
||||
"%cAn error occurred during route handling or page rendering.",
|
||||
"color:red",
|
||||
);
|
||||
let codeFrame: string | undefined;
|
||||
if (this.#dev && error instanceof Error) {
|
||||
codeFrame = await getCodeFrame(error);
|
||||
|
||||
if (codeFrame) {
|
||||
console.error();
|
||||
console.error(codeFrame);
|
||||
}
|
||||
}
|
||||
console.error(error);
|
||||
|
||||
ctx.error = error;
|
||||
ctx.render = errorHandlerRender(req, ctx, error, codeFrame);
|
||||
return this.#extractResult.error.handler(req, ctx);
|
||||
};
|
||||
|
||||
if (this.#dev) {
|
||||
const devErrorUrl = withBase(
|
||||
DEV_ERROR_OVERLAY_URL,
|
||||
this.#state.config.basePath,
|
||||
);
|
||||
const baseRoute = toBaseRoute(devErrorUrl);
|
||||
internalRoutes[devErrorUrl] = {
|
||||
baseRoute,
|
||||
methods: {
|
||||
default: async (req, ctx) => {
|
||||
const resp = await internalRender({
|
||||
request: req,
|
||||
context: ctx,
|
||||
route: {
|
||||
component: ErrorOverlay,
|
||||
inheritLayouts: false,
|
||||
appWrapper: false,
|
||||
csp: false,
|
||||
url: req.url,
|
||||
name: "error overlay route",
|
||||
handler: (_req: Request, ctx: FreshContext) => ctx.render(),
|
||||
baseRoute,
|
||||
pattern: baseRoute,
|
||||
},
|
||||
plugins: this.#plugins,
|
||||
app: this.#extractResult.app,
|
||||
layouts: [],
|
||||
imports: [],
|
||||
dependenciesFn: () => [],
|
||||
renderFn: this.#renderFn,
|
||||
codeFrame: undefined,
|
||||
});
|
||||
|
||||
if (resp instanceof Response) {
|
||||
return resp;
|
||||
}
|
||||
|
||||
return sendResponse(resp, {
|
||||
status: 200,
|
||||
isDev: this.#dev,
|
||||
statusText: undefined,
|
||||
headers: undefined,
|
||||
});
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// This page is shown when the user uses the tailwindcss plugin and
|
||||
// hasn't configured AOT builds.
|
||||
if (
|
||||
!this.#state.config.dev &&
|
||||
this.#state.loadSnapshot && !this.#state.didLoadSnapshot &&
|
||||
this.#state.config.plugins.some((plugin) => plugin.name === "tailwind")
|
||||
) {
|
||||
if (DENO_DEPLOYMENT_ID !== undefined) {
|
||||
// Don't fail hard here and instead rewrite all routes to a special
|
||||
// error route. Otherwise the first user experience of deploying a
|
||||
// Fresh project would be pretty disruptive
|
||||
console.error(
|
||||
"%cError: Ahead of time builds not configured but required by the tailwindcss plugin.\nTo resolve this error, set up ahead of time builds: https://fresh.deno.dev/docs/concepts/ahead-of-time-builds",
|
||||
"color: red",
|
||||
);
|
||||
console.log();
|
||||
|
||||
// Clear all routes so that everything redirects to the tailwind
|
||||
// error page.
|
||||
routes = {};
|
||||
|
||||
const freshErrorPage = genRender({
|
||||
appWrapper: false,
|
||||
inheritLayouts: false,
|
||||
component: TailwindErrorPage,
|
||||
csp: false,
|
||||
name: "tailwind_error_route",
|
||||
pattern: "*",
|
||||
url: "",
|
||||
baseRoute: toBaseRoute("*"),
|
||||
handler: (_req: Request, ctx: FreshContext) => ctx.render(),
|
||||
}, STATUS_CODE.InternalServerError);
|
||||
otherHandler = (req, ctx) => {
|
||||
const render = freshErrorPage(req, ctx);
|
||||
return render();
|
||||
};
|
||||
} else {
|
||||
// Not on Deno Deploy. The user likely forgot to run `deno task build`
|
||||
console.warn(
|
||||
'%cNo pre-compiled tailwind styles found.\n\nDid you forget to run "deno task build" prior to starting the production server?',
|
||||
"color: yellow",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return { internalRoutes, staticRoutes, routes, otherHandler, errorHandler };
|
||||
}
|
||||
|
||||
#staticFileHandler(
|
||||
localUrl: URL,
|
||||
size: number,
|
||||
contentType: string,
|
||||
etag: string,
|
||||
): router.MatchHandler {
|
||||
return async (req: Request) => {
|
||||
const url = new URL(req.url);
|
||||
const key = url.searchParams.get(ASSET_CACHE_BUST_KEY);
|
||||
if (key !== null && BUILD_ID !== key) {
|
||||
url.searchParams.delete(ASSET_CACHE_BUST_KEY);
|
||||
const location = url.pathname + url.search;
|
||||
return new Response(null, {
|
||||
status: 307,
|
||||
headers: {
|
||||
location,
|
||||
},
|
||||
});
|
||||
}
|
||||
const headers = new Headers({
|
||||
"content-type": contentType,
|
||||
etag,
|
||||
vary: "If-None-Match",
|
||||
});
|
||||
if (key !== null) {
|
||||
headers.set("Cache-Control", "public, max-age=31536000, immutable");
|
||||
}
|
||||
const ifNoneMatch = req.headers.get("if-none-match");
|
||||
if (ifNoneMatch === etag || ifNoneMatch === "W/" + etag) {
|
||||
return new Response(null, { status: 304, headers });
|
||||
} else if (req.method === "HEAD") {
|
||||
headers.set("content-length", String(size));
|
||||
return new Response(null, { status: 200, headers });
|
||||
} else {
|
||||
const file = await Deno.open(localUrl);
|
||||
headers.set("content-length", String(size));
|
||||
return new Response(file.readable, { headers });
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
async #bundleAssetRoute(filePath: string) {
|
||||
const snapshot = await this.buildSnapshot();
|
||||
const contents = await snapshot.read(filePath);
|
||||
if (!contents) return new Response(null, { status: 404 });
|
||||
|
||||
const headers: Record<string, string> = {
|
||||
"Cache-Control": this.#dev
|
||||
? "no-cache, no-store, max-age=0, must-revalidate"
|
||||
: "public, max-age=604800, immutable",
|
||||
};
|
||||
|
||||
const type = contentType(extname(filePath));
|
||||
if (type) headers["Content-Type"] = type;
|
||||
|
||||
return new Response(contents, {
|
||||
status: 200,
|
||||
headers,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const createRenderNotFound = (
|
||||
extractResult: FsExtractResult,
|
||||
dev: boolean,
|
||||
plugins: Plugin<Record<string, unknown>>[],
|
||||
renderFunction: RenderFunction,
|
||||
buildSnapshot: BuildSnapshot | null,
|
||||
): UnknownRenderFunction => {
|
||||
const dependenciesFn = (path: string) => {
|
||||
const snapshot = buildSnapshot;
|
||||
return snapshot?.dependencies(path) ?? [];
|
||||
};
|
||||
|
||||
return async (req, ctx) => {
|
||||
const notFound = extractResult.notFound;
|
||||
if (!notFound.component) {
|
||||
return sendResponse(["Not found.", "", undefined], {
|
||||
status: STATUS_CODE.NotFound,
|
||||
isDev: dev,
|
||||
statusText: undefined,
|
||||
headers: undefined,
|
||||
});
|
||||
}
|
||||
|
||||
const layouts = selectSharedRoutes(
|
||||
ROOT_BASE_ROUTE,
|
||||
extractResult.layouts,
|
||||
);
|
||||
|
||||
const imports: string[] = [];
|
||||
const resp = await internalRender({
|
||||
request: req,
|
||||
context: ctx,
|
||||
route: notFound,
|
||||
plugins: plugins,
|
||||
app: extractResult.app,
|
||||
layouts,
|
||||
imports,
|
||||
dependenciesFn,
|
||||
renderFn: renderFunction,
|
||||
});
|
||||
|
||||
if (resp instanceof Response) {
|
||||
return resp;
|
||||
}
|
||||
|
||||
return sendResponse(resp, {
|
||||
status: STATUS_CODE.NotFound,
|
||||
isDev: dev,
|
||||
statusText: undefined,
|
||||
headers: undefined,
|
||||
});
|
||||
};
|
||||
};
|
||||
|
||||
// Normalize a path for use in a URL. Returns null if the path is unparsable.
|
||||
export function normalizeURLPath(path: string): string | null {
|
||||
try {
|
||||
const pathUrl = new URL("file:///");
|
||||
pathUrl.pathname = path;
|
||||
return pathUrl.pathname;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function serializeCSPDirectives(csp: ContentSecurityPolicyDirectives): string {
|
||||
return Object.entries(csp)
|
||||
.filter(([_key, value]) => value !== undefined)
|
||||
.map(([k, v]: [string, string | string[]]) => {
|
||||
// Turn camel case into snake case.
|
||||
const key = k.replace(/[A-Z]/g, (m) => `-${m.toLowerCase()}`);
|
||||
const value = Array.isArray(v) ? v.join(" ") : v;
|
||||
return `${key} ${value}`;
|
||||
})
|
||||
.join("; ");
|
||||
}
|
||||
|
||||
function collectEntrypoints(
|
||||
dev: boolean,
|
||||
islands: Island[],
|
||||
plugins: Plugin[],
|
||||
): Record<string, string> {
|
||||
const entrypointBase = "../runtime/entrypoints";
|
||||
const entryPoints: Record<string, string> = {
|
||||
main: dev
|
||||
? import.meta.resolve(`${entrypointBase}/main_dev.ts`)
|
||||
: import.meta.resolve(`${entrypointBase}/main.ts`),
|
||||
deserializer: import.meta.resolve(`${entrypointBase}/deserializer.ts`),
|
||||
};
|
||||
|
||||
if (dev) {
|
||||
entryPoints.fresh_dev_client = import.meta.resolve(
|
||||
`${entrypointBase}/client.ts`,
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
import.meta.resolve("@preact/signals");
|
||||
entryPoints.signals = import.meta.resolve(`${entrypointBase}/signals.ts`);
|
||||
} catch {
|
||||
// @preact/signals is not in the import map
|
||||
}
|
||||
|
||||
for (const island of islands) {
|
||||
entryPoints[`island-${island.name}`] = island.url;
|
||||
}
|
||||
|
||||
for (const plugin of plugins) {
|
||||
for (const [name, url] of Object.entries(plugin.entrypoints ?? {})) {
|
||||
entryPoints[`plugin-${plugin.name}-${name}`] = url;
|
||||
}
|
||||
}
|
||||
|
||||
return entryPoints;
|
||||
}
|
||||
|
||||
function sendResponse(
|
||||
resp: [string, string, ContentSecurityPolicy | undefined],
|
||||
options: {
|
||||
status: number;
|
||||
statusText: string | undefined;
|
||||
headers?: HeadersInit;
|
||||
isDev: boolean;
|
||||
},
|
||||
) {
|
||||
const [body, uuid, csp] = resp;
|
||||
const headers: Headers = new Headers({
|
||||
"content-type": "text/html; charset=utf-8",
|
||||
"x-fresh-uuid": uuid,
|
||||
});
|
||||
|
||||
if (csp) {
|
||||
if (options.isDev) {
|
||||
csp.directives.connectSrc = [
|
||||
...(csp.directives.connectSrc ?? []),
|
||||
SELF,
|
||||
];
|
||||
}
|
||||
const directive = serializeCSPDirectives(csp.directives);
|
||||
if (csp.reportOnly) {
|
||||
headers.set("content-security-policy-report-only", directive);
|
||||
} else {
|
||||
headers.set("content-security-policy", directive);
|
||||
}
|
||||
}
|
||||
|
||||
if (options.headers) {
|
||||
if (Array.isArray(options.headers)) {
|
||||
for (const [key, value] of options.headers) {
|
||||
headers.append(key, value);
|
||||
}
|
||||
} else if (options.headers instanceof Headers) {
|
||||
options.headers.forEach((value, key) => {
|
||||
headers.append(key, value);
|
||||
});
|
||||
} else {
|
||||
for (const [key, value] of Object.entries(options.headers)) {
|
||||
headers.append(key, value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return new Response(body, {
|
||||
status: options.status,
|
||||
statusText: options.statusText,
|
||||
headers,
|
||||
});
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
export default function DefaultErrorPage() {
|
||||
return (
|
||||
<div class="frsh-error-page">
|
||||
<div style="max-width: 48rem; padding: 2rem 1rem; margin: 0 auto; font-family: sans-serif">
|
||||
<h1>
|
||||
An error occurred during route handling or page rendering.
|
||||
</h1>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,48 +0,0 @@
|
||||
import { ComponentChildren } from "preact";
|
||||
import { AsyncLayout, AsyncRoute, FreshConfig, RouteContext } from "./types.ts";
|
||||
import { checkAsyncComponent } from "./render.ts";
|
||||
|
||||
export function defineConfig(config: FreshConfig): FreshConfig {
|
||||
return config;
|
||||
}
|
||||
|
||||
// Route creation helpers
|
||||
export function defineRoute<
|
||||
T,
|
||||
>(
|
||||
fn: (
|
||||
req: Request,
|
||||
ctx: RouteContext<void, T>,
|
||||
) => ComponentChildren | Response | Promise<ComponentChildren | Response>,
|
||||
): AsyncRoute<void, T> {
|
||||
// deno-lint-ignore no-explicit-any
|
||||
if (checkAsyncComponent(fn)) return fn as any;
|
||||
// deno-lint-ignore require-await
|
||||
return async (req, ctx) => fn(req, ctx);
|
||||
}
|
||||
|
||||
// Layout creation helper
|
||||
export function defineLayout<T>(
|
||||
fn: (
|
||||
req: Request,
|
||||
ctx: RouteContext<void, T>,
|
||||
) => ComponentChildren | Response | Promise<ComponentChildren | Response>,
|
||||
): AsyncLayout<void, T> {
|
||||
// deno-lint-ignore no-explicit-any
|
||||
if (checkAsyncComponent(fn)) return fn as any;
|
||||
// deno-lint-ignore require-await
|
||||
return async (req, ctx) => fn(req, ctx);
|
||||
}
|
||||
|
||||
// App creation helper
|
||||
export function defineApp<T>(
|
||||
fn: (
|
||||
req: Request,
|
||||
ctx: RouteContext<void, T>,
|
||||
) => ComponentChildren | Response | Promise<ComponentChildren | Response>,
|
||||
): AsyncLayout<void, T> {
|
||||
// deno-lint-ignore no-explicit-any
|
||||
if (checkAsyncComponent(fn)) return fn as any;
|
||||
// deno-lint-ignore require-await
|
||||
return async (req, ctx) => fn(req, ctx);
|
||||
}
|
||||
@@ -1,35 +0,0 @@
|
||||
// -- std --
|
||||
export {
|
||||
basename,
|
||||
dirname,
|
||||
extname,
|
||||
fromFileUrl,
|
||||
isAbsolute,
|
||||
join,
|
||||
SEPARATOR,
|
||||
toFileUrl,
|
||||
} from "https://deno.land/std@0.216.0/path/mod.ts";
|
||||
export { walk } from "https://deno.land/std@0.216.0/fs/walk.ts";
|
||||
export * as colors from "https://deno.land/std@0.216.0/fmt/colors.ts";
|
||||
export {
|
||||
type Handler as ServeHandler,
|
||||
serve,
|
||||
} from "https://deno.land/std@0.216.0/http/server.ts";
|
||||
export { STATUS_CODE } from "https://deno.land/std@0.216.0/http/status.ts";
|
||||
export {
|
||||
contentType,
|
||||
} from "https://deno.land/std@0.216.0/media_types/content_type.ts";
|
||||
export { encodeHex } from "https://deno.land/std@0.216.0/encoding/hex.ts";
|
||||
export { escape } from "https://deno.land/std@0.216.0/regexp/escape.ts";
|
||||
export * as JSONC from "https://deno.land/std@0.216.0/jsonc/mod.ts";
|
||||
export { renderToString } from "https://esm.sh/*preact-render-to-string@6.3.1";
|
||||
export {
|
||||
assertEquals,
|
||||
assertThrows,
|
||||
} from "https://deno.land/std@0.216.0/assert/mod.ts";
|
||||
export {
|
||||
isIdentifierChar,
|
||||
isIdentifierStart,
|
||||
} from "https://esm.sh/@babel/helper-validator-identifier@7.22.20";
|
||||
export { normalize } from "https://deno.land/std@0.216.0/path/posix/mod.ts";
|
||||
export { assertSnapshot } from "https://deno.land/std@0.216.0/testing/snapshot.ts";
|
||||
@@ -1,164 +0,0 @@
|
||||
import { ComponentChildren, h } from "preact";
|
||||
import { render } from "./render.ts";
|
||||
import { PageProps } from "../server/mod.ts";
|
||||
|
||||
// Just to get some syntax highlighting
|
||||
const css = (arr: TemplateStringsArray, ...exts: never[]) => {
|
||||
if (exts.length) throw new Error("Not allowed");
|
||||
return arr[0];
|
||||
};
|
||||
|
||||
export const errorCss = css`
|
||||
:root {
|
||||
--bg: #fff;
|
||||
--bg-code-frame: rgb(255, 0, 32, 0.1);
|
||||
--bg-active-line: #fbcecc;
|
||||
--text: #222;
|
||||
--text2: #444;
|
||||
--title: #e84644;
|
||||
--code: #333;
|
||||
font-family: sans-serif;
|
||||
line-height: 1.4;
|
||||
color: var(--text);
|
||||
background: var(--bg);
|
||||
}
|
||||
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
padding: 0;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
@media (prefers-color-scheme: dark) {
|
||||
:root {
|
||||
--bg-code-frame: rgba(251, 93, 113, 0.2);
|
||||
--bg-active-line: #4f1919;
|
||||
--bg: #353535;
|
||||
--text: #f7f7f7;
|
||||
--text2: #ddd;
|
||||
--code: #fdd1d1;
|
||||
}
|
||||
}
|
||||
|
||||
.inner {
|
||||
max-width: 48rem;
|
||||
padding: 4rem 1rem;
|
||||
margin: 0 auto;
|
||||
}
|
||||
|
||||
.title {
|
||||
color: var(--title);
|
||||
font-weight: normal;
|
||||
font-size: 1.5rem;
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
|
||||
.code-frame {
|
||||
overflow: auto;
|
||||
padding: 0.5rem;
|
||||
margin-bottom: 0.5rem;
|
||||
background: var(--bg-code-frame);
|
||||
color: var(--code);
|
||||
}
|
||||
.line {
|
||||
padding: 0.25rem 0.5rem;
|
||||
}
|
||||
.active-line {
|
||||
display: inline-block;
|
||||
width: 100%;
|
||||
background: var(--bg-active-line);
|
||||
}
|
||||
|
||||
.stack {
|
||||
overflow-x: auto;
|
||||
}
|
||||
|
||||
.close-btn {
|
||||
position: absolute;
|
||||
top: 1rem;
|
||||
right: 1rem;
|
||||
color: var(--title);
|
||||
display: block;
|
||||
width: 3rem;
|
||||
height: 3rem;
|
||||
background: none;
|
||||
border: none;
|
||||
transform: translate3d(0, 0, 0);
|
||||
}
|
||||
.close-btn:active {
|
||||
transform: translate3d(0, 2px, 0);
|
||||
}
|
||||
.close-btn:hover {
|
||||
cursor: pointer;
|
||||
filter: drop-shadow(0 0 0.75rem crimson);
|
||||
}
|
||||
`;
|
||||
|
||||
function CodeFrame(props: { codeFrame: string }) {
|
||||
const lines: ComponentChildren[] = [];
|
||||
|
||||
props.codeFrame.trimEnd().split("\n").forEach(
|
||||
(line, i, arr) => {
|
||||
const vnode = (
|
||||
<span
|
||||
class={"line" + (line.startsWith(">") ? " active-line" : "")}
|
||||
>
|
||||
{line}
|
||||
</span>
|
||||
);
|
||||
|
||||
lines.push(vnode);
|
||||
if (i < arr.length - 1) lines.push("\n");
|
||||
},
|
||||
);
|
||||
return (
|
||||
<pre class="code-frame">
|
||||
<code>{lines}</code>
|
||||
</pre>
|
||||
);
|
||||
}
|
||||
|
||||
export function ErrorOverlay(props: PageProps) {
|
||||
const url = props.url;
|
||||
const title = url.searchParams.get("message") || "Internal Server Error";
|
||||
const stack = url.searchParams.get("stack");
|
||||
const codeFrame = url.searchParams.get("code-frame");
|
||||
|
||||
return (
|
||||
<>
|
||||
<div class="frsh-error-page">
|
||||
<style dangerouslySetInnerHTML={{ __html: errorCss }} />
|
||||
<div class="inner">
|
||||
<div class="header">
|
||||
<button class="close-btn" aria-label="close" id="close-btn">
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
strokeWidth={1.5}
|
||||
stroke="currentColor"
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
d="M9.75 9.75l4.5 4.5m0-4.5l-4.5 4.5M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
|
||||
/>
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
<div>
|
||||
<h1 class="title">{title}</h1>
|
||||
{codeFrame ? <CodeFrame codeFrame={codeFrame} /> : null}
|
||||
{stack ? <pre class="stack">{stack}</pre> : null}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<script
|
||||
dangerouslySetInnerHTML={{
|
||||
__html:
|
||||
`document.querySelector("#close-btn").addEventListener("click", () => parent.postMessage("close-error-overlay"));`,
|
||||
}}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,565 +0,0 @@
|
||||
import { ComponentType, h } from "preact";
|
||||
import {
|
||||
AppModule,
|
||||
ErrorPage,
|
||||
ErrorPageModule,
|
||||
InternalFreshState,
|
||||
Island,
|
||||
IslandModule,
|
||||
LayoutModule,
|
||||
LayoutRoute,
|
||||
MiddlewareHandler,
|
||||
MiddlewareModule,
|
||||
MiddlewareRoute,
|
||||
Plugin,
|
||||
Route,
|
||||
RouteModule,
|
||||
StaticFile,
|
||||
UnknownPage,
|
||||
UnknownPageModule,
|
||||
} from "./types.ts";
|
||||
import * as router from "./router.ts";
|
||||
import DefaultErrorHandler from "./default_error_page.tsx";
|
||||
import {
|
||||
basename,
|
||||
contentType,
|
||||
dirname,
|
||||
extname,
|
||||
join,
|
||||
SEPARATOR,
|
||||
toFileUrl,
|
||||
walk,
|
||||
} from "./deps.ts";
|
||||
import { BUILD_ID } from "./build_id.ts";
|
||||
import { toBaseRoute } from "./compose.ts";
|
||||
import { stringToIdentifier } from "./init_safe_deps.ts";
|
||||
|
||||
export const ROOT_BASE_ROUTE = toBaseRoute("/");
|
||||
|
||||
const DEFAULT_APP: AppModule = {
|
||||
default: ({ Component }: { Component: ComponentType }) => h(Component, {}),
|
||||
};
|
||||
|
||||
const DEFAULT_NOT_FOUND: UnknownPage = {
|
||||
baseRoute: toBaseRoute("/"),
|
||||
pattern: "",
|
||||
url: "",
|
||||
name: "_404",
|
||||
handler: (req) => router.defaultOtherHandler(req),
|
||||
csp: false,
|
||||
appWrapper: true,
|
||||
inheritLayouts: true,
|
||||
};
|
||||
|
||||
const DEFAULT_ERROR: ErrorPage = {
|
||||
baseRoute: toBaseRoute("/"),
|
||||
pattern: "",
|
||||
url: "",
|
||||
name: "_500",
|
||||
component: DefaultErrorHandler,
|
||||
handler: (_req, ctx) => ctx.render(),
|
||||
csp: false,
|
||||
appWrapper: true,
|
||||
inheritLayouts: true,
|
||||
};
|
||||
|
||||
export interface FsExtractResult {
|
||||
app: AppModule;
|
||||
layouts: LayoutRoute[];
|
||||
notFound: UnknownPage;
|
||||
error: ErrorPage;
|
||||
middlewares: MiddlewareRoute[];
|
||||
islands: Island[];
|
||||
routes: Route[];
|
||||
staticFiles: StaticFile[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract all routes, and prepare them into the `Page` structure.
|
||||
*/
|
||||
export async function extractRoutes(
|
||||
state: InternalFreshState,
|
||||
): Promise<FsExtractResult> {
|
||||
const { config, manifest } = state;
|
||||
|
||||
// Get the manifest' base URL.
|
||||
const baseUrl = new URL("./", manifest.baseUrl).href;
|
||||
|
||||
const routes: Route[] = [];
|
||||
const islands: Island[] = [];
|
||||
const middlewares: MiddlewareRoute[] = [];
|
||||
let app: AppModule = DEFAULT_APP;
|
||||
const layouts: LayoutRoute[] = [];
|
||||
let notFound: UnknownPage = DEFAULT_NOT_FOUND;
|
||||
let error: ErrorPage = DEFAULT_ERROR;
|
||||
const allRoutes = [
|
||||
...Object.entries(manifest.routes),
|
||||
...(config.plugins ? getMiddlewareRoutesFromPlugins(config.plugins) : []),
|
||||
...(config.plugins ? getRoutesFromPlugins(config.plugins) : []),
|
||||
];
|
||||
|
||||
// Presort all routes so that we only need to sort once
|
||||
allRoutes.sort((a, b) => sortRoutePaths(a[0], b[0]));
|
||||
|
||||
for (
|
||||
const [self, module] of allRoutes
|
||||
) {
|
||||
const url = new URL(self, baseUrl).href;
|
||||
if (!url.startsWith(baseUrl + "routes")) {
|
||||
throw new TypeError("Page is not a child of the basepath.");
|
||||
}
|
||||
const path = url.substring(baseUrl.length + "routes".length);
|
||||
let baseRoute = path.substring(1, path.length - extname(path).length);
|
||||
baseRoute = join(state.config.basePath.slice(1), baseRoute).replaceAll(
|
||||
SEPARATOR,
|
||||
"/",
|
||||
);
|
||||
const name = baseRoute.replace(/\//g, "-");
|
||||
const isLayout = path.endsWith("/_layout.tsx") ||
|
||||
path.endsWith("/_layout.ts") || path.endsWith("/_layout.jsx") ||
|
||||
path.endsWith("/_layout.js");
|
||||
const isMiddleware = path.endsWith("/_middleware.tsx") ||
|
||||
path.endsWith("/_middleware.ts") || path.endsWith("/_middleware.jsx") ||
|
||||
path.endsWith("/_middleware.js");
|
||||
if (
|
||||
!path.startsWith("/_") && !isLayout && !isMiddleware
|
||||
) {
|
||||
const { default: component, config } = module as RouteModule;
|
||||
let pattern = pathToPattern(baseRoute);
|
||||
if (config?.routeOverride) {
|
||||
pattern = String(config.routeOverride);
|
||||
}
|
||||
let { handler } = module as RouteModule;
|
||||
if (!handler && "handlers" in module) {
|
||||
throw new Error(
|
||||
`Found named export "handlers" in ${self} instead of "handler". Did you mean "handler"?`,
|
||||
);
|
||||
}
|
||||
handler ??= {};
|
||||
if (
|
||||
component && typeof handler === "object" && handler.GET === undefined
|
||||
) {
|
||||
handler.GET = (_req, { render }) => render();
|
||||
}
|
||||
if (
|
||||
typeof handler === "object" && handler.GET !== undefined &&
|
||||
handler.HEAD === undefined
|
||||
) {
|
||||
const GET = handler.GET;
|
||||
handler.HEAD = async (req, ctx) => {
|
||||
const resp = await GET(req, ctx);
|
||||
resp.body?.cancel();
|
||||
return new Response(null, {
|
||||
headers: resp.headers,
|
||||
status: resp.status,
|
||||
statusText: resp.statusText,
|
||||
});
|
||||
};
|
||||
}
|
||||
const route: Route = {
|
||||
baseRoute: toBaseRoute(baseRoute),
|
||||
pattern,
|
||||
url,
|
||||
name,
|
||||
component,
|
||||
handler,
|
||||
csp: Boolean(config?.csp ?? false),
|
||||
appWrapper: !config?.skipAppWrapper,
|
||||
inheritLayouts: !config?.skipInheritedLayouts,
|
||||
};
|
||||
routes.push(route);
|
||||
} else if (isMiddleware) {
|
||||
middlewares.push({
|
||||
baseRoute: toBaseRoute(baseRoute),
|
||||
module: module as MiddlewareModule,
|
||||
});
|
||||
} else if (
|
||||
path === "/_app.tsx" || path === "/_app.ts" ||
|
||||
path === "/_app.jsx" || path === "/_app.js"
|
||||
) {
|
||||
app = module as AppModule;
|
||||
} else if (isLayout) {
|
||||
const mod = module as LayoutModule;
|
||||
const config = mod.config;
|
||||
layouts.push({
|
||||
baseRoute: toBaseRoute(baseRoute),
|
||||
handler: mod.handler,
|
||||
component: mod.default,
|
||||
appWrapper: !config?.skipAppWrapper,
|
||||
inheritLayouts: !config?.skipInheritedLayouts,
|
||||
});
|
||||
} else if (
|
||||
path === "/_404.tsx" || path === "/_404.ts" ||
|
||||
path === "/_404.jsx" || path === "/_404.js"
|
||||
) {
|
||||
const { default: component, config } = module as UnknownPageModule;
|
||||
let { handler } = module as UnknownPageModule;
|
||||
if (component && handler === undefined) {
|
||||
handler = (_req, { render }) => render();
|
||||
}
|
||||
|
||||
notFound = {
|
||||
baseRoute: ROOT_BASE_ROUTE,
|
||||
pattern: pathToPattern(baseRoute),
|
||||
url,
|
||||
name,
|
||||
component,
|
||||
handler: handler ?? ((req) => router.defaultOtherHandler(req)),
|
||||
csp: Boolean(config?.csp ?? false),
|
||||
appWrapper: !config?.skipAppWrapper,
|
||||
inheritLayouts: !config?.skipInheritedLayouts,
|
||||
};
|
||||
} else if (
|
||||
path === "/_500.tsx" || path === "/_500.ts" ||
|
||||
path === "/_500.jsx" || path === "/_500.js"
|
||||
) {
|
||||
const { default: component, config: routeConfig } =
|
||||
module as ErrorPageModule;
|
||||
let { handler } = module as ErrorPageModule;
|
||||
if (component && handler === undefined) {
|
||||
handler = (_req, { render }) => render();
|
||||
}
|
||||
|
||||
error = {
|
||||
baseRoute: toBaseRoute("/"),
|
||||
pattern: pathToPattern(baseRoute),
|
||||
url,
|
||||
name,
|
||||
component,
|
||||
handler: handler ?? router.defaultErrorHandler,
|
||||
csp: Boolean(routeConfig?.csp ?? false),
|
||||
appWrapper: !routeConfig?.skipAppWrapper,
|
||||
inheritLayouts: !routeConfig?.skipInheritedLayouts,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const processedIslands: {
|
||||
name: string;
|
||||
path: string;
|
||||
module: IslandModule;
|
||||
}[] = [];
|
||||
|
||||
for (const plugin of config.plugins || []) {
|
||||
if (!plugin.islands) continue;
|
||||
const base = dirname(plugin.islands.baseLocation);
|
||||
|
||||
for (const specifier of plugin.islands.paths) {
|
||||
const full = join(base, specifier);
|
||||
const module = await import(full);
|
||||
const name = sanitizeIslandName(basename(full, extname(full)));
|
||||
processedIslands.push({
|
||||
name,
|
||||
path: full,
|
||||
module,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
for (const [self, module] of Object.entries(manifest.islands)) {
|
||||
const url = new URL(self, baseUrl).href;
|
||||
if (!url.startsWith(baseUrl)) {
|
||||
throw new TypeError("Island is not a child of the basepath.");
|
||||
}
|
||||
let path = url.substring(baseUrl.length);
|
||||
if (path.startsWith("islands")) {
|
||||
path = path.slice("islands".length + 1);
|
||||
}
|
||||
const baseRoute = path.substring(0, path.length - extname(path).length);
|
||||
|
||||
processedIslands.push({
|
||||
name: sanitizeIslandName(baseRoute),
|
||||
path: url,
|
||||
module,
|
||||
});
|
||||
}
|
||||
|
||||
for (const processedIsland of processedIslands) {
|
||||
for (
|
||||
const [exportName, exportedFunction] of Object.entries(
|
||||
processedIsland.module,
|
||||
)
|
||||
) {
|
||||
if (typeof exportedFunction !== "function") continue;
|
||||
const name = processedIsland.name.toLowerCase();
|
||||
const id = `${name}_${exportName.toLowerCase()}`;
|
||||
islands.push({
|
||||
id,
|
||||
name,
|
||||
url: processedIsland.path,
|
||||
// deno-lint-ignore no-explicit-any
|
||||
component: exportedFunction as ComponentType<any>,
|
||||
exportName,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const staticFiles: StaticFile[] = [];
|
||||
try {
|
||||
const staticDirs = [config.staticDir];
|
||||
|
||||
// Only fall through to files in /_fresh/static when not in dev
|
||||
if (state.loadSnapshot) {
|
||||
const outDirStatic = join(config.build.outDir, "static");
|
||||
staticDirs.push(outDirStatic);
|
||||
}
|
||||
|
||||
for (const staticDir of staticDirs) {
|
||||
const staticDirUrl = toFileUrl(staticDir);
|
||||
const entries = walk(staticDir, {
|
||||
includeFiles: true,
|
||||
includeDirs: false,
|
||||
followSymlinks: false,
|
||||
});
|
||||
const encoder = new TextEncoder();
|
||||
for await (const entry of entries) {
|
||||
const localUrl = toFileUrl(entry.path);
|
||||
const path = localUrl.href.substring(staticDirUrl.href.length);
|
||||
const stat = await Deno.stat(localUrl);
|
||||
const type = contentType(extname(path)) ??
|
||||
"application/octet-stream";
|
||||
const etag = await crypto.subtle.digest(
|
||||
"SHA-1",
|
||||
encoder.encode(BUILD_ID + path),
|
||||
).then((hash) =>
|
||||
Array.from(new Uint8Array(hash))
|
||||
.map((byte) => byte.toString(16).padStart(2, "0"))
|
||||
.join("")
|
||||
);
|
||||
const staticFile: StaticFile = {
|
||||
localUrl,
|
||||
path: join(state.config.basePath, path),
|
||||
size: stat.size,
|
||||
contentType: type,
|
||||
etag,
|
||||
};
|
||||
staticFiles.push(staticFile);
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
if (err.cause instanceof Deno.errors.NotFound) {
|
||||
// Do nothing.
|
||||
} else {
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
app,
|
||||
error,
|
||||
islands,
|
||||
layouts,
|
||||
middlewares,
|
||||
notFound,
|
||||
routes,
|
||||
staticFiles,
|
||||
};
|
||||
}
|
||||
|
||||
const APP_REG = /_app\.[tj]sx?$/;
|
||||
|
||||
/**
|
||||
* Sort route paths where special Fresh files like `_app`,
|
||||
* `_layout` and `_middleware` are sorted in front.
|
||||
*/
|
||||
export function sortRoutePaths(a: string, b: string) {
|
||||
// The `_app` route should always be the first
|
||||
if (APP_REG.test(a)) return -1;
|
||||
else if (APP_REG.test(b)) return 1;
|
||||
|
||||
let segmentIdx = 0;
|
||||
const aLen = a.length;
|
||||
const bLen = b.length;
|
||||
const maxLen = aLen > bLen ? aLen : bLen;
|
||||
for (let i = 0; i < maxLen; i++) {
|
||||
const charA = a.charAt(i);
|
||||
const charB = b.charAt(i);
|
||||
const nextA = i + 1 < aLen ? a.charAt(i + 1) : "";
|
||||
const nextB = i + 1 < bLen ? b.charAt(i + 1) : "";
|
||||
|
||||
if (charA === "/" || charB === "/") {
|
||||
segmentIdx = i;
|
||||
// If the other path doesn't close the segment
|
||||
// then we don't need to continue
|
||||
if (charA !== "/") return -1;
|
||||
if (charB !== "/") return 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (i === segmentIdx + 1) {
|
||||
const scoreA = getRoutePathScore(charA, nextA);
|
||||
const scoreB = getRoutePathScore(charB, nextB);
|
||||
if (scoreA === scoreB) continue;
|
||||
return scoreA > scoreB ? -1 : 1;
|
||||
}
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Assign a score based on the first two characters of a path segment.
|
||||
* The goal is to sort `_middleware` and `_layout` in front of everything
|
||||
* and `[` or `[...` last respectively.
|
||||
*/
|
||||
function getRoutePathScore(char: string, nextChar: string): number {
|
||||
if (char === "_") {
|
||||
if (nextChar === "m") return 4;
|
||||
return 3;
|
||||
} else if (char === "[") {
|
||||
if (nextChar === ".") {
|
||||
return 0;
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
return 2;
|
||||
}
|
||||
|
||||
/**
|
||||
* Transform a filesystem URL path to a `path-to-regex` style matcher. */
|
||||
export function pathToPattern(path: string): string {
|
||||
const parts = path.split("/");
|
||||
if (parts[parts.length - 1] === "index") {
|
||||
if (parts.length === 1) {
|
||||
return "/";
|
||||
}
|
||||
parts.pop();
|
||||
}
|
||||
|
||||
let route = "";
|
||||
|
||||
for (let i = 0; i < parts.length; i++) {
|
||||
const part = parts[i];
|
||||
|
||||
// Case: /[...foo].tsx
|
||||
if (part.startsWith("[...") && part.endsWith("]")) {
|
||||
route += `/:${part.slice(4, part.length - 1)}*`;
|
||||
continue;
|
||||
}
|
||||
|
||||
// Route groups like /foo/(bar) should not be included in URL
|
||||
// matching. They are transparent and need to be removed here.
|
||||
// Case: /foo/(bar) -> /foo
|
||||
// Case: /foo/(bar)/bob -> /foo/bob
|
||||
// Case: /(foo)/bar -> /bar
|
||||
if (part.startsWith("(") && part.endsWith(")")) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Disallow neighbouring params like `/[id][bar].tsx` because
|
||||
// it's ambiguous where the `id` param ends and `bar` begins.
|
||||
if (part.includes("][")) {
|
||||
throw new SyntaxError(
|
||||
`Invalid route pattern: "${path}". A parameter cannot be followed by another parameter without any characters in between.`,
|
||||
);
|
||||
}
|
||||
|
||||
// Case: /[[id]].tsx
|
||||
// Case: /[id].tsx
|
||||
// Case: /[id]@[bar].tsx
|
||||
// Case: /[id]-asdf.tsx
|
||||
// Case: /[id]-asdf[bar].tsx
|
||||
// Case: /asdf[bar].tsx
|
||||
let pattern = "";
|
||||
let groupOpen = 0;
|
||||
let optional = false;
|
||||
for (let j = 0; j < part.length; j++) {
|
||||
const char = part[j];
|
||||
if (char === "[") {
|
||||
if (part[j + 1] === "[") {
|
||||
// Disallow optional dynamic params like `foo-[[bar]]`
|
||||
if (part[j - 1] !== "/" && !!part[j - 1]) {
|
||||
throw new SyntaxError(
|
||||
`Invalid route pattern: "${path}". An optional parameter needs to be a full segment.`,
|
||||
);
|
||||
}
|
||||
groupOpen++;
|
||||
optional = true;
|
||||
pattern += "{/";
|
||||
j++;
|
||||
}
|
||||
pattern += ":";
|
||||
groupOpen++;
|
||||
} else if (char === "]") {
|
||||
if (part[j + 1] === "]") {
|
||||
// Disallow optional dynamic params like `[[foo]]-bar`
|
||||
if (part[j + 2] !== "/" && !!part[j + 2]) {
|
||||
throw new SyntaxError(
|
||||
`Invalid route pattern: "${path}". An optional parameter needs to be a full segment.`,
|
||||
);
|
||||
}
|
||||
groupOpen--;
|
||||
pattern += "}?";
|
||||
j++;
|
||||
}
|
||||
if (--groupOpen < 0) {
|
||||
throw new SyntaxError(`Invalid route pattern: "${path}"`);
|
||||
}
|
||||
} else {
|
||||
pattern += char;
|
||||
}
|
||||
}
|
||||
|
||||
route += (optional ? "" : "/") + pattern;
|
||||
}
|
||||
|
||||
// Case: /(group)/index.tsx
|
||||
if (route === "") {
|
||||
route = "/";
|
||||
}
|
||||
|
||||
return route;
|
||||
}
|
||||
|
||||
function toPascalCase(text: string): string {
|
||||
return text.replace(
|
||||
/(^\w|-\w)/g,
|
||||
(substring) => substring.replace(/-/, "").toUpperCase(),
|
||||
);
|
||||
}
|
||||
|
||||
function sanitizeIslandName(name: string): string {
|
||||
const fileName = stringToIdentifier(name);
|
||||
return toPascalCase(fileName);
|
||||
}
|
||||
|
||||
function formatMiddlewarePath(path: string): string {
|
||||
const prefix = !path.startsWith("/") ? "/" : "";
|
||||
const suffix = !path.endsWith("/") ? "/" : "";
|
||||
return prefix + path + suffix;
|
||||
}
|
||||
|
||||
function getMiddlewareRoutesFromPlugins(
|
||||
plugins: Plugin[],
|
||||
): [string, MiddlewareModule][] {
|
||||
const middlewares = plugins.flatMap((plugin) => plugin.middlewares ?? []);
|
||||
|
||||
const mws: Record<
|
||||
string,
|
||||
[string, { handler: MiddlewareHandler[] }]
|
||||
> = {};
|
||||
for (let i = 0; i < middlewares.length; i++) {
|
||||
const mw = middlewares[i];
|
||||
const handler = mw.middleware.handler;
|
||||
const key = `./routes${formatMiddlewarePath(mw.path)}_middleware.ts`;
|
||||
if (!mws[key]) mws[key] = [key, { handler: [] }];
|
||||
mws[key][1].handler.push(...Array.isArray(handler) ? handler : [handler]);
|
||||
}
|
||||
|
||||
return Object.values(mws);
|
||||
}
|
||||
|
||||
function formatRoutePath(path: string) {
|
||||
return path.startsWith("/") ? path : "/" + path;
|
||||
}
|
||||
|
||||
function getRoutesFromPlugins(plugins: Plugin[]): [string, RouteModule][] {
|
||||
return plugins.flatMap((plugin) => plugin.routes ?? [])
|
||||
.map((route) => {
|
||||
return [`./routes${formatRoutePath(route.path)}.ts`, {
|
||||
// deno-lint-ignore no-explicit-any
|
||||
default: route.component as any,
|
||||
handler: route.handler,
|
||||
}];
|
||||
});
|
||||
}
|
||||
@@ -1,79 +0,0 @@
|
||||
import { assertEquals, assertThrows } from "./deps.ts";
|
||||
import { pathToPattern, sortRoutePaths } from "./fs_extract.ts";
|
||||
|
||||
Deno.test("pathToPattern", async (t) => {
|
||||
await t.step("creates pattern", () => {
|
||||
assertEquals(pathToPattern("foo/bar"), "/foo/bar");
|
||||
});
|
||||
|
||||
await t.step("parses index routes", () => {
|
||||
assertEquals(pathToPattern("foo/index"), "/foo");
|
||||
});
|
||||
|
||||
await t.step("parses parameters", () => {
|
||||
assertEquals(pathToPattern("foo/[name]"), "/foo/:name");
|
||||
assertEquals(pathToPattern("foo/[name]/bar/[bob]"), "/foo/:name/bar/:bob");
|
||||
});
|
||||
|
||||
await t.step("parses catchall", () => {
|
||||
assertEquals(pathToPattern("foo/[...name]"), "/foo/:name*");
|
||||
});
|
||||
|
||||
await t.step("parses multiple params in same part", () => {
|
||||
assertEquals(pathToPattern("foo/[mod]@[version]"), "/foo/:mod@:version");
|
||||
assertEquals(pathToPattern("foo/[bar].json"), "/foo/:bar.json");
|
||||
assertEquals(pathToPattern("foo/foo[bar]"), "/foo/foo:bar");
|
||||
});
|
||||
|
||||
await t.step("parses optional params", () => {
|
||||
assertEquals(pathToPattern("foo/[[name]]"), "/foo{/:name}?");
|
||||
assertEquals(pathToPattern("foo/[name]/[[bob]]"), "/foo/:name{/:bob}?");
|
||||
assertEquals(pathToPattern("foo/[[name]]/bar"), "/foo{/:name}?/bar");
|
||||
assertEquals(
|
||||
pathToPattern("foo/[[name]]/bar/[[bob]]"),
|
||||
"/foo{/:name}?/bar{/:bob}?",
|
||||
);
|
||||
});
|
||||
|
||||
await t.step("throws on invalid patterns", () => {
|
||||
assertThrows(() => pathToPattern("foo/[foo][bar]"));
|
||||
assertThrows(() => pathToPattern("foo/foo]"));
|
||||
assertThrows(() => pathToPattern("foo/[foo]]"));
|
||||
assertThrows(() => pathToPattern("foo/foo-[[name]]-bar/baz"));
|
||||
assertThrows(() => pathToPattern("foo/[[name]]-bar/baz"));
|
||||
assertThrows(() => pathToPattern("foo/foo-[[name]]/baz"));
|
||||
assertThrows(() => pathToPattern("foo/foo-[[name]]"));
|
||||
assertThrows(() => pathToPattern("foo/[[name]]-bar"));
|
||||
});
|
||||
});
|
||||
|
||||
Deno.test("sortRoutePaths", () => {
|
||||
const routes = [
|
||||
"/foo/[id]",
|
||||
"/foo/[...slug]",
|
||||
"/foo/bar",
|
||||
"/foo/_layout",
|
||||
"/foo/index",
|
||||
"/foo/_middleware",
|
||||
"/foo/bar/_middleware",
|
||||
"/foo/bar/index",
|
||||
"/foo/bar/[...foo]",
|
||||
"/foo/bar/baz",
|
||||
"/foo/bar/_layout",
|
||||
];
|
||||
const sorted = [
|
||||
"/foo/_middleware",
|
||||
"/foo/_layout",
|
||||
"/foo/bar",
|
||||
"/foo/index",
|
||||
"/foo/bar/_middleware",
|
||||
"/foo/bar/_layout",
|
||||
"/foo/bar/index",
|
||||
"/foo/bar/baz",
|
||||
"/foo/bar/[...foo]",
|
||||
"/foo/[id]",
|
||||
"/foo/[...slug]",
|
||||
];
|
||||
routes.sort(sortRoutePaths);
|
||||
assertEquals(routes, sorted);
|
||||
});
|
||||
@@ -1,15 +0,0 @@
|
||||
// This utility is based on https://github.com/zertosh/htmlescape
|
||||
// License: https://github.com/zertosh/htmlescape/blob/0527ca7156a524d256101bb310a9f970f63078ad/LICENSE
|
||||
|
||||
const ESCAPE_LOOKUP: { [match: string]: string } = {
|
||||
">": "\\u003e",
|
||||
"<": "\\u003c",
|
||||
"\u2028": "\\u2028",
|
||||
"\u2029": "\\u2029",
|
||||
};
|
||||
|
||||
const ESCAPE_REGEX = /[><\u2028\u2029]/g;
|
||||
|
||||
export function htmlEscapeJsonString(str: string): string {
|
||||
return str.replace(ESCAPE_REGEX, (match) => ESCAPE_LOOKUP[match]);
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
import { htmlEscapeJsonString } from "./htmlescape.ts";
|
||||
import { assertEquals } from "../../tests/deps.ts";
|
||||
|
||||
Deno.test("with angle brackets should escape", () => {
|
||||
const evilObj = { evil: "<script></script>" };
|
||||
assertEquals(
|
||||
htmlEscapeJsonString(JSON.stringify(evilObj)),
|
||||
'{"evil":"\\u003cscript\\u003e\\u003c/script\\u003e"}',
|
||||
);
|
||||
});
|
||||
|
||||
Deno.test("with angle brackets should parse back", () => {
|
||||
const evilObj = { evil: "<script></script>" };
|
||||
assertEquals(
|
||||
JSON.parse(htmlEscapeJsonString(JSON.stringify(evilObj))),
|
||||
evilObj,
|
||||
);
|
||||
});
|
||||
@@ -1,34 +0,0 @@
|
||||
// This file includes dependencies that are safe to use even
|
||||
// when the user has no `deno.json` in their project folder.
|
||||
// This commonly occurs when the user is bootstrapping a new
|
||||
// project.
|
||||
|
||||
export {
|
||||
isIdentifierChar,
|
||||
isIdentifierStart,
|
||||
} from "https://esm.sh/@babel/helper-validator-identifier@7.22.20";
|
||||
import {
|
||||
isIdentifierChar,
|
||||
isIdentifierStart,
|
||||
} from "https://esm.sh/@babel/helper-validator-identifier@7.22.20";
|
||||
|
||||
export function stringToIdentifier(str: string): string {
|
||||
let ident = "";
|
||||
for (let i = 0; i < str.length; i++) {
|
||||
const char = str.charCodeAt(i);
|
||||
if (i === 0 && !isIdentifierStart(char)) {
|
||||
ident += "_";
|
||||
if (isIdentifierChar(char)) {
|
||||
ident += str[i];
|
||||
}
|
||||
} else if (!isIdentifierChar(char)) {
|
||||
if (ident[ident.length - 1] !== "_") {
|
||||
ident += "_";
|
||||
}
|
||||
} else if (ident[ident.length - 1] !== "_" || str[i] !== "_") {
|
||||
ident += str[i];
|
||||
}
|
||||
}
|
||||
|
||||
return ident;
|
||||
}
|
||||
@@ -1,119 +0,0 @@
|
||||
import { ServerContext } from "./context.ts";
|
||||
export type { FromManifestConfig, FromManifestOptions } from "./context.ts";
|
||||
export { STATUS_CODE } from "./deps.ts";
|
||||
import {
|
||||
ErrorHandler,
|
||||
FreshConfig,
|
||||
Handler,
|
||||
Handlers,
|
||||
IslandModule,
|
||||
LayoutConfig,
|
||||
MiddlewareModule,
|
||||
RouteConfig,
|
||||
ServeHandlerInfo,
|
||||
UnknownHandler,
|
||||
} from "./types.ts";
|
||||
import { startServer } from "./boot.ts";
|
||||
export {
|
||||
defineApp,
|
||||
defineConfig,
|
||||
defineLayout,
|
||||
defineRoute,
|
||||
} from "./defines.ts";
|
||||
export type {
|
||||
AppContext,
|
||||
AppProps,
|
||||
DenoConfig,
|
||||
ErrorHandler,
|
||||
ErrorHandlerContext,
|
||||
ErrorPageProps,
|
||||
FreshConfig,
|
||||
FreshContext,
|
||||
FreshOptions,
|
||||
Handler,
|
||||
HandlerContext,
|
||||
Handlers,
|
||||
LayoutConfig,
|
||||
LayoutContext,
|
||||
LayoutProps,
|
||||
MiddlewareHandler,
|
||||
MiddlewareHandlerContext,
|
||||
MultiHandler,
|
||||
PageProps,
|
||||
Plugin,
|
||||
PluginAsyncRenderContext,
|
||||
PluginAsyncRenderFunction,
|
||||
PluginIslands,
|
||||
PluginMiddleware,
|
||||
PluginRenderContext,
|
||||
PluginRenderFunction,
|
||||
PluginRenderFunctionResult,
|
||||
PluginRenderResult,
|
||||
PluginRenderScripts,
|
||||
PluginRenderStyleTag,
|
||||
PluginRoute,
|
||||
RenderFunction,
|
||||
ResolvedFreshConfig,
|
||||
RouteConfig,
|
||||
RouteContext,
|
||||
RouterOptions,
|
||||
ServeHandlerInfo,
|
||||
StartOptions,
|
||||
UnknownHandler,
|
||||
UnknownHandlerContext,
|
||||
UnknownPageProps,
|
||||
} from "./types.ts";
|
||||
export { RenderContext } from "./render.ts";
|
||||
export type { InnerRenderFunction } from "./render.ts";
|
||||
export type { DestinationKind } from "./router.ts";
|
||||
|
||||
export interface Manifest {
|
||||
routes: Record<
|
||||
string,
|
||||
{
|
||||
// Use a more loose route definition type because
|
||||
// TS has trouble inferring normal vs aync functions. It cannot infer based on function arity
|
||||
default?: (
|
||||
// deno-lint-ignore no-explicit-any
|
||||
propsOrRequest: any,
|
||||
// deno-lint-ignore no-explicit-any
|
||||
ctx: any,
|
||||
// deno-lint-ignore no-explicit-any
|
||||
) => Promise<any | Response> | any;
|
||||
handler?:
|
||||
// deno-lint-ignore no-explicit-any
|
||||
| Handler<any, any>
|
||||
// deno-lint-ignore no-explicit-any
|
||||
| Handlers<any, any>
|
||||
| UnknownHandler
|
||||
| ErrorHandler;
|
||||
config?: RouteConfig | LayoutConfig;
|
||||
} | MiddlewareModule
|
||||
>;
|
||||
islands: Record<string, IslandModule>;
|
||||
baseUrl: string;
|
||||
}
|
||||
|
||||
export { ServerContext };
|
||||
|
||||
export async function createHandler(
|
||||
manifest: Manifest,
|
||||
config: FreshConfig = {},
|
||||
): Promise<
|
||||
(req: Request, connInfo?: ServeHandlerInfo) => Promise<Response>
|
||||
> {
|
||||
const ctx = await ServerContext.fromManifest(manifest, config);
|
||||
return ctx.handler();
|
||||
}
|
||||
|
||||
export async function start(manifest: Manifest, config: FreshConfig = {}) {
|
||||
const ctx = await ServerContext.fromManifest(manifest, {
|
||||
...config,
|
||||
dev: false,
|
||||
});
|
||||
const realConfig = config.server ?? config;
|
||||
await startServer(ctx.handler(), {
|
||||
...realConfig,
|
||||
basePath: config?.router?.basePath ?? "",
|
||||
});
|
||||
}
|
||||
@@ -1,399 +0,0 @@
|
||||
import { h, VNode } from "preact";
|
||||
import {
|
||||
AppModule,
|
||||
AsyncLayout,
|
||||
AsyncRoute,
|
||||
ErrorPage,
|
||||
FreshContext,
|
||||
LayoutRoute,
|
||||
PageProps,
|
||||
Plugin,
|
||||
PluginRenderFunctionResult,
|
||||
PluginRenderResult,
|
||||
RenderFunction,
|
||||
Route,
|
||||
UnknownPage,
|
||||
} from "./types.ts";
|
||||
import { NONE, UNSAFE_INLINE } from "../runtime/csp.ts";
|
||||
import { ContentSecurityPolicy } from "../runtime/csp.ts";
|
||||
import { RenderState } from "./rendering/state.ts";
|
||||
import { renderHtml, renderOuterDocument } from "./rendering/template.tsx";
|
||||
import { renderFreshTags } from "./rendering/fresh_tags.tsx";
|
||||
import { DEV_ERROR_OVERLAY_URL } from "./constants.ts";
|
||||
import { colors } from "./deps.ts";
|
||||
import { withBase } from "./router.ts";
|
||||
|
||||
export const DEFAULT_RENDER_FN: RenderFunction = (_ctx, render) => {
|
||||
render();
|
||||
};
|
||||
|
||||
export interface RenderOptions<Data> {
|
||||
request: Request;
|
||||
context: FreshContext;
|
||||
route: Route<Data> | UnknownPage | ErrorPage;
|
||||
plugins: Plugin[];
|
||||
app: AppModule;
|
||||
layouts: LayoutRoute[];
|
||||
imports: string[];
|
||||
dependenciesFn: (path: string) => string[];
|
||||
renderFn: RenderFunction;
|
||||
codeFrame?: string;
|
||||
lang?: string;
|
||||
}
|
||||
|
||||
export type InnerRenderFunction = () => string;
|
||||
|
||||
export class RenderContext {
|
||||
#id: string;
|
||||
#state: Map<string, unknown> = new Map();
|
||||
#styles: string[] = [];
|
||||
#url: URL;
|
||||
#route: string;
|
||||
#lang: string;
|
||||
|
||||
constructor(id: string, url: URL, route: string, lang: string) {
|
||||
this.#id = id;
|
||||
this.#url = url;
|
||||
this.#route = route;
|
||||
this.#lang = lang;
|
||||
}
|
||||
|
||||
/** A unique ID for this logical JIT render. */
|
||||
get id(): string {
|
||||
return this.#id;
|
||||
}
|
||||
|
||||
/**
|
||||
* State that is persisted between multiple renders with the same render
|
||||
* context. This is useful because one logical JIT render could have multiple
|
||||
* preact render passes due to suspense.
|
||||
*/
|
||||
get state(): Map<string, unknown> {
|
||||
return this.#state;
|
||||
}
|
||||
|
||||
/**
|
||||
* All of the CSS style rules that should be inlined into the document.
|
||||
* Adding to this list across multiple renders is supported (even across
|
||||
* suspense!). The CSS rules will always be inserted on the client in the
|
||||
* order specified here.
|
||||
*/
|
||||
get styles(): string[] {
|
||||
return this.#styles;
|
||||
}
|
||||
|
||||
/** The URL of the page being rendered. */
|
||||
get url(): URL {
|
||||
return this.#url;
|
||||
}
|
||||
|
||||
/** The route matcher (e.g. /blog/:id) that the request matched for this page
|
||||
* to be rendered. */
|
||||
get route(): string {
|
||||
return this.#route;
|
||||
}
|
||||
|
||||
/** The language of the page being rendered. Defaults to "en". */
|
||||
get lang(): string {
|
||||
return this.#lang;
|
||||
}
|
||||
set lang(lang: string) {
|
||||
this.#lang = lang;
|
||||
}
|
||||
}
|
||||
|
||||
function defaultCsp() {
|
||||
return {
|
||||
directives: { defaultSrc: [NONE], styleSrc: [UNSAFE_INLINE] },
|
||||
reportOnly: false,
|
||||
};
|
||||
}
|
||||
|
||||
export function checkAsyncComponent<T>(
|
||||
component: unknown,
|
||||
): component is AsyncRoute<T> | AsyncLayout<T> {
|
||||
return typeof component === "function" &&
|
||||
component.constructor.name === "AsyncFunction";
|
||||
}
|
||||
|
||||
/**
|
||||
* This function renders out a page. Rendering is synchronous and non streaming.
|
||||
* Suspense boundaries are not supported.
|
||||
*/
|
||||
export async function render<Data>(
|
||||
opts: RenderOptions<Data>,
|
||||
): Promise<[string, string, ContentSecurityPolicy | undefined] | Response> {
|
||||
const component = opts.route.component;
|
||||
|
||||
// Only inherit layouts up to the nearest root layout.
|
||||
// Note that the route itself can act as the root layout.
|
||||
let layouts = opts.layouts;
|
||||
if (opts.route.inheritLayouts) {
|
||||
let rootIdx = 0;
|
||||
let layoutIdx = opts.layouts.length;
|
||||
while (layoutIdx--) {
|
||||
if (!opts.layouts[layoutIdx].inheritLayouts) {
|
||||
rootIdx = layoutIdx;
|
||||
break;
|
||||
}
|
||||
}
|
||||
layouts = opts.layouts.slice(rootIdx);
|
||||
} else {
|
||||
layouts = [];
|
||||
}
|
||||
|
||||
const { params, data, state, error, url, basePath } = opts.context;
|
||||
|
||||
const props: PageProps = {
|
||||
basePath,
|
||||
config: opts.context.config,
|
||||
destination: opts.context.destination,
|
||||
isPartial: opts.context.isPartial,
|
||||
params,
|
||||
error,
|
||||
codeFrame: opts.context.codeFrame,
|
||||
remoteAddr: opts.context.remoteAddr,
|
||||
localAddr: opts.context.localAddr,
|
||||
Component: () => null,
|
||||
pattern: opts.context.pattern,
|
||||
url,
|
||||
route: opts.context.route,
|
||||
data,
|
||||
state,
|
||||
};
|
||||
|
||||
const csp: ContentSecurityPolicy | undefined = opts.route.csp
|
||||
? defaultCsp()
|
||||
: undefined;
|
||||
if (csp) {
|
||||
// Clear the csp
|
||||
const newCsp = defaultCsp();
|
||||
csp.directives = newCsp.directives;
|
||||
csp.reportOnly = newCsp.reportOnly;
|
||||
}
|
||||
|
||||
const ctx = new RenderContext(
|
||||
crypto.randomUUID(),
|
||||
url,
|
||||
opts.route.pattern,
|
||||
opts.lang ?? "en",
|
||||
);
|
||||
|
||||
const context = opts.context;
|
||||
|
||||
// Prepare render order
|
||||
// deno-lint-ignore no-explicit-any
|
||||
const renderStack: any[] = [];
|
||||
// Check if appLayout is enabled
|
||||
if (
|
||||
opts.route.appWrapper &&
|
||||
layouts.every((layout) => layout.appWrapper)
|
||||
) {
|
||||
renderStack.push(opts.app.default);
|
||||
}
|
||||
for (let i = 0; i < layouts.length; i++) {
|
||||
renderStack.push(layouts[i].component);
|
||||
}
|
||||
renderStack.push(component);
|
||||
|
||||
// Build the final stack of component functions
|
||||
const componentStack = new Array(renderStack.length).fill(null);
|
||||
for (let i = 0; i < renderStack.length; i++) {
|
||||
const fn = renderStack[i];
|
||||
if (!fn) continue;
|
||||
|
||||
if (checkAsyncComponent(fn)) {
|
||||
// Don't pass <Component /> when it's the route component
|
||||
const isRouteComponent = fn === component;
|
||||
const componentCtx = isRouteComponent ? context : {
|
||||
...context,
|
||||
Component() {
|
||||
return h(componentStack[i + 1], props);
|
||||
},
|
||||
};
|
||||
// deno-lint-ignore no-explicit-any
|
||||
const res = await fn(opts.request, componentCtx as any);
|
||||
|
||||
// Bail out of rendering if we returned a response
|
||||
if (res instanceof Response) {
|
||||
return res;
|
||||
}
|
||||
|
||||
const componentFn = () => res;
|
||||
// Set displayName to make debugging easier
|
||||
// deno-lint-ignore no-explicit-any
|
||||
componentFn.displayName = (fn as any).displayName || fn.name;
|
||||
componentStack[i] = componentFn;
|
||||
} else {
|
||||
componentStack[i] = () => {
|
||||
return h(fn, {
|
||||
...props,
|
||||
Component() {
|
||||
return h(componentStack[i + 1], null);
|
||||
},
|
||||
// deno-lint-ignore no-explicit-any
|
||||
} as any);
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// CAREFUL: Rendering is synchronous internally and all state
|
||||
// should be managed through the `RenderState` instance. That
|
||||
// ensures that each render request is associated with the same
|
||||
// data.
|
||||
const renderState = new RenderState(
|
||||
crypto.randomUUID(),
|
||||
{
|
||||
url,
|
||||
route: opts.route.pattern,
|
||||
data,
|
||||
state,
|
||||
params,
|
||||
basePath,
|
||||
},
|
||||
componentStack,
|
||||
csp,
|
||||
error,
|
||||
);
|
||||
|
||||
let bodyHtml: string | null = null;
|
||||
|
||||
const syncPlugins = opts.plugins.filter((p) => p.render);
|
||||
|
||||
const renderResults: [Plugin, PluginRenderResult][] = [];
|
||||
|
||||
function renderSync(): PluginRenderFunctionResult {
|
||||
const plugin = syncPlugins.shift();
|
||||
if (plugin) {
|
||||
const res = plugin.render!({ render: renderSync });
|
||||
if (res === undefined) {
|
||||
throw new Error(
|
||||
`${plugin?.name}'s render hook did not return a PluginRenderResult object.`,
|
||||
);
|
||||
}
|
||||
renderResults.push([plugin, res]);
|
||||
|
||||
if (res.htmlText !== undefined) {
|
||||
bodyHtml = res.htmlText;
|
||||
}
|
||||
} else {
|
||||
bodyHtml = renderHtml(renderState);
|
||||
}
|
||||
if (bodyHtml === null) {
|
||||
throw new Error(
|
||||
`The 'render' function was not called by ${plugin?.name}'s render hook.`,
|
||||
);
|
||||
}
|
||||
return {
|
||||
htmlText: bodyHtml,
|
||||
requiresHydration: renderState.encounteredIslands.size > 0,
|
||||
};
|
||||
}
|
||||
|
||||
const asyncPlugins = opts.plugins.filter((p) => p.renderAsync);
|
||||
|
||||
let asyncRenderResponse: Response | undefined;
|
||||
async function renderAsync(): Promise<PluginRenderFunctionResult> {
|
||||
const plugin = asyncPlugins.shift();
|
||||
if (plugin) {
|
||||
const res = await plugin.renderAsync!({ renderAsync });
|
||||
if (res === undefined) {
|
||||
throw new Error(
|
||||
`${plugin?.name}'s async render hook did not return a PluginRenderResult object.`,
|
||||
);
|
||||
}
|
||||
renderResults.push([plugin, res]);
|
||||
if (bodyHtml === null) {
|
||||
throw new Error(
|
||||
`The 'renderAsync' function was not called by ${plugin?.name}'s async render hook.`,
|
||||
);
|
||||
}
|
||||
|
||||
if (res.htmlText !== undefined) {
|
||||
bodyHtml = res.htmlText;
|
||||
}
|
||||
} else {
|
||||
await opts.renderFn(ctx, () => renderSync().htmlText);
|
||||
|
||||
if (bodyHtml === null) {
|
||||
throw new Error(
|
||||
`The 'render' function was not called by the legacy async render hook.`,
|
||||
);
|
||||
}
|
||||
}
|
||||
return {
|
||||
htmlText: bodyHtml,
|
||||
requiresHydration: renderState.encounteredIslands.size > 0,
|
||||
};
|
||||
}
|
||||
|
||||
await renderAsync();
|
||||
if (renderState.error !== null) {
|
||||
throw renderState.error;
|
||||
}
|
||||
|
||||
const idx = renderState.headVNodes.findIndex((vnode) =>
|
||||
vnode !== null && typeof vnode === "object" && "type" in vnode &&
|
||||
props !== null && vnode.type === "title"
|
||||
);
|
||||
if (idx !== -1) {
|
||||
renderState.docTitle = renderState.headVNodes[idx] as VNode<
|
||||
{ children: string }
|
||||
>;
|
||||
renderState.headVNodes.splice(idx, 1);
|
||||
}
|
||||
|
||||
if (asyncRenderResponse !== undefined) {
|
||||
return asyncRenderResponse;
|
||||
}
|
||||
|
||||
// Includes everything inside `<body>`
|
||||
bodyHtml = bodyHtml as unknown as string;
|
||||
|
||||
// Create Fresh script + style tags
|
||||
const result = renderFreshTags(renderState, {
|
||||
bodyHtml,
|
||||
imports: opts.imports,
|
||||
csp,
|
||||
dependenciesFn: opts.dependenciesFn,
|
||||
styles: ctx.styles,
|
||||
pluginRenderResults: renderResults,
|
||||
basePath,
|
||||
});
|
||||
|
||||
// Append error overlay in dev mode
|
||||
if (opts.context.config.dev) {
|
||||
const devErrorUrl = withBase(DEV_ERROR_OVERLAY_URL, basePath);
|
||||
if (error !== undefined && url.pathname !== devErrorUrl) {
|
||||
const url = new URL(devErrorUrl, "https://localhost/");
|
||||
if (error instanceof Error) {
|
||||
let message = error.message;
|
||||
const idx = message.indexOf("\n");
|
||||
if (idx > -1) message = message.slice(0, idx);
|
||||
url.searchParams.append("message", message);
|
||||
if (error.stack) {
|
||||
const stack = colors.stripAnsiCode(error.stack);
|
||||
url.searchParams.append("stack", stack);
|
||||
}
|
||||
} else {
|
||||
url.searchParams.append("message", String(error));
|
||||
}
|
||||
if (opts.codeFrame) {
|
||||
const codeFrame = colors.stripAnsiCode(opts.codeFrame);
|
||||
url.searchParams.append("code-frame", codeFrame);
|
||||
}
|
||||
|
||||
result.bodyHtml +=
|
||||
`<iframe id="fresh-error-overlay" src="${url.pathname}?${url.searchParams.toString()}" style="unset: all; position: fixed; top: 0; left: 0; z-index: 99999; width: 100%; height: 100%; border: none;"></iframe>`;
|
||||
}
|
||||
}
|
||||
|
||||
// Render outer document up to `<body>`
|
||||
const html = renderOuterDocument(renderState, {
|
||||
bodyHtml: result.bodyHtml,
|
||||
preloads: [...result.preloadSet],
|
||||
moduleScripts: result.moduleScripts,
|
||||
lang: ctx.lang,
|
||||
});
|
||||
return [html, renderState.renderUuid, csp];
|
||||
}
|
||||
@@ -1,205 +0,0 @@
|
||||
import { bundleAssetUrl } from "../constants.ts";
|
||||
import { RenderState } from "./state.ts";
|
||||
import { htmlEscapeJsonString } from "../htmlescape.ts";
|
||||
import { serialize } from "../serializer.ts";
|
||||
import {
|
||||
Plugin,
|
||||
PluginRenderLink,
|
||||
PluginRenderResult,
|
||||
PluginRenderStyleTag,
|
||||
} from "../types.ts";
|
||||
import { ContentSecurityPolicy, nonce } from "../../runtime/csp.ts";
|
||||
import { h } from "preact";
|
||||
|
||||
export type SerializedState = [islands: unknown[], plugins: unknown[]];
|
||||
|
||||
export function renderFreshTags(
|
||||
renderState: RenderState,
|
||||
opts: {
|
||||
bodyHtml: string;
|
||||
csp?: ContentSecurityPolicy;
|
||||
imports: string[];
|
||||
randomNonce?: string;
|
||||
dependenciesFn: (path: string) => string[];
|
||||
styles: string[];
|
||||
pluginRenderResults: [Plugin, PluginRenderResult][];
|
||||
basePath: string;
|
||||
},
|
||||
) {
|
||||
const { isPartial } = renderState;
|
||||
|
||||
if (opts.csp) {
|
||||
opts.csp.directives.scriptSrc = [
|
||||
...opts.csp.directives.scriptSrc ?? [],
|
||||
nonce(renderState.getNonce()),
|
||||
];
|
||||
}
|
||||
|
||||
const moduleScripts: [string, string][] = [];
|
||||
for (const url of opts.imports) {
|
||||
moduleScripts.push([url, renderState.getNonce()]);
|
||||
}
|
||||
|
||||
const preloadSet = new Set<string>();
|
||||
function addImport(path: string): string {
|
||||
const url = opts.basePath + bundleAssetUrl(`/${path}`);
|
||||
if (!isPartial) {
|
||||
preloadSet.add(url);
|
||||
for (const depPath of opts.dependenciesFn(path)) {
|
||||
const url = bundleAssetUrl(`/${depPath}`);
|
||||
preloadSet.add(url);
|
||||
}
|
||||
}
|
||||
return url;
|
||||
}
|
||||
|
||||
const state: SerializedState = [
|
||||
renderState.islandProps,
|
||||
[],
|
||||
];
|
||||
const styleTags: PluginRenderStyleTag[] = [];
|
||||
const linkTags: PluginRenderLink[] = [];
|
||||
const pluginScripts: [string, string, number][] = [];
|
||||
|
||||
for (const [plugin, res] of opts.pluginRenderResults) {
|
||||
for (const hydrate of res.scripts ?? []) {
|
||||
const i = state[1].push(hydrate.state) - 1;
|
||||
pluginScripts.push([plugin.name, hydrate.entrypoint, i]);
|
||||
}
|
||||
styleTags.splice(styleTags.length, 0, ...res.styles ?? []);
|
||||
linkTags.splice(linkTags.length, 0, ...res.links ?? []);
|
||||
}
|
||||
|
||||
// The inline script that will hydrate the page.
|
||||
let script = "";
|
||||
|
||||
// Serialize the state into the <script id="__FRSH_STATE-<uuid>"> tag and generate the
|
||||
// inline script to deserialize it. This script starts by deserializing the
|
||||
// state in the tag. This potentially requires importing @preact/signals.
|
||||
let hasSignals = false;
|
||||
let requiresDeserializer = false;
|
||||
if (state[0].length > 0 || state[1].length > 0) {
|
||||
// Careful: This must be unique per render to avoid injected content
|
||||
// via `dangerouslySetInnerHTML` being able to overwrite our state.
|
||||
const stateId = `__FRSH_STATE_${renderState.renderUuid}`;
|
||||
|
||||
const res = serialize(state);
|
||||
const escapedState = htmlEscapeJsonString(res.serialized);
|
||||
opts.bodyHtml +=
|
||||
`<script id="${stateId}" type="application/json" nonce="${renderState.getNonce()}">${escapedState}</script>`;
|
||||
|
||||
hasSignals = res.hasSignals;
|
||||
requiresDeserializer = res.requiresDeserializer;
|
||||
|
||||
if (res.requiresDeserializer) {
|
||||
const url = addImport("deserializer.js");
|
||||
script += `import { deserialize } from "${url}";`;
|
||||
}
|
||||
if (res.hasSignals) {
|
||||
const url = addImport("signals.js");
|
||||
script += `import { signal } from "${url}";`;
|
||||
}
|
||||
script += `const ST = document.getElementById("${stateId}").textContent;`;
|
||||
script += `const STATE = `;
|
||||
if (res.requiresDeserializer) {
|
||||
if (res.hasSignals) {
|
||||
script += `deserialize(ST, signal);`;
|
||||
} else {
|
||||
script += `deserialize(ST);`;
|
||||
}
|
||||
} else {
|
||||
script += `JSON.parse(ST).v;`;
|
||||
}
|
||||
}
|
||||
|
||||
// Then it imports all plugin scripts and executes them (with their respective
|
||||
// state).
|
||||
if (pluginScripts.length > 0) {
|
||||
// Use `reportError` if available, otherwise throw in a different event
|
||||
// loop tick to avoid halting the current script.
|
||||
script +=
|
||||
`function runPlugin(fn,args){try{fn(args)}catch(err){setTimeout(() => {throw err})}}`;
|
||||
}
|
||||
for (const [pluginName, entrypoint, i] of pluginScripts) {
|
||||
const url = addImport(`plugin-${pluginName}-${entrypoint}.js`);
|
||||
script += `import p${i} from "${url}";runPlugin(p${i},STATE[1][${i}]);`;
|
||||
}
|
||||
|
||||
const needsMainScript = renderState.encounteredIslands.size > 0 ||
|
||||
renderState.partialCount > 0;
|
||||
if (needsMainScript) {
|
||||
// Load the main.js script
|
||||
const url = addImport("main.js");
|
||||
script += `import { revive } from "${url}";`;
|
||||
}
|
||||
|
||||
// Finally, it loads all island scripts and hydrates the islands using the
|
||||
// reviver from the "main" script.
|
||||
let islandRegistry = "";
|
||||
const islandMapping: Record<string, { url: string; export: string }> = {};
|
||||
if (renderState.encounteredIslands.size > 0) {
|
||||
// Prepare the inline script that loads and revives the islands
|
||||
for (const island of renderState.encounteredIslands) {
|
||||
const url = addImport(`island-${island.name}.js`);
|
||||
script += island.exportName === "default"
|
||||
? `import ${island.name}_${island.exportName} from "${url}";`
|
||||
: `import { ${island.exportName} as ${island.name}_${island.exportName} } from "${url}";`;
|
||||
islandRegistry += `${island.id}:${island.name}_${island.exportName},`;
|
||||
islandMapping[island.id] = {
|
||||
export: island.exportName,
|
||||
url,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// Always revive to detect partials
|
||||
if (needsMainScript) {
|
||||
script += `const propsArr = typeof STATE !== "undefined" ? STATE[0] : [];`;
|
||||
script += `revive({${islandRegistry}}, propsArr);`;
|
||||
}
|
||||
|
||||
// Append the inline script.
|
||||
if (isPartial && Object.keys(islandMapping).length > 0) {
|
||||
const escapedData = htmlEscapeJsonString(
|
||||
JSON.stringify({
|
||||
islands: islandMapping,
|
||||
signals: hasSignals ? addImport("signals.js") : null,
|
||||
deserializer: requiresDeserializer
|
||||
? addImport("deserializer.js")
|
||||
: null,
|
||||
}),
|
||||
);
|
||||
const nonce = renderState.csp ? ` nonce="${renderState.getNonce()}"` : "";
|
||||
opts.bodyHtml +=
|
||||
`<script id="__FRSH_PARTIAL_DATA_${renderState.renderUuid}" type="application/json"${nonce}>${escapedData}</script>`;
|
||||
}
|
||||
if (script !== "") {
|
||||
opts.bodyHtml +=
|
||||
`<script type="module" nonce="${renderState.getNonce()}">${script}</script>`;
|
||||
}
|
||||
|
||||
if (opts.styles.length > 0) {
|
||||
const node = h("style", {
|
||||
id: "__FRSH_STYLE",
|
||||
dangerouslySetInnerHTML: { __html: opts.styles.join("\n") },
|
||||
});
|
||||
|
||||
renderState.headVNodes.splice(0, 0, node);
|
||||
}
|
||||
|
||||
for (const style of styleTags) {
|
||||
const node = h("style", {
|
||||
id: style.id,
|
||||
media: style.media,
|
||||
dangerouslySetInnerHTML: { __html: style.cssText },
|
||||
});
|
||||
renderState.headVNodes.splice(0, 0, node);
|
||||
}
|
||||
|
||||
for (const link of linkTags) {
|
||||
const node = h("link", link);
|
||||
renderState.headVNodes.splice(0, 0, node);
|
||||
}
|
||||
|
||||
return { bodyHtml: opts.bodyHtml, preloadSet, moduleScripts };
|
||||
}
|
||||
@@ -1,489 +0,0 @@
|
||||
import {
|
||||
Component,
|
||||
type ComponentChildren,
|
||||
ComponentType,
|
||||
Fragment,
|
||||
h,
|
||||
isValidElement,
|
||||
type Options as PreactOptions,
|
||||
options as preactOptions,
|
||||
type VNode,
|
||||
} from "preact";
|
||||
import { assetHashingHook } from "../../runtime/utils.ts";
|
||||
import { Partial, PartialProps } from "../../runtime/Partial.tsx";
|
||||
import { join, renderToString, SEPARATOR } from "../deps.ts";
|
||||
import { RenderState } from "./state.ts";
|
||||
import { Island } from "../types.ts";
|
||||
import {
|
||||
CLIENT_NAV_ATTR,
|
||||
DATA_KEY_ATTR,
|
||||
LOADING_ATTR,
|
||||
PartialMode,
|
||||
} from "../../constants.ts";
|
||||
import { setActiveUrl } from "../../runtime/active_url.ts";
|
||||
import { withBase } from "../router.ts";
|
||||
|
||||
// See: https://github.com/preactjs/preact/blob/7748dcb83cedd02e37b3713634e35b97b26028fd/src/internal.d.ts#L3C1-L16
|
||||
enum HookType {
|
||||
useState = 1,
|
||||
useReducer = 2,
|
||||
useEffect = 3,
|
||||
useLayoutEffect = 4,
|
||||
useRef = 5,
|
||||
useImperativeHandle = 6,
|
||||
useMemo = 7,
|
||||
useCallback = 8,
|
||||
useContext = 9,
|
||||
useErrorBoundary = 10,
|
||||
// Not a real hook, but the devtools treat is as such
|
||||
useDebugvalue = 11,
|
||||
}
|
||||
|
||||
// These hooks are long stable, but when we originally added them we
|
||||
// weren't sure if they should be public.
|
||||
interface AdvancedPreactOptions extends PreactOptions {
|
||||
/** Attach a hook that is invoked after a tree was mounted or was updated. */
|
||||
__c?(vnode: VNode, commitQueue: Component[]): void;
|
||||
/** Attach a hook that is invoked before a vnode has rendered. */
|
||||
__r?(vnode: VNode): void;
|
||||
errorBoundaries?: boolean;
|
||||
/** before diff hook */
|
||||
__b?(vnode: VNode): void;
|
||||
/** Attach a hook that is invoked before a hook's state is queried. */
|
||||
__h?(component: Component, index: number, type: HookType): void;
|
||||
}
|
||||
const options = preactOptions as AdvancedPreactOptions;
|
||||
|
||||
// Enable error boundaries in Preact.
|
||||
options.errorBoundaries = true;
|
||||
|
||||
// Set up a preact option hook to track when vnode with custom functions are
|
||||
// created.
|
||||
let current: RenderState | null = null;
|
||||
// Keep track of which component rendered which vnode. This allows us
|
||||
// to detect when an island is rendered within another instead of being
|
||||
// passed as children.
|
||||
let ownerStack: VNode[] = [];
|
||||
// Keep track of all available islands
|
||||
const islandByComponent = new Map<ComponentType, Island>();
|
||||
export function setAllIslands(islands: Island[]) {
|
||||
for (let i = 0; i < islands.length; i++) {
|
||||
const island = islands[i];
|
||||
islandByComponent.set(island.component, island);
|
||||
}
|
||||
}
|
||||
|
||||
export function setRenderState(state: RenderState | null): void {
|
||||
if (current) current.clearTmpState();
|
||||
current = state;
|
||||
ownerStack = state?.ownerStack ?? [];
|
||||
}
|
||||
|
||||
// Check if an older version of `preact-render-to-string` is used
|
||||
const supportsUnstableComments = renderToString(h(Fragment, {
|
||||
// @ts-ignore unstable features not supported in types
|
||||
UNSTABLE_comment: "foo",
|
||||
}) as VNode) !== "";
|
||||
|
||||
if (!supportsUnstableComments) {
|
||||
console.warn(
|
||||
"⚠️ Found old version of 'preact-render-to-string'. Please upgrade it to >=6.1.0",
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Wrap a node with comment markers in the HTML
|
||||
*/
|
||||
function wrapWithMarker(vnode: ComponentChildren, markerText: string) {
|
||||
// Newer versions of preact-render-to-string allow you to render comments
|
||||
if (supportsUnstableComments) {
|
||||
return h(
|
||||
Fragment,
|
||||
null,
|
||||
h(Fragment, {
|
||||
// @ts-ignore unstable property is not typed
|
||||
UNSTABLE_comment: markerText,
|
||||
}),
|
||||
vnode,
|
||||
h(Fragment, {
|
||||
// @ts-ignore unstable property is not typed
|
||||
UNSTABLE_comment: "/" + markerText,
|
||||
}),
|
||||
);
|
||||
} else {
|
||||
return h(
|
||||
`!--${markerText}--`,
|
||||
null,
|
||||
vnode,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Whenever a slot (=jsx children) is rendered, remove this from the slot
|
||||
* tracking Set. After everything was rendered we'll know which slots
|
||||
* weren't and can send them down to the client
|
||||
*/
|
||||
function SlotTracker(
|
||||
props: { id: string; children?: ComponentChildren },
|
||||
): VNode {
|
||||
current?.slots.delete(props.id);
|
||||
// deno-lint-ignore no-explicit-any
|
||||
return props.children as any;
|
||||
}
|
||||
|
||||
/**
|
||||
* Copy props but exclude children
|
||||
*/
|
||||
function excludeChildren(props: Record<string, unknown>) {
|
||||
const out: Record<string, unknown> = {};
|
||||
for (const k in props) {
|
||||
if (k !== "children") out[k] = props[k];
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the current component was rendered in an island
|
||||
*/
|
||||
function hasIslandOwner(current: RenderState, vnode: VNode): boolean {
|
||||
let tmpVNode = vnode;
|
||||
let owner;
|
||||
while ((owner = current.owners.get(tmpVNode)) !== undefined) {
|
||||
if (islandByComponent.has(owner.type as ComponentType)) {
|
||||
return true;
|
||||
}
|
||||
tmpVNode = owner;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
function encodePartialMode(mode: PartialProps["mode"]): PartialMode {
|
||||
if (mode === "replace") return PartialMode.REPLACE;
|
||||
else if (mode === "append") return PartialMode.APPEND;
|
||||
else if (mode === "prepend") return PartialMode.PREPEND;
|
||||
throw new Error(`Unknown partial mode "${mode}"`);
|
||||
}
|
||||
|
||||
const patched = new WeakSet<VNode>();
|
||||
|
||||
const oldVNodeHook = options.vnode;
|
||||
const oldDiff = options.__b;
|
||||
const oldDiffed = options.diffed;
|
||||
const oldRender = options.__r;
|
||||
const oldHook = options.__h;
|
||||
|
||||
options.vnode = (vnode) => {
|
||||
assetHashingHook(vnode);
|
||||
|
||||
// Work around `preact/debug` string event handler error which
|
||||
// errors when an event handler gets a string. This makes sense
|
||||
// on the client where this is a common vector for XSS. On the
|
||||
// server when the string was not created through concatenation
|
||||
// it is fine. Internally, `preact/debug` only checks for the
|
||||
// lowercase variant.
|
||||
if (typeof vnode.type === "string") {
|
||||
const props = vnode.props as Record<string, unknown>;
|
||||
for (const key in props) {
|
||||
const value = props[key];
|
||||
if (key.startsWith("on") && typeof value === "string") {
|
||||
delete props[key];
|
||||
props["ON" + key.slice(2)] = value;
|
||||
}
|
||||
}
|
||||
// Don't do key preservation for nodes in <head>.
|
||||
if (
|
||||
vnode.key && vnode.type !== "meta" && vnode.type !== "title" &&
|
||||
vnode.type !== "style" && vnode.type !== "script" && vnode.type !== "link"
|
||||
) {
|
||||
props[DATA_KEY_ATTR] = vnode.key;
|
||||
}
|
||||
|
||||
if (props[LOADING_ATTR]) {
|
||||
// Avoid automatic signals unwrapping
|
||||
props[LOADING_ATTR] = { value: props[LOADING_ATTR] };
|
||||
}
|
||||
|
||||
if (typeof props[CLIENT_NAV_ATTR] === "boolean") {
|
||||
props[CLIENT_NAV_ATTR] = props[CLIENT_NAV_ATTR] ? "true" : "false";
|
||||
}
|
||||
|
||||
if (typeof props.href === "string") {
|
||||
props.href = withBase(props.href, current?.basePath);
|
||||
}
|
||||
|
||||
if (typeof props.src === "string") {
|
||||
props.src = withBase(props.src, current?.basePath);
|
||||
}
|
||||
|
||||
srcsetRewrite:
|
||||
if (typeof props.srcset === "string") {
|
||||
// Bail out on complex syntax that's too complicated for now
|
||||
if (props.srcset.includes("(")) break srcsetRewrite;
|
||||
|
||||
const parts = props.srcset.split(",");
|
||||
const out: string[] = [];
|
||||
for (const part of parts) {
|
||||
const trimmed = part.trimStart();
|
||||
if (trimmed === "") break srcsetRewrite;
|
||||
|
||||
let urlEnd = trimmed.indexOf(" ");
|
||||
if (urlEnd === -1) urlEnd = trimmed.length;
|
||||
|
||||
const leadingWhitespace = part.length - trimmed.length;
|
||||
const leading = part.substring(0, leadingWhitespace);
|
||||
const url = trimmed.substring(0, urlEnd);
|
||||
const trailing = trimmed.substring(urlEnd);
|
||||
|
||||
if (url.startsWith("/") && current?.basePath) {
|
||||
const joinedPath = join("/", current.basePath, url).replaceAll(
|
||||
SEPARATOR,
|
||||
"/",
|
||||
);
|
||||
out.push(leading + joinedPath + trailing);
|
||||
} else {
|
||||
out.push(part);
|
||||
}
|
||||
}
|
||||
props.srcset = out.join(",");
|
||||
}
|
||||
} else if (
|
||||
current && typeof vnode.type === "function" && vnode.type !== Fragment &&
|
||||
ownerStack.length > 0
|
||||
) {
|
||||
current.owners.set(vnode, ownerStack[ownerStack.length - 1]);
|
||||
}
|
||||
|
||||
if (oldVNodeHook) oldVNodeHook(vnode);
|
||||
};
|
||||
|
||||
options.__b = (vnode: VNode<Record<string, unknown>>) => {
|
||||
// Add CSP nonce to inline script tags
|
||||
if (typeof vnode.type === "string" && vnode.type === "script") {
|
||||
if (!vnode.props.nonce) {
|
||||
vnode.props.nonce = current!.getNonce();
|
||||
}
|
||||
}
|
||||
|
||||
if (
|
||||
current && current.renderingUserTemplate
|
||||
) {
|
||||
// Internally rendering happens in two phases. This is done so
|
||||
// that the `<Head>` component works. When we do the first render
|
||||
// we cache all attributes on `<html>`, `<head>` + its children, and
|
||||
// `<body>`. When doing so, we'll replace the tags with a Fragment node
|
||||
// so that they don't end up in the rendered HTML. Effectively this
|
||||
// means we'll only serialize the contents of `<body>`.
|
||||
//
|
||||
// After that render is finished we know all additional
|
||||
// meta tags that were inserted via `<Head>` and all islands that
|
||||
// we can add as preloads. Then we do a second render of the outer
|
||||
// HTML tags with the updated value and merge in the HTML generate by
|
||||
// the first render into `<body>` directly.
|
||||
if (
|
||||
typeof vnode.type === "string"
|
||||
) {
|
||||
if (vnode.type === "html") {
|
||||
current.renderedHtmlTag = true;
|
||||
current.docHtml = excludeChildren(vnode.props);
|
||||
vnode.type = Fragment;
|
||||
} else if (vnode.type === "head") {
|
||||
current.docHead = excludeChildren(vnode.props);
|
||||
current.headChildren = true;
|
||||
vnode.type = Fragment;
|
||||
vnode.props = {
|
||||
__freshHead: true,
|
||||
children: vnode.props.children,
|
||||
};
|
||||
} else if (vnode.type === "body") {
|
||||
current.docBody = excludeChildren(vnode.props);
|
||||
vnode.type = Fragment;
|
||||
} else if (current.headChildren) {
|
||||
if (vnode.type === "title") {
|
||||
current.docTitle = h("title", vnode.props);
|
||||
vnode.props = { children: null };
|
||||
} else {
|
||||
current.docHeadNodes.push({
|
||||
type: vnode.type,
|
||||
props: vnode.props,
|
||||
});
|
||||
}
|
||||
vnode.type = Fragment;
|
||||
vnode.props = { children: null };
|
||||
} else if (LOADING_ATTR in vnode.props) {
|
||||
current.islandProps.push({
|
||||
[LOADING_ATTR]: vnode.props[LOADING_ATTR],
|
||||
});
|
||||
vnode.props[LOADING_ATTR] = current.islandProps.length - 1;
|
||||
} else if (vnode.type === "a") {
|
||||
setActiveUrl(vnode, current.url.pathname);
|
||||
}
|
||||
} else if (typeof vnode.type === "function") {
|
||||
// Detect island vnodes and wrap them with a marker
|
||||
const island = islandByComponent.get(vnode.type);
|
||||
patchIsland:
|
||||
if (
|
||||
vnode.type !== Fragment &&
|
||||
island &&
|
||||
!patched.has(vnode)
|
||||
) {
|
||||
current.islandDepth++;
|
||||
|
||||
// Check if an island is rendered inside another island, not just
|
||||
// passed as a child.In that case we treat it like a normal
|
||||
// Component. Example:
|
||||
// function Island() {
|
||||
// return <OtherIsland />
|
||||
// }
|
||||
if (hasIslandOwner(current, vnode)) {
|
||||
break patchIsland;
|
||||
}
|
||||
|
||||
// At this point we know that we need to patch the island. Mark the
|
||||
// island in that we have already patched it.
|
||||
const originalType = vnode.type;
|
||||
patched.add(vnode);
|
||||
|
||||
vnode.type = (props) => {
|
||||
if (!current) return null;
|
||||
|
||||
const { encounteredIslands, islandProps, slots } = current;
|
||||
encounteredIslands.add(island);
|
||||
|
||||
// Only passing children JSX to islands is supported for now
|
||||
const id = islandProps.length;
|
||||
if ("children" in props) {
|
||||
let children = props.children;
|
||||
|
||||
// Guard against passing objects as children to JSX
|
||||
if (
|
||||
typeof children === "function" || (
|
||||
children !== null && typeof children === "object" &&
|
||||
!Array.isArray(children) &&
|
||||
!isValidElement(children)
|
||||
)
|
||||
) {
|
||||
const name = originalType.displayName || originalType.name ||
|
||||
"Anonymous";
|
||||
|
||||
throw new Error(
|
||||
`Invalid JSX child passed to island <${name} />. To resolve this error, pass the data as a standard prop instead.`,
|
||||
);
|
||||
}
|
||||
|
||||
const markerText = `frsh-slot-${island.id}:${id}:children`;
|
||||
// @ts-ignore nonono
|
||||
props.children = wrapWithMarker(
|
||||
children,
|
||||
markerText,
|
||||
);
|
||||
slots.set(markerText, children);
|
||||
children = props.children;
|
||||
// deno-lint-ignore no-explicit-any
|
||||
(props as any).children = h(
|
||||
SlotTracker,
|
||||
{ id: markerText },
|
||||
children,
|
||||
);
|
||||
}
|
||||
|
||||
const child = h(originalType, props) as VNode;
|
||||
patched.add(child);
|
||||
islandProps.push(props);
|
||||
|
||||
return wrapWithMarker(
|
||||
child,
|
||||
`frsh-${island.id}:${islandProps.length - 1}:${vnode.key ?? ""}`,
|
||||
);
|
||||
};
|
||||
// deno-lint-ignore no-explicit-any
|
||||
} else if (vnode.type === (Partial as any)) {
|
||||
current.partialCount++;
|
||||
current.partialDepth++;
|
||||
if (hasIslandOwner(current, vnode)) {
|
||||
throw new Error(
|
||||
`<Partial> components cannot be used inside islands.`,
|
||||
);
|
||||
}
|
||||
const name = vnode.props.name as string;
|
||||
if (current.encounteredPartials.has(name)) {
|
||||
current.error = new Error(
|
||||
`Duplicate partial name "${name}" found. The partial name prop is expected to be unique among partial components.`,
|
||||
);
|
||||
}
|
||||
current.encounteredPartials.add(name);
|
||||
|
||||
const mode = encodePartialMode(
|
||||
// deno-lint-ignore no-explicit-any
|
||||
(vnode.props as any).mode ?? "replace",
|
||||
);
|
||||
vnode.props.children = wrapWithMarker(
|
||||
vnode.props.children,
|
||||
`frsh-partial:${name}:${mode}:${vnode.key ?? ""}`,
|
||||
);
|
||||
} else if (
|
||||
vnode.key && (current.islandDepth > 0 || current.partialDepth > 0)
|
||||
) {
|
||||
const child = h(vnode.type, vnode.props);
|
||||
vnode.type = Fragment;
|
||||
vnode.props = {
|
||||
children: wrapWithMarker(child, `frsh-key:${vnode.key}`),
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
oldDiff?.(vnode);
|
||||
};
|
||||
options.__r = (vnode) => {
|
||||
if (
|
||||
typeof vnode.type === "function" &&
|
||||
vnode.type !== Fragment
|
||||
) {
|
||||
ownerStack.push(vnode);
|
||||
}
|
||||
oldRender?.(vnode);
|
||||
};
|
||||
options.diffed = (vnode: VNode<Record<string, unknown>>) => {
|
||||
if (typeof vnode.type === "function") {
|
||||
if (vnode.type !== Fragment) {
|
||||
if (current) {
|
||||
if (islandByComponent.has(vnode.type)) {
|
||||
current.islandDepth--;
|
||||
} else if (vnode.type === Partial as ComponentType) {
|
||||
current.partialDepth--;
|
||||
}
|
||||
}
|
||||
|
||||
ownerStack.pop();
|
||||
} else if (vnode.props.__freshHead) {
|
||||
if (current) {
|
||||
current.headChildren = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
oldDiffed?.(vnode);
|
||||
};
|
||||
|
||||
options.__h = (component, idx, type) => {
|
||||
// deno-lint-ignore no-explicit-any
|
||||
const vnode = (component as any).__v;
|
||||
// Warn when using stateful hooks outside of islands
|
||||
if (
|
||||
// Only error for stateful hooks for now.
|
||||
(type === HookType.useState || type === HookType.useReducer) && current &&
|
||||
!islandByComponent.has(vnode.type) && !hasIslandOwner(current, vnode) &&
|
||||
!current.error
|
||||
) {
|
||||
const name = HookType[type];
|
||||
const message =
|
||||
`Hook "${name}" cannot be used outside of an island component.`;
|
||||
const hint = type === HookType.useState
|
||||
? `\n\nInstead, use the "useSignal" hook to share state across islands.`
|
||||
: "";
|
||||
|
||||
// Don't throw here because that messes up internal Preact state
|
||||
current.error = new Error(message + hint);
|
||||
}
|
||||
oldHook?.(component, idx, type);
|
||||
};
|
||||
@@ -1,83 +0,0 @@
|
||||
import { type ComponentChildren, type VNode } from "preact";
|
||||
import { Island } from "../types.ts";
|
||||
import { ContentSecurityPolicy } from "../../runtime/csp.ts";
|
||||
import { PARTIAL_SEARCH_PARAM } from "../../constants.ts";
|
||||
|
||||
export interface RenderStateRouteOptions {
|
||||
url: URL;
|
||||
route: string;
|
||||
// deno-lint-ignore no-explicit-any
|
||||
data?: any;
|
||||
// deno-lint-ignore no-explicit-any
|
||||
state?: any;
|
||||
error?: unknown;
|
||||
params: Record<string, string | string[]>;
|
||||
basePath: string;
|
||||
}
|
||||
|
||||
export class RenderState {
|
||||
readonly renderUuid: string;
|
||||
// deno-lint-ignore no-explicit-any
|
||||
componentStack: any[];
|
||||
renderingUserTemplate = false;
|
||||
encounteredIslands = new Set<Island>();
|
||||
islandProps: unknown[] = [];
|
||||
slots = new Map<string, ComponentChildren>();
|
||||
headChildren = false;
|
||||
renderedHtmlTag = false;
|
||||
// deno-lint-ignore no-explicit-any
|
||||
docTitle: VNode<any> | null = null;
|
||||
docHtml: Record<string, unknown> | null = null;
|
||||
docHead: Record<string, unknown> | null = null;
|
||||
docBody: Record<string, unknown> | null = null;
|
||||
docHeadNodes: { type: string; props: Record<string, unknown> }[] = [];
|
||||
headVNodes: ComponentChildren[] = [];
|
||||
// Route options
|
||||
routeOptions: RenderStateRouteOptions;
|
||||
csp: ContentSecurityPolicy | undefined;
|
||||
// Preact state
|
||||
ownerStack: VNode[] = [];
|
||||
owners = new Map<VNode, VNode>();
|
||||
#nonce = "";
|
||||
error: Error | null = null;
|
||||
isPartial: boolean;
|
||||
encounteredPartials = new Set<string>();
|
||||
partialCount = 0;
|
||||
partialDepth = 0;
|
||||
islandDepth = 0;
|
||||
url: URL;
|
||||
basePath: string;
|
||||
|
||||
constructor(
|
||||
renderUuid: string,
|
||||
routeOptions: RenderStateRouteOptions,
|
||||
// deno-lint-ignore no-explicit-any
|
||||
componentStack: any[],
|
||||
csp?: ContentSecurityPolicy,
|
||||
error?: unknown,
|
||||
) {
|
||||
this.renderUuid = renderUuid;
|
||||
this.routeOptions = routeOptions;
|
||||
this.csp = csp;
|
||||
this.componentStack = componentStack;
|
||||
this.url = routeOptions.url;
|
||||
this.isPartial = routeOptions.url.searchParams.has(PARTIAL_SEARCH_PARAM);
|
||||
this.basePath = routeOptions.basePath;
|
||||
|
||||
if (error) this.routeOptions.error = error;
|
||||
}
|
||||
|
||||
getNonce(): string {
|
||||
if (this.#nonce === "") {
|
||||
this.#nonce = crypto.randomUUID().replace(/-/g, "");
|
||||
}
|
||||
return this.#nonce;
|
||||
}
|
||||
|
||||
clearTmpState() {
|
||||
this.renderingUserTemplate = false;
|
||||
this.ownerStack = [];
|
||||
this.owners.clear();
|
||||
this.encounteredPartials.clear();
|
||||
}
|
||||
}
|
||||
@@ -1,148 +0,0 @@
|
||||
import { RenderState } from "./state.ts";
|
||||
import { setRenderState } from "./preact_hooks.ts";
|
||||
import { renderToString } from "../deps.ts";
|
||||
import {
|
||||
ComponentType,
|
||||
Fragment,
|
||||
h,
|
||||
isValidElement,
|
||||
toChildArray,
|
||||
VNode,
|
||||
} from "preact";
|
||||
import { HEAD_CONTEXT } from "../../runtime/head.ts";
|
||||
import { CSP_CONTEXT } from "../../runtime/csp.ts";
|
||||
import { withBase } from "../router.ts";
|
||||
|
||||
export function renderHtml(state: RenderState) {
|
||||
setRenderState(state);
|
||||
state.renderingUserTemplate = true;
|
||||
state.headChildren = false;
|
||||
|
||||
const componentStack = state.componentStack;
|
||||
try {
|
||||
const routeComponent = componentStack[componentStack.length - 1];
|
||||
let finalComp = h(routeComponent, state.routeOptions) as VNode;
|
||||
|
||||
// Skip page component
|
||||
let i = componentStack.length - 1;
|
||||
while (i--) {
|
||||
const component = componentStack[i] as ComponentType;
|
||||
const curComp = finalComp;
|
||||
|
||||
finalComp = h(component, {
|
||||
...state.routeOptions,
|
||||
Component() {
|
||||
return curComp;
|
||||
},
|
||||
// deno-lint-ignore no-explicit-any
|
||||
} as any) as VNode;
|
||||
}
|
||||
|
||||
const app = h(
|
||||
CSP_CONTEXT.Provider,
|
||||
// deno-lint-ignore no-explicit-any
|
||||
{ value: state.csp } as any,
|
||||
h(HEAD_CONTEXT.Provider, {
|
||||
value: state.headVNodes,
|
||||
children: finalComp,
|
||||
}),
|
||||
) as VNode;
|
||||
|
||||
let html = renderToString(app);
|
||||
|
||||
for (const [id, children] of state.slots.entries()) {
|
||||
const slotHtml = renderToString(h(Fragment, null, children) as VNode);
|
||||
const templateId = id.replace(/:/g, "-");
|
||||
html += `<template id="${templateId}">${slotHtml}</template>`;
|
||||
}
|
||||
|
||||
return html;
|
||||
} finally {
|
||||
setRenderState(null);
|
||||
}
|
||||
}
|
||||
|
||||
export function renderOuterDocument(
|
||||
state: RenderState,
|
||||
opts: {
|
||||
bodyHtml: string;
|
||||
lang?: string;
|
||||
preloads: string[];
|
||||
moduleScripts: [src: string, nonce: string][];
|
||||
},
|
||||
) {
|
||||
const {
|
||||
docHtml,
|
||||
docHead,
|
||||
renderedHtmlTag,
|
||||
docBody,
|
||||
docHeadNodes,
|
||||
headVNodes,
|
||||
} = state;
|
||||
let docTitle = state.docTitle;
|
||||
|
||||
// Filter out duplicate head vnodes by "key" if set
|
||||
const filteredHeadNodes: VNode[] = [];
|
||||
|
||||
if (headVNodes.length > 0) {
|
||||
const seen = new Map<string, VNode>();
|
||||
const userChildren = toChildArray(headVNodes);
|
||||
for (let i = 0; i < userChildren.length; i++) {
|
||||
const child = userChildren[i];
|
||||
|
||||
if (isValidElement(child)) {
|
||||
if (child.type === "title") {
|
||||
docTitle = child;
|
||||
} else if (child.key !== undefined) {
|
||||
seen.set(child.key, child);
|
||||
} else {
|
||||
filteredHeadNodes.push(child);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (seen.size > 0) {
|
||||
filteredHeadNodes.push(...seen.values());
|
||||
}
|
||||
}
|
||||
|
||||
const page = h(
|
||||
"html",
|
||||
docHtml ?? { lang: opts.lang },
|
||||
h(
|
||||
"head",
|
||||
docHead,
|
||||
!renderedHtmlTag ? h("meta", { charset: "utf-8" }) : null,
|
||||
!renderedHtmlTag
|
||||
? (h("meta", {
|
||||
name: "viewport",
|
||||
content: "width=device-width, initial-scale=1.0",
|
||||
}))
|
||||
: null,
|
||||
docTitle,
|
||||
docHeadNodes.map((node) => h(node.type, node.props)),
|
||||
opts.preloads.map((src) =>
|
||||
h("link", { rel: "modulepreload", href: withBase(src, state.basePath) })
|
||||
),
|
||||
opts.moduleScripts.map(([src, nonce]) =>
|
||||
h("script", {
|
||||
src: withBase(src, state.basePath),
|
||||
nonce,
|
||||
type: "module",
|
||||
})
|
||||
),
|
||||
filteredHeadNodes,
|
||||
),
|
||||
h("body", {
|
||||
...docBody,
|
||||
dangerouslySetInnerHTML: { __html: opts.bodyHtml },
|
||||
}),
|
||||
) as VNode;
|
||||
|
||||
try {
|
||||
setRenderState(state);
|
||||
return "<!DOCTYPE html>" + renderToString(page);
|
||||
} finally {
|
||||
setRenderState(null);
|
||||
}
|
||||
}
|
||||
@@ -1,261 +0,0 @@
|
||||
import { PARTIAL_SEARCH_PARAM } from "../constants.ts";
|
||||
import { BaseRoute, FreshContext } from "./types.ts";
|
||||
|
||||
export type Handler<T = Record<string, unknown>> = (
|
||||
req: Request,
|
||||
ctx: FreshContext<T>,
|
||||
) => Response | Promise<Response>;
|
||||
|
||||
export type FinalHandler = (
|
||||
req: Request,
|
||||
ctx: FreshContext,
|
||||
route?: InternalRoute,
|
||||
) => {
|
||||
destination: DestinationKind;
|
||||
handler: () => Response | Promise<Response>;
|
||||
};
|
||||
|
||||
export type ErrorHandler<T = Record<string, unknown>> = (
|
||||
req: Request,
|
||||
ctx: FreshContext<T>,
|
||||
err: unknown,
|
||||
) => Response | Promise<Response>;
|
||||
|
||||
type UnknownMethodHandler = (
|
||||
req: Request,
|
||||
ctx: FreshContext,
|
||||
knownMethods: KnownMethod[],
|
||||
) => Response | Promise<Response>;
|
||||
|
||||
export type MatchHandler = (
|
||||
req: Request,
|
||||
ctx: FreshContext,
|
||||
) => Response | Promise<Response>;
|
||||
|
||||
export interface Routes {
|
||||
[key: string]: {
|
||||
baseRoute: BaseRoute;
|
||||
methods: {
|
||||
[K in KnownMethod | "default"]?: MatchHandler;
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
export type DestinationKind = "internal" | "static" | "route" | "notFound";
|
||||
|
||||
export type InternalRoute = {
|
||||
baseRoute: BaseRoute;
|
||||
originalPattern: string;
|
||||
pattern: URLPattern | string;
|
||||
methods: { [K in KnownMethod]?: MatchHandler };
|
||||
default?: MatchHandler;
|
||||
destination: DestinationKind;
|
||||
};
|
||||
|
||||
export interface RouterOptions {
|
||||
internalRoutes: Routes;
|
||||
staticRoutes: Routes;
|
||||
routes: Routes;
|
||||
otherHandler: Handler;
|
||||
errorHandler: ErrorHandler;
|
||||
unknownMethodHandler?: UnknownMethodHandler;
|
||||
}
|
||||
|
||||
export type KnownMethod = typeof knownMethods[number];
|
||||
|
||||
export const knownMethods = [
|
||||
"GET",
|
||||
"HEAD",
|
||||
"POST",
|
||||
"PUT",
|
||||
"DELETE",
|
||||
"OPTIONS",
|
||||
"PATCH",
|
||||
] as const;
|
||||
|
||||
export function defaultOtherHandler(_req: Request): Response {
|
||||
return new Response(null, {
|
||||
status: 404,
|
||||
});
|
||||
}
|
||||
|
||||
export function defaultErrorHandler(
|
||||
_req: Request,
|
||||
ctx: FreshContext,
|
||||
): Response {
|
||||
console.error(ctx.error);
|
||||
|
||||
return new Response(null, {
|
||||
status: 500,
|
||||
});
|
||||
}
|
||||
|
||||
export function defaultUnknownMethodHandler(
|
||||
_req: Request,
|
||||
_ctx: FreshContext,
|
||||
knownMethods: KnownMethod[],
|
||||
): Response {
|
||||
return new Response(null, {
|
||||
status: 405,
|
||||
headers: {
|
||||
Accept: knownMethods.join(", "),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export const IS_PATTERN = /[*:{}+?()]/;
|
||||
|
||||
function processRoutes(
|
||||
processedRoutes: Array<InternalRoute | null>,
|
||||
routes: Routes,
|
||||
destination: DestinationKind,
|
||||
) {
|
||||
for (const [path, def] of Object.entries(routes)) {
|
||||
const pattern = destination === "static" || !IS_PATTERN.test(path)
|
||||
? path
|
||||
: new URLPattern({ pathname: path });
|
||||
|
||||
const entry: InternalRoute = {
|
||||
baseRoute: def.baseRoute,
|
||||
pattern,
|
||||
originalPattern: path,
|
||||
methods: {},
|
||||
default: undefined,
|
||||
destination,
|
||||
};
|
||||
|
||||
for (const [method, handler] of Object.entries(def.methods)) {
|
||||
if (method === "default") {
|
||||
entry.default = handler;
|
||||
} else if (knownMethods.includes(method as KnownMethod)) {
|
||||
entry.methods[method as KnownMethod] = handler;
|
||||
}
|
||||
}
|
||||
|
||||
processedRoutes.push(entry);
|
||||
}
|
||||
}
|
||||
|
||||
export interface RouteResult {
|
||||
route: InternalRoute | undefined;
|
||||
params: Record<string, string>;
|
||||
isPartial: boolean;
|
||||
}
|
||||
|
||||
export function getParamsAndRoute(
|
||||
{
|
||||
internalRoutes,
|
||||
staticRoutes,
|
||||
routes,
|
||||
}: RouterOptions,
|
||||
): (
|
||||
url: URL,
|
||||
) => RouteResult {
|
||||
const processedRoutes: Array<InternalRoute | null> = [];
|
||||
processRoutes(processedRoutes, internalRoutes, "internal");
|
||||
processRoutes(processedRoutes, staticRoutes, "static");
|
||||
processRoutes(processedRoutes, routes, "route");
|
||||
|
||||
const statics = new Map<string, RouteResult>();
|
||||
|
||||
return (url: URL) => {
|
||||
const isPartial = url.searchParams.has(PARTIAL_SEARCH_PARAM);
|
||||
const pathname = url.pathname;
|
||||
|
||||
const cached = statics.get(pathname);
|
||||
if (cached !== undefined) {
|
||||
cached.isPartial = isPartial;
|
||||
return cached;
|
||||
}
|
||||
|
||||
for (let i = 0; i < processedRoutes.length; i++) {
|
||||
const route = processedRoutes[i];
|
||||
if (route === null) continue;
|
||||
|
||||
// Static routes where the full pattern contains no dynamic
|
||||
// parts and must be an exact match. We use that for static
|
||||
// files.
|
||||
if (typeof route.pattern === "string") {
|
||||
if (route.pattern === pathname) {
|
||||
processedRoutes[i] = null;
|
||||
const res = { route: route, params: {}, isPartial };
|
||||
statics.set(route.pattern, res);
|
||||
return res;
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
const res = route.pattern.exec(url);
|
||||
|
||||
if (res !== null) {
|
||||
return {
|
||||
route: route,
|
||||
params: res.pathname.groups,
|
||||
isPartial,
|
||||
};
|
||||
}
|
||||
}
|
||||
return {
|
||||
route: undefined,
|
||||
params: {},
|
||||
isPartial,
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
export function router(
|
||||
{
|
||||
otherHandler,
|
||||
unknownMethodHandler,
|
||||
}: RouterOptions,
|
||||
): FinalHandler {
|
||||
unknownMethodHandler ??= defaultUnknownMethodHandler;
|
||||
|
||||
return (req, ctx, route) => {
|
||||
if (route) {
|
||||
// If not overridden, HEAD requests should be handled as GET requests but without the body.
|
||||
if (req.method === "HEAD" && !route.methods["HEAD"]) {
|
||||
req = new Request(req.url, { method: "GET", headers: req.headers });
|
||||
}
|
||||
|
||||
for (const [method, handler] of Object.entries(route.methods)) {
|
||||
if (req.method === method) {
|
||||
return {
|
||||
destination: route.destination,
|
||||
handler: () => handler(req, ctx),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
if (route.default) {
|
||||
return {
|
||||
destination: route.destination,
|
||||
handler: () => route.default!(req, ctx),
|
||||
};
|
||||
} else {
|
||||
return {
|
||||
destination: route.destination,
|
||||
handler: () =>
|
||||
unknownMethodHandler!(
|
||||
req,
|
||||
ctx,
|
||||
Object.keys(route.methods) as KnownMethod[],
|
||||
),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
destination: "notFound",
|
||||
handler: () => otherHandler!(req, ctx),
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
export function withBase(src: string, base?: string) {
|
||||
if (base !== undefined && src.startsWith("/") && !src.startsWith(base)) {
|
||||
return base + src;
|
||||
}
|
||||
return src;
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
import { assertEquals } from "./deps.ts";
|
||||
import { IS_PATTERN } from "./router.ts";
|
||||
|
||||
Deno.test("IS_PATTERN", () => {
|
||||
assertEquals(IS_PATTERN.test("/foo"), false);
|
||||
assertEquals(IS_PATTERN.test("/foo/bar/baz.jpg"), false);
|
||||
assertEquals(IS_PATTERN.test("/foo/:path"), true);
|
||||
assertEquals(IS_PATTERN.test("/foo/*"), true);
|
||||
assertEquals(IS_PATTERN.test("/foo{/bar}?"), true);
|
||||
assertEquals(IS_PATTERN.test("/foo/(\\d+)"), true);
|
||||
assertEquals(IS_PATTERN.test("/foo/(a)"), true);
|
||||
});
|
||||
@@ -1,215 +0,0 @@
|
||||
/**
|
||||
* This module contains a serializer for island props. The serializer is capable
|
||||
* of serializing the following:
|
||||
*
|
||||
* - `null`
|
||||
* - `boolean`
|
||||
* - `number`
|
||||
* - `bigint`
|
||||
* - `string`
|
||||
* - `array`
|
||||
* - `object` (no prototypes)
|
||||
* - `Uint8Array`
|
||||
* - `Signal` from `@preact/signals`
|
||||
*
|
||||
* Circular references are supported and objects with the same reference are
|
||||
* serialized only once.
|
||||
*
|
||||
* The corresponding deserializer is in `src/runtime/deserializer.ts`.
|
||||
*/
|
||||
import { isValidElement, VNode } from "preact";
|
||||
import { KEY } from "../runtime/deserializer.ts";
|
||||
|
||||
interface SerializeResult {
|
||||
/** The string serialization. */
|
||||
serialized: string;
|
||||
/** If the deserializer is required to deserialize this string. If this is
|
||||
* `false` the serialized string can be deserialized with `JSON.parse`. */
|
||||
requiresDeserializer: boolean;
|
||||
/** If the serialization contains serialized signals. If this is `true` the
|
||||
* deserializer must be passed a factory functions for signals. */
|
||||
hasSignals: boolean;
|
||||
}
|
||||
|
||||
interface Signal {
|
||||
peek(): unknown;
|
||||
value: unknown;
|
||||
}
|
||||
|
||||
// deno-lint-ignore no-explicit-any
|
||||
function isSignal(x: any): x is Signal {
|
||||
return (
|
||||
x !== null &&
|
||||
typeof x === "object" &&
|
||||
typeof x.peek === "function" &&
|
||||
"value" in x
|
||||
);
|
||||
}
|
||||
|
||||
// deno-lint-ignore no-explicit-any
|
||||
function isVNode(x: any): x is VNode {
|
||||
return x !== null && typeof x === "object" && "type" in x && "ref" in x &&
|
||||
"__k" in x &&
|
||||
isValidElement(x);
|
||||
}
|
||||
|
||||
export function serialize(data: unknown): SerializeResult {
|
||||
let requiresDeserializer = false;
|
||||
let hasSignals = false;
|
||||
const seen = new Map<unknown, (string | null)[]>();
|
||||
const references = new Map<(string | null)[], (string | null)[][]>();
|
||||
|
||||
const keyStack: (string | null)[] = [];
|
||||
const parentStack: unknown[] = [];
|
||||
|
||||
let earlyReturn = false;
|
||||
|
||||
const toSerialize = {
|
||||
v: data,
|
||||
get r() {
|
||||
earlyReturn = true;
|
||||
if (references.size > 0) {
|
||||
const refs = [];
|
||||
for (const [targetPath, refPaths] of references) {
|
||||
refs.push([targetPath, ...refPaths]);
|
||||
}
|
||||
return refs;
|
||||
}
|
||||
return undefined;
|
||||
},
|
||||
};
|
||||
|
||||
function replacer(
|
||||
this: unknown,
|
||||
key: string | null,
|
||||
value: unknown,
|
||||
): unknown {
|
||||
if (value === toSerialize || earlyReturn) {
|
||||
return value;
|
||||
}
|
||||
|
||||
// Bypass signal's `.toJSON` method because we want to serialize
|
||||
// the signal itself including the signal's value and not just
|
||||
// the value. This is needed because `JSON.stringify` always
|
||||
// calls `.toJSON` automatically if available.
|
||||
// deno-lint-ignore no-explicit-any
|
||||
if (key !== null && isSignal((this as any)[key])) {
|
||||
// deno-lint-ignore no-explicit-any
|
||||
value = (this as any)[key];
|
||||
}
|
||||
|
||||
// For some object types, the path in the object graph from root is not the
|
||||
// same between the serialized representation, and deserialized objects. For
|
||||
// these cases, we have to change the contents of the key stack to match the
|
||||
// deserialized object.
|
||||
if (typeof this === "object" && this !== null && KEY in this) {
|
||||
if (this[KEY] === "s" && key === "v") key = "value"; // signals
|
||||
if (this[KEY] === "l" && key === "v") key = null; // literals (magic key object)
|
||||
}
|
||||
|
||||
if (this !== toSerialize) {
|
||||
const parentIndex = parentStack.indexOf(this);
|
||||
parentStack.splice(parentIndex + 1);
|
||||
keyStack.splice(parentIndex);
|
||||
keyStack.push(key);
|
||||
// the parent is pushed before return
|
||||
}
|
||||
|
||||
if (typeof value === "object" && value !== null) {
|
||||
const path = seen.get(value);
|
||||
const currentPath = [...keyStack];
|
||||
if (path !== undefined) {
|
||||
requiresDeserializer = true;
|
||||
const referenceArr = references.get(path);
|
||||
if (referenceArr === undefined) {
|
||||
references.set(path, [currentPath]);
|
||||
} else {
|
||||
referenceArr.push(currentPath);
|
||||
}
|
||||
return 0;
|
||||
} else if (isVNode(value)) {
|
||||
requiresDeserializer = true;
|
||||
// No need to serialize JSX as we pick that up from
|
||||
// the rendered HTML in the browser.
|
||||
const res = null;
|
||||
parentStack.push(res);
|
||||
return res;
|
||||
} else {
|
||||
seen.set(value, currentPath);
|
||||
}
|
||||
}
|
||||
|
||||
if (isSignal(value)) {
|
||||
requiresDeserializer = true;
|
||||
hasSignals = true;
|
||||
const res = { [KEY]: "s", v: value.peek() };
|
||||
parentStack.push(res);
|
||||
return res;
|
||||
} else if (typeof value === "bigint") {
|
||||
requiresDeserializer = true;
|
||||
const res = { [KEY]: "b", d: value.toString() };
|
||||
parentStack.push(res);
|
||||
return res;
|
||||
} else if (value instanceof Uint8Array) {
|
||||
requiresDeserializer = true;
|
||||
const res = { [KEY]: "u8a", d: b64encode(value) };
|
||||
parentStack.push(res);
|
||||
return res;
|
||||
} else if (typeof value === "object" && value && KEY in value) {
|
||||
requiresDeserializer = true;
|
||||
// deno-lint-ignore no-explicit-any
|
||||
const v: any = { ...value };
|
||||
const k = v[KEY];
|
||||
delete v[KEY];
|
||||
const res = { [KEY]: "l", k, v };
|
||||
parentStack.push(res);
|
||||
return res;
|
||||
} else {
|
||||
parentStack.push(value);
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
const serialized = JSON.stringify(toSerialize, replacer);
|
||||
return { serialized, requiresDeserializer, hasSignals };
|
||||
}
|
||||
|
||||
// deno-fmt-ignore
|
||||
const base64abc = [
|
||||
"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O",
|
||||
"P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "a", "b", "c", "d",
|
||||
"e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s",
|
||||
"t", "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5", "6", "7",
|
||||
"8", "9", "+", "/",
|
||||
];
|
||||
|
||||
/**
|
||||
* CREDIT: https://gist.github.com/enepomnyaschih/72c423f727d395eeaa09697058238727
|
||||
* Encodes a given Uint8Array, ArrayBuffer or string into RFC4648 base64 representation
|
||||
*/
|
||||
export function b64encode(buffer: ArrayBuffer): string {
|
||||
const uint8 = new Uint8Array(buffer);
|
||||
let result = "",
|
||||
i;
|
||||
const l = uint8.length;
|
||||
for (i = 2; i < l; i += 3) {
|
||||
result += base64abc[uint8[i - 2] >> 2];
|
||||
result += base64abc[((uint8[i - 2] & 0x03) << 4) | (uint8[i - 1] >> 4)];
|
||||
result += base64abc[((uint8[i - 1] & 0x0f) << 2) | (uint8[i] >> 6)];
|
||||
result += base64abc[uint8[i] & 0x3f];
|
||||
}
|
||||
if (i === l + 1) {
|
||||
// 1 octet yet to write
|
||||
result += base64abc[uint8[i - 2] >> 2];
|
||||
result += base64abc[(uint8[i - 2] & 0x03) << 4];
|
||||
result += "==";
|
||||
}
|
||||
if (i === l) {
|
||||
// 2 octets yet to write
|
||||
result += base64abc[uint8[i - 2] >> 2];
|
||||
result += base64abc[((uint8[i - 2] & 0x03) << 4) | (uint8[i - 1] >> 4)];
|
||||
result += base64abc[(uint8[i - 1] & 0x0f) << 2];
|
||||
result += "=";
|
||||
}
|
||||
return result;
|
||||
}
|
||||
@@ -1,233 +0,0 @@
|
||||
// deno-lint-ignore-file no-explicit-any
|
||||
|
||||
import { serialize } from "./serializer.ts";
|
||||
import {
|
||||
assert,
|
||||
assertEquals,
|
||||
assertSnapshot,
|
||||
assertThrows,
|
||||
} from "../../tests/deps.ts";
|
||||
import { deserialize, KEY } from "../runtime/deserializer.ts";
|
||||
import { signal } from "@preact/signals-core";
|
||||
import { signal as signal130 } from "@preact/signals-core@1.3.0";
|
||||
import { signal as signal123 } from "@preact/signals-core@1.2.3";
|
||||
|
||||
Deno.test("serializer - primitives & plain objects", async (t) => {
|
||||
const data = {
|
||||
a: 1,
|
||||
b: "2",
|
||||
c: true,
|
||||
d: null,
|
||||
f: [1, 2, 3],
|
||||
g: { a: 1, b: 2, c: 3 },
|
||||
};
|
||||
const res = serialize(data);
|
||||
assert(!res.requiresDeserializer);
|
||||
assert(!res.hasSignals);
|
||||
await assertSnapshot(t, res.serialized);
|
||||
const deserialized = deserialize(res.serialized);
|
||||
assertEquals(deserialized, data);
|
||||
});
|
||||
|
||||
Deno.test("serializer - bigint", async (t) => {
|
||||
const data = { a: 999999999999999999n };
|
||||
const res = serialize(data);
|
||||
assert(res.requiresDeserializer);
|
||||
assert(!res.hasSignals);
|
||||
await assertSnapshot(t, res.serialized);
|
||||
const deserialized = deserialize(res.serialized);
|
||||
assertEquals(deserialized, data);
|
||||
});
|
||||
|
||||
Deno.test("serializer - Uint8Array", async (t) => {
|
||||
const data = { a: new Uint8Array([1, 2, 3]) };
|
||||
const res = serialize(data);
|
||||
assert(res.requiresDeserializer);
|
||||
assert(!res.hasSignals);
|
||||
await assertSnapshot(t, res.serialized);
|
||||
const deserialized = deserialize(res.serialized);
|
||||
assertEquals(deserialized, data);
|
||||
});
|
||||
|
||||
Deno.test("serializer - signals", async (t) => {
|
||||
const data = {
|
||||
a: 1,
|
||||
b: signal(2),
|
||||
};
|
||||
const res = serialize(data);
|
||||
assert(res.requiresDeserializer);
|
||||
assert(res.hasSignals);
|
||||
await assertSnapshot(t, res.serialized);
|
||||
const deserialized: any = deserialize(res.serialized, signal);
|
||||
assertEquals(typeof deserialized, "object");
|
||||
assertEquals(deserialized.a, 1);
|
||||
assertEquals(deserialized.b.value, 2);
|
||||
assertEquals(deserialized.b.peek(), 2);
|
||||
});
|
||||
|
||||
Deno.test("serializer - @preact/signals-core 1.2.3", async (t) => {
|
||||
const data = {
|
||||
a: 1,
|
||||
b: signal123(2),
|
||||
};
|
||||
const res = serialize(data);
|
||||
assert(res.requiresDeserializer);
|
||||
assert(res.hasSignals);
|
||||
await assertSnapshot(t, res.serialized);
|
||||
const deserialized: any = deserialize(res.serialized, signal);
|
||||
assertEquals(typeof deserialized, "object");
|
||||
assertEquals(deserialized.a, 1);
|
||||
assertEquals(deserialized.b.value, 2);
|
||||
assertEquals(deserialized.b.peek(), 2);
|
||||
});
|
||||
|
||||
Deno.test("serializer - @preact/signals-core 1.3.0", async (t) => {
|
||||
const data = {
|
||||
a: 1,
|
||||
b: signal130(2),
|
||||
};
|
||||
const res = serialize(data);
|
||||
assert(res.requiresDeserializer);
|
||||
assert(res.hasSignals);
|
||||
await assertSnapshot(t, res.serialized);
|
||||
const deserialized: any = deserialize(res.serialized, signal);
|
||||
assertEquals(typeof deserialized, "object");
|
||||
assertEquals(deserialized.a, 1);
|
||||
assertEquals(deserialized.b.value, 2);
|
||||
assertEquals(deserialized.b.peek(), 2);
|
||||
});
|
||||
|
||||
Deno.test("serializer - multiple versions of @preact/signals-core", async (t) => {
|
||||
const data = {
|
||||
a: 1,
|
||||
b: signal(2),
|
||||
c: signal123(2),
|
||||
d: signal130(2),
|
||||
};
|
||||
const res = serialize(data);
|
||||
assert(res.requiresDeserializer);
|
||||
assert(res.hasSignals);
|
||||
await assertSnapshot(t, res.serialized);
|
||||
const deserialized: any = deserialize(res.serialized, signal);
|
||||
assertEquals(typeof deserialized, "object");
|
||||
assertEquals(deserialized.a, 1);
|
||||
assertEquals(deserialized.b.value, 2);
|
||||
assertEquals(deserialized.b.peek(), 2);
|
||||
assertEquals(deserialized.c.value, 2);
|
||||
assertEquals(deserialized.c.peek(), 2);
|
||||
assertEquals(deserialized.d.value, 2);
|
||||
assertEquals(deserialized.d.peek(), 2);
|
||||
});
|
||||
|
||||
Deno.test("serializer - magic key", async (t) => {
|
||||
const data = { [KEY]: "f", a: 1 };
|
||||
const res = serialize(data);
|
||||
assert(res.requiresDeserializer);
|
||||
assert(!res.hasSignals);
|
||||
await assertSnapshot(t, res.serialized);
|
||||
const deserialized = deserialize(res.serialized);
|
||||
assertEquals(deserialized, data);
|
||||
});
|
||||
|
||||
Deno.test("serializer - circular reference objects", async (t) => {
|
||||
const data: any = { a: 1 };
|
||||
data.b = data;
|
||||
const res = serialize(data);
|
||||
assert(res.requiresDeserializer);
|
||||
assert(!res.hasSignals);
|
||||
await assertSnapshot(t, res.serialized);
|
||||
const deserialized = deserialize(res.serialized);
|
||||
assertEquals(deserialized, data);
|
||||
});
|
||||
|
||||
Deno.test("serializer - circular reference nested objects", async (t) => {
|
||||
const data: any = { a: 1, b: { c: 2 } };
|
||||
data.b.d = data;
|
||||
const res = serialize(data);
|
||||
assert(res.requiresDeserializer);
|
||||
assert(!res.hasSignals);
|
||||
await assertSnapshot(t, res.serialized);
|
||||
const deserialized = deserialize(res.serialized);
|
||||
assertEquals(deserialized, data);
|
||||
});
|
||||
|
||||
Deno.test("serializer - circular reference array", async (t) => {
|
||||
const data: any = [1, 2, 3];
|
||||
data.push(data);
|
||||
const res = serialize(data);
|
||||
assert(res.requiresDeserializer);
|
||||
assert(!res.hasSignals);
|
||||
await assertSnapshot(t, res.serialized);
|
||||
const deserialized: any = deserialize(res.serialized);
|
||||
assertEquals(deserialized, data);
|
||||
assertEquals(deserialized.length, 4);
|
||||
});
|
||||
|
||||
Deno.test("serializer - multiple reference", async (t) => {
|
||||
const data: any = { a: 1, b: { c: 2 } };
|
||||
data.d = data.b;
|
||||
const res = serialize(data);
|
||||
assert(res.requiresDeserializer);
|
||||
assert(!res.hasSignals);
|
||||
await assertSnapshot(t, res.serialized);
|
||||
const deserialized = deserialize(res.serialized);
|
||||
assertEquals(deserialized, data);
|
||||
});
|
||||
|
||||
Deno.test("serializer - multiple reference signals", async (t) => {
|
||||
const inner: any = { [KEY]: "x", x: 1 };
|
||||
inner.y = inner;
|
||||
const s = signal(inner);
|
||||
const data = { inner, a: s, b: { c: s } };
|
||||
const res = serialize(data);
|
||||
assert(res.requiresDeserializer);
|
||||
assert(res.hasSignals);
|
||||
await assertSnapshot(t, res.serialized);
|
||||
const deserialized: any = deserialize(res.serialized, signal);
|
||||
assertEquals(deserialized.a.value, inner);
|
||||
assertEquals(deserialized.a.peek(), inner);
|
||||
assertEquals(deserialized.b.c.value, inner);
|
||||
assertEquals(deserialized.b.c.peek(), inner);
|
||||
deserialized.a.value = 2;
|
||||
assertEquals(deserialized.a.value, 2);
|
||||
assertEquals(deserialized.b.c.value, 2);
|
||||
});
|
||||
|
||||
Deno.test("serializer - multiple reference in magic key", async (t) => {
|
||||
const inner = { foo: "bar" };
|
||||
const literal: any = { [KEY]: "x", inner };
|
||||
const data = { literal, inner };
|
||||
const res = serialize(data);
|
||||
assert(res.requiresDeserializer);
|
||||
assert(!res.hasSignals);
|
||||
await assertSnapshot(t, res.serialized);
|
||||
const deserialized: any = deserialize(res.serialized);
|
||||
assertEquals(deserialized, data);
|
||||
});
|
||||
|
||||
Deno.test("serializer - multiple reference in signal", async (t) => {
|
||||
const inner = { foo: "bar" };
|
||||
const s = signal(inner);
|
||||
const data = { s, inner };
|
||||
const res = serialize(data);
|
||||
assert(res.requiresDeserializer);
|
||||
assert(res.hasSignals);
|
||||
await assertSnapshot(t, res.serialized);
|
||||
const deserialized: any = deserialize(res.serialized, signal);
|
||||
assertEquals(deserialized.s.value, inner);
|
||||
assertEquals(deserialized.s.peek(), inner);
|
||||
assertEquals(deserialized.inner, inner);
|
||||
});
|
||||
|
||||
Deno.test("deserializer - no prototype pollution with manual input", () => {
|
||||
const serialized = String.raw`{
|
||||
"v": {
|
||||
"*": ["onerror"]
|
||||
},
|
||||
"r": [
|
||||
[["*"], ["constructor", "prototype", "*"]]
|
||||
]
|
||||
}`;
|
||||
assertThrows(() => deserialize(serialized, signal));
|
||||
assertEquals({}.constructor.prototype["*"], undefined);
|
||||
});
|
||||
@@ -1,675 +0,0 @@
|
||||
import { ComponentChildren, ComponentType, VNode } from "preact";
|
||||
import * as router from "./router.ts";
|
||||
import { InnerRenderFunction, RenderContext } from "./render.ts";
|
||||
import { Manifest } from "./mod.ts";
|
||||
|
||||
export interface DenoConfig {
|
||||
imports?: Record<string, string>;
|
||||
importMap?: string;
|
||||
tasks?: Record<string, string>;
|
||||
lint?: {
|
||||
rules: { tags?: string[] };
|
||||
exclude?: string[];
|
||||
};
|
||||
fmt?: {
|
||||
exclude?: string[];
|
||||
};
|
||||
exclude?: string[];
|
||||
compilerOptions?: {
|
||||
jsx?: string;
|
||||
jsxImportSource?: string;
|
||||
};
|
||||
}
|
||||
|
||||
// --- APPLICATION CONFIGURATION ---
|
||||
export interface FreshConfig {
|
||||
build?: {
|
||||
/**
|
||||
* The directory to write generated files to when `dev.ts build` is run.
|
||||
* This can be an absolute path, a file URL or a relative path.
|
||||
*/
|
||||
outDir?: string;
|
||||
/**
|
||||
* This sets the target environment for the generated code. Newer
|
||||
* language constructs will be transformed to match the specified
|
||||
* support range. See https://esbuild.github.io/api/#target
|
||||
* @default {"es2022"}
|
||||
*/
|
||||
target?: string | string[];
|
||||
};
|
||||
render?: RenderFunction;
|
||||
plugins?: Plugin[];
|
||||
staticDir?: string;
|
||||
router?: RouterOptions;
|
||||
server?: Partial<Deno.ServeTlsOptions>;
|
||||
|
||||
// Older versions of Fresh merged the `Deno.ServeTlsOptions` directly.
|
||||
// We've moved this to `server`.
|
||||
|
||||
/**
|
||||
* Server private key in PEM format
|
||||
* @deprecated Use `server.cert` instead
|
||||
*/
|
||||
cert?: string;
|
||||
/**
|
||||
* Cert chain in PEM format
|
||||
* @deprecated Use `server.key` instead
|
||||
*/
|
||||
key?: string;
|
||||
/**
|
||||
* The port to listen on.
|
||||
* @default {8000}
|
||||
* @deprecated Use `server.port` instead
|
||||
*/
|
||||
port?: number;
|
||||
/**
|
||||
* A literal IP address or host name that can be resolved to an IP address.
|
||||
*
|
||||
* __Note about `0.0.0.0`__ While listening `0.0.0.0` works on all platforms,
|
||||
* the browsers on Windows don't work with the address `0.0.0.0`.
|
||||
* You should show the message like `server running on localhost:8080` instead of
|
||||
* `server running on 0.0.0.0:8080` if your program supports Windows.
|
||||
*
|
||||
* @default {"0.0.0.0"}
|
||||
* @deprecated Use `server.hostname` instead
|
||||
*/
|
||||
hostname?: string;
|
||||
/**
|
||||
* An {@linkcode AbortSignal} to close the server and all connections.
|
||||
* @deprecated Use `server.signal` instead
|
||||
*/
|
||||
signal?: AbortSignal;
|
||||
/**
|
||||
* Sets `SO_REUSEPORT` on POSIX systems.
|
||||
* @deprecated Use `server.reusePort` instead
|
||||
*/
|
||||
reusePort?: boolean;
|
||||
/**
|
||||
* The handler to invoke when route handlers throw an error.
|
||||
* @deprecated Use `server.onError` instead
|
||||
*/
|
||||
onError?: (error: unknown) => Response | Promise<Response>;
|
||||
|
||||
/**
|
||||
* The callback which is called when the server starts listening.
|
||||
* @deprecated Use `server.onListen` instead
|
||||
*/
|
||||
onListen?: (params: { hostname: string; port: number }) => void;
|
||||
}
|
||||
|
||||
export interface InternalFreshState {
|
||||
config: ResolvedFreshConfig;
|
||||
manifest: Manifest;
|
||||
loadSnapshot: boolean;
|
||||
didLoadSnapshot: boolean;
|
||||
denoJsonPath: string;
|
||||
denoJson: DenoConfig;
|
||||
build: boolean;
|
||||
}
|
||||
|
||||
export interface ResolvedFreshConfig {
|
||||
dev: boolean;
|
||||
build: {
|
||||
outDir: string;
|
||||
target: string | string[];
|
||||
};
|
||||
render: RenderFunction;
|
||||
plugins: Plugin[];
|
||||
staticDir: string;
|
||||
router?: RouterOptions;
|
||||
server: Partial<Deno.ServeTlsOptions>;
|
||||
basePath: string;
|
||||
}
|
||||
|
||||
export interface RouterOptions {
|
||||
/**
|
||||
* Controls whether Fresh will append a trailing slash to the URL.
|
||||
* @default {false}
|
||||
*/
|
||||
trailingSlash?: boolean;
|
||||
/**
|
||||
* Configures the pattern of files to ignore in islands and routes.
|
||||
*
|
||||
* By default Fresh will ignore test files,
|
||||
* for example files with a `.test.ts` or a `_test.ts` suffix.
|
||||
*
|
||||
* @default {/(?:[^/]*_|[^/]*\.|)test\.(?:ts|tsx|mts|js|mjs|jsx|)\/*$/}
|
||||
*/
|
||||
ignoreFilePattern?: RegExp;
|
||||
/**
|
||||
* Serve fresh from a base path instead of from the root.
|
||||
* "/foo/bar" -> http://localhost:8000/foo/bar
|
||||
* @default {undefined}
|
||||
*/
|
||||
basePath?: string;
|
||||
}
|
||||
|
||||
export type RenderFunction = (
|
||||
ctx: RenderContext,
|
||||
render: InnerRenderFunction,
|
||||
) => void | Promise<void>;
|
||||
|
||||
/// --- ROUTES ---
|
||||
|
||||
// deno-lint-ignore no-explicit-any
|
||||
export type PageProps<T = any, S = Record<string, unknown>> = Omit<
|
||||
FreshContext<
|
||||
S,
|
||||
T
|
||||
>,
|
||||
"render" | "next" | "renderNotFound"
|
||||
>;
|
||||
|
||||
export interface StaticFile {
|
||||
/** The URL to the static file on disk. */
|
||||
localUrl: URL;
|
||||
/** The path to the file as it would be in the incoming request. */
|
||||
path: string;
|
||||
/** The size of the file. */
|
||||
size: number;
|
||||
/** The content-type of the file. */
|
||||
contentType: string;
|
||||
/** Hash of the file contents. */
|
||||
etag: string;
|
||||
}
|
||||
|
||||
export interface FreshContext<
|
||||
State = Record<string, unknown>,
|
||||
// deno-lint-ignore no-explicit-any
|
||||
Data = any,
|
||||
NotFoundData = Data,
|
||||
> {
|
||||
/** @types deprecated */
|
||||
localAddr?: Deno.NetAddr;
|
||||
remoteAddr: Deno.NetAddr;
|
||||
url: URL;
|
||||
basePath: string;
|
||||
route: string;
|
||||
/** @deprecated Use `.route` instead */
|
||||
pattern: string;
|
||||
destination: router.DestinationKind;
|
||||
params: Record<string, string>;
|
||||
isPartial: boolean;
|
||||
state: State;
|
||||
config: ResolvedFreshConfig;
|
||||
data: Data;
|
||||
/** The error that caused the error page to be loaded. */
|
||||
error?: unknown;
|
||||
/** Sringified code frame of the error rendering failed (only in development mode) */
|
||||
codeFrame?: unknown;
|
||||
|
||||
// These properties may be different
|
||||
renderNotFound: (data?: NotFoundData) => Response | Promise<Response>;
|
||||
render: (
|
||||
data?: Data,
|
||||
options?: RenderOptions,
|
||||
) => Response | Promise<Response>;
|
||||
Component: ComponentType<unknown>;
|
||||
next: () => Promise<Response>;
|
||||
}
|
||||
/**
|
||||
* Context passed to async route components.
|
||||
*/
|
||||
// deno-lint-ignore no-explicit-any
|
||||
export type RouteContext<T = any, S = Record<string, unknown>> = Omit<
|
||||
FreshContext<
|
||||
S,
|
||||
T
|
||||
>,
|
||||
"next" | "render"
|
||||
>;
|
||||
|
||||
export interface RouteConfig {
|
||||
/**
|
||||
* A route override for the page. This is useful for pages where the route
|
||||
* can not be expressed through the filesystem routing capabilities.
|
||||
*
|
||||
* The route override must be a path-to-regexp compatible route matcher.
|
||||
*/
|
||||
routeOverride?: string;
|
||||
|
||||
/**
|
||||
* If Content-Security-Policy should be enabled for this page. If 'true', a
|
||||
* locked down policy will be used that allows only the scripts and styles
|
||||
* that are generated by Fresh. Additional scripts and styles can be added
|
||||
* using the `useCSP` hook.
|
||||
*/
|
||||
csp?: boolean;
|
||||
|
||||
/**
|
||||
* Skip already inherited layouts
|
||||
* Default: `false`
|
||||
*/
|
||||
skipInheritedLayouts?: boolean;
|
||||
|
||||
/**
|
||||
* Skip rendering the `routes/_app` template
|
||||
* Default: `false`
|
||||
*/
|
||||
skipAppWrapper?: boolean;
|
||||
}
|
||||
|
||||
export interface RenderOptions extends ResponseInit {}
|
||||
|
||||
export type ServeHandlerInfo = Deno.ServeHandlerInfo & {
|
||||
/**
|
||||
* Backwards compatible with std/server
|
||||
* @deprecated
|
||||
*/
|
||||
localAddr?: Deno.NetAddr;
|
||||
};
|
||||
|
||||
export type ServeHandler = (
|
||||
request: Request,
|
||||
info: ServeHandlerInfo,
|
||||
) => Response | Promise<Response>;
|
||||
|
||||
// deno-lint-ignore no-explicit-any
|
||||
export type Handler<T = any, State = Record<string, unknown>> = (
|
||||
req: Request,
|
||||
ctx: FreshContext<State, T>,
|
||||
) => Response | Promise<Response>;
|
||||
|
||||
// deno-lint-ignore no-explicit-any
|
||||
export type Handlers<T = any, State = Record<string, unknown>> = {
|
||||
[K in router.KnownMethod]?: Handler<T, State>;
|
||||
};
|
||||
|
||||
export interface RouteModule {
|
||||
default?: PageComponent<PageProps>;
|
||||
// deno-lint-ignore no-explicit-any
|
||||
handler?: Handler<any, any> | Handlers<any, any>;
|
||||
config?: RouteConfig;
|
||||
}
|
||||
|
||||
// deno-lint-ignore no-explicit-any
|
||||
export type AsyncRoute<T = any, S = Record<string, unknown>> = (
|
||||
req: Request,
|
||||
ctx: FreshContext<S, T>,
|
||||
) => Promise<ComponentChildren | Response>;
|
||||
// deno-lint-ignore no-explicit-any
|
||||
export type PageComponent<T = any, S = Record<string, unknown>> =
|
||||
| ComponentType<PageProps<T, S>>
|
||||
| AsyncRoute<T, S>
|
||||
// deno-lint-ignore no-explicit-any
|
||||
| ((props: any) => VNode<any> | ComponentChildren);
|
||||
|
||||
// deno-lint-ignore no-explicit-any
|
||||
export interface Route<Data = any> {
|
||||
baseRoute: BaseRoute;
|
||||
pattern: string;
|
||||
url: string;
|
||||
name: string;
|
||||
component?: PageComponent<Data> | AsyncLayout<Data> | AsyncRoute<Data>;
|
||||
handler: Handler<Data> | Handlers<Data>;
|
||||
csp: boolean;
|
||||
appWrapper: boolean;
|
||||
inheritLayouts: boolean;
|
||||
}
|
||||
|
||||
// --- APP ---
|
||||
export interface AppModule {
|
||||
default: ComponentType<PageProps> | AsyncLayout;
|
||||
}
|
||||
|
||||
// deno-lint-ignore no-explicit-any
|
||||
export type AsyncLayout<T = any, S = Record<string, unknown>> = (
|
||||
req: Request,
|
||||
ctx: FreshContext<S, T>,
|
||||
) => Promise<ComponentChildren | Response>;
|
||||
|
||||
export interface LayoutConfig {
|
||||
/**
|
||||
* Skip already inherited layouts
|
||||
* Default: `false`
|
||||
*/
|
||||
skipAppWrapper?: boolean;
|
||||
/**
|
||||
* Skip rendering the `routes/_app`.
|
||||
* Default: `false`
|
||||
*/
|
||||
skipInheritedLayouts?: boolean;
|
||||
}
|
||||
|
||||
export interface LayoutModule {
|
||||
// deno-lint-ignore no-explicit-any
|
||||
handler?: Handler<any, any> | Handlers<any, any>;
|
||||
default: ComponentType<PageProps> | AsyncLayout;
|
||||
config?: LayoutConfig;
|
||||
}
|
||||
|
||||
export interface LayoutRoute {
|
||||
baseRoute: BaseRoute;
|
||||
// deno-lint-ignore no-explicit-any
|
||||
handler?: Handler<any, any> | Handlers<any, any>;
|
||||
component: LayoutModule["default"];
|
||||
appWrapper: boolean;
|
||||
inheritLayouts: boolean;
|
||||
}
|
||||
|
||||
// --- UNKNOWN PAGE ---
|
||||
|
||||
export type UnknownHandler = (
|
||||
req: Request,
|
||||
ctx: FreshContext,
|
||||
) => Response | Promise<Response>;
|
||||
|
||||
export interface UnknownPageModule {
|
||||
default?: PageComponent<PageProps>;
|
||||
handler?: UnknownHandler;
|
||||
config?: RouteConfig;
|
||||
}
|
||||
|
||||
export interface UnknownPage {
|
||||
baseRoute: BaseRoute;
|
||||
pattern: string;
|
||||
url: string;
|
||||
name: string;
|
||||
component?: PageComponent<PageProps>;
|
||||
handler: UnknownHandler;
|
||||
csp: boolean;
|
||||
appWrapper: boolean;
|
||||
inheritLayouts: boolean;
|
||||
}
|
||||
|
||||
export type UnknownRenderFunction = (
|
||||
req: Request,
|
||||
ctx: FreshContext,
|
||||
) => Promise<Response>;
|
||||
|
||||
// --- ERROR PAGE ---
|
||||
|
||||
// Nominal/Branded type. Ensures that the string has the expected format
|
||||
export type BaseRoute = string & { readonly __brand: unique symbol };
|
||||
|
||||
export type ErrorHandler = (
|
||||
req: Request,
|
||||
ctx: FreshContext,
|
||||
) => Response | Promise<Response>;
|
||||
|
||||
export interface ErrorPageModule {
|
||||
default?: PageComponent<PageProps>;
|
||||
handler?: ErrorHandler;
|
||||
config?: RouteConfig;
|
||||
}
|
||||
|
||||
export interface ErrorPage {
|
||||
baseRoute: BaseRoute;
|
||||
pattern: string;
|
||||
url: string;
|
||||
name: string;
|
||||
component?: PageComponent<PageProps>;
|
||||
handler: ErrorHandler;
|
||||
csp: boolean;
|
||||
appWrapper: boolean;
|
||||
inheritLayouts: boolean;
|
||||
}
|
||||
|
||||
// --- MIDDLEWARES ---
|
||||
export interface MiddlewareRoute {
|
||||
baseRoute: BaseRoute;
|
||||
module: Middleware;
|
||||
}
|
||||
|
||||
export type MiddlewareHandler<State = Record<string, unknown>> = (
|
||||
req: Request,
|
||||
ctx: FreshContext<State>,
|
||||
) => Response | Promise<Response>;
|
||||
|
||||
// deno-lint-ignore no-explicit-any
|
||||
export interface MiddlewareModule<State = any> {
|
||||
handler: MiddlewareHandler<State> | MiddlewareHandler<State>[];
|
||||
}
|
||||
|
||||
export interface Middleware<State = Record<string, unknown>> {
|
||||
handler: MiddlewareHandler<State> | MiddlewareHandler<State>[];
|
||||
}
|
||||
|
||||
// --- ISLANDS ---
|
||||
|
||||
export interface IslandModule {
|
||||
// deno-lint-ignore no-explicit-any
|
||||
[key: string]: ComponentType<any> | unknown;
|
||||
}
|
||||
|
||||
export interface Island {
|
||||
id: string;
|
||||
name: string;
|
||||
url: string;
|
||||
component: ComponentType<unknown>;
|
||||
exportName: string;
|
||||
}
|
||||
|
||||
// --- PLUGINS ---
|
||||
|
||||
export interface Plugin<State = Record<string, unknown>> {
|
||||
/** The name of the plugin. Must be snake-case. */
|
||||
name: string;
|
||||
|
||||
/** A map of a snake-case names to a import specifiers. The entrypoints
|
||||
* declared here can later be used in the "scripts" option of
|
||||
* `PluginRenderResult` to load the entrypoint's code on the client.
|
||||
*/
|
||||
entrypoints?: Record<string, string>;
|
||||
|
||||
/** The render hook is called on the server every time some JSX needs to
|
||||
* be turned into HTML. The render hook needs to call the `ctx.render`
|
||||
* function exactly once.
|
||||
*
|
||||
* The hook can return a `PluginRenderResult` object that can do things like
|
||||
* inject CSS into the page, or load additional JS files on the client.
|
||||
*/
|
||||
render?(ctx: PluginRenderContext): PluginRenderResult;
|
||||
|
||||
/** The asynchronous render hook is called on the server every time some
|
||||
* JSX needs to be turned into HTML, wrapped around all synchronous render
|
||||
* hooks. The render hook needs to call the `ctx.renderAsync` function
|
||||
* exactly once, and await the result.
|
||||
*
|
||||
* This is useful for when plugins are generating styles and scripts with
|
||||
* asynchronous dependencies. Unlike the synchronous render hook, async render
|
||||
* hooks for multiple pages can be running at the same time. This means that
|
||||
* unlike the synchronous render hook, you can not use global variables to
|
||||
* propagate state between the render hook and the renderer.
|
||||
*/
|
||||
renderAsync?(ctx: PluginAsyncRenderContext): Promise<PluginRenderResult>;
|
||||
|
||||
/**
|
||||
* Called before running the Fresh build task
|
||||
*/
|
||||
buildStart?(config: ResolvedFreshConfig): Promise<void> | void;
|
||||
/**
|
||||
* Called after completing the Fresh build task
|
||||
*/
|
||||
buildEnd?(): Promise<void> | void;
|
||||
|
||||
/**
|
||||
* Called after configuration has been loaded
|
||||
*/
|
||||
configResolved?(config: ResolvedFreshConfig): Promise<void> | void;
|
||||
|
||||
routes?: PluginRoute[];
|
||||
|
||||
middlewares?: PluginMiddleware<State>[];
|
||||
|
||||
islands?: PluginIslands;
|
||||
}
|
||||
|
||||
export interface PluginRenderContext {
|
||||
render: PluginRenderFunction;
|
||||
}
|
||||
|
||||
export interface PluginAsyncRenderContext {
|
||||
renderAsync: PluginAsyncRenderFunction;
|
||||
}
|
||||
|
||||
export interface PluginRenderResult {
|
||||
/** CSS styles to be injected into the page. */
|
||||
styles?: PluginRenderStyleTag[];
|
||||
/** JS scripts to ship to the client. */
|
||||
scripts?: PluginRenderScripts[];
|
||||
/** Link tags for the page */
|
||||
links?: PluginRenderLink[];
|
||||
/** Body HTML transformed by the plugin */
|
||||
htmlText?: string;
|
||||
}
|
||||
|
||||
export interface PluginRenderStyleTag {
|
||||
cssText: string;
|
||||
media?: string;
|
||||
id?: string;
|
||||
}
|
||||
|
||||
export type PluginRenderLink = {
|
||||
crossOrigin?: string;
|
||||
href?: string;
|
||||
hreflang?: string;
|
||||
media?: string;
|
||||
referrerPolicy?: string;
|
||||
rel?: string;
|
||||
title?: string;
|
||||
type?: string;
|
||||
};
|
||||
|
||||
export interface PluginRenderScripts {
|
||||
/** The "key" of the entrypoint (as specified in `Plugin.entrypoints`) for the
|
||||
* script that should be loaded. The script must be an ES module that exports
|
||||
* a default function.
|
||||
*
|
||||
* The default function is invoked with the `state` argument specified below.
|
||||
*/
|
||||
entrypoint: string;
|
||||
/** The state argument that is passed to the default export invocation of the
|
||||
* entrypoint's default export. The state must be JSON-serializable.
|
||||
*/
|
||||
state: unknown;
|
||||
}
|
||||
|
||||
export type PluginRenderFunction = () => PluginRenderFunctionResult;
|
||||
|
||||
export type PluginAsyncRenderFunction = () =>
|
||||
| PluginRenderFunctionResult
|
||||
| Promise<PluginRenderFunctionResult>;
|
||||
|
||||
export interface PluginRenderFunctionResult {
|
||||
/** The HTML text that was rendered. */
|
||||
htmlText: string;
|
||||
/** If the renderer encountered any islands that require hydration on the
|
||||
* client. */
|
||||
requiresHydration: boolean;
|
||||
}
|
||||
|
||||
export interface PluginMiddleware<State = Record<string, unknown>> {
|
||||
/** A path in the format of a filename path without filetype */
|
||||
path: string;
|
||||
|
||||
middleware: Middleware<State>;
|
||||
}
|
||||
|
||||
export interface PluginRoute {
|
||||
/** A path in the format of a filename path without filetype */
|
||||
path: string;
|
||||
|
||||
component?:
|
||||
| ComponentType<PageProps>
|
||||
| ComponentType<AppProps>
|
||||
| AsyncRoute
|
||||
| AsyncLayout;
|
||||
|
||||
// deno-lint-ignore no-explicit-any
|
||||
handler?: Handler<any, any> | Handlers<any, any>;
|
||||
}
|
||||
|
||||
export interface PluginIslands {
|
||||
baseLocation: string;
|
||||
paths: string[];
|
||||
}
|
||||
|
||||
// --- Deprecated types ---
|
||||
|
||||
/**
|
||||
* @deprecated This type was a short-lived alternative to `Handlers`. Please use `Handlers` instead.
|
||||
*/
|
||||
export type MultiHandler<T> = Handlers<T>;
|
||||
|
||||
/**
|
||||
* @deprecated Use {@linkcode FreshConfig} instead
|
||||
*/
|
||||
export type StartOptions = FreshConfig;
|
||||
|
||||
/**
|
||||
* @deprecated Use {@linkcode FreshConfig} interface instead.
|
||||
*/
|
||||
export type FreshOptions = FreshConfig;
|
||||
|
||||
/**
|
||||
* @deprecated Use {@linkcode FreshContext} interface instead
|
||||
*/
|
||||
export type HandlerContext<
|
||||
Data = unknown,
|
||||
State = Record<string, unknown>,
|
||||
NotFoundData = Data,
|
||||
> = FreshContext<State, Data, NotFoundData>;
|
||||
|
||||
/**
|
||||
* @deprecated Use {@linkcode FreshContext} interface instead
|
||||
*/
|
||||
// deno-lint-ignore no-explicit-any
|
||||
export type AppContext<T = any, S = Record<string, unknown>> = FreshContext<
|
||||
S,
|
||||
T
|
||||
>;
|
||||
|
||||
/**
|
||||
* @deprecated Use {@linkcode FreshContext} interface instead
|
||||
*/
|
||||
// deno-lint-ignore no-explicit-any
|
||||
export type LayoutContext<T = any, S = Record<string, unknown>> = FreshContext<
|
||||
S,
|
||||
T
|
||||
>;
|
||||
|
||||
/**
|
||||
* @deprecated Use {@linkcode FreshContext} interface instead
|
||||
*/
|
||||
export type UnknownHandlerContext<State = Record<string, unknown>> =
|
||||
FreshContext<State>;
|
||||
|
||||
/**
|
||||
* @deprecated Use {@linkcode FreshContext} interface instead
|
||||
*/
|
||||
export type ErrorHandlerContext<State = Record<string, unknown>> = FreshContext<
|
||||
State
|
||||
>;
|
||||
|
||||
/**
|
||||
* @deprecated Use {@linkcode FreshContext} interface instead
|
||||
*/
|
||||
export type MiddlewareHandlerContext<State = Record<string, unknown>> =
|
||||
FreshContext<State>;
|
||||
|
||||
/**
|
||||
* @deprecated Use {@linkcode PageProps} instead
|
||||
*/
|
||||
// deno-lint-ignore no-explicit-any
|
||||
export type LayoutProps<T = any, S = Record<string, unknown>> = PageProps<T, S>;
|
||||
|
||||
/**
|
||||
* @deprecated Use {@linkcode PageProps} instead
|
||||
*/
|
||||
// deno-lint-ignore no-explicit-any
|
||||
export type UnknownPageProps<T = any, S = Record<string, unknown>> = PageProps<
|
||||
T,
|
||||
S
|
||||
>;
|
||||
|
||||
/**
|
||||
* @deprecated Use {@linkcode PageProps} instead
|
||||
*/
|
||||
// deno-lint-ignore no-explicit-any
|
||||
export type AppProps<T = any, S = Record<string, unknown>> = PageProps<T, S>;
|
||||
|
||||
/**
|
||||
* @deprecated Use {@linkcode PageProps} instead
|
||||
*/
|
||||
export type ErrorPageProps = PageProps;
|
||||
Reference in New Issue
Block a user