test(docs): type check docs code examples (#3180)

This PR adds the initial seeds of type checking the code in all code
blocks for the Markdown Docs.

- Adds a unit test, disabled due to the many remaining errors, that can
help find incorrect code
- Fixes a bunch of syntax errors, type errors, and other code issues
found in the docs

## Future improvements

A lot of remaining issues is mostly related to missing imports, e.g.
`App`, `staticFiles`, `HttpError` etc. There's a couple of different
directions to solve this in future PR's.

- Add explicit imports to all docs examples (may become unnecessarily
verbose)
- Add code to docs code blocks, but with a hint to remove it when
rendering the markdown as HTML
   ```tsx
   import { App } from "fresh";
   // #docs-start

   // Everything above marker above is trimmed away
   const app = new App();
   ```
- Add a `types.d.ts` with "global" types used during type checking, so
globals, imports and so on can be handled globally

I do think that some examples probably should be more explicit with
imports, but it would be overkill for a lot of places such as `app.md`
and `context.md`.
This commit is contained in:
Christian Svensson
2025-08-05 23:56:04 +02:00
committed by GitHub
parent e014d80a0f
commit b7f1abb0d0
13 changed files with 142 additions and 24 deletions
+4 -4
View File
@@ -20,7 +20,7 @@ app.listen();
All items are applied from top to bottom. This means that when you defined a All items are applied from top to bottom. This means that when you defined a
middleware _after_ a `.get()` handler, it won't be included. middleware _after_ a `.get()` handler, it won't be included.
```ts main.ts ```tsx main.tsx
const app = new App() const app = new App()
.use((ctx) => { .use((ctx) => {
// Will be called for all middlewares // Will be called for all middlewares
@@ -278,9 +278,9 @@ Setting a middleware:
```ts ```ts
// top level error handler // top level error handler
app.onError("*", ctx => { app.onError("*", (ctx) => {
return new Response(String(ctx.error), { status: 500 }) return new Response(String(ctx.error), { status: 500 });
})) });
``` ```
Setting a route: Setting a route:
+1 -1
View File
@@ -28,7 +28,7 @@ app.get("/", (ctx) => {
console.log("path: ", ctx.url.pathname); console.log("path: ", ctx.url.pathname);
const hasParam = ctx.url.searchParams.has("q"); const hasParam = ctx.url.searchParams.has("q");
return new Response(`Has q param: ${String(hasParam)}); return new Response(`Has q param: ${hasParam}`);
}); });
``` ```
+1 -1
View File
@@ -25,7 +25,7 @@ if (Deno.args.includes("build")) {
```ts main.ts ```ts main.ts
import { App, staticFiles } from "fresh"; import { App, staticFiles } from "fresh";
const app = new App({ root: import.meta.url }) const app = new App({ basePath: "/foo" })
.use(staticFiles()) .use(staticFiles())
.fsRoutes(); // This inserts all file based routes here .fsRoutes(); // This inserts all file based routes here
``` ```
+5 -1
View File
@@ -29,7 +29,7 @@ An island can be used anywhere like a regular Preact component. Fresh will take
care of making it interactive on the client. care of making it interactive on the client.
```tsx main.tsx ```tsx main.tsx
import MyIsland from "../islands/my-island.tsx"; import MyIsland from "./islands/my-island.tsx";
const app = new App() const app = new App()
.get("/", (ctx) => ctx.render(<MyIsland />)); .get("/", (ctx) => ctx.render(<MyIsland />));
@@ -94,6 +94,10 @@ In essence, Fresh allows you to mix static and interactive parts in your app in
a way that's most optimal for your app. We'll keep sending only the JavaScript a way that's most optimal for your app. We'll keep sending only the JavaScript
that is needed for the islands to the browser. that is needed for the islands to the browser.
```tsx islands/other-island.tsx
export default (props: { foo: string }) => <>{props.foo}</>;
```
```tsx route/index.tsx ```tsx route/index.tsx
import MyIsland from "../islands/my-island.tsx"; import MyIsland from "../islands/my-island.tsx";
import OtherIsland from "../islands/other-island.tsx"; import OtherIsland from "../islands/other-island.tsx";
+1 -1
View File
@@ -80,7 +80,7 @@ const middleware1 = define.middleware(async (ctx) => {
return await ctx.next(); return await ctx.next();
}); });
const middleware1 = define.middleware(async (ctx) => { const middleware2 = define.middleware(async (ctx) => {
console.log("B"); console.log("B");
return await ctx.next(); return await ctx.next();
}); });
+7 -7
View File
@@ -10,21 +10,21 @@ request.
const app = new App() const app = new App()
.get("/", () => new Response("hello")) // Responds to: GET / .get("/", () => new Response("hello")) // Responds to: GET /
.get("/other", () => new Response("other")) // Responds to: GET /other .get("/other", () => new Response("other")) // Responds to: GET /other
.post("/upload", () => new Response("upload")); // Responds to: POST /upload .post("/upload", () => new Response("upload")) // Responds to: POST /upload
.get("/books/:id", (ctx) => { .get("/books/:id", (ctx) => {
// Responds to: GET /books/my-book, /books/cool-book, etc // Responds to: GET /books/my-book, /books/cool-book, etc
const id = ctx.params.id const id = ctx.params.id;
return new Response(`Book id: ${id}`)); return new Response(`Book id: ${id}`);
}) })
.get("/blog/:post/comments", () => { .get("/blog/:post/comments", () => {
// Responds to: GET /blog/my-post/comments, /blog/hello/comments, etc // Responds to: GET /blog/my-post/comments, /blog/hello/comments, etc
const post = ctx.params.post const post = ctx.params.post;
return new Response(`Blog post comments for post: ${post}`) return new Response(`Blog post comments for post: ${post}`);
}) })
.get("/foo/*", (ctx) => { .get("/foo/*", (ctx) => {
// Responds to: GET /foo/bar, /foo/bar/baz, etc // Responds to: GET /foo/bar, /foo/bar/baz, etc
return new Response("foo")); return new Response("foo");
}) });
``` ```
Fresh supports the full Fresh supports the full
+2 -1
View File
@@ -252,9 +252,10 @@ function testApp() {
.get("/", () => new Response("hello")); .get("/", () => new Response("hello"));
// Applies build snapshot to this app instance. // Applies build snapshot to this app instance.
applySnapshot(app); applySnapshot(app);
return app;
} }
Deno.test("My Test", () => { Deno.test("My Test", async () => {
const handler = testApp().handler(); const handler = testApp().handler();
const response = await handler(new Request("http://localhost")); const response = await handler(new Request("http://localhost"));
+2 -2
View File
@@ -13,8 +13,8 @@ web applications.
import { App } from "fresh"; import { App } from "fresh";
const app = new App() const app = new App()
.get("/", () => new Response("hello world")); .get("/", () => new Response("hello world"))
.get("/jsx", ctx => ctx.render(<h1>render JSX!</h1>)); .get("/jsx", (ctx) => ctx.render(<h1>render JSX!</h1>));
app.listen(); app.listen();
``` ```
+2
View File
@@ -14,6 +14,8 @@ header. to HTTP requests. These allow the server to indicate which origins
from. from.
```ts main.ts ```ts main.ts
import { app, csrf } from "fresh";
const app = new App(); const app = new App();
app.use(csrf()); app.use(csrf());
+1 -1
View File
@@ -60,7 +60,7 @@ decided on your own when it's best to update to v4.
```ts dev.ts ```ts dev.ts
import { Builder } from "fresh/dev"; import { Builder } from "fresh/dev";
import { tailwind } from "@fresh/plugin-tailwindcss-v3"; import { tailwind } from "@fresh/plugin-tailwind-v3";
tailwind(builder, {}); tailwind(builder, {});
``` ```
+3 -2
View File
@@ -19,7 +19,7 @@ import { App } from "fresh";
const middleware = define.middleware((ctx) => { const middleware = define.middleware((ctx) => {
ctx.state.text = "middleware text"; ctx.state.text = "middleware text";
return await ctx.next(); return ctx.next();
}); });
Deno.test("My middleware - sets ctx.state.text", async () => { Deno.test("My middleware - sets ctx.state.text", async () => {
@@ -124,9 +124,10 @@ function testApp() {
// Applies build snapshot to this app instance. // Applies build snapshot to this app instance.
applySnapshot(app); applySnapshot(app);
return app;
} }
Deno.test("My Test", () => { Deno.test("My Test", async () => {
const handler = testApp().handler(); const handler = testApp().handler();
const response = await handler(new Request("http://localhost")); const response = await handler(new Request("http://localhost"));
+109
View File
@@ -0,0 +1,109 @@
import twDenoJson from "../plugin-tailwindcss/deno.json" with { type: "json" };
import * as Marked from "marked";
import { ensureDir, walk } from "@std/fs";
import { dirname, join, relative } from "@std/path";
// import { expect } from "@std/expect/expect";
import { withTmpDir } from "../src/test_utils.ts";
import { FRESH_VERSION, PREACT_VERSION } from "../update/src/update.ts";
Deno.test("Docs Code example checks", async () => {
await using tmp = await withTmpDir();
for await (const { path, code } of docsMarkdownFiles()) {
const codePath = join(tmp.dir, path);
await ensureDir(dirname(codePath));
await Deno.writeTextFile(codePath, code);
}
const denoJson = {
lock: false,
imports: {
fresh: `jsr:@fresh/core@${FRESH_VERSION}`,
"@fresh/plugin-tailwind-v3":
`jsr:@fresh/plugin-tailwind@^${twDenoJson.version}`,
"@fresh/plugin-tailwind":
`jsr:@fresh/plugin-tailwind@^${twDenoJson.version}`,
preact: `npm:preact@^${PREACT_VERSION}`,
"@deno/gfm": "jsr:@deno/gfm@^0.11.0",
"@std/expect": "jsr:@std/expect@^1.0.16",
},
compilerOptions: {
lib: ["dom", "dom.asynciterable", "deno.ns", "deno.unstable"],
jsx: "precompile",
jsxImportSource: "preact",
jsxPrecompileSkipElements: ["a", "img", "source", "body", "html", "head"],
},
};
await Deno.writeTextFile(
join(tmp.dir, "deno.json"),
JSON.stringify(denoJson, undefined, 2),
);
// Download and cache all dependencies (reduces `stdout` noise)
await new Deno.Command(Deno.execPath(), {
args: ["cache", "**/*"],
cwd: tmp.dir,
}).output();
const { stdout, stderr } = await new Deno.Command(Deno.execPath(), {
args: ["check", "**/*"],
cwd: tmp.dir,
}).output();
const decoder = new TextDecoder();
const output = `${decoder.decode(stdout)}\n${decoder.decode(stderr)}`;
// Log `deno check` output (can be removed if expects below are enabled)
// deno-lint-ignore no-console
console.log(output);
// TODO: Enable after fixing docs check issues
// expect(code).toBe(0);
// expect(output).toBe("");
});
async function* docsMarkdownFiles() {
// Limit to checking Fresh v2 (canary) docs for now
const docsDir = join(import.meta.dirname!, "..", "docs", "canary");
const docsIter = walk(docsDir, { exts: [".md"], includeDirs: false });
for await (const entry of docsIter) {
for (const { file, code } of await extractTsCode(entry.path)) {
const path = join(relative(docsDir, entry.path), file);
yield { path, code };
}
}
}
async function extractTsCode(path: string) {
const code: { file: string; code: string }[] = [];
const input = await Deno.readTextFile(path);
let index = 0;
const tokens = await Marked.lexer(input, { gfm: true, async: true });
Marked.walkTokens(tokens, (token) => {
// Get rid of `Marked.Tokens.Generic`
const t = token as Marked.MarkedToken;
if (t.type !== "code") return;
const result = /^([tj]sx?)\s*/.exec(t.lang ?? "");
if (!result) return;
// Codeblock must be TS/JS
index += 1;
// Probably a filename, but perhaps a title,
// so get rid of non-file safe characters
const [match, ext] = result;
let file = t.lang!.slice(match.length)
.toLocaleLowerCase()
.replaceAll(/[^a-z0-9._\-\/\\]/g, "_")
.replaceAll(/_{2,}/g, "_") || String(index);
if (!file.endsWith(ext)) file += `.${ext}`;
code.push({ file, code: t.text });
});
return code;
}
+4 -3
View File
@@ -235,15 +235,16 @@ export function renderMarkdown(
opts: MarkdownOptions = {}, opts: MarkdownOptions = {},
): { headings: MarkdownHeading[]; html: string } { ): { headings: MarkdownHeading[]; html: string } {
const renderer = new DefaultRenderer(); const renderer = new DefaultRenderer();
const markedOpts: Marked.MarkedOptions = { const markedOpts: Marked.MarkedOptions & { async: false } = {
gfm: true, gfm: true,
async: false,
renderer, renderer,
}; };
try { try {
const html = opts.inline const html = opts.inline
? Marked.parseInline(input, markedOpts) as string ? Marked.parseInline(input, markedOpts)
: Marked.parse(input, markedOpts) as string; : Marked.parse(input, markedOpts);
return { headings: renderer.headings, html }; return { headings: renderer.headings, html };
} catch (err) { } catch (err) {