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:
@@ -20,7 +20,7 @@ app.listen();
|
||||
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.
|
||||
|
||||
```ts main.ts
|
||||
```tsx main.tsx
|
||||
const app = new App()
|
||||
.use((ctx) => {
|
||||
// Will be called for all middlewares
|
||||
@@ -278,9 +278,9 @@ Setting a middleware:
|
||||
|
||||
```ts
|
||||
// top level error handler
|
||||
app.onError("*", ctx => {
|
||||
return new Response(String(ctx.error), { status: 500 })
|
||||
}))
|
||||
app.onError("*", (ctx) => {
|
||||
return new Response(String(ctx.error), { status: 500 });
|
||||
});
|
||||
```
|
||||
|
||||
Setting a route:
|
||||
|
||||
@@ -28,7 +28,7 @@ app.get("/", (ctx) => {
|
||||
console.log("path: ", ctx.url.pathname);
|
||||
|
||||
const hasParam = ctx.url.searchParams.has("q");
|
||||
return new Response(`Has q param: ${String(hasParam)});
|
||||
return new Response(`Has q param: ${hasParam}`);
|
||||
});
|
||||
```
|
||||
|
||||
|
||||
@@ -25,7 +25,7 @@ if (Deno.args.includes("build")) {
|
||||
```ts main.ts
|
||||
import { App, staticFiles } from "fresh";
|
||||
|
||||
const app = new App({ root: import.meta.url })
|
||||
const app = new App({ basePath: "/foo" })
|
||||
.use(staticFiles())
|
||||
.fsRoutes(); // This inserts all file based routes here
|
||||
```
|
||||
|
||||
@@ -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.
|
||||
|
||||
```tsx main.tsx
|
||||
import MyIsland from "../islands/my-island.tsx";
|
||||
import MyIsland from "./islands/my-island.tsx";
|
||||
|
||||
const app = new App()
|
||||
.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
|
||||
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
|
||||
import MyIsland from "../islands/my-island.tsx";
|
||||
import OtherIsland from "../islands/other-island.tsx";
|
||||
|
||||
@@ -80,7 +80,7 @@ const middleware1 = define.middleware(async (ctx) => {
|
||||
return await ctx.next();
|
||||
});
|
||||
|
||||
const middleware1 = define.middleware(async (ctx) => {
|
||||
const middleware2 = define.middleware(async (ctx) => {
|
||||
console.log("B");
|
||||
return await ctx.next();
|
||||
});
|
||||
|
||||
@@ -10,21 +10,21 @@ request.
|
||||
const app = new App()
|
||||
.get("/", () => new Response("hello")) // Responds to: GET /
|
||||
.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) => {
|
||||
// Responds to: GET /books/my-book, /books/cool-book, etc
|
||||
const id = ctx.params.id
|
||||
return new Response(`Book id: ${id}`));
|
||||
const id = ctx.params.id;
|
||||
return new Response(`Book id: ${id}`);
|
||||
})
|
||||
.get("/blog/:post/comments", () => {
|
||||
// Responds to: GET /blog/my-post/comments, /blog/hello/comments, etc
|
||||
const post = ctx.params.post
|
||||
return new Response(`Blog post comments for post: ${post}`)
|
||||
const post = ctx.params.post;
|
||||
return new Response(`Blog post comments for post: ${post}`);
|
||||
})
|
||||
.get("/foo/*", (ctx) => {
|
||||
// Responds to: GET /foo/bar, /foo/bar/baz, etc
|
||||
return new Response("foo"));
|
||||
})
|
||||
return new Response("foo");
|
||||
});
|
||||
```
|
||||
|
||||
Fresh supports the full
|
||||
|
||||
@@ -252,9 +252,10 @@ function testApp() {
|
||||
.get("/", () => new Response("hello"));
|
||||
// Applies build snapshot to this app instance.
|
||||
applySnapshot(app);
|
||||
return app;
|
||||
}
|
||||
|
||||
Deno.test("My Test", () => {
|
||||
Deno.test("My Test", async () => {
|
||||
const handler = testApp().handler();
|
||||
|
||||
const response = await handler(new Request("http://localhost"));
|
||||
|
||||
@@ -13,8 +13,8 @@ web applications.
|
||||
import { App } from "fresh";
|
||||
|
||||
const app = new App()
|
||||
.get("/", () => new Response("hello world"));
|
||||
.get("/jsx", ctx => ctx.render(<h1>render JSX!</h1>));
|
||||
.get("/", () => new Response("hello world"))
|
||||
.get("/jsx", (ctx) => ctx.render(<h1>render JSX!</h1>));
|
||||
|
||||
app.listen();
|
||||
```
|
||||
|
||||
@@ -14,6 +14,8 @@ header. to HTTP requests. These allow the server to indicate which origins
|
||||
from.
|
||||
|
||||
```ts main.ts
|
||||
import { app, csrf } from "fresh";
|
||||
|
||||
const app = new App();
|
||||
|
||||
app.use(csrf());
|
||||
|
||||
@@ -60,7 +60,7 @@ decided on your own when it's best to update to v4.
|
||||
|
||||
```ts dev.ts
|
||||
import { Builder } from "fresh/dev";
|
||||
import { tailwind } from "@fresh/plugin-tailwindcss-v3";
|
||||
import { tailwind } from "@fresh/plugin-tailwind-v3";
|
||||
|
||||
tailwind(builder, {});
|
||||
```
|
||||
|
||||
@@ -19,7 +19,7 @@ import { App } from "fresh";
|
||||
|
||||
const middleware = define.middleware((ctx) => {
|
||||
ctx.state.text = "middleware text";
|
||||
return await ctx.next();
|
||||
return ctx.next();
|
||||
});
|
||||
|
||||
Deno.test("My middleware - sets ctx.state.text", async () => {
|
||||
@@ -124,9 +124,10 @@ function testApp() {
|
||||
|
||||
// Applies build snapshot to this app instance.
|
||||
applySnapshot(app);
|
||||
return app;
|
||||
}
|
||||
|
||||
Deno.test("My Test", () => {
|
||||
Deno.test("My Test", async () => {
|
||||
const handler = testApp().handler();
|
||||
|
||||
const response = await handler(new Request("http://localhost"));
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -235,15 +235,16 @@ export function renderMarkdown(
|
||||
opts: MarkdownOptions = {},
|
||||
): { headings: MarkdownHeading[]; html: string } {
|
||||
const renderer = new DefaultRenderer();
|
||||
const markedOpts: Marked.MarkedOptions = {
|
||||
const markedOpts: Marked.MarkedOptions & { async: false } = {
|
||||
gfm: true,
|
||||
async: false,
|
||||
renderer,
|
||||
};
|
||||
|
||||
try {
|
||||
const html = opts.inline
|
||||
? Marked.parseInline(input, markedOpts) as string
|
||||
: Marked.parse(input, markedOpts) as string;
|
||||
? Marked.parseInline(input, markedOpts)
|
||||
: Marked.parse(input, markedOpts);
|
||||
|
||||
return { headings: renderer.headings, html };
|
||||
} catch (err) {
|
||||
|
||||
Reference in New Issue
Block a user