fix: browser not reloaded when no island present (#1956)

This commit is contained in:
Marvin Hagemeister
2023-10-18 11:16:51 +02:00
committed by GitHub
parent 3ad39dbf40
commit b984da9113
15 changed files with 239 additions and 19 deletions
+5 -4
View File
@@ -10,10 +10,11 @@ export { escape as regexpEscape } from "https://deno.land/std@0.193.0/regexp/esc
import * as esbuildWasm from "https://deno.land/x/esbuild@v0.19.4/wasm.js";
import * as esbuildNative from "https://deno.land/x/esbuild@v0.19.4/mod.js";
// @ts-ignore trust me
// deno-lint-ignore no-deprecated-deno-api
const esbuild: typeof esbuildWasm = Deno.run === undefined
? esbuildWasm
: esbuildNative;
const esbuild: typeof esbuildWasm =
// deno-lint-ignore no-deprecated-deno-api
Deno.run === undefined || Deno.env.get("FRESH_ESBUILD_LOADER") === "portable"
? esbuildWasm
: esbuildNative;
const esbuildWasmURL = new URL("./esbuild_v0.19.4.wasm", import.meta.url).href;
export { esbuild, esbuildWasm as esbuildTypes, esbuildWasmURL };
-1
View File
@@ -1,3 +1,2 @@
import "preact/debug";
import "../client.ts";
export * from "./main.ts";
+1
View File
@@ -1,6 +1,7 @@
import { INTERNAL_PREFIX } from "../runtime/utils.ts";
import { BUILD_ID } from "./build_id.ts";
export const DEV_CLIENT_URL = `${INTERNAL_PREFIX}/fresh_dev_client.js`;
export const ALIVE_URL = `${INTERNAL_PREFIX}/alive`;
export const JS_PREFIX = `/js`;
export const DEBUG = !Deno.env.get("DENO_DEPLOYMENT_ID");
+21 -14
View File
@@ -10,7 +10,7 @@ import {
import { ComponentType, h } from "preact";
import * as router from "./router.ts";
import { FreshConfig, Manifest } from "./mod.ts";
import { ALIVE_URL, JS_PREFIX } from "./constants.ts";
import { ALIVE_URL, DEV_CLIENT_URL, JS_PREFIX } from "./constants.ts";
import { BUILD_ID, setBuildId } from "./build_id.ts";
import DefaultErrorHandler from "./default_error_page.tsx";
import {
@@ -490,6 +490,7 @@ export class ServerContext {
);
const trailingSlashEnabled = this.#routerOptions?.trailingSlash;
const isDev = this.#dev;
const bundleAssetRoute = this.#bundleAssetRoute();
return async function handler(
req: Request,
@@ -497,20 +498,24 @@ export class ServerContext {
) {
const url = new URL(req.url);
// Live reload: Send updates to browser
if (isDev && url.pathname === ALIVE_URL) {
if (req.headers.get("upgrade") !== "websocket") {
return new Response(null, { status: 501 });
if (isDev) {
// Live reload: Send updates to browser
if (url.pathname === ALIVE_URL) {
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 } = Deno.upgradeWebSocket(req);
return response;
} else if (url.pathname === DEV_CLIENT_URL) {
return bundleAssetRoute(req, connInfo, { path: "client.js" });
}
// 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 } = Deno.upgradeWebSocket(req);
return response;
}
// Redirect requests that end with a trailing slash to their non-trailing
@@ -771,6 +776,7 @@ export class ServerContext {
status: number,
) => {
const imports: string[] = [];
if (this.#dev) imports.push(DEV_CLIENT_URL);
return (
req: Request,
params: Record<string, string>,
@@ -1296,6 +1302,7 @@ function collectEntrypoints(
? import.meta.resolve(`${entrypointBase}/main_dev.ts`)
: import.meta.resolve(`${entrypointBase}/main.ts`),
deserializer: import.meta.resolve(`${entrypointBase}/deserializer.ts`),
client: import.meta.resolve(`${entrypointBase}/client.ts`),
};
try {
+1
View File
@@ -37,4 +37,5 @@ export {
dirname,
fromFileUrl,
join,
relative,
} from "https://deno.land/std@0.193.0/path/mod.ts";
+15
View File
@@ -0,0 +1,15 @@
{
"lock": false,
"imports": {
"$fresh/": "../../",
"preact": "https://esm.sh/preact@10.15.1",
"preact/": "https://esm.sh/preact@10.15.1/",
"preact-render-to-string": "https://esm.sh/*preact-render-to-string@6.2.1",
"@preact/signals": "https://esm.sh/*@preact/signals@1.1.5",
"@preact/signals-core": "https://esm.sh/@preact/signals-core@1.3.1"
},
"compilerOptions": {
"jsx": "react-jsx",
"jsxImportSource": "preact"
}
}
+5
View File
@@ -0,0 +1,5 @@
#!/usr/bin/env -S deno run -A --watch=static/,routes/
import dev from "$fresh/dev.ts";
await dev(import.meta.url, "./main.ts");
+22
View File
@@ -0,0 +1,22 @@
// 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`.
import * as $0 from "./routes/index.tsx";
import * as $1 from "./routes/island.tsx";
import * as $2 from "./routes/no_island.tsx";
import * as $$0 from "./islands/Counter.tsx";
const manifest = {
routes: {
"./routes/index.tsx": $0,
"./routes/island.tsx": $1,
"./routes/no_island.tsx": $2,
},
islands: {
"./islands/Counter.tsx": $$0,
},
baseUrl: import.meta.url,
};
export default manifest;
+12
View File
@@ -0,0 +1,12 @@
import { useSignal } from "@preact/signals";
export default function Counter() {
const sig = useSignal(0);
return (
<div class="counter">
<p>{sig}</p>
<button onClick={() => sig.value++}>update</button>
</div>
);
}
+10
View File
@@ -0,0 +1,10 @@
/// <reference no-default-lib="true" />
/// <reference lib="dom" />
/// <reference lib="dom.iterable" />
/// <reference lib="dom.asynciterable" />
/// <reference lib="deno.ns" />
import { start } from "$fresh/server.ts";
import manifest from "./fresh.gen.ts";
await start(manifest);
+27
View File
@@ -0,0 +1,27 @@
import * as path from "https://deno.land/std@0.192.0/path/mod.ts";
const __dirname = path.dirname(path.fromFileUrl(import.meta.url));
const links: string[] = [];
for (const file of Deno.readDirSync(__dirname)) {
if (file.name.startsWith("index")) continue;
const name = path.basename(file.name, path.extname(file.name));
links.push(name);
}
export default function Home() {
return (
<div>
<h1>Tests</h1>
<ul>
{links.sort().map((link) => {
return (
<li key={link}>
<a href={`/${link}`}>{link}</a>
</li>
);
})}
</ul>
</div>
);
}
+10
View File
@@ -0,0 +1,10 @@
import Counter from "../islands/Counter.tsx";
export default function Home() {
return (
<div class="foo">
<h1>foo</h1>
<Counter />
</div>
);
}
+3
View File
@@ -0,0 +1,3 @@
export default function Home() {
return <h1 class="foo">foo</h1>;
}
+107
View File
@@ -0,0 +1,107 @@
import { copy } from "https://deno.land/std@0.204.0/fs/copy.ts";
import {
basename,
delay,
dirname,
join,
Page,
puppeteer,
relative,
} from "./deps.ts";
import { startFreshServer } from "./test_utils.ts";
import { retry } from "$std/async/retry.ts";
async function withTmpFixture(
name: string,
fn: (page: Page, address: string, dir: string) => Promise<void>,
) {
const tmp = join(await Deno.makeTempDir(), "project");
const src = join(Deno.cwd(), dirname(name));
await copy(src, tmp);
// Update Fresh path
const denoJsonPath = join(tmp, "deno.json");
const json = JSON.parse(await Deno.readTextFile(denoJsonPath));
json.imports["$fresh/"] = relative(denoJsonPath, Deno.cwd()) + "/";
await Deno.writeTextFile(denoJsonPath, JSON.stringify(json, null, 2));
// Watcher tests tend to be flaky
await retry(async () => {
const { lines, serverProcess, address } = await startFreshServer({
args: ["run", "-A", "--watch", join(tmp, basename(name))],
env: {
"FRESH_ESBUILD_LOADER": "portable",
},
});
try {
await delay(100);
const browser = await puppeteer.launch({ args: ["--no-sandbox"] });
try {
const page = await browser.newPage();
await fn(page, address, tmp);
} finally {
await browser.close();
}
} finally {
serverProcess.kill("SIGTERM");
// Wait until the process exits
await serverProcess.status;
// Drain the lines stream
for await (const _ of lines) { /* noop */ }
}
}, { maxAttempts: 3 });
}
Deno.test({
name: "page reloads with no island present",
// Watcher tests are pretty flaky in CI and non-UNIX systems.
// Until we know why, we'll gate these tests behind an
// environment variable.
ignore: !Deno.env.has("FRESH_WATCH_TESTS"),
fn: async () => {
await withTmpFixture(
"./tests/fixture_hmr/dev.ts",
async (page, address, dir) => {
await page.goto(`${address}/no_island`);
await page.waitForSelector("h1");
// Trigger file change
const file = join(dir, "routes", "no_island.tsx");
const text = await Deno.readTextFile(file);
await Deno.writeTextFile(file, text.replaceAll("foo", "bar"));
await page.waitForSelector(".bar");
},
);
},
});
Deno.test({
name: "page reloads with island",
// Watcher tests are pretty flaky in CI and non-UNIX systems.
// Until we know why, we'll gate these tests behind an
// environment variable.
ignore: !Deno.env.has("FRESH_WATCH_TESTS"),
fn: async () => {
await withTmpFixture(
"./tests/fixture_hmr/dev.ts",
async (page, address, dir) => {
await page.goto(`${address}/island`);
await page.waitForSelector("h1");
// Trigger file change
const file = join(dir, "routes", "island.tsx");
const text = await Deno.readTextFile(file);
await Deno.writeTextFile(file, text.replaceAll("foo", "bar"));
await page.waitForSelector(".bar");
// TODO: Once we support proper HMR check that state stays
// the same
},
);
},
});