feat: co-locate islands + non-route files (#1600)

This commit is contained in:
Marvin Hagemeister
2023-08-07 20:33:08 +02:00
committed by GitHub
parent d8211dad28
commit 97c6876bf7
9 changed files with 171 additions and 67 deletions
+5 -1
View File
@@ -13,7 +13,11 @@ export {
} from "https://deno.land/std@0.193.0/path/mod.ts";
export { DAY, WEEK } from "https://deno.land/std@0.193.0/datetime/constants.ts";
export * as colors from "https://deno.land/std@0.193.0/fmt/colors.ts";
export { walk, WalkError } from "https://deno.land/std@0.193.0/fs/walk.ts";
export {
walk,
type WalkEntry,
WalkError,
} from "https://deno.land/std@0.193.0/fs/walk.ts";
export { parse } from "https://deno.land/std@0.193.0/flags/mod.ts";
export { gte } from "https://deno.land/std@0.193.0/semver/mod.ts";
export { existsSync } from "https://deno.land/std@0.193.0/fs/mod.ts";
+49 -28
View File
@@ -8,6 +8,7 @@ import {
posix,
relative,
walk,
WalkEntry,
} from "./deps.ts";
import { error } from "./error.ts";
@@ -30,18 +31,19 @@ export function ensureMinDenoVersion() {
}
}
async function collectDir(dir: string): Promise<string[]> {
async function collectDir(
dir: string,
callback: (entry: WalkEntry, dir: string) => void,
): Promise<void> {
// Check if provided path is a directory
try {
const stat = await Deno.stat(dir);
if (!stat.isDirectory) return [];
if (!stat.isDirectory) return;
} catch (err) {
if (err instanceof Deno.errors.NotFound) return [];
if (err instanceof Deno.errors.NotFound) return;
throw err;
}
const paths = [];
const fileNames = new Set<string>();
const routesFolder = walk(dir, {
includeDirs: false,
includeFiles: true,
@@ -49,21 +51,8 @@ async function collectDir(dir: string): Promise<string[]> {
});
for await (const entry of routesFolder) {
const fileNameWithoutExt = relative(dir, entry.path).split(".").slice(0, -1)
.join(".");
if (fileNames.has(fileNameWithoutExt)) {
throw new Error(
`Route conflict detected. Multiple files have the same name: ${dir}${fileNameWithoutExt}`,
);
}
fileNames.add(fileNameWithoutExt);
paths.push(relative(dir, entry.path));
callback(entry, dir);
}
paths.sort();
return paths;
}
interface Manifest {
@@ -71,12 +60,46 @@ interface Manifest {
islands: string[];
}
const GROUP_REG = /[/\\\\]\((_[^/\\\\]+)\)[/\\\\]/;
export async function collect(directory: string): Promise<Manifest> {
const [routes, islands] = await Promise.all([
collectDir(join(directory, "./routes")),
collectDir(join(directory, "./islands")),
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") {
console.log(rel);
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);
}),
collectDir(join(directory, "./islands"), (entry, dir) => {
const rel = join("islands", relative(dir, entry.path));
islands.push(rel);
}),
]);
routes.sort();
islands.sort();
return { routes, islands };
}
@@ -100,14 +123,14 @@ export async function generate(directory: string, manifest: Manifest) {
${
routes.map((file, i) =>
`import * as $${i} from "${toImportSpecifier(join("routes", file))}";`
`import * as $${i} from "${toImportSpecifier(file)}";`
).join(
"\n",
)
}
${
islands.map((file, i) =>
`import * as $$${i} from "${toImportSpecifier(join("islands", file))}";`
`import * as $$${i} from "${toImportSpecifier(file)}";`
)
.join("\n")
}
@@ -116,7 +139,7 @@ const manifest = {
routes: {
${
routes.map((file, i) =>
`${JSON.stringify(`${toImportSpecifier(join("routes", file))}`)}: $${i},`
`${JSON.stringify(`${toImportSpecifier(file)}`)}: $${i},`
)
.join("\n ")
}
@@ -124,9 +147,7 @@ const manifest = {
islands: {
${
islands.map((file, i) =>
`${
JSON.stringify(`${toImportSpecifier(join("islands", file))}`)
}: $$${i},`
`${JSON.stringify(`${toImportSpecifier(file)}`)}: $$${i},`
)
.join("\n ")
}
+6 -3
View File
@@ -317,8 +317,11 @@ export class ServerContext {
if (!url.startsWith(baseUrl)) {
throw new TypeError("Island is not a child of the basepath.");
}
const path = url.substring(baseUrl.length).substring("islands".length);
const baseRoute = path.substring(1, path.length - extname(path).length);
let path = url.substring(baseUrl.length);
if (path.startsWith("islands")) {
path = path.slice("islands".length + 1);
}
const baseRoute = path.substring(0, path.length - extname(path).length);
for (const [exportName, exportedFunction] of Object.entries(module)) {
if (typeof exportedFunction !== "function") {
@@ -1154,7 +1157,7 @@ function toPascalCase(text: string): string {
}
function sanitizeIslandName(name: string): string {
const fileName = name.replaceAll("/", "_");
const fileName = name.replaceAll(/[/\\\\\(\)]/g, "_");
return toPascalCase(fileName);
}
+38 -34
View File
@@ -47,23 +47,24 @@ import * as $41 from "./routes/movies/[foo]@[bar].ts";
import * as $42 from "./routes/not_found.ts";
import * as $43 from "./routes/params.tsx";
import * as $44 from "./routes/props/[id].tsx";
import * as $45 from "./routes/route-groups/(bar)/(baz)/_layout.tsx";
import * as $46 from "./routes/route-groups/(bar)/(baz)/baz.tsx";
import * as $47 from "./routes/route-groups/(bar)/_layout.tsx";
import * as $48 from "./routes/route-groups/(bar)/bar.tsx";
import * as $49 from "./routes/route-groups/(bar)/boof/index.tsx";
import * as $50 from "./routes/route-groups/(foo)/_layout.tsx";
import * as $51 from "./routes/route-groups/(foo)/index.tsx";
import * as $52 from "./routes/signal_shared.tsx";
import * as $53 from "./routes/state-in-props/_middleware.ts";
import * as $54 from "./routes/state-in-props/index.tsx";
import * as $55 from "./routes/state-middleware/_middleware.ts";
import * as $56 from "./routes/state-middleware/foo/_middleware.ts";
import * as $57 from "./routes/state-middleware/foo/index.tsx";
import * as $58 from "./routes/static.tsx";
import * as $59 from "./routes/status_overwrite.tsx";
import * as $60 from "./routes/umlaut-äöüß.tsx";
import * as $61 from "./routes/wildcard.tsx";
import * as $45 from "./routes/route-groups-islands/index.tsx";
import * as $46 from "./routes/route-groups/(bar)/(baz)/_layout.tsx";
import * as $47 from "./routes/route-groups/(bar)/(baz)/baz.tsx";
import * as $48 from "./routes/route-groups/(bar)/_layout.tsx";
import * as $49 from "./routes/route-groups/(bar)/bar.tsx";
import * as $50 from "./routes/route-groups/(bar)/boof/index.tsx";
import * as $51 from "./routes/route-groups/(foo)/_layout.tsx";
import * as $52 from "./routes/route-groups/(foo)/index.tsx";
import * as $53 from "./routes/signal_shared.tsx";
import * as $54 from "./routes/state-in-props/_middleware.ts";
import * as $55 from "./routes/state-in-props/index.tsx";
import * as $56 from "./routes/state-middleware/_middleware.ts";
import * as $57 from "./routes/state-middleware/foo/_middleware.ts";
import * as $58 from "./routes/state-middleware/foo/index.tsx";
import * as $59 from "./routes/static.tsx";
import * as $60 from "./routes/status_overwrite.tsx";
import * as $61 from "./routes/umlaut-äöüß.tsx";
import * as $62 from "./routes/wildcard.tsx";
import * as $$0 from "./islands/Counter.tsx";
import * as $$1 from "./islands/MultipleCounters.tsx";
import * as $$2 from "./islands/ReturningNull.tsx";
@@ -74,6 +75,7 @@ import * as $$6 from "./islands/Test.tsx";
import * as $$7 from "./islands/folder/Counter.tsx";
import * as $$8 from "./islands/folder/subfolder/Counter.tsx";
import * as $$9 from "./islands/kebab-case-counter-test.tsx";
import * as $$10 from "./routes/route-groups-islands/(_islands)/Counter.tsx";
const manifest = {
routes: {
@@ -122,23 +124,24 @@ const manifest = {
"./routes/not_found.ts": $42,
"./routes/params.tsx": $43,
"./routes/props/[id].tsx": $44,
"./routes/route-groups/(bar)/(baz)/_layout.tsx": $45,
"./routes/route-groups/(bar)/(baz)/baz.tsx": $46,
"./routes/route-groups/(bar)/_layout.tsx": $47,
"./routes/route-groups/(bar)/bar.tsx": $48,
"./routes/route-groups/(bar)/boof/index.tsx": $49,
"./routes/route-groups/(foo)/_layout.tsx": $50,
"./routes/route-groups/(foo)/index.tsx": $51,
"./routes/signal_shared.tsx": $52,
"./routes/state-in-props/_middleware.ts": $53,
"./routes/state-in-props/index.tsx": $54,
"./routes/state-middleware/_middleware.ts": $55,
"./routes/state-middleware/foo/_middleware.ts": $56,
"./routes/state-middleware/foo/index.tsx": $57,
"./routes/static.tsx": $58,
"./routes/status_overwrite.tsx": $59,
"./routes/umlaut-äöüß.tsx": $60,
"./routes/wildcard.tsx": $61,
"./routes/route-groups-islands/index.tsx": $45,
"./routes/route-groups/(bar)/(baz)/_layout.tsx": $46,
"./routes/route-groups/(bar)/(baz)/baz.tsx": $47,
"./routes/route-groups/(bar)/_layout.tsx": $48,
"./routes/route-groups/(bar)/bar.tsx": $49,
"./routes/route-groups/(bar)/boof/index.tsx": $50,
"./routes/route-groups/(foo)/_layout.tsx": $51,
"./routes/route-groups/(foo)/index.tsx": $52,
"./routes/signal_shared.tsx": $53,
"./routes/state-in-props/_middleware.ts": $54,
"./routes/state-in-props/index.tsx": $55,
"./routes/state-middleware/_middleware.ts": $56,
"./routes/state-middleware/foo/_middleware.ts": $57,
"./routes/state-middleware/foo/index.tsx": $58,
"./routes/static.tsx": $59,
"./routes/status_overwrite.tsx": $60,
"./routes/umlaut-äöüß.tsx": $61,
"./routes/wildcard.tsx": $62,
},
islands: {
"./islands/Counter.tsx": $$0,
@@ -151,6 +154,7 @@ const manifest = {
"./islands/folder/Counter.tsx": $$7,
"./islands/folder/subfolder/Counter.tsx": $$8,
"./islands/kebab-case-counter-test.tsx": $$9,
"./routes/route-groups-islands/(_islands)/Counter.tsx": $$10,
},
baseUrl: import.meta.url,
};
@@ -0,0 +1,15 @@
import { useSignal } from "@preact/signals";
export default function Counter() {
const signal = useSignal(0);
return (
<div>
<p>{signal}</p>
<button
onClick={() => signal.value += 1}
>
+1
</button>
</div>
);
}
@@ -0,0 +1,3 @@
export default function InvalidPage() {
return <p>This should not be visible</p>;
}
@@ -0,0 +1,10 @@
import Counter from "./(_islands)/Counter.tsx";
export default function GroupPage() {
return (
<div>
<h1>Group page</h1>
<Counter />
</div>
);
}
@@ -0,0 +1,3 @@
export default function InvalidPage() {
return <p>This should not be visible</p>;
}
+42 -1
View File
@@ -1,4 +1,11 @@
import { assertTextMany, fetchHtml, withFresh } from "./test_utils.ts";
import { assertEquals } from "$std/testing/asserts.ts";
import {
assertTextMany,
fetchHtml,
waitForText,
withFresh,
withPageName,
} from "./test_utils.ts";
Deno.test("applies only _layout file of one group", async () => {
await withFresh(
@@ -30,3 +37,37 @@ Deno.test("applies only _layout files in parent groups #2", async () => {
},
);
});
Deno.test("can co-locate islands inside routes folder", async () => {
await withPageName(
"./tests/fixture/main.ts",
async (page, address) => {
await page.goto(`${address}/route-groups-islands/`);
await page.waitForSelector("button");
await page.click("button");
await waitForText(page, "p", "1");
},
);
});
Deno.test("does not treat files in (_islands) as routes", async () => {
await withFresh(
"./tests/fixture/main.ts",
async (address) => {
const res = await fetch(`${address}/route-groups-islands/invalid`);
assertEquals(res.status, 404);
res.body?.cancel();
},
);
});
Deno.test("does not treat files in (_...) as routes", async () => {
await withFresh(
"./tests/fixture/main.ts",
async (address) => {
const res = await fetch(`${address}/route-groups-islands/sub`);
assertEquals(res.status, 404);
res.body?.cancel();
},
);
});