feat: add build.outDir option (#1797)
This commit is contained in:
+17
-19
@@ -1,28 +1,20 @@
|
||||
import { ServerContext } from "../server/context.ts";
|
||||
import { FreshOptions, Manifest } from "../server/mod.ts";
|
||||
import { dirname, fromFileUrl, join, toFileUrl } from "../server/deps.ts";
|
||||
import { fs } from "./deps.ts";
|
||||
import { getServerContext } from "../server/context.ts";
|
||||
import { join } from "../server/deps.ts";
|
||||
import { colors, fs } from "./deps.ts";
|
||||
import { BuildSnapshotJson } from "../build/mod.ts";
|
||||
import { BUILD_ID } from "$fresh/src/server/build_id.ts";
|
||||
import { BUILD_ID } from "../server/build_id.ts";
|
||||
import { InternalFreshOptions } from "../server/types.ts";
|
||||
|
||||
export async function build(
|
||||
manifestPath: string,
|
||||
opts: FreshOptions,
|
||||
config: InternalFreshOptions,
|
||||
) {
|
||||
const manifest = (await import(toFileUrl(manifestPath).href))
|
||||
.default as Manifest;
|
||||
|
||||
const outDir = join(dirname(fromFileUrl(manifest.baseUrl)), "_fresh");
|
||||
|
||||
// Ensure that build dir is empty
|
||||
await fs.emptyDir(outDir);
|
||||
await fs.emptyDir(config.build.outDir);
|
||||
|
||||
const ctx = await ServerContext.fromManifest(manifest, {
|
||||
...opts,
|
||||
skipSnapshot: true,
|
||||
});
|
||||
await Promise.all(config.plugins.map((plugin) => plugin.buildStart?.()));
|
||||
|
||||
// Bundle assets
|
||||
const ctx = await getServerContext(config);
|
||||
const snapshot = await ctx.buildSnapshot();
|
||||
|
||||
// Write output files to disk
|
||||
@@ -30,7 +22,7 @@ export async function build(
|
||||
const data = await snapshot.read(fileName);
|
||||
if (data === null) return;
|
||||
|
||||
return Deno.writeFile(join(outDir, fileName), data);
|
||||
return Deno.writeFile(join(config.build.outDir, fileName), data);
|
||||
}));
|
||||
|
||||
// Write dependency snapshot file to disk
|
||||
@@ -43,6 +35,12 @@ export async function build(
|
||||
jsonSnapshot.files[filePath] = dependencies;
|
||||
}
|
||||
|
||||
const snapshotPath = join(outDir, "snapshot.json");
|
||||
const snapshotPath = join(config.build.outDir, "snapshot.json");
|
||||
await Deno.writeTextFile(snapshotPath, JSON.stringify(jsonSnapshot, null, 2));
|
||||
|
||||
console.log(
|
||||
`Assets written to: ${colors.green(config.build.outDir)}`,
|
||||
);
|
||||
|
||||
await Promise.all(config.plugins.map((plugin) => plugin.buildEnd?.()));
|
||||
}
|
||||
|
||||
+19
-24
@@ -1,13 +1,11 @@
|
||||
import { updateCheck } from "./update_check.ts";
|
||||
import { DAY, dirname, fromFileUrl, fs, join, toFileUrl } from "./deps.ts";
|
||||
import {
|
||||
FreshOptions,
|
||||
Manifest as ServerManifest,
|
||||
ServerContext,
|
||||
} from "../server/mod.ts";
|
||||
import { DAY, dirname, fromFileUrl, join, toFileUrl } from "./deps.ts";
|
||||
import { FreshOptions, Manifest as ServerManifest } from "../server/mod.ts";
|
||||
import { build } from "./build.ts";
|
||||
import { collect, ensureMinDenoVersion, generate, Manifest } from "./mod.ts";
|
||||
import { startFromContext } from "../server/boot.ts";
|
||||
import { getFreshConfigWithDefaults } from "../server/config.ts";
|
||||
import { getServerContext } from "$fresh/src/server/context.ts";
|
||||
|
||||
export async function dev(
|
||||
base: string,
|
||||
@@ -40,25 +38,22 @@ export async function dev(
|
||||
const manifest = (await import(toFileUrl(join(dir, "fresh.gen.ts")).href))
|
||||
.default as ServerManifest;
|
||||
|
||||
const outDir = join(dir, "_fresh");
|
||||
|
||||
const isBuild = Deno.args.includes("build");
|
||||
if (isBuild) {
|
||||
// Ensure that build dir is empty
|
||||
await fs.emptyDir(outDir);
|
||||
|
||||
options = options ?? {};
|
||||
const plugins = options.plugins ?? [];
|
||||
|
||||
await Promise.all(plugins.map((plugin) => plugin.buildStart?.()));
|
||||
await build(join(dir, "fresh.gen.ts"), options);
|
||||
await Promise.all(plugins.map((plugin) => plugin.buildEnd?.()));
|
||||
if (Deno.args.includes("build")) {
|
||||
const config = await getFreshConfigWithDefaults(
|
||||
manifest,
|
||||
options ?? {},
|
||||
);
|
||||
config.dev = false;
|
||||
config.loadSnapshot = false;
|
||||
await build(config);
|
||||
} else if (options) {
|
||||
const ctx = await ServerContext.fromManifest(manifest, {
|
||||
...options,
|
||||
skipSnapshot: true,
|
||||
dev: true,
|
||||
});
|
||||
const config = await getFreshConfigWithDefaults(
|
||||
manifest,
|
||||
options,
|
||||
);
|
||||
config.dev = true;
|
||||
config.loadSnapshot = false;
|
||||
const ctx = await getServerContext(config);
|
||||
await startFromContext(ctx, options);
|
||||
} else {
|
||||
// Legacy entry point: Back then `dev.ts` would call `main.ts` but
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
import { DEV_MODE } from "./constants.ts";
|
||||
import { dirname, fromFileUrl, isAbsolute, join, JSONC } from "./deps.ts";
|
||||
import { FromManifestOptions, Manifest } from "./mod.ts";
|
||||
import { DenoConfig, InternalFreshOptions } 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 getFreshConfigWithDefaults(
|
||||
manifest: Manifest,
|
||||
opts: FromManifestOptions,
|
||||
): Promise<InternalFreshOptions> {
|
||||
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 config: InternalFreshOptions = {
|
||||
loadSnapshot: typeof opts.skipSnapshot === "boolean"
|
||||
? !opts.skipSnapshot
|
||||
: false,
|
||||
dev: opts.dev ?? DEV_MODE,
|
||||
denoJsonPath,
|
||||
denoJson,
|
||||
manifest,
|
||||
build: {
|
||||
outDir: "",
|
||||
},
|
||||
plugins: opts.plugins ?? [],
|
||||
staticDir: "",
|
||||
render: opts.render,
|
||||
router: opts.router,
|
||||
};
|
||||
|
||||
config.build.outDir = opts.build?.outDir
|
||||
? parseFileOrUrl(opts.build.outDir, base)
|
||||
: join(base, "_fresh");
|
||||
|
||||
config.staticDir = opts.staticDir
|
||||
? parseFileOrUrl(opts.staticDir, base)
|
||||
: join(base, "static");
|
||||
|
||||
return config;
|
||||
}
|
||||
|
||||
function parseFileOrUrl(input: string, base: string) {
|
||||
if (input.startsWith("file://")) {
|
||||
return fromFileUrl(input);
|
||||
} else if (!isAbsolute(input)) {
|
||||
return join(base, input);
|
||||
}
|
||||
|
||||
return input;
|
||||
}
|
||||
+306
-353
@@ -1,10 +1,7 @@
|
||||
import {
|
||||
colors,
|
||||
dirname,
|
||||
extname,
|
||||
fromFileUrl,
|
||||
join,
|
||||
JSONC,
|
||||
Status,
|
||||
toFileUrl,
|
||||
typeByExtension,
|
||||
@@ -12,7 +9,7 @@ import {
|
||||
} from "./deps.ts";
|
||||
import { ComponentType, h } from "preact";
|
||||
import * as router from "./router.ts";
|
||||
import { DenoConfig, Manifest } from "./mod.ts";
|
||||
import { Manifest } from "./mod.ts";
|
||||
import {
|
||||
ALIVE_URL,
|
||||
JS_PREFIX,
|
||||
@@ -28,6 +25,7 @@ import {
|
||||
ErrorPageModule,
|
||||
FreshOptions,
|
||||
Handler,
|
||||
InternalFreshOptions,
|
||||
Island,
|
||||
LayoutModule,
|
||||
LayoutRoute,
|
||||
@@ -64,6 +62,7 @@ import {
|
||||
import { InternalRoute } from "./router.ts";
|
||||
import { setAllIslands } from "./rendering/preact_hooks.ts";
|
||||
import { getCodeFrame } from "./code_frame.ts";
|
||||
import { getFreshConfigWithDefaults } from "./config.ts";
|
||||
|
||||
const DEFAULT_CONN_INFO: ServeHandlerInfo = {
|
||||
localAddr: { transport: "tcp", hostname: "localhost", port: 8080 },
|
||||
@@ -72,12 +71,6 @@ const DEFAULT_CONN_INFO: ServeHandlerInfo = {
|
||||
|
||||
const ROOT_BASE_ROUTE = toBaseRoute("/");
|
||||
|
||||
function isObject(value: unknown) {
|
||||
return typeof value === "object" &&
|
||||
!Array.isArray(value) &&
|
||||
value !== null;
|
||||
}
|
||||
|
||||
interface StaticFile {
|
||||
/** The URL to the static file on disk. */
|
||||
localUrl: URL;
|
||||
@@ -96,6 +89,303 @@ export type FromManifestOptions = FreshOptions & {
|
||||
dev?: boolean;
|
||||
};
|
||||
|
||||
export async function getServerContext(opts: InternalFreshOptions) {
|
||||
const { manifest, denoJson: config, denoJsonPath: configPath } = opts;
|
||||
// Get the manifest' base URL.
|
||||
const baseUrl = new URL("./", manifest.baseUrl).href;
|
||||
|
||||
// Restore snapshot if available
|
||||
let snapshot: BuildSnapshot | null = null;
|
||||
if (opts.loadSnapshot) {
|
||||
const snapshotDirPath = opts.build.outDir;
|
||||
try {
|
||||
if ((await Deno.stat(snapshotDirPath)).isDirectory) {
|
||||
console.log(
|
||||
`Using snapshot found at ${colors.cyan(snapshotDirPath)}`,
|
||||
);
|
||||
|
||||
const snapshotPath = join(snapshotDirPath, "snapshot.json");
|
||||
const json = JSON.parse(
|
||||
await Deno.readTextFile(snapshotPath),
|
||||
) as BuildSnapshotJson;
|
||||
setBuildId(json.build_id);
|
||||
|
||||
const dependencies = new Map<string, string[]>(
|
||||
Object.entries(json.files),
|
||||
);
|
||||
|
||||
const files = new Map<string, string>();
|
||||
Object.keys(json.files).forEach((name) => {
|
||||
const filePath = join(snapshotDirPath, name);
|
||||
files.set(name, filePath);
|
||||
});
|
||||
|
||||
snapshot = new AotSnapshot(files, dependencies);
|
||||
}
|
||||
} catch (err) {
|
||||
if (!(err instanceof Deno.errors.NotFound)) {
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
config.compilerOptions ??= {};
|
||||
|
||||
let jsx: "react" | "react-jsx";
|
||||
switch (config.compilerOptions.jsx) {
|
||||
case "react":
|
||||
case undefined:
|
||||
jsx = "react";
|
||||
break;
|
||||
case "react-jsx":
|
||||
jsx = "react-jsx";
|
||||
break;
|
||||
default:
|
||||
throw new Error("Unknown jsx option: " + config.compilerOptions.jsx);
|
||||
}
|
||||
|
||||
const jsxConfig: JSXConfig = {
|
||||
jsx,
|
||||
jsxImportSource: config.compilerOptions.jsxImportSource,
|
||||
};
|
||||
|
||||
// Extract all routes, and prepare them into the `Page` structure.
|
||||
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),
|
||||
...(opts.plugins ? getMiddlewareRoutesFromPlugins(opts.plugins) : []),
|
||||
...(opts.plugins ? getRoutesFromPlugins(opts.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).substring("routes".length);
|
||||
const baseRoute = path.substring(1, path.length - extname(path).length);
|
||||
const name = baseRoute.replace("/", "-");
|
||||
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 } = 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 ??
|
||||
((req, ctx) => router.defaultErrorHandler(req, ctx, ctx.error)),
|
||||
csp: Boolean(config?.csp ?? false),
|
||||
appWrapper: !config?.skipAppWrapper,
|
||||
inheritLayouts: !config?.skipInheritedLayouts,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
|
||||
for (const [exportName, exportedFunction] of Object.entries(module)) {
|
||||
if (typeof exportedFunction !== "function") {
|
||||
continue;
|
||||
}
|
||||
const name = sanitizeIslandName(baseRoute);
|
||||
const id = `${name}_${exportName}`.toLowerCase();
|
||||
islands.push({
|
||||
id,
|
||||
name,
|
||||
url,
|
||||
component: exportedFunction,
|
||||
exportName,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const staticFiles: StaticFile[] = [];
|
||||
try {
|
||||
const staticDirUrl = toFileUrl(opts.staticDir);
|
||||
const entries = walk(opts.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 contentType = typeByExtension(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,
|
||||
size: stat.size,
|
||||
contentType,
|
||||
etag,
|
||||
};
|
||||
staticFiles.push(staticFile);
|
||||
}
|
||||
} catch (err) {
|
||||
if (err.cause instanceof Deno.errors.NotFound) {
|
||||
// Do nothing.
|
||||
} else {
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
if (opts.dev) {
|
||||
// Ensure that debugging hooks are set up for SSR rendering
|
||||
await import("preact/debug");
|
||||
}
|
||||
|
||||
return new ServerContext(
|
||||
routes,
|
||||
islands,
|
||||
staticFiles,
|
||||
opts.render ?? DEFAULT_RENDER_FN,
|
||||
middlewares,
|
||||
app,
|
||||
layouts,
|
||||
notFound,
|
||||
error,
|
||||
opts.plugins ?? [],
|
||||
configPath,
|
||||
jsxConfig,
|
||||
opts.dev,
|
||||
opts.router ?? DEFAULT_ROUTER_OPTIONS,
|
||||
snapshot,
|
||||
);
|
||||
}
|
||||
|
||||
export class ServerContext {
|
||||
#dev: boolean;
|
||||
#routes: Route[];
|
||||
@@ -156,324 +446,17 @@ export class ServerContext {
|
||||
manifest: Manifest,
|
||||
opts: FromManifestOptions,
|
||||
): Promise<ServerContext> {
|
||||
const dev = Deno.env.get("__FRSH_LEGACY_DEV") === "true" ||
|
||||
const isLegacyDev = Deno.env.get("__FRSH_LEGACY_DEV") === "true";
|
||||
const dev = isLegacyDev ||
|
||||
Boolean(opts.dev);
|
||||
setDevMode(dev);
|
||||
|
||||
// Get the manifest' base URL.
|
||||
const baseUrl = new URL("./", manifest.baseUrl).href;
|
||||
|
||||
const { config, path: configPath } = await readDenoConfig(
|
||||
fromFileUrl(baseUrl),
|
||||
);
|
||||
if (typeof config.importMap !== "string" && !isObject(config.imports)) {
|
||||
throw new Error(
|
||||
"deno.json must contain an 'importMap' or 'imports' property.",
|
||||
);
|
||||
if (isLegacyDev) {
|
||||
opts.skipSnapshot = true;
|
||||
}
|
||||
|
||||
// Restore snapshot if available
|
||||
let snapshot: BuildSnapshot | null = null;
|
||||
// Load from snapshot if not explicitly requested not to
|
||||
let loadFromSnapshot = !opts.skipSnapshot;
|
||||
// We still need to check for a legacy entry point :S
|
||||
if (Deno.env.has("__FRSH_LEGACY_DEV")) {
|
||||
loadFromSnapshot = false;
|
||||
}
|
||||
if (loadFromSnapshot) {
|
||||
const snapshotDirPath = join(
|
||||
dirname(fromFileUrl(manifest.baseUrl)),
|
||||
"_fresh",
|
||||
);
|
||||
try {
|
||||
if ((await Deno.stat(snapshotDirPath)).isDirectory) {
|
||||
console.log(
|
||||
`Using snapshot found at ${colors.cyan(snapshotDirPath)}`,
|
||||
);
|
||||
|
||||
const snapshotPath = join(snapshotDirPath, "snapshot.json");
|
||||
const json = JSON.parse(
|
||||
await Deno.readTextFile(snapshotPath),
|
||||
) as BuildSnapshotJson;
|
||||
setBuildId(json.build_id);
|
||||
|
||||
const dependencies = new Map<string, string[]>(
|
||||
Object.entries(json.files),
|
||||
);
|
||||
|
||||
const files = new Map<string, string>();
|
||||
Object.keys(json.files).forEach((name) => {
|
||||
const filePath = join(snapshotDirPath, name);
|
||||
files.set(name, filePath);
|
||||
});
|
||||
|
||||
snapshot = new AotSnapshot(files, dependencies);
|
||||
}
|
||||
} catch (err) {
|
||||
if (!(err instanceof Deno.errors.NotFound)) {
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
config.compilerOptions ??= {};
|
||||
|
||||
let jsx: "react" | "react-jsx";
|
||||
switch (config.compilerOptions.jsx) {
|
||||
case "react":
|
||||
case undefined:
|
||||
jsx = "react";
|
||||
break;
|
||||
case "react-jsx":
|
||||
jsx = "react-jsx";
|
||||
break;
|
||||
default:
|
||||
throw new Error("Unknown jsx option: " + config.compilerOptions.jsx);
|
||||
}
|
||||
|
||||
const jsxConfig: JSXConfig = {
|
||||
jsx,
|
||||
jsxImportSource: config.compilerOptions.jsxImportSource,
|
||||
};
|
||||
|
||||
// Extract all routes, and prepare them into the `Page` structure.
|
||||
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),
|
||||
...(opts.plugins ? getMiddlewareRoutesFromPlugins(opts.plugins) : []),
|
||||
...(opts.plugins ? getRoutesFromPlugins(opts.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).substring("routes".length);
|
||||
const baseRoute = path.substring(1, path.length - extname(path).length);
|
||||
const name = baseRoute.replace("/", "-");
|
||||
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 } = 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 ??
|
||||
((req, ctx) => router.defaultErrorHandler(req, ctx, ctx.error)),
|
||||
csp: Boolean(config?.csp ?? false),
|
||||
appWrapper: !config?.skipAppWrapper,
|
||||
inheritLayouts: !config?.skipInheritedLayouts,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
|
||||
for (const [exportName, exportedFunction] of Object.entries(module)) {
|
||||
if (typeof exportedFunction !== "function") {
|
||||
continue;
|
||||
}
|
||||
const name = sanitizeIslandName(baseRoute);
|
||||
const id = `${name}_${exportName}`.toLowerCase();
|
||||
islands.push({
|
||||
id,
|
||||
name,
|
||||
url,
|
||||
component: exportedFunction,
|
||||
exportName,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const staticFiles: StaticFile[] = [];
|
||||
try {
|
||||
const staticFolder = new URL(
|
||||
opts.staticDir ?? "./static",
|
||||
manifest.baseUrl,
|
||||
);
|
||||
const entries = walk(fromFileUrl(staticFolder), {
|
||||
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(staticFolder.href.length);
|
||||
const stat = await Deno.stat(localUrl);
|
||||
const contentType = typeByExtension(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,
|
||||
size: stat.size,
|
||||
contentType,
|
||||
etag,
|
||||
};
|
||||
staticFiles.push(staticFile);
|
||||
}
|
||||
} catch (err) {
|
||||
if (err.cause instanceof Deno.errors.NotFound) {
|
||||
// Do nothing.
|
||||
} else {
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
if (dev) {
|
||||
// Ensure that debugging hooks are set up for SSR rendering
|
||||
await import("preact/debug");
|
||||
}
|
||||
|
||||
return new ServerContext(
|
||||
routes,
|
||||
islands,
|
||||
staticFiles,
|
||||
opts.render ?? DEFAULT_RENDER_FN,
|
||||
middlewares,
|
||||
app,
|
||||
layouts,
|
||||
notFound,
|
||||
error,
|
||||
opts.plugins ?? [],
|
||||
configPath,
|
||||
jsxConfig,
|
||||
dev,
|
||||
opts.router ?? DEFAULT_ROUTER_OPTIONS,
|
||||
snapshot,
|
||||
);
|
||||
const config = await getFreshConfigWithDefaults(manifest, opts);
|
||||
return getServerContext(config);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1352,36 +1335,6 @@ function collectEntrypoints(
|
||||
return entryPoints;
|
||||
}
|
||||
|
||||
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 formatMiddlewarePath(path: string): string {
|
||||
const prefix = !path.startsWith("/") ? "/" : "";
|
||||
const suffix = !path.endsWith("/") ? "/" : "";
|
||||
|
||||
@@ -3,6 +3,7 @@ export {
|
||||
dirname,
|
||||
extname,
|
||||
fromFileUrl,
|
||||
isAbsolute,
|
||||
join,
|
||||
toFileUrl,
|
||||
} from "https://deno.land/std@0.193.0/path/mod.ts";
|
||||
|
||||
+6
-19
@@ -24,6 +24,7 @@ export {
|
||||
export type {
|
||||
AppContext,
|
||||
AppProps,
|
||||
DenoConfig,
|
||||
ErrorHandler,
|
||||
ErrorHandlerContext,
|
||||
ErrorPageProps,
|
||||
@@ -81,24 +82,6 @@ export interface Manifest {
|
||||
baseUrl: string;
|
||||
}
|
||||
|
||||
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;
|
||||
};
|
||||
}
|
||||
|
||||
export { ServerContext };
|
||||
|
||||
export async function createHandler(
|
||||
@@ -112,6 +95,10 @@ export async function createHandler(
|
||||
}
|
||||
|
||||
export async function start(routes: Manifest, opts: StartOptions = {}) {
|
||||
const ctx = await ServerContext.fromManifest(routes, opts);
|
||||
const ctx = await ServerContext.fromManifest(routes, {
|
||||
...opts,
|
||||
skipSnapshot: false,
|
||||
dev: false,
|
||||
});
|
||||
await startFromContext(ctx, opts);
|
||||
}
|
||||
|
||||
@@ -1,18 +1,59 @@
|
||||
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 type StartOptions = Partial<Deno.ServeTlsOptions> & FreshOptions;
|
||||
|
||||
export interface FreshOptions {
|
||||
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;
|
||||
};
|
||||
render?: RenderFunction;
|
||||
plugins?: Plugin[];
|
||||
staticDir?: string;
|
||||
router?: RouterOptions;
|
||||
}
|
||||
|
||||
export interface InternalFreshOptions {
|
||||
dev: boolean;
|
||||
loadSnapshot: boolean;
|
||||
denoJsonPath: string;
|
||||
denoJson: DenoConfig;
|
||||
manifest: Manifest;
|
||||
build: {
|
||||
outDir: string;
|
||||
};
|
||||
render?: RenderFunction;
|
||||
plugins: Plugin[];
|
||||
staticDir: string;
|
||||
router?: RouterOptions;
|
||||
}
|
||||
|
||||
export interface RouterOptions {
|
||||
/**
|
||||
* Controls whether Fresh will append a trailing slash to the URL.
|
||||
|
||||
Reference in New Issue
Block a user