@@ -1,55 +0,0 @@
|
||||
import { getServerContext } from "../server/context.ts";
|
||||
import { join } from "../server/deps.ts";
|
||||
import { colors, emptyDir } from "./deps.ts";
|
||||
import { BuildSnapshotJson } from "../build/mod.ts";
|
||||
import { BUILD_ID } from "../server/build_id.ts";
|
||||
import { InternalFreshState } from "../server/types.ts";
|
||||
|
||||
export async function build(
|
||||
state: InternalFreshState,
|
||||
) {
|
||||
const outDir = state.config.build.outDir;
|
||||
const plugins = state.config.plugins;
|
||||
|
||||
// Ensure that build dir is empty
|
||||
await emptyDir(outDir);
|
||||
|
||||
// Create a directory for static assets produced during the build
|
||||
await Deno.mkdir(join(outDir, "static"));
|
||||
|
||||
await Promise.all(
|
||||
plugins.map((plugin) => plugin.configResolved?.(state.config)),
|
||||
);
|
||||
await Promise.all(plugins.map((plugin) => plugin.buildStart?.(state.config)));
|
||||
|
||||
// Bundle assets
|
||||
const ctx = await getServerContext(state);
|
||||
const snapshot = await ctx.buildSnapshot();
|
||||
|
||||
// Write output files to disk
|
||||
await Promise.all(snapshot.paths.map(async (fileName) => {
|
||||
const data = await snapshot.read(fileName);
|
||||
if (data === null) return;
|
||||
|
||||
return Deno.writeFile(join(outDir, fileName), data);
|
||||
}));
|
||||
|
||||
// Write dependency snapshot file to disk
|
||||
const jsonSnapshot: BuildSnapshotJson = {
|
||||
build_id: BUILD_ID,
|
||||
files: {},
|
||||
};
|
||||
for (const filePath of snapshot.paths) {
|
||||
const dependencies = snapshot.dependencies(filePath);
|
||||
jsonSnapshot.files[filePath] = dependencies;
|
||||
}
|
||||
|
||||
const snapshotPath = join(outDir, "snapshot.json");
|
||||
await Deno.writeTextFile(snapshotPath, JSON.stringify(jsonSnapshot, null, 2));
|
||||
|
||||
console.log(
|
||||
`Assets written to: ${colors.green(outDir)}`,
|
||||
);
|
||||
|
||||
await Promise.all(plugins.map((plugin) => plugin.buildEnd?.()));
|
||||
}
|
||||
@@ -0,0 +1,250 @@
|
||||
import {
|
||||
App,
|
||||
getBuildCache,
|
||||
getIslandRegistry,
|
||||
type ListenOptions,
|
||||
setBuildCache,
|
||||
} from "../app.ts";
|
||||
import { fsAdapter } from "../fs.ts";
|
||||
import * as path from "@std/path";
|
||||
import * as colors from "@std/fmt/colors";
|
||||
import { bundleJs } from "./esbuild.ts";
|
||||
import * as JSONC from "@std/jsonc";
|
||||
import { liveReload } from "./middlewares/live_reload.ts";
|
||||
import {
|
||||
cssAssetHash,
|
||||
FreshFileTransformer,
|
||||
type OnTransformOptions,
|
||||
} from "./file_transformer.ts";
|
||||
import type { TransformFn } from "./file_transformer.ts";
|
||||
import { DiskBuildCache, MemoryBuildCache } from "./dev_build_cache.ts";
|
||||
import type { Island } from "../context.ts";
|
||||
import { BUILD_ID } from "../runtime/build_id.ts";
|
||||
import { updateCheck } from "./update_check.ts";
|
||||
import { DAY } from "@std/datetime";
|
||||
import { devErrorOverlay } from "./middlewares/error_overlay/middleware.tsx";
|
||||
|
||||
export interface BuildOptions {
|
||||
/**
|
||||
* 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[];
|
||||
}
|
||||
|
||||
export interface FreshBuilder {
|
||||
onTransformStaticFile(
|
||||
options: OnTransformOptions,
|
||||
callback: TransformFn,
|
||||
): void;
|
||||
build<T>(app: App<T>, options?: BuildOptions): Promise<void>;
|
||||
listen<T>(app: App<T>, options?: ListenOptions & BuildOptions): Promise<void>;
|
||||
}
|
||||
|
||||
export class Builder implements FreshBuilder {
|
||||
#transformer = new FreshFileTransformer(fsAdapter);
|
||||
#addedInternalTransforms = false;
|
||||
#options: { target: string | string[] };
|
||||
|
||||
constructor(options: BuildOptions = {}) {
|
||||
this.#options = {
|
||||
target: options.target ?? ["chrome99", "firefox99", "safari15"],
|
||||
};
|
||||
}
|
||||
|
||||
onTransformStaticFile(
|
||||
options: OnTransformOptions,
|
||||
callback: TransformFn,
|
||||
): void {
|
||||
this.#transformer.onTransform(options, callback);
|
||||
}
|
||||
|
||||
async listen<T>(app: App<T>, options: ListenOptions = {}): Promise<void> {
|
||||
// Run update check in background
|
||||
updateCheck(DAY).catch(() => {});
|
||||
|
||||
const devApp = new App<T>(app.config)
|
||||
.use(liveReload())
|
||||
.use(devErrorOverlay())
|
||||
.mountApp("*", app);
|
||||
|
||||
setBuildCache(
|
||||
devApp,
|
||||
new MemoryBuildCache(
|
||||
devApp.config,
|
||||
BUILD_ID,
|
||||
this.#transformer,
|
||||
this.#options.target,
|
||||
),
|
||||
);
|
||||
|
||||
await Promise.all([
|
||||
devApp.listen(options),
|
||||
this.#build(devApp, true),
|
||||
]);
|
||||
return;
|
||||
}
|
||||
|
||||
async build<T>(app: App<T>): Promise<void> {
|
||||
setBuildCache(
|
||||
app,
|
||||
new DiskBuildCache(
|
||||
app.config,
|
||||
BUILD_ID,
|
||||
this.#transformer,
|
||||
this.#options.target,
|
||||
),
|
||||
);
|
||||
return await this.#build(app, false);
|
||||
}
|
||||
|
||||
async #build<T>(app: App<T>, dev: boolean): Promise<void> {
|
||||
const { build } = app.config;
|
||||
const staticOutDir = path.join(build.outDir, "static");
|
||||
|
||||
if (!this.#addedInternalTransforms) {
|
||||
this.#addedInternalTransforms = true;
|
||||
cssAssetHash(this.#transformer);
|
||||
}
|
||||
|
||||
const target = this.#options.target;
|
||||
|
||||
try {
|
||||
await Deno.remove(staticOutDir);
|
||||
} catch {
|
||||
// Ignore
|
||||
}
|
||||
|
||||
const buildCache = getBuildCache(app)! as MemoryBuildCache | DiskBuildCache;
|
||||
|
||||
const entryPoints: Record<string, string> = {
|
||||
"fresh-runtime": dev ? "@fresh/core/client-dev" : "@fresh/core/client",
|
||||
};
|
||||
const seenEntries = new Map<string, Island>();
|
||||
const mapIslandToEntry = new Map<Island, string>();
|
||||
const islandRegistry = getIslandRegistry(app);
|
||||
for (const island of islandRegistry.values()) {
|
||||
const filePath = island.file instanceof URL
|
||||
? island.file.href
|
||||
: island.file;
|
||||
|
||||
const seen = seenEntries.get(filePath);
|
||||
if (seen !== undefined) {
|
||||
mapIslandToEntry.set(island, seen.name);
|
||||
} else {
|
||||
entryPoints[island.name] = filePath;
|
||||
seenEntries.set(filePath, island);
|
||||
mapIslandToEntry.set(island, island.name);
|
||||
}
|
||||
}
|
||||
|
||||
const denoJson = await readDenoConfig(app.config.root);
|
||||
|
||||
const jsxImportSource = denoJson.config.compilerOptions?.jsxImportSource;
|
||||
if (jsxImportSource === undefined) {
|
||||
throw new Error(
|
||||
`Option compilerOptions > jsxImportSource not set in: ${denoJson.filePath}`,
|
||||
);
|
||||
}
|
||||
|
||||
// Check precompile option
|
||||
if (denoJson.config.compilerOptions?.jsx === "precompile") {
|
||||
const expected = ["a", "img", "source", "body", "html", "head"];
|
||||
const skipped = denoJson.config.compilerOptions.jsxPrecompileSkipElements;
|
||||
if (!skipped || expected.some((name) => !skipped.includes(name))) {
|
||||
throw new Error(
|
||||
`Expected option compilerOptions > jsxPrecompileSkipElements to contain ${
|
||||
expected.map((name) => `"${name}"`).join(", ")
|
||||
}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const output = await bundleJs({
|
||||
cwd: app.config.root,
|
||||
outDir: staticOutDir,
|
||||
dev: dev ?? false,
|
||||
target,
|
||||
buildId: BUILD_ID,
|
||||
entryPoints,
|
||||
jsxImportSource,
|
||||
denoJsonPath: denoJson.filePath,
|
||||
});
|
||||
|
||||
for (let i = 0; i < output.files.length; i++) {
|
||||
const file = output.files[i];
|
||||
const pathname = `/${file.path}`;
|
||||
await buildCache.addProcessedFile(pathname, file.contents, file.hash);
|
||||
}
|
||||
|
||||
// Go through same entry islands
|
||||
for (const [island, entry] of mapIslandToEntry.entries()) {
|
||||
const chunk = output.entryToChunk.get(entry);
|
||||
if (chunk === undefined) {
|
||||
throw new Error(
|
||||
`Missing chunk for ${island.file}#${island.exportName}`,
|
||||
);
|
||||
}
|
||||
buildCache.islands.set(island.name, `/${chunk}`);
|
||||
}
|
||||
|
||||
await buildCache.flush();
|
||||
|
||||
if (!dev) {
|
||||
console.log(
|
||||
`Assets written to: ${colors.cyan(build.outDir)}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
jsxPrecompileSkipElements?: string[];
|
||||
};
|
||||
}
|
||||
|
||||
export async function readDenoConfig(
|
||||
directory: string,
|
||||
): Promise<{ config: DenoConfig; filePath: string }> {
|
||||
let dir = directory;
|
||||
while (true) {
|
||||
for (const name of ["deno.json", "deno.jsonc"]) {
|
||||
const filePath = path.join(dir, name);
|
||||
try {
|
||||
const file = await Deno.readTextFile(filePath);
|
||||
if (name.endsWith(".jsonc")) {
|
||||
return { config: JSONC.parse(file) as DenoConfig, filePath };
|
||||
} else {
|
||||
return { config: JSON.parse(file), filePath };
|
||||
}
|
||||
} catch (err) {
|
||||
if (!(err instanceof Deno.errors.NotFound)) {
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
}
|
||||
const parent = path.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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
import { expect } from "@std/expect";
|
||||
import * as path from "@std/path";
|
||||
import { Builder } from "./builder.ts";
|
||||
import { App } from "../app.ts";
|
||||
|
||||
Deno.test("Builder - chain onTransformStaticFile", async () => {
|
||||
const logs: string[] = [];
|
||||
const builder = new Builder();
|
||||
builder.onTransformStaticFile(
|
||||
{ pluginName: "A", filter: /\.css$/ },
|
||||
() => {
|
||||
logs.push("A");
|
||||
},
|
||||
);
|
||||
builder.onTransformStaticFile(
|
||||
{ pluginName: "B", filter: /\.css$/ },
|
||||
() => {
|
||||
logs.push("B");
|
||||
},
|
||||
);
|
||||
builder.onTransformStaticFile(
|
||||
{ pluginName: "C", filter: /\.css$/ },
|
||||
() => {
|
||||
logs.push("C");
|
||||
},
|
||||
);
|
||||
|
||||
const tmp = await Deno.makeTempDir();
|
||||
await Deno.writeTextFile(path.join(tmp, "foo.css"), "body { color: red; }");
|
||||
const app = new App({
|
||||
staticDir: tmp,
|
||||
build: {
|
||||
outDir: path.join(tmp, "dist"),
|
||||
},
|
||||
});
|
||||
await builder.build(app);
|
||||
|
||||
expect(logs).toEqual(["A", "B", "C"]);
|
||||
});
|
||||
|
||||
Deno.test({
|
||||
name: "Builder - hashes CSS urls by default",
|
||||
fn: async () => {
|
||||
const builder = new Builder();
|
||||
const tmp = await Deno.makeTempDir();
|
||||
await Deno.writeTextFile(
|
||||
path.join(tmp, "foo.css"),
|
||||
"body { background: url('/foo.jpg'); }",
|
||||
);
|
||||
const app = new App({
|
||||
staticDir: tmp,
|
||||
build: {
|
||||
outDir: path.join(tmp, "dist"),
|
||||
},
|
||||
});
|
||||
await builder.build(app);
|
||||
|
||||
const css = await Deno.readTextFile(
|
||||
path.join(tmp, "dist", "static", "foo.css"),
|
||||
);
|
||||
expect(css).toContain('body { background: url("/foo.jpg?__frsh_c=');
|
||||
},
|
||||
sanitizeOps: false,
|
||||
sanitizeResources: false,
|
||||
});
|
||||
@@ -1,24 +0,0 @@
|
||||
import { join, toFileUrl } from "./deps.ts";
|
||||
import { manifest } from "./mod.ts";
|
||||
import { type FreshConfig } from "../server/mod.ts";
|
||||
|
||||
const args = Deno.args;
|
||||
|
||||
switch (args[0]) {
|
||||
case "manifest": {
|
||||
if (args[1]) {
|
||||
const CONFIG_TS_PATH = join(args[1], "fresh.config.ts");
|
||||
const url = toFileUrl(CONFIG_TS_PATH).toString();
|
||||
const config: FreshConfig = (await import(url)).default;
|
||||
await manifest(args[1], config?.router?.ignoreFilePattern);
|
||||
} else {
|
||||
console.error("Missing input for manifest command");
|
||||
Deno.exit(1);
|
||||
}
|
||||
break;
|
||||
}
|
||||
default: {
|
||||
console.error("Invalid command");
|
||||
Deno.exit(1);
|
||||
}
|
||||
}
|
||||
@@ -1,32 +0,0 @@
|
||||
// std
|
||||
export {
|
||||
basename,
|
||||
dirname,
|
||||
extname,
|
||||
fromFileUrl,
|
||||
join,
|
||||
relative,
|
||||
resolve,
|
||||
SEPARATOR,
|
||||
toFileUrl,
|
||||
} from "https://deno.land/std@0.216.0/path/mod.ts";
|
||||
export { normalize } from "https://deno.land/std@0.216.0/path/posix/mod.ts";
|
||||
export { DAY, WEEK } from "https://deno.land/std@0.216.0/datetime/constants.ts";
|
||||
export * as colors from "https://deno.land/std@0.216.0/fmt/colors.ts";
|
||||
export {
|
||||
walk,
|
||||
type WalkEntry,
|
||||
WalkError,
|
||||
} from "https://deno.land/std@0.216.0/fs/walk.ts";
|
||||
export { parse } from "https://deno.land/std@0.216.0/flags/mod.ts";
|
||||
export {
|
||||
greaterOrEqual,
|
||||
lessThan,
|
||||
parse as semverParse,
|
||||
} from "https://deno.land/std@0.216.0/semver/mod.ts";
|
||||
export { emptyDir, existsSync } from "https://deno.land/std@0.216.0/fs/mod.ts";
|
||||
export * as JSONC from "https://deno.land/std@0.216.0/jsonc/mod.ts";
|
||||
export { assertEquals } from "https://deno.land/std@0.216.0/assert/mod.ts";
|
||||
|
||||
// ts-morph
|
||||
export { Node, Project } from "https://deno.land/x/ts_morph@21.0.1/mod.ts";
|
||||
@@ -0,0 +1,292 @@
|
||||
import type { BuildCache, StaticFile } from "../build_cache.ts";
|
||||
import * as path from "@std/path";
|
||||
import type { ResolvedFreshConfig } from "../config.ts";
|
||||
import type { BuildSnapshot } from "../build_cache.ts";
|
||||
import { encodeHex } from "@std/encoding/hex";
|
||||
import { crypto } from "@std/crypto";
|
||||
import { fsAdapter } from "../fs.ts";
|
||||
import type { FreshFileTransformer } from "./file_transformer.ts";
|
||||
import { assertInDir } from "../utils.ts";
|
||||
|
||||
export interface MemoryFile {
|
||||
hash: string | null;
|
||||
content: Uint8Array;
|
||||
}
|
||||
|
||||
export interface DevBuildCache extends BuildCache {
|
||||
islands: Map<string, string>;
|
||||
|
||||
addUnprocessedFile(pathname: string): void;
|
||||
|
||||
addProcessedFile(
|
||||
pathname: string,
|
||||
content: Uint8Array,
|
||||
hash: string | null,
|
||||
): Promise<void>;
|
||||
|
||||
flush(): Promise<void>;
|
||||
}
|
||||
|
||||
export class MemoryBuildCache implements DevBuildCache {
|
||||
hasSnapshot = true;
|
||||
islands = new Map<string, string>();
|
||||
#processedFiles = new Map<string, MemoryFile>();
|
||||
#unprocessedFiles = new Map<string, string>();
|
||||
#ready = Promise.withResolvers<void>();
|
||||
|
||||
constructor(
|
||||
public config: ResolvedFreshConfig,
|
||||
public buildId: string,
|
||||
public transformer: FreshFileTransformer,
|
||||
public target: string | string[],
|
||||
) {
|
||||
}
|
||||
|
||||
async readFile(pathname: string): Promise<StaticFile | null> {
|
||||
await this.#ready.promise;
|
||||
const processed = this.#processedFiles.get(pathname);
|
||||
if (processed !== undefined) {
|
||||
return {
|
||||
hash: processed.hash,
|
||||
readable: processed.content,
|
||||
size: processed.content.byteLength,
|
||||
};
|
||||
}
|
||||
|
||||
const unprocessed = this.#unprocessedFiles.get(pathname);
|
||||
if (unprocessed !== undefined) {
|
||||
try {
|
||||
const [stat, file] = await Promise.all([
|
||||
Deno.stat(unprocessed),
|
||||
Deno.open(unprocessed, { read: true }),
|
||||
]);
|
||||
|
||||
return {
|
||||
hash: null,
|
||||
size: stat.size,
|
||||
readable: file.readable,
|
||||
};
|
||||
} catch (_err) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
let entry = pathname.startsWith("/") ? pathname.slice(1) : pathname;
|
||||
entry = path.join(this.config.staticDir, entry);
|
||||
const relative = path.relative(this.config.staticDir, entry);
|
||||
if (relative.startsWith(".")) {
|
||||
throw new Error(
|
||||
`Processed file resolved outside of static dir ${entry}`,
|
||||
);
|
||||
}
|
||||
|
||||
// Might be a file that we still need to process
|
||||
const transformed = await this.transformer.process(
|
||||
entry,
|
||||
"development",
|
||||
this.target,
|
||||
);
|
||||
|
||||
if (transformed !== null) {
|
||||
for (let i = 0; i < transformed.length; i++) {
|
||||
const file = transformed[i];
|
||||
const relative = path.relative(this.config.staticDir, file.path);
|
||||
if (relative.startsWith(".")) {
|
||||
throw new Error(
|
||||
`Processed file resolved outside of static dir ${file.path}`,
|
||||
);
|
||||
}
|
||||
const pathname = `/${relative}`;
|
||||
|
||||
this.addProcessedFile(pathname, file.content, null);
|
||||
}
|
||||
if (this.#processedFiles.has(pathname)) {
|
||||
return this.readFile(pathname);
|
||||
}
|
||||
} else {
|
||||
try {
|
||||
const filePath = path.join(this.config.staticDir, pathname);
|
||||
const relative = path.relative(this.config.staticDir, filePath);
|
||||
if (!relative.startsWith(".") && (await Deno.stat(filePath)).isFile) {
|
||||
this.addUnprocessedFile(pathname);
|
||||
return this.readFile(pathname);
|
||||
}
|
||||
} catch (err) {
|
||||
if (!(err instanceof Deno.errors.NotFound)) {
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
getIslandChunkName(islandName: string): string | null {
|
||||
return this.islands.get(islandName) ?? null;
|
||||
}
|
||||
|
||||
addUnprocessedFile(pathname: string): void {
|
||||
this.#unprocessedFiles.set(
|
||||
pathname,
|
||||
path.join(this.config.staticDir, pathname),
|
||||
);
|
||||
}
|
||||
|
||||
// deno-lint-ignore require-await
|
||||
async addProcessedFile(
|
||||
pathname: string,
|
||||
content: Uint8Array,
|
||||
hash: string | null,
|
||||
): Promise<void> {
|
||||
this.#processedFiles.set(pathname, { content, hash });
|
||||
}
|
||||
|
||||
// deno-lint-ignore require-await
|
||||
async flush(): Promise<void> {
|
||||
this.#ready.resolve();
|
||||
}
|
||||
}
|
||||
|
||||
// await fsAdapter.mkdirp(staticOutDir);
|
||||
export class DiskBuildCache implements DevBuildCache {
|
||||
hasSnapshot = true;
|
||||
islands = new Map<string, string>();
|
||||
#processedFiles = new Map<string, string | null>();
|
||||
#unprocessedFiles = new Map<string, string>();
|
||||
#transformer: FreshFileTransformer;
|
||||
#target: string | string[];
|
||||
|
||||
constructor(
|
||||
public config: ResolvedFreshConfig,
|
||||
public buildId: string,
|
||||
transformer: FreshFileTransformer,
|
||||
target: string | string[],
|
||||
) {
|
||||
this.#transformer = transformer;
|
||||
this.#target = target;
|
||||
}
|
||||
|
||||
getIslandChunkName(islandName: string): string | null {
|
||||
return this.islands.get(islandName) ?? null;
|
||||
}
|
||||
|
||||
addUnprocessedFile(pathname: string): void {
|
||||
this.#unprocessedFiles.set(
|
||||
pathname,
|
||||
path.join(this.config.staticDir, pathname),
|
||||
);
|
||||
}
|
||||
|
||||
async addProcessedFile(
|
||||
pathname: string,
|
||||
content: Uint8Array,
|
||||
hash: string | null,
|
||||
) {
|
||||
this.#processedFiles.set(pathname, hash);
|
||||
|
||||
const outDir = pathname === "/metafile.json"
|
||||
? this.config.build.outDir
|
||||
: path.join(this.config.build.outDir, "static");
|
||||
const filePath = path.join(outDir, pathname);
|
||||
assertInDir(filePath, outDir);
|
||||
|
||||
await fsAdapter.mkdirp(path.dirname(filePath));
|
||||
await Deno.writeFile(filePath, content);
|
||||
}
|
||||
|
||||
// deno-lint-ignore require-await
|
||||
async readFile(_pathname: string): Promise<StaticFile | null> {
|
||||
throw new Error("Not implemented in build mode");
|
||||
}
|
||||
|
||||
async flush(): Promise<void> {
|
||||
const staticDir = this.config.staticDir;
|
||||
|
||||
if (await fsAdapter.isDirectory(staticDir)) {
|
||||
const entries = fsAdapter.walk(staticDir, {
|
||||
includeDirs: false,
|
||||
includeFiles: true,
|
||||
followSymlinks: false,
|
||||
// Skip any folder or file starting with a "."
|
||||
skip: [/\/\.[^/]+(\/|$)/],
|
||||
});
|
||||
|
||||
for await (const entry of entries) {
|
||||
const result = await this.#transformer.process(
|
||||
entry.path,
|
||||
"production",
|
||||
this.#target,
|
||||
);
|
||||
|
||||
if (result !== null) {
|
||||
for (let i = 0; i < result.length; i++) {
|
||||
const file = result[i];
|
||||
assertInDir(file.path, staticDir);
|
||||
const pathname = `/${path.relative(staticDir, file.path)}`;
|
||||
await this.addProcessedFile(pathname, file.content, null);
|
||||
}
|
||||
} else {
|
||||
const relative = path.relative(staticDir, entry.path);
|
||||
const pathname = `/${relative}`;
|
||||
this.addUnprocessedFile(pathname);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const snapshot: BuildSnapshot = {
|
||||
version: 1,
|
||||
buildId: this.buildId,
|
||||
islands: {},
|
||||
staticFiles: {},
|
||||
};
|
||||
|
||||
for (const [name, chunk] of this.islands.entries()) {
|
||||
snapshot.islands[name] = chunk;
|
||||
}
|
||||
|
||||
for (const [name, filePath] of this.#unprocessedFiles.entries()) {
|
||||
const file = await Deno.open(filePath);
|
||||
const hash = await hashContent(file.readable);
|
||||
|
||||
snapshot.staticFiles[name] = {
|
||||
hash,
|
||||
generated: false,
|
||||
};
|
||||
}
|
||||
|
||||
for (const [name, maybeHash] of this.#processedFiles.entries()) {
|
||||
let hash = maybeHash;
|
||||
|
||||
// Ignore esbuild meta file. It's not intended for serving
|
||||
if (name === "/metafile.json") {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (maybeHash === null) {
|
||||
const filePath = path.join(this.config.build.outDir, "static", name);
|
||||
const file = await Deno.open(filePath);
|
||||
hash = await hashContent(file.readable);
|
||||
}
|
||||
|
||||
snapshot.staticFiles[name] = {
|
||||
hash,
|
||||
generated: true,
|
||||
};
|
||||
}
|
||||
|
||||
await Deno.writeTextFile(
|
||||
path.join(this.config.build.outDir, "snapshot.json"),
|
||||
JSON.stringify(snapshot, null, 2),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async function hashContent(
|
||||
content: Uint8Array | ReadableStream<Uint8Array>,
|
||||
): Promise<string> {
|
||||
const hashBuf = await crypto.subtle.digest(
|
||||
"SHA-256",
|
||||
content,
|
||||
);
|
||||
return encodeHex(hashBuf);
|
||||
}
|
||||
@@ -1,78 +0,0 @@
|
||||
import { updateCheck } from "./update_check.ts";
|
||||
import { DAY, dirname, fromFileUrl, join, toFileUrl } from "./deps.ts";
|
||||
import { FreshConfig, Manifest as ServerManifest } from "../server/mod.ts";
|
||||
import { build } from "./build.ts";
|
||||
import { collect, ensureMinDenoVersion, generate, Manifest } from "./mod.ts";
|
||||
import { startServer } from "../server/boot.ts";
|
||||
import { getInternalFreshState } from "../server/config.ts";
|
||||
import { getServerContext } from "../server/context.ts";
|
||||
|
||||
export async function dev(
|
||||
base: string,
|
||||
entrypoint: string,
|
||||
config?: FreshConfig,
|
||||
) {
|
||||
ensureMinDenoVersion();
|
||||
|
||||
// Run update check in background
|
||||
updateCheck(DAY).catch(() => {});
|
||||
|
||||
const dir = dirname(fromFileUrl(base));
|
||||
|
||||
let currentManifest: Manifest;
|
||||
const prevManifest = Deno.env.get("FRSH_DEV_PREVIOUS_MANIFEST");
|
||||
if (prevManifest) {
|
||||
currentManifest = JSON.parse(prevManifest);
|
||||
} else {
|
||||
currentManifest = { islands: [], routes: [] };
|
||||
}
|
||||
const newManifest = await collect(dir, config?.router?.ignoreFilePattern);
|
||||
Deno.env.set("FRSH_DEV_PREVIOUS_MANIFEST", JSON.stringify(newManifest));
|
||||
|
||||
const manifestChanged =
|
||||
!arraysEqual(newManifest.routes, currentManifest.routes) ||
|
||||
!arraysEqual(newManifest.islands, currentManifest.islands);
|
||||
|
||||
if (manifestChanged) await generate(dir, newManifest);
|
||||
|
||||
const manifest = (await import(toFileUrl(join(dir, "fresh.gen.ts")).href))
|
||||
.default as ServerManifest;
|
||||
|
||||
if (Deno.args.includes("build")) {
|
||||
const state = await getInternalFreshState(
|
||||
manifest,
|
||||
config ?? {},
|
||||
);
|
||||
state.config.dev = false;
|
||||
state.loadSnapshot = false;
|
||||
state.build = true;
|
||||
await build(state);
|
||||
} else if (config) {
|
||||
const state = await getInternalFreshState(
|
||||
manifest,
|
||||
config,
|
||||
);
|
||||
state.config.dev = true;
|
||||
state.loadSnapshot = false;
|
||||
const ctx = await getServerContext(state);
|
||||
await startServer(ctx.handler(), {
|
||||
...state.config.server,
|
||||
basePath: state.config.basePath,
|
||||
});
|
||||
} else {
|
||||
// Legacy entry point: Back then `dev.ts` would call `main.ts` but
|
||||
// this causes duplicate plugin instantiation if both `dev.ts` and
|
||||
// `main.ts` instantiate plugins.
|
||||
Deno.env.set("__FRSH_LEGACY_DEV", "true");
|
||||
entrypoint = new URL(entrypoint, base).href;
|
||||
await import(entrypoint);
|
||||
}
|
||||
}
|
||||
|
||||
function arraysEqual<T>(a: T[], b: T[]): boolean {
|
||||
if (a.length !== b.length) return false;
|
||||
for (let i = 0; i < a.length; ++i) {
|
||||
if (a[i] !== b[i]) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
export function printError(message: string) {
|
||||
console.error(`%cerror%c: ${message}`, "color: red; font-weight: bold", "");
|
||||
}
|
||||
|
||||
export function error(message: string): never {
|
||||
printError(message);
|
||||
Deno.exit(1);
|
||||
}
|
||||
@@ -0,0 +1,201 @@
|
||||
import { denoPlugins } from "@luca/esbuild-deno-loader";
|
||||
import type { Plugin as EsbuildPlugin } from "esbuild";
|
||||
import * as path from "@std/path";
|
||||
|
||||
export interface FreshBundleOptions {
|
||||
dev: boolean;
|
||||
cwd: string;
|
||||
buildId: string;
|
||||
outDir: string;
|
||||
denoJsonPath: string;
|
||||
entryPoints: Record<string, string>;
|
||||
target: string | string[];
|
||||
jsxImportSource?: string;
|
||||
}
|
||||
|
||||
export interface BuildOutput {
|
||||
entryToChunk: Map<string, string>;
|
||||
dependencies: Map<string, string[]>;
|
||||
files: Array<{ hash: string | null; contents: Uint8Array; path: string }>;
|
||||
}
|
||||
|
||||
let esbuild: null | typeof import("esbuild-wasm") = null;
|
||||
|
||||
const PREACT_ENV = Deno.env.get("PREACT_PATH");
|
||||
|
||||
export async function bundleJs(
|
||||
options: FreshBundleOptions,
|
||||
): Promise<BuildOutput> {
|
||||
if (esbuild === null) {
|
||||
esbuild = Deno.env.get("FRESH_ESBUILD_LOADER") === "portable"
|
||||
? await import("esbuild-wasm")
|
||||
: await import("esbuild");
|
||||
|
||||
await esbuild.initialize({});
|
||||
}
|
||||
|
||||
try {
|
||||
await Deno.mkdir(options.cwd, { recursive: true });
|
||||
} catch (err) {
|
||||
if (!(err instanceof Deno.errors.AlreadyExists)) {
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
const bundle = await esbuild.build({
|
||||
entryPoints: options.entryPoints,
|
||||
|
||||
platform: "browser",
|
||||
target: options.target,
|
||||
|
||||
format: "esm",
|
||||
bundle: true,
|
||||
splitting: true,
|
||||
treeShaking: true,
|
||||
sourcemap: options.dev ? "linked" : false,
|
||||
minify: !options.dev,
|
||||
|
||||
jsxDev: options.dev,
|
||||
jsx: "automatic",
|
||||
jsxImportSource: options.jsxImportSource ?? "preact",
|
||||
|
||||
absWorkingDir: options.cwd,
|
||||
outdir: ".",
|
||||
write: false,
|
||||
metafile: true,
|
||||
|
||||
plugins: [
|
||||
preactDebugger(PREACT_ENV),
|
||||
buildIdPlugin(options.buildId),
|
||||
windowsPathFixer(),
|
||||
...denoPlugins({ configPath: options.denoJsonPath }),
|
||||
],
|
||||
});
|
||||
|
||||
const files: BuildOutput["files"] = [];
|
||||
for (let i = 0; i < bundle.outputFiles.length; i++) {
|
||||
const outputFile = bundle.outputFiles[i];
|
||||
const relative = path.relative(options.cwd, outputFile.path);
|
||||
files.push({
|
||||
path: relative,
|
||||
contents: outputFile.contents,
|
||||
hash: outputFile.hash,
|
||||
});
|
||||
}
|
||||
|
||||
files.push({
|
||||
path: "metafile.json",
|
||||
contents: new TextEncoder().encode(JSON.stringify(bundle.metafile)),
|
||||
hash: null,
|
||||
});
|
||||
|
||||
const entryToChunk = new Map<string, string>();
|
||||
const dependencies = new Map<string, string[]>();
|
||||
|
||||
const entryToName = new Map(
|
||||
Array.from(Object.entries(options.entryPoints)).map(
|
||||
(entry) => [entry[1], entry[0]],
|
||||
),
|
||||
);
|
||||
|
||||
if (bundle.metafile) {
|
||||
const metaOutputs = new Map(Object.entries(bundle.metafile.outputs));
|
||||
|
||||
for (const [entryPath, entry] of metaOutputs.entries()) {
|
||||
const imports = entry.imports
|
||||
.filter(({ kind }) => kind === "import-statement")
|
||||
.map(({ path }) => path);
|
||||
dependencies.set(entryPath, imports);
|
||||
|
||||
if (entryPath !== "fresh-runtime.js" && entry.entryPoint !== undefined) {
|
||||
const filePath = path.join(options.cwd, entry.entryPoint);
|
||||
|
||||
const name = entryToName.get(filePath)!;
|
||||
entryToChunk.set(name, entryPath);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!options.dev) {
|
||||
await esbuild.stop();
|
||||
}
|
||||
|
||||
return {
|
||||
files,
|
||||
entryToChunk,
|
||||
dependencies,
|
||||
};
|
||||
}
|
||||
|
||||
function buildIdPlugin(buildId: string): EsbuildPlugin {
|
||||
return {
|
||||
name: "fresh-build-id",
|
||||
setup(build) {
|
||||
build.onResolve({ filter: /runtime[/\\]+build_id\.ts$/ }, (args) => {
|
||||
return {
|
||||
path: args.path,
|
||||
namespace: "fresh-internal",
|
||||
};
|
||||
});
|
||||
build.onLoad({
|
||||
filter: /runtime[/\\]build_id\.ts$/,
|
||||
namespace: "fresh-internal",
|
||||
}, () => {
|
||||
return {
|
||||
contents: `export const BUILD_ID = "${buildId}";`,
|
||||
};
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function toPreactModPath(mod: string): string {
|
||||
if (mod === "preact/debug") {
|
||||
return path.join("debug", "dist", "debug.module.js");
|
||||
} else if (mod === "preact/hooks") {
|
||||
return path.join("hooks", "dist", "hooks.module.js");
|
||||
} else if (mod === "preact/devtools") {
|
||||
return path.join("devtools", "dist", "devtools.module.js");
|
||||
} else if (mod === "preact/compat") {
|
||||
return path.join("compat", "dist", "compat.module.js");
|
||||
} else if (mod === "preact/jsx-runtime" || mod === "preact/jsx-dev-runtime") {
|
||||
return path.join("jsx-runtime", "dist", "jsxRuntime.module.js");
|
||||
} else {
|
||||
return path.join("dist", "preact.module.js");
|
||||
}
|
||||
}
|
||||
|
||||
function preactDebugger(preactPath: string | undefined): EsbuildPlugin {
|
||||
return {
|
||||
name: "fresh-preact-debugger",
|
||||
setup(build) {
|
||||
if (preactPath === undefined) return;
|
||||
|
||||
build.onResolve({ filter: /^preact/ }, (args) => {
|
||||
const resolved = path.resolve(preactPath, toPreactModPath(args.path));
|
||||
|
||||
return {
|
||||
path: resolved,
|
||||
};
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function windowsPathFixer(): EsbuildPlugin {
|
||||
return {
|
||||
name: "fresh-fix-windows",
|
||||
setup(build) {
|
||||
if (Deno.build.os === "windows") {
|
||||
build.onResolve({ filter: /\.*/ }, (args) => {
|
||||
if (args.path.startsWith("\\")) {
|
||||
const normalized = path.resolve(args.path);
|
||||
return {
|
||||
path: normalized,
|
||||
};
|
||||
}
|
||||
});
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,247 @@
|
||||
import type { FsAdapter } from "../fs.ts";
|
||||
import { BUILD_ID } from "../runtime/build_id.ts";
|
||||
import { assetInternal } from "../runtime/shared_internal.tsx";
|
||||
|
||||
export type TransformMode = "development" | "production";
|
||||
|
||||
export interface OnTransformOptions {
|
||||
pluginName: string;
|
||||
filter: RegExp;
|
||||
}
|
||||
|
||||
export interface OnTransformResult {
|
||||
content: string | Uint8Array;
|
||||
path?: string;
|
||||
map?: string | Uint8Array;
|
||||
}
|
||||
|
||||
export interface OnTransformArgs {
|
||||
path: string;
|
||||
target: string | string[];
|
||||
text: string;
|
||||
content: Uint8Array;
|
||||
mode: TransformMode;
|
||||
}
|
||||
export type TransformFn = (
|
||||
args: OnTransformArgs,
|
||||
) =>
|
||||
| void
|
||||
| OnTransformResult
|
||||
| Array<{ path: string } & Omit<OnTransformResult, "path">>
|
||||
| Promise<
|
||||
| void
|
||||
| OnTransformResult
|
||||
| Array<{ path: string } & Omit<OnTransformResult, "path">>
|
||||
>;
|
||||
|
||||
export interface Transformer {
|
||||
options: OnTransformOptions;
|
||||
fn: TransformFn;
|
||||
}
|
||||
|
||||
export interface ProcessedFile {
|
||||
path: string;
|
||||
content: Uint8Array;
|
||||
map: Uint8Array | null;
|
||||
inputFiles: string[];
|
||||
}
|
||||
|
||||
interface TransformReq {
|
||||
newFile: boolean;
|
||||
filePath: string;
|
||||
content: Uint8Array;
|
||||
map: null | Uint8Array;
|
||||
inputFiles: string[];
|
||||
}
|
||||
|
||||
export class FreshFileTransformer {
|
||||
#transformers: Transformer[] = [];
|
||||
#fs: FsAdapter;
|
||||
|
||||
constructor(fs: FsAdapter) {
|
||||
this.#fs = fs;
|
||||
}
|
||||
|
||||
onTransform(options: OnTransformOptions, callback: TransformFn): void {
|
||||
this.#transformers.push({ options, fn: callback });
|
||||
}
|
||||
|
||||
async process(
|
||||
filePath: string,
|
||||
mode: TransformMode,
|
||||
target: string | string[],
|
||||
): Promise<ProcessedFile[] | null> {
|
||||
// Pre-check if we have any transformer for this file at all
|
||||
let hasTransformer = false;
|
||||
for (let i = 0; i < this.#transformers.length; i++) {
|
||||
if (this.#transformers[i].options.filter.test(filePath)) {
|
||||
hasTransformer = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!hasTransformer) {
|
||||
return null;
|
||||
}
|
||||
|
||||
let content: Uint8Array;
|
||||
try {
|
||||
content = await this.#fs.readFile(filePath);
|
||||
} catch (err) {
|
||||
if (err instanceof Deno.errors.NotFound) {
|
||||
return null;
|
||||
}
|
||||
|
||||
throw err;
|
||||
}
|
||||
|
||||
const queue: TransformReq[] = [{
|
||||
newFile: false,
|
||||
content,
|
||||
filePath,
|
||||
map: null,
|
||||
inputFiles: [filePath],
|
||||
}];
|
||||
const outFiles: ProcessedFile[] = [];
|
||||
|
||||
const seen = new Set<string>();
|
||||
|
||||
let req: TransformReq | undefined = undefined;
|
||||
while ((req = queue.pop()) !== undefined) {
|
||||
if (seen.has(req.filePath)) continue;
|
||||
seen.add(req.filePath);
|
||||
|
||||
let transformed = false;
|
||||
for (let i = 0; i < this.#transformers.length; i++) {
|
||||
const transformer = this.#transformers[i];
|
||||
|
||||
const { options, fn } = transformer;
|
||||
options.filter.lastIndex = 0;
|
||||
if (!options.filter.test(req.filePath)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const result = await fn({
|
||||
path: req.filePath,
|
||||
mode,
|
||||
target,
|
||||
content: req!.content,
|
||||
get text() {
|
||||
return new TextDecoder().decode(req!.content);
|
||||
},
|
||||
});
|
||||
|
||||
if (result !== undefined) {
|
||||
if (Array.isArray(result)) {
|
||||
for (let i = 0; i < result.length; i++) {
|
||||
const item = result[i];
|
||||
if (item.path === undefined) {
|
||||
throw new Error(
|
||||
`The ".path" property must be set when returning multiple files in a transformer. [${transformer.options.pluginName}]`,
|
||||
);
|
||||
}
|
||||
|
||||
const outContent = typeof item.content === "string"
|
||||
? new TextEncoder().encode(item.content)
|
||||
: item.content;
|
||||
|
||||
const outMap = item.map !== undefined
|
||||
? typeof item.map === "string"
|
||||
? new TextEncoder().encode(item.map)
|
||||
: item.map
|
||||
: null;
|
||||
|
||||
if (req.filePath === item.path) {
|
||||
if (req.content === outContent && req.map === outMap) {
|
||||
continue;
|
||||
}
|
||||
|
||||
transformed = true;
|
||||
req.content = outContent;
|
||||
req.map = outMap;
|
||||
} else {
|
||||
let found = false;
|
||||
for (let i = 0; i < queue.length; i++) {
|
||||
const req = queue[i];
|
||||
if (req.filePath === item.path) {
|
||||
found = true;
|
||||
transformed = true;
|
||||
req.content = outContent;
|
||||
req.map = outMap;
|
||||
}
|
||||
}
|
||||
|
||||
if (!found) {
|
||||
queue.push({
|
||||
newFile: true,
|
||||
filePath: item.path,
|
||||
content: outContent,
|
||||
map: outMap,
|
||||
inputFiles: req.inputFiles.slice(),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
const outContent = typeof result.content === "string"
|
||||
? new TextEncoder().encode(result.content)
|
||||
: result.content;
|
||||
|
||||
const outMap = result.map !== undefined
|
||||
? typeof result.map === "string"
|
||||
? new TextEncoder().encode(result.map)
|
||||
: result.map
|
||||
: null;
|
||||
|
||||
if (req.content === outContent && req.map === outMap) {
|
||||
continue;
|
||||
}
|
||||
|
||||
transformed = true;
|
||||
req.content = outContent;
|
||||
req.map = outMap;
|
||||
req.filePath = result.path ?? req.filePath;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: Keep transforming until no one processes anymore
|
||||
if (transformed || req.newFile) {
|
||||
outFiles.push({
|
||||
content: req.content,
|
||||
map: req.map,
|
||||
path: req.filePath,
|
||||
inputFiles: req.inputFiles,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return outFiles.length > 0 ? outFiles : null;
|
||||
}
|
||||
}
|
||||
|
||||
const CSS_URL_REGEX = /url\((["'][^'"]+["']|[^)]+)\)/g;
|
||||
|
||||
export function cssAssetHash(transformer: FreshFileTransformer) {
|
||||
transformer.onTransform({
|
||||
pluginName: "fresh-css",
|
||||
filter: /\.css$/,
|
||||
}, (args) => {
|
||||
const replaced = args.text.replaceAll(CSS_URL_REGEX, (_, str) => {
|
||||
let rawUrl = str;
|
||||
if (str[0] === "'" || str[0] === '"') {
|
||||
rawUrl = str.slice(1, -1);
|
||||
}
|
||||
|
||||
if (rawUrl.length === 0) {
|
||||
return str;
|
||||
}
|
||||
|
||||
return `url(${JSON.stringify(assetInternal(rawUrl, BUILD_ID))})`;
|
||||
});
|
||||
|
||||
return {
|
||||
content: replaced,
|
||||
};
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,229 @@
|
||||
import { expect } from "@std/expect";
|
||||
import type { FsAdapter } from "../fs.ts";
|
||||
import {
|
||||
FreshFileTransformer,
|
||||
type ProcessedFile,
|
||||
} from "./file_transformer.ts";
|
||||
import { delay } from "../test_utils.ts";
|
||||
|
||||
function testTransformer(files: Record<string, string>) {
|
||||
const mockFs: FsAdapter = {
|
||||
isDirectory: () => Promise.resolve(false),
|
||||
mkdirp: () => Promise.resolve(),
|
||||
walk: async function* foo() {
|
||||
},
|
||||
readFile: (file) => {
|
||||
if (file instanceof URL) throw new Error("Not supported");
|
||||
// deno-lint-ignore no-explicit-any
|
||||
const content = (files as any)[file];
|
||||
const buf = new TextEncoder().encode(content);
|
||||
return Promise.resolve(buf);
|
||||
},
|
||||
};
|
||||
return new FreshFileTransformer(mockFs);
|
||||
}
|
||||
|
||||
function consumeResult(result: ProcessedFile[]) {
|
||||
const out: {
|
||||
path: string;
|
||||
content: string;
|
||||
map: string | null;
|
||||
inputFiles: string[];
|
||||
}[] = [];
|
||||
for (let i = 0; i < result.length; i++) {
|
||||
const file = result[i];
|
||||
|
||||
out.push({
|
||||
path: file.path,
|
||||
content: typeof file.content === "string"
|
||||
? file.content
|
||||
: new TextDecoder().decode(file.content),
|
||||
map: file.map !== null
|
||||
? typeof file.map === "string"
|
||||
? file.map
|
||||
: new TextDecoder().decode(file.map)
|
||||
: null,
|
||||
inputFiles: file.inputFiles,
|
||||
});
|
||||
}
|
||||
|
||||
return out.sort((a, b) => a.path.localeCompare(b.path));
|
||||
}
|
||||
|
||||
Deno.test("FileTransformer - transform sync", async () => {
|
||||
const transformer = testTransformer({
|
||||
"foo.txt": "foo",
|
||||
});
|
||||
|
||||
transformer.onTransform({ pluginName: "foo", filter: /.*/ }, (args) => {
|
||||
return {
|
||||
content: args.text + "bar",
|
||||
};
|
||||
});
|
||||
|
||||
const result = await transformer.process("foo.txt", "development", "");
|
||||
const files = await consumeResult(result!);
|
||||
expect(files).toEqual([
|
||||
{ content: "foobar", map: null, path: "foo.txt", inputFiles: ["foo.txt"] },
|
||||
]);
|
||||
});
|
||||
|
||||
Deno.test("FileTransformer - transform async", async () => {
|
||||
const transformer = testTransformer({
|
||||
"foo.txt": "foo",
|
||||
});
|
||||
|
||||
transformer.onTransform({ pluginName: "foo", filter: /.*/ }, async (args) => {
|
||||
await delay(1);
|
||||
return {
|
||||
content: args.text + "bar",
|
||||
};
|
||||
});
|
||||
|
||||
const result = await transformer.process("foo.txt", "development", "");
|
||||
const files = await consumeResult(result!);
|
||||
expect(files).toEqual([
|
||||
{ content: "foobar", map: null, path: "foo.txt", inputFiles: ["foo.txt"] },
|
||||
]);
|
||||
});
|
||||
|
||||
Deno.test("FileTransformer - transform return Uint8Array", async () => {
|
||||
const transformer = testTransformer({
|
||||
"foo.txt": "foo",
|
||||
});
|
||||
|
||||
transformer.onTransform({ pluginName: "foo", filter: /.*/ }, () => {
|
||||
return {
|
||||
content: new TextEncoder().encode("foobar"),
|
||||
};
|
||||
});
|
||||
|
||||
const result = await transformer.process("foo.txt", "development", "");
|
||||
const files = await consumeResult(result!);
|
||||
expect(files).toEqual([
|
||||
{ content: "foobar", map: null, path: "foo.txt", inputFiles: ["foo.txt"] },
|
||||
]);
|
||||
});
|
||||
|
||||
Deno.test("FileTransformer - pass transformed content", async () => {
|
||||
const transformer = testTransformer({
|
||||
"input.txt": "input",
|
||||
});
|
||||
|
||||
transformer.onTransform({ pluginName: "A", filter: /.*/ }, (args) => {
|
||||
return {
|
||||
content: args.text + " -> A",
|
||||
};
|
||||
});
|
||||
transformer.onTransform({ pluginName: "B", filter: /.*/ }, (args) => {
|
||||
return {
|
||||
content: args.text + " -> B",
|
||||
};
|
||||
});
|
||||
|
||||
const result = await transformer.process("input.txt", "development", "");
|
||||
const files = await consumeResult(result!);
|
||||
expect(files).toEqual([
|
||||
{
|
||||
content: "input -> A -> B",
|
||||
map: null,
|
||||
path: "input.txt",
|
||||
inputFiles: ["input.txt"],
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
Deno.test(
|
||||
"FileTransformer - pass transformed content with multiple",
|
||||
async () => {
|
||||
const transformer = testTransformer({
|
||||
"input.txt": "input",
|
||||
});
|
||||
|
||||
transformer.onTransform({ pluginName: "A", filter: /.*/ }, (args) => {
|
||||
return [{
|
||||
path: args.path,
|
||||
content: args.text + " -> A",
|
||||
}];
|
||||
});
|
||||
transformer.onTransform({ pluginName: "B", filter: /.*/ }, (args) => {
|
||||
return {
|
||||
content: args.text + " -> B",
|
||||
};
|
||||
});
|
||||
|
||||
const result = await transformer.process("input.txt", "development", "");
|
||||
const files = await consumeResult(result!);
|
||||
expect(files).toEqual([
|
||||
{
|
||||
content: "input -> A -> B",
|
||||
map: null,
|
||||
path: "input.txt",
|
||||
inputFiles: ["input.txt"],
|
||||
},
|
||||
]);
|
||||
},
|
||||
);
|
||||
|
||||
Deno.test("FileTransformer - return multiple results", async () => {
|
||||
const transformer = testTransformer({
|
||||
"foo.txt": "foo",
|
||||
});
|
||||
|
||||
const received: string[] = [];
|
||||
transformer.onTransform({ pluginName: "A", filter: /foo\.txt$/ }, () => {
|
||||
return [{
|
||||
path: "a.txt",
|
||||
content: "A",
|
||||
}, {
|
||||
path: "b.txt",
|
||||
content: "B",
|
||||
}];
|
||||
});
|
||||
transformer.onTransform({ pluginName: "B", filter: /.*/ }, (args) => {
|
||||
received.push(args.path);
|
||||
});
|
||||
|
||||
const result = await transformer.process("foo.txt", "development", "");
|
||||
const files = await consumeResult(result!);
|
||||
expect(files).toEqual([
|
||||
{ content: "A", map: null, path: "a.txt", inputFiles: ["foo.txt"] },
|
||||
{ content: "B", map: null, path: "b.txt", inputFiles: ["foo.txt"] },
|
||||
]);
|
||||
expect(received).toEqual(["foo.txt", "b.txt", "a.txt"]);
|
||||
});
|
||||
|
||||
Deno.test(
|
||||
"FileTransformer - track input files through temporary results",
|
||||
async () => {
|
||||
const transformer = testTransformer({
|
||||
"foo.txt": "foo",
|
||||
});
|
||||
|
||||
transformer.onTransform({ pluginName: "A", filter: /foo\.txt$/ }, () => {
|
||||
return [{
|
||||
path: "a.txt",
|
||||
content: "A",
|
||||
}, {
|
||||
path: "b.txt",
|
||||
content: "B",
|
||||
}];
|
||||
});
|
||||
transformer.onTransform(
|
||||
{ pluginName: "B", filter: /[ab]\.txt$/ },
|
||||
(args) => {
|
||||
return {
|
||||
path: "c" + args.path,
|
||||
content: args.text + "C",
|
||||
};
|
||||
},
|
||||
);
|
||||
|
||||
const result = await transformer.process("foo.txt", "development", "");
|
||||
const files = await consumeResult(result!);
|
||||
expect(files).toEqual([
|
||||
{ content: "AC", map: null, path: "ca.txt", inputFiles: ["foo.txt"] },
|
||||
{ content: "BC", map: null, path: "cb.txt", inputFiles: ["foo.txt"] },
|
||||
]);
|
||||
},
|
||||
);
|
||||
@@ -1,39 +0,0 @@
|
||||
export const RECOMMENDED_PREACT_VERSION = "10.22.0";
|
||||
export const RECOMMENDED_PREACT_SIGNALS_VERSION = "1.2.2";
|
||||
export const RECOMMENDED_PREACT_SIGNALS_CORE_VERSION = "1.5.1";
|
||||
export const RECOMMENDED_TWIND_CORE_VERSION = "1.1.3";
|
||||
export const RECOMMENDED_TWIND_PRESET_AUTOPREFIX_VERSION = "1.0.7";
|
||||
export const RECOMMENDED_TWIND_PRESET_TAILWIND_VERSION = "1.1.4";
|
||||
export const RECOMMENDED_STD_VERSION = "0.216.0";
|
||||
export const RECOMMENDED_TAILIWIND_VERSION = "3.4.1";
|
||||
|
||||
export function freshImports(imports: Record<string, string>) {
|
||||
imports["$fresh/"] = new URL("../../", import.meta.url).href;
|
||||
imports["preact"] = `https://esm.sh/preact@${RECOMMENDED_PREACT_VERSION}`;
|
||||
imports["preact/"] = `https://esm.sh/preact@${RECOMMENDED_PREACT_VERSION}/`;
|
||||
imports["@preact/signals"] =
|
||||
`https://esm.sh/*@preact/signals@${RECOMMENDED_PREACT_SIGNALS_VERSION}`;
|
||||
imports["@preact/signals-core"] =
|
||||
`https://esm.sh/*@preact/signals-core@${RECOMMENDED_PREACT_SIGNALS_CORE_VERSION}`;
|
||||
}
|
||||
|
||||
export function twindImports(imports: Record<string, string>) {
|
||||
imports["@twind/core"] =
|
||||
`https://esm.sh/@twind/core@${RECOMMENDED_TWIND_CORE_VERSION}`;
|
||||
imports["@twind/preset-tailwind"] =
|
||||
`https://esm.sh/@twind/preset-tailwind@${RECOMMENDED_TWIND_PRESET_TAILWIND_VERSION}/`;
|
||||
imports["@twind/preset-autoprefix"] =
|
||||
`https://esm.sh/@twind/preset-autoprefix@${RECOMMENDED_TWIND_PRESET_AUTOPREFIX_VERSION}/`;
|
||||
}
|
||||
|
||||
export function tailwindImports(imports: Record<string, string>) {
|
||||
imports["tailwindcss"] = `npm:tailwindcss@${RECOMMENDED_TAILIWIND_VERSION}`;
|
||||
imports["tailwindcss/"] =
|
||||
`npm:/tailwindcss@${RECOMMENDED_TAILIWIND_VERSION}/`;
|
||||
imports["tailwindcss/plugin"] =
|
||||
`npm:/tailwindcss@${RECOMMENDED_TAILIWIND_VERSION}/plugin.js`;
|
||||
}
|
||||
|
||||
export function dotenvImports(imports: Record<string, string>) {
|
||||
imports["$std/"] = `https://deno.land/std@${RECOMMENDED_STD_VERSION}/`;
|
||||
}
|
||||
@@ -1,134 +0,0 @@
|
||||
import { stringToIdentifier } from "../server/init_safe_deps.ts";
|
||||
import { extname, join, normalize } from "./deps.ts";
|
||||
|
||||
/**
|
||||
* Import specifiers must have forward slashes
|
||||
*/
|
||||
function toImportSpecifier(file: string) {
|
||||
let specifier = normalize(file).replace(/\\/g, "/");
|
||||
if (!specifier.startsWith(".")) {
|
||||
specifier = "./" + specifier;
|
||||
}
|
||||
return specifier;
|
||||
}
|
||||
|
||||
// Create a valid JS identifier out of the project relative specifier.
|
||||
// Note that we only need to deal with strings that _must_ have been
|
||||
// valid file names in Windows, macOS and Linux and every identifier we
|
||||
// create here will be prefixed with at least one "$". This greatly
|
||||
// simplifies the invalid characters we have to account for.
|
||||
export function specifierToIdentifier(specifier: string, used: Set<string>) {
|
||||
specifier = specifier.replace(/^(?:\.\/routes|\.\/islands)\//, "");
|
||||
const ext = extname(specifier);
|
||||
if (ext) specifier = specifier.slice(0, -ext.length);
|
||||
|
||||
// Turn the specifier into a readable JS identifier
|
||||
let ident = stringToIdentifier(specifier);
|
||||
|
||||
if (used.has(ident)) {
|
||||
let check = ident;
|
||||
let i = 1;
|
||||
while (used.has(check)) {
|
||||
check = `${ident}_${i++}`;
|
||||
}
|
||||
ident = check;
|
||||
}
|
||||
|
||||
used.add(ident);
|
||||
return ident;
|
||||
}
|
||||
|
||||
export interface Manifest {
|
||||
routes: string[];
|
||||
islands: string[];
|
||||
}
|
||||
|
||||
export async function generate(directory: string, manifest: Manifest) {
|
||||
const { routes, islands } = manifest;
|
||||
|
||||
// Keep track of which identifier we've already used
|
||||
const used = new Set<string>();
|
||||
|
||||
const normalizedRoutes = new Map<string, string>();
|
||||
for (let i = 0; i < routes.length; i++) {
|
||||
const file = routes[i];
|
||||
const specifier = toImportSpecifier(file);
|
||||
const identifier = specifierToIdentifier(specifier, used);
|
||||
normalizedRoutes.set(specifier, identifier);
|
||||
}
|
||||
|
||||
const normalizedIslands: { specifier: string; identifier: string }[] = [];
|
||||
for (let i = 0; i < islands.length; i++) {
|
||||
const file = islands[i];
|
||||
const specifier = toImportSpecifier(file);
|
||||
const identifier = specifierToIdentifier(specifier, used);
|
||||
normalizedIslands.push({ specifier, identifier });
|
||||
}
|
||||
|
||||
const output = `// DO NOT EDIT. This file is generated by Fresh.
|
||||
// This file SHOULD be checked into source version control.
|
||||
// This file is automatically updated during development when running \`dev.ts\`.
|
||||
|
||||
${
|
||||
Array.from(normalizedRoutes.entries()).map(([specifier, identifier]) =>
|
||||
`import * as $${identifier} from "${specifier}";`
|
||||
).join(
|
||||
"\n",
|
||||
)
|
||||
}
|
||||
${
|
||||
normalizedIslands.map(({ specifier, identifier }) =>
|
||||
`import * as $${identifier} from "${specifier}";`
|
||||
)
|
||||
.join("\n")
|
||||
}
|
||||
import type { Manifest } from "$fresh/server.ts";
|
||||
|
||||
const manifest = {
|
||||
routes: {
|
||||
${
|
||||
Array.from(normalizedRoutes.entries()).map(([specifier, identifier]) =>
|
||||
`${JSON.stringify(`${specifier}`)}: $${identifier},`
|
||||
)
|
||||
.join("\n ")
|
||||
}
|
||||
},
|
||||
islands: {
|
||||
${
|
||||
normalizedIslands.map(({ specifier, identifier }) =>
|
||||
`${JSON.stringify(`${specifier}`)}: $${identifier},`
|
||||
)
|
||||
.join("\n ")
|
||||
}
|
||||
},
|
||||
baseUrl: import.meta.url,
|
||||
} satisfies Manifest;
|
||||
|
||||
export default manifest;
|
||||
`;
|
||||
|
||||
const proc = new Deno.Command(Deno.execPath(), {
|
||||
args: ["fmt", "-"],
|
||||
stdin: "piped",
|
||||
stdout: "piped",
|
||||
stderr: "null",
|
||||
}).spawn();
|
||||
|
||||
const raw = new ReadableStream({
|
||||
start(controller) {
|
||||
controller.enqueue(new TextEncoder().encode(output));
|
||||
controller.close();
|
||||
},
|
||||
});
|
||||
await raw.pipeTo(proc.stdin);
|
||||
const { stdout } = await proc.output();
|
||||
|
||||
const manifestStr = new TextDecoder().decode(stdout);
|
||||
const manifestPath = join(directory, "./fresh.gen.ts");
|
||||
|
||||
await Deno.writeTextFile(manifestPath, manifestStr);
|
||||
console.log(
|
||||
`%cThe manifest has been generated for ${routes.length} routes and ${islands.length} islands.`,
|
||||
"color: blue; font-weight: bold",
|
||||
);
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
import { assertEquals } from "./deps.ts";
|
||||
import { specifierToIdentifier } from "./manifest.ts";
|
||||
|
||||
const run = specifierToIdentifier;
|
||||
|
||||
Deno.test("specifierToIdentifier", () => {
|
||||
const used = new Set<string>();
|
||||
assertEquals(run("foo/bar.ts", used), "foo_bar");
|
||||
assertEquals(run("foo/bar.json.ts", used), "foo_bar_json");
|
||||
assertEquals(run("foo/[id]/bar", used), "foo_id_bar");
|
||||
assertEquals(run("foo/[...all]/bar", used), "foo_all_bar");
|
||||
assertEquals(run("foo/[[optional]]/bar", used), "foo_optional_bar");
|
||||
assertEquals(run("foo/as-df/bar", used), "foo_as_df_bar");
|
||||
assertEquals(run("foo/as@df", used), "foo_as_df");
|
||||
assertEquals(run("foo/foo.bar.baz.tsx", used), "foo_foo_bar_baz");
|
||||
assertEquals(run("404", used), "_404");
|
||||
assertEquals(run("foo/_middleware", used), "foo_middleware");
|
||||
});
|
||||
|
||||
Deno.test("specifierToIdentifier deals with duplicates", () => {
|
||||
const used = new Set<string>();
|
||||
assertEquals(run("foo/bar", used), "foo_bar");
|
||||
assertEquals(run("foo/bar", used), "foo_bar_1");
|
||||
});
|
||||
@@ -0,0 +1,134 @@
|
||||
import * as path from "@std/path";
|
||||
import * as colors from "@std/fmt/colors";
|
||||
|
||||
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;
|
||||
}
|
||||
function getFirstUserFile(
|
||||
stack: string,
|
||||
rootDir: 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://")) {
|
||||
const filePath = path.fromFileUrl(file);
|
||||
if (path.relative(rootDir, filePath).startsWith(".")) {
|
||||
continue;
|
||||
}
|
||||
|
||||
return {
|
||||
fnName,
|
||||
file,
|
||||
line,
|
||||
column,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function getCodeFrame(stack: string, rootDir: string) {
|
||||
const file = getFirstUserFile(stack, rootDir);
|
||||
if (file) {
|
||||
try {
|
||||
const filePath = path.fromFileUrl(file.file);
|
||||
const text = Deno.readTextFileSync(filePath);
|
||||
return createCodeFrame(
|
||||
text,
|
||||
file.line - 1,
|
||||
file.column - 1,
|
||||
);
|
||||
} catch (err) {
|
||||
// Ignore
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import { DEV_ERROR_OVERLAY_URL } from "../../../constants.ts";
|
||||
import { HttpError } from "../../../error.ts";
|
||||
import type { MiddlewareFn } from "../../../middlewares/mod.ts";
|
||||
import { FreshScripts } from "../../../runtime/server/preact_hooks.tsx";
|
||||
import { ErrorOverlay } from "./overlay.tsx";
|
||||
|
||||
export function devErrorOverlay<T>(): MiddlewareFn<T> {
|
||||
return async (ctx) => {
|
||||
const { config, url } = ctx;
|
||||
if (url.pathname === config.basePath + DEV_ERROR_OVERLAY_URL) {
|
||||
return ctx.render(<ErrorOverlay url={url} />);
|
||||
}
|
||||
|
||||
try {
|
||||
return await ctx.next();
|
||||
} catch (err) {
|
||||
if (ctx.req.headers.get("accept")?.includes("text/html")) {
|
||||
let init: ResponseInit | undefined;
|
||||
if (err instanceof HttpError) {
|
||||
if (err.status < 500) throw err;
|
||||
init = { status: err.status };
|
||||
}
|
||||
|
||||
// At this point we're pretty sure to have a server error
|
||||
console.error(err);
|
||||
|
||||
return ctx.render(<FreshScripts />, init);
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
import { expect } from "@std/expect";
|
||||
import { App } from "../../../app.ts";
|
||||
import { FakeServer } from "../../../test_utils.ts";
|
||||
import { devErrorOverlay } from "./middleware.tsx";
|
||||
import { HttpError } from "../../../error.ts";
|
||||
|
||||
Deno.test("error overlay - show when error is thrown", async () => {
|
||||
const app = new App();
|
||||
app.use(devErrorOverlay());
|
||||
app.config.mode = "development";
|
||||
|
||||
app.get("/", () => {
|
||||
throw new Error("fail");
|
||||
});
|
||||
|
||||
const server = new FakeServer(await app.handler());
|
||||
const res = await server.get("/", {
|
||||
headers: {
|
||||
accept: "text/html",
|
||||
},
|
||||
});
|
||||
const content = await res.text();
|
||||
expect(content).toContain("fresh-error-overlay");
|
||||
});
|
||||
|
||||
Deno.test("error overlay - should not be visible for HttpError <500", async () => {
|
||||
const app = new App();
|
||||
app.use(devErrorOverlay());
|
||||
app.config.mode = "development";
|
||||
|
||||
app
|
||||
.get("/", () => {
|
||||
throw new HttpError(404);
|
||||
})
|
||||
.get("/500", () => {
|
||||
throw new HttpError(500);
|
||||
});
|
||||
|
||||
const server = new FakeServer(await app.handler());
|
||||
let res = await server.get("/", {
|
||||
headers: {
|
||||
accept: "text/html",
|
||||
},
|
||||
});
|
||||
let content = await res.text();
|
||||
expect(content).not.toContain("fresh-error-overlay");
|
||||
expect(res.status).toEqual(404);
|
||||
|
||||
res = await server.get("/500", {
|
||||
headers: {
|
||||
accept: "text/html",
|
||||
},
|
||||
});
|
||||
content = await res.text();
|
||||
expect(content).toContain("fresh-error-overlay");
|
||||
expect(res.status).toEqual(500);
|
||||
});
|
||||
@@ -0,0 +1,168 @@
|
||||
import type { ComponentChildren } from "preact";
|
||||
|
||||
// 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>
|
||||
);
|
||||
}
|
||||
|
||||
const DEFAULT_MESSAGE = "Internal Server Error";
|
||||
|
||||
export function ErrorOverlay(props: { url: URL }) {
|
||||
const url = props.url;
|
||||
const title = url.searchParams.get("message") || DEFAULT_MESSAGE;
|
||||
const stack = url.searchParams.get("stack");
|
||||
const codeFrame = url.searchParams.get("code-frame");
|
||||
|
||||
if (title === DEFAULT_MESSAGE && !stack && !codeFrame) {
|
||||
return null;
|
||||
}
|
||||
|
||||
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"));`,
|
||||
}}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import type { MiddlewareFn } from "../../middlewares/mod.ts";
|
||||
import { ALIVE_URL } from "../../constants.ts";
|
||||
|
||||
// Live reload: Send updates to browser
|
||||
export function liveReload<T>(): MiddlewareFn<T> {
|
||||
const revision = Date.now();
|
||||
|
||||
return (ctx) => {
|
||||
const { config, req, url } = ctx;
|
||||
|
||||
const aliveUrl = config.basePath + ALIVE_URL;
|
||||
|
||||
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,
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
return response;
|
||||
}
|
||||
|
||||
return ctx.next();
|
||||
};
|
||||
}
|
||||
+8
-109
@@ -1,111 +1,10 @@
|
||||
import {
|
||||
greaterOrEqual,
|
||||
join,
|
||||
relative,
|
||||
semverParse,
|
||||
walk,
|
||||
WalkEntry,
|
||||
} from "./deps.ts";
|
||||
export { generate, type Manifest } from "./manifest.ts";
|
||||
import { generate, type Manifest } from "./manifest.ts";
|
||||
import { error } from "./error.ts";
|
||||
const MIN_DENO_VERSION = "1.31.0";
|
||||
const TEST_FILE_PATTERN = /[._]test\.(?:[tj]sx?|[mc][tj]s)$/;
|
||||
import { setMode } from "../runtime/server/mod.tsx";
|
||||
|
||||
export function ensureMinDenoVersion() {
|
||||
// Check that the minimum supported Deno version is being used.
|
||||
if (
|
||||
!greaterOrEqual(
|
||||
semverParse(Deno.version.deno),
|
||||
semverParse(MIN_DENO_VERSION),
|
||||
)
|
||||
) {
|
||||
let message =
|
||||
`Deno version ${MIN_DENO_VERSION} or higher is required. Please update Deno.\n\n`;
|
||||
export { Builder, type FreshBuilder } from "./builder.ts";
|
||||
export {
|
||||
type OnTransformArgs,
|
||||
type OnTransformOptions,
|
||||
type TransformFn,
|
||||
} from "./file_transformer.ts";
|
||||
|
||||
if (Deno.execPath().includes("homebrew")) {
|
||||
message +=
|
||||
"You seem to have installed Deno via homebrew. To update, run: `brew upgrade deno`\n";
|
||||
} else {
|
||||
message += "To update, run: `deno upgrade`\n";
|
||||
}
|
||||
|
||||
error(message);
|
||||
}
|
||||
}
|
||||
|
||||
async function collectDir(
|
||||
dir: string,
|
||||
callback: (entry: WalkEntry, dir: string) => void,
|
||||
ignoreFilePattern = TEST_FILE_PATTERN,
|
||||
): Promise<void> {
|
||||
// Check if provided path is a directory
|
||||
try {
|
||||
const stat = await Deno.stat(dir);
|
||||
if (!stat.isDirectory) return;
|
||||
} catch (err) {
|
||||
if (err instanceof Deno.errors.NotFound) return;
|
||||
throw err;
|
||||
}
|
||||
|
||||
const routesFolder = walk(dir, {
|
||||
includeDirs: false,
|
||||
includeFiles: true,
|
||||
exts: ["tsx", "jsx", "ts", "js"],
|
||||
skip: [ignoreFilePattern],
|
||||
});
|
||||
|
||||
for await (const entry of routesFolder) {
|
||||
callback(entry, dir);
|
||||
}
|
||||
}
|
||||
|
||||
const GROUP_REG = /[/\\\\]\((_[^/\\\\]+)\)[/\\\\]/;
|
||||
export async function collect(
|
||||
directory: string,
|
||||
ignoreFilePattern?: RegExp,
|
||||
): Promise<Manifest> {
|
||||
const filePaths = new Set<string>();
|
||||
|
||||
const routes: string[] = [];
|
||||
const islands: string[] = [];
|
||||
await Promise.all([
|
||||
collectDir(join(directory, "./routes"), (entry, dir) => {
|
||||
const rel = join("routes", relative(dir, entry.path));
|
||||
const normalized = rel.slice(0, rel.lastIndexOf("."));
|
||||
|
||||
// A `(_islands)` path segment is a local island folder.
|
||||
// Any route path segment wrapped in `(_...)` is ignored
|
||||
// during route collection.
|
||||
const match = normalized.match(GROUP_REG);
|
||||
if (match && match[1].startsWith("_")) {
|
||||
if (match[1] === "_islands") {
|
||||
islands.push(rel);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (filePaths.has(normalized)) {
|
||||
throw new Error(
|
||||
`Route conflict detected. Multiple files have the same name: ${dir}${normalized}`,
|
||||
);
|
||||
}
|
||||
filePaths.add(normalized);
|
||||
routes.push(rel);
|
||||
}, ignoreFilePattern),
|
||||
collectDir(join(directory, "./islands"), (entry, dir) => {
|
||||
const rel = join("islands", relative(dir, entry.path));
|
||||
islands.push(rel);
|
||||
}, ignoreFilePattern),
|
||||
]);
|
||||
|
||||
routes.sort();
|
||||
islands.sort();
|
||||
|
||||
return { routes, islands };
|
||||
}
|
||||
|
||||
export async function manifest(path: string, ignoreFilePattern?: RegExp) {
|
||||
const manifest = await collect(path, ignoreFilePattern);
|
||||
await generate(path, manifest);
|
||||
}
|
||||
setMode("development");
|
||||
|
||||
+10
-9
@@ -1,4 +1,6 @@
|
||||
import { colors, join, lessThan, semverParse } from "./deps.ts";
|
||||
import * as semver from "@std/semver";
|
||||
import * as colors from "@std/fmt/colors";
|
||||
import * as path from "@std/path";
|
||||
|
||||
export interface CheckFile {
|
||||
last_checked: string;
|
||||
@@ -33,7 +35,7 @@ function getHomeDir(): string | null {
|
||||
|
||||
function getFreshCacheDir(): string | null {
|
||||
const home = getHomeDir();
|
||||
if (home) return join(home, "fresh");
|
||||
if (home) return path.join(home, "fresh");
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -47,10 +49,9 @@ async function fetchLatestVersion() {
|
||||
}
|
||||
|
||||
async function readCurrentVersion() {
|
||||
const versions = (await import("../../versions.json", {
|
||||
return (await import("../../deno.json", {
|
||||
with: { type: "json" },
|
||||
})).default as string[];
|
||||
return versions[0];
|
||||
})).default.version;
|
||||
}
|
||||
|
||||
export async function updateCheck(
|
||||
@@ -70,7 +71,7 @@ export async function updateCheck(
|
||||
|
||||
const home = getCacheDir();
|
||||
if (!home) return;
|
||||
const filePath = join(home, "latest.json");
|
||||
const filePath = path.join(home, "latest.json");
|
||||
try {
|
||||
await Deno.mkdir(home, { recursive: true });
|
||||
} catch (err) {
|
||||
@@ -113,12 +114,12 @@ export async function updateCheck(
|
||||
}
|
||||
|
||||
// Only show update message if current version is smaller than latest
|
||||
const currentVersion = semverParse(checkFile.current_version);
|
||||
const latestVersion = semverParse(checkFile.latest_version);
|
||||
const currentVersion = semver.parse(checkFile.current_version);
|
||||
const latestVersion = semver.parse(checkFile.latest_version);
|
||||
if (
|
||||
(!checkFile.last_shown ||
|
||||
Date.now() >= new Date(checkFile.last_shown).getTime() + interval) &&
|
||||
lessThan(currentVersion, latestVersion)
|
||||
semver.lessThan(currentVersion, latestVersion)
|
||||
) {
|
||||
checkFile.last_shown = new Date().toISOString();
|
||||
|
||||
|
||||
@@ -0,0 +1,394 @@
|
||||
import * as path from "@std/path";
|
||||
import denoJson from "../../deno.json" with { type: "json" };
|
||||
import { WEEK } from "@std/datetime";
|
||||
import { getStdOutput } from "../../tests/test_utils.tsx";
|
||||
import { expect } from "@std/expect";
|
||||
import type { CheckFile } from "./update_check.ts";
|
||||
|
||||
const CURRENT_VERSION = denoJson.version;
|
||||
|
||||
const cwd = import.meta.dirname!;
|
||||
|
||||
Deno.test("stores update check file in $HOME/fresh", async () => {
|
||||
const tmpDirName = await Deno.makeTempDir();
|
||||
const filePath = path.join(tmpDirName, "latest.json");
|
||||
|
||||
await new Deno.Command(Deno.execPath(), {
|
||||
args: [
|
||||
"run",
|
||||
"-A",
|
||||
path.join(cwd, "../../tests/fixture_update_check/mod.ts"),
|
||||
],
|
||||
cwd,
|
||||
env: {
|
||||
CI: "false",
|
||||
TEST_HOME: tmpDirName,
|
||||
},
|
||||
}).output();
|
||||
|
||||
const text = JSON.parse(await Deno.readTextFile(filePath));
|
||||
expect(text).toEqual({
|
||||
current_version: CURRENT_VERSION,
|
||||
latest_version: "99.99.999",
|
||||
last_checked: text.last_checked,
|
||||
last_shown: text.last_shown,
|
||||
});
|
||||
|
||||
await Deno.remove(tmpDirName, { recursive: true });
|
||||
});
|
||||
|
||||
Deno.test("skips update check on specific environment variables", async (t) => {
|
||||
const envs = ["FRESH_NO_UPDATE_CHECK", "CI", "DENO_DEPLOYMENT_ID"];
|
||||
|
||||
for (const env of envs) {
|
||||
await t.step(`checking ${env}`, async () => {
|
||||
const tmpDirName = await Deno.makeTempDir();
|
||||
const out = await new Deno.Command(Deno.execPath(), {
|
||||
args: [
|
||||
"run",
|
||||
"-A",
|
||||
path.join(cwd, "../../tests/fixture_update_check/mod.ts"),
|
||||
],
|
||||
cwd,
|
||||
env: {
|
||||
[env]: "true",
|
||||
TEST_HOME: tmpDirName,
|
||||
LATEST_VERSION: "1.30.0",
|
||||
},
|
||||
stderr: "piped",
|
||||
stdout: "piped",
|
||||
}).output();
|
||||
|
||||
const { stdout } = getStdOutput(out);
|
||||
expect(stdout).not.toMatch(/Fresh 1\.30\.0 is available/);
|
||||
|
||||
await Deno.remove(tmpDirName, { recursive: true });
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
Deno.test("shows update message on version mismatch", async () => {
|
||||
const tmpDirName = await Deno.makeTempDir();
|
||||
const filePath = path.join(tmpDirName, "latest.json");
|
||||
|
||||
await Deno.writeTextFile(
|
||||
filePath,
|
||||
JSON.stringify({
|
||||
current_version: "1.1.0",
|
||||
latest_version: "1.1.0",
|
||||
last_checked: new Date(0).toISOString(),
|
||||
}),
|
||||
);
|
||||
|
||||
const out = await new Deno.Command(Deno.execPath(), {
|
||||
args: [
|
||||
"run",
|
||||
"-A",
|
||||
path.join(cwd, "../../tests/fixture_update_check/mod.ts"),
|
||||
],
|
||||
cwd,
|
||||
env: {
|
||||
CI: "false",
|
||||
TEST_HOME: tmpDirName,
|
||||
LATEST_VERSION: "999.999.0",
|
||||
},
|
||||
stderr: "piped",
|
||||
stdout: "piped",
|
||||
}).output();
|
||||
|
||||
const { stdout } = getStdOutput(out);
|
||||
expect(stdout).toMatch(/Fresh 999\.999\.0 is available/);
|
||||
|
||||
// Updates check file
|
||||
const text = JSON.parse(await Deno.readTextFile(filePath));
|
||||
expect(text).toEqual({
|
||||
current_version: CURRENT_VERSION,
|
||||
latest_version: "999.999.0",
|
||||
last_checked: text.last_checked,
|
||||
last_shown: text.last_shown,
|
||||
});
|
||||
|
||||
await Deno.remove(tmpDirName, { recursive: true });
|
||||
});
|
||||
|
||||
Deno.test("only fetch new version defined by interval", async (t) => {
|
||||
const tmpDirName = await Deno.makeTempDir();
|
||||
|
||||
await t.step("fetches latest version initially", async () => {
|
||||
const out = await new Deno.Command(Deno.execPath(), {
|
||||
args: [
|
||||
"run",
|
||||
"-A",
|
||||
path.join(cwd, "../../tests/fixture_update_check/mod.ts"),
|
||||
],
|
||||
cwd,
|
||||
env: {
|
||||
CI: "false",
|
||||
UPDATE_INTERVAL: "100000",
|
||||
TEST_HOME: tmpDirName,
|
||||
LATEST_VERSION: "1.30.0",
|
||||
},
|
||||
stderr: "piped",
|
||||
stdout: "piped",
|
||||
}).output();
|
||||
|
||||
const { stdout } = getStdOutput(out);
|
||||
expect(stdout).toMatch(/fetching latest version/);
|
||||
});
|
||||
|
||||
await t.step("should not fetch if interval has not passed", async () => {
|
||||
const out = await new Deno.Command(Deno.execPath(), {
|
||||
args: [
|
||||
"run",
|
||||
"-A",
|
||||
path.join(cwd, "../../tests/fixture_update_check/mod.ts"),
|
||||
],
|
||||
cwd,
|
||||
env: {
|
||||
CI: "false",
|
||||
UPDATE_INTERVAL: "100000",
|
||||
TEST_HOME: tmpDirName,
|
||||
LATEST_VERSION: "1.30.0",
|
||||
},
|
||||
stderr: "piped",
|
||||
stdout: "piped",
|
||||
}).output();
|
||||
|
||||
const { stdout } = getStdOutput(out);
|
||||
expect(stdout).not.toMatch(/fetching latest version/);
|
||||
});
|
||||
|
||||
await t.step("fetches if interval has passed", async () => {
|
||||
const out = await new Deno.Command(Deno.execPath(), {
|
||||
args: [
|
||||
"run",
|
||||
"-A",
|
||||
path.join(cwd, "../../tests/fixture_update_check/mod.ts"),
|
||||
],
|
||||
cwd,
|
||||
env: {
|
||||
CI: "false",
|
||||
UPDATE_INTERVAL: "1 ",
|
||||
TEST_HOME: tmpDirName,
|
||||
LATEST_VERSION: "1.30.0",
|
||||
},
|
||||
}).output();
|
||||
|
||||
const { stdout } = getStdOutput(out);
|
||||
expect(stdout).toMatch(/fetching latest version/);
|
||||
});
|
||||
|
||||
await Deno.remove(tmpDirName, { recursive: true });
|
||||
});
|
||||
|
||||
Deno.test("updates current version in cache file", async () => {
|
||||
const tmpDirName = await Deno.makeTempDir();
|
||||
|
||||
const checkFile: CheckFile = {
|
||||
current_version: "1.2.0",
|
||||
latest_version: "1.2.0",
|
||||
last_checked: new Date(Date.now() - WEEK).toISOString(),
|
||||
};
|
||||
|
||||
await Deno.writeTextFile(
|
||||
path.join(tmpDirName, "latest.json"),
|
||||
JSON.stringify(checkFile, null, 2),
|
||||
);
|
||||
|
||||
const out = await new Deno.Command(Deno.execPath(), {
|
||||
args: [
|
||||
"run",
|
||||
"-A",
|
||||
path.join(cwd, "../../tests/fixture_update_check/mod.ts"),
|
||||
],
|
||||
cwd,
|
||||
env: {
|
||||
CI: "false",
|
||||
TEST_HOME: tmpDirName,
|
||||
LATEST_VERSION: CURRENT_VERSION,
|
||||
},
|
||||
stderr: "piped",
|
||||
stdout: "piped",
|
||||
}).output();
|
||||
|
||||
const { stdout } = getStdOutput(out);
|
||||
expect(stdout).not.toMatch(/Fresh .* is available/);
|
||||
|
||||
await Deno.remove(tmpDirName, { recursive: true });
|
||||
});
|
||||
|
||||
Deno.test("only shows update message when current < latest", async () => {
|
||||
const tmpDirName = await Deno.makeTempDir();
|
||||
|
||||
const checkFile: CheckFile = {
|
||||
current_version: "9999.999.0",
|
||||
latest_version: "1.2.0",
|
||||
last_checked: new Date().toISOString(),
|
||||
};
|
||||
|
||||
await Deno.writeTextFile(
|
||||
path.join(tmpDirName, "latest.json"),
|
||||
JSON.stringify(checkFile, null, 2),
|
||||
);
|
||||
|
||||
const out = await new Deno.Command(Deno.execPath(), {
|
||||
args: [
|
||||
"run",
|
||||
"-A",
|
||||
path.join(cwd, "../../tests/fixture_update_check/mod.ts"),
|
||||
],
|
||||
cwd,
|
||||
env: {
|
||||
CI: "false",
|
||||
TEST_HOME: tmpDirName,
|
||||
LATEST_VERSION: CURRENT_VERSION,
|
||||
CURRENT_VERSION: "99999.9999.0",
|
||||
},
|
||||
stderr: "piped",
|
||||
stdout: "piped",
|
||||
}).output();
|
||||
|
||||
const { stdout } = getStdOutput(out);
|
||||
expect(stdout).not.toMatch(/Fresh .* is available/);
|
||||
|
||||
await Deno.remove(tmpDirName, { recursive: true });
|
||||
});
|
||||
|
||||
Deno.test("migrates to last_shown property", async () => {
|
||||
const tmpDirName = await Deno.makeTempDir();
|
||||
|
||||
const checkFile: CheckFile = {
|
||||
latest_version: "1.4.0",
|
||||
current_version: "1.2.0",
|
||||
last_checked: new Date().toISOString(),
|
||||
};
|
||||
|
||||
await Deno.writeTextFile(
|
||||
path.join(tmpDirName, "latest.json"),
|
||||
JSON.stringify(checkFile, null, 2),
|
||||
);
|
||||
|
||||
const out = await new Deno.Command(Deno.execPath(), {
|
||||
args: [
|
||||
"run",
|
||||
"-A",
|
||||
path.join(cwd, "../../tests/fixture_update_check/mod.ts"),
|
||||
],
|
||||
cwd,
|
||||
env: {
|
||||
CI: "false",
|
||||
TEST_HOME: tmpDirName,
|
||||
CURRENT_VERSION: "1.2.0",
|
||||
LATEST_VERSION: "99999.9999.0",
|
||||
},
|
||||
stderr: "piped",
|
||||
stdout: "piped",
|
||||
}).output();
|
||||
|
||||
const { stdout } = getStdOutput(out);
|
||||
expect(stdout).toMatch(/Fresh .* is available/);
|
||||
|
||||
const checkFileAfter = JSON.parse(
|
||||
await Deno.readTextFile(
|
||||
path.join(tmpDirName, "latest.json"),
|
||||
),
|
||||
);
|
||||
|
||||
// Check if last version was written
|
||||
expect(typeof checkFileAfter.last_shown).toEqual("string");
|
||||
|
||||
await Deno.remove(tmpDirName, { recursive: true });
|
||||
});
|
||||
|
||||
Deno.test("doesn't show update if last_shown + interval >= today", async () => {
|
||||
const tmpDirName = await Deno.makeTempDir();
|
||||
|
||||
const todayMinus1Hour = new Date();
|
||||
todayMinus1Hour.setHours(todayMinus1Hour.getHours() - 1);
|
||||
|
||||
const checkFile: CheckFile = {
|
||||
current_version: "1.2.0",
|
||||
latest_version: "1.6.0",
|
||||
last_checked: new Date().toISOString(),
|
||||
last_shown: todayMinus1Hour.toISOString(),
|
||||
};
|
||||
|
||||
await Deno.writeTextFile(
|
||||
path.join(tmpDirName, "latest.json"),
|
||||
JSON.stringify(checkFile, null, 2),
|
||||
);
|
||||
|
||||
const out = await new Deno.Command(Deno.execPath(), {
|
||||
args: [
|
||||
"run",
|
||||
"-A",
|
||||
path.join(cwd, "../../tests/fixture_update_check/mod.ts"),
|
||||
],
|
||||
cwd,
|
||||
env: {
|
||||
CI: "false",
|
||||
TEST_HOME: tmpDirName,
|
||||
CURRENT_VERSION: "1.2.0",
|
||||
LATEST_VERSION: "99999.9999.0",
|
||||
},
|
||||
stderr: "piped",
|
||||
stdout: "piped",
|
||||
}).output();
|
||||
|
||||
const { stdout } = getStdOutput(out);
|
||||
expect(stdout).not.toMatch(/Fresh .* is available/);
|
||||
|
||||
await Deno.remove(tmpDirName, { recursive: true });
|
||||
});
|
||||
|
||||
Deno.test(
|
||||
"shows update if last_shown + interval < today",
|
||||
async () => {
|
||||
const tmpDirName = await Deno.makeTempDir();
|
||||
|
||||
const yesterday = new Date();
|
||||
yesterday.setDate(yesterday.getDate() - 1);
|
||||
|
||||
const checkFile: CheckFile = {
|
||||
current_version: "1.2.0",
|
||||
latest_version: "99.999.99",
|
||||
last_checked: new Date().toISOString(),
|
||||
last_shown: yesterday.toISOString(),
|
||||
};
|
||||
|
||||
await Deno.writeTextFile(
|
||||
path.join(tmpDirName, "latest.json"),
|
||||
JSON.stringify(checkFile, null, 2),
|
||||
);
|
||||
|
||||
const out = await new Deno.Command(Deno.execPath(), {
|
||||
args: [
|
||||
"run",
|
||||
"-A",
|
||||
path.join(cwd, "../../tests/fixture_update_check/mod.ts"),
|
||||
],
|
||||
cwd,
|
||||
env: {
|
||||
CI: "false",
|
||||
TEST_HOME: tmpDirName,
|
||||
CURRENT_VERSION: CURRENT_VERSION,
|
||||
LATEST_VERSION: "99999.9999.0",
|
||||
},
|
||||
stderr: "piped",
|
||||
stdout: "piped",
|
||||
}).output();
|
||||
|
||||
const { stdout } = getStdOutput(out);
|
||||
expect(stdout).toMatch(/Fresh .* is available/);
|
||||
|
||||
const checkFileAfter = JSON.parse(
|
||||
await Deno.readTextFile(
|
||||
path.join(tmpDirName, "latest.json"),
|
||||
),
|
||||
);
|
||||
|
||||
expect(checkFileAfter.last_shown).not.toEqual(yesterday.toISOString());
|
||||
|
||||
await Deno.remove(tmpDirName, { recursive: true });
|
||||
},
|
||||
);
|
||||
Reference in New Issue
Block a user