GitHub 0
Skip to content

Extend whoasks with layers

A layer is a plain object that adds a form, renders a form from your own source, changes the pick or sets the HTML to Markdown converter.

A layer is a plain object. whoasks(...layers) merges the layers it gets. An integration is a function that returns a layer, and the app passes its result to whoasks(). There is no plugin type, no hook registry, and no lifecycle.

import { whoasks, type Layer } from "whoasks";

const layer: Layer = {}; // every slot is optional
const site = whoasks(layer);
ts
SlotTypeAnswers
formsRecord<string, Form>What can a request ask for
renderRecord<string, Render>Who makes this form for this URL, without asking the converter
ask(ask, request) => changeShould the pick change, within what the request allowed
convertConvert | falseHow HTML becomes Markdown
strictbooleanShould respond answer 406
  • forms: a later layer replaces a form with the same name, built-in forms included.
  • render: each form keeps its renderers in layer order. The first one that returns a body wins.
  • ask: every hook runs, in layer order. Each sees the pick as the hooks before it left it.
  • convert and strict: the last layer that sets one wins.
  • whoasks from "whoasks" puts { convert: mdream() } before your layers, so your convert replaces it. whoasks from "whoasks/core" starts with nothing.
import { whoasks, type Layer } from "whoasks";

export const yaml: Layer = {
  forms: { yaml: { types: ["application/yaml"], ext: ".yaml" } },
};

const site = whoasks(yaml);

export function route(request: Request): Promise<Response> {
  return site.respond(request, {
    json: { n: 1 },
    yaml: () => "n: 1\n",
  });
}
yaml.ts

The key in forms is the form's name. types are the media types that name it in Accept. A wildcard or a URL override sends the first one.

ext is optional. It makes a twin URL, and without its dot it is also a ?format= value.

On the route above, Accept: application/yaml and ?format=yaml get application/yaml. Accept: */* gets JSON, the first key.

whoasks does not serialize YAML. The value you give for yaml is a string. A form with a renderer is also offered on pages behind handle, as shown in the next section.

You can also add a form for error responses:

const problem: Layer = {
  forms: { problem: { types: ["application/problem+json"] } },
};

// In a route of whoasks(problem):
return site.respond(
  request,
  { problem: body, markdown: () => `failed validate. ${body.title}` },
  { status: 422 },
);
ts

The object under problem goes through JSON.stringify and is sent as application/problem+json.

A content source knows the Markdown a page was written in. A renderer returns it, so that page is not converted from HTML.

import { whoasks, type Layer, type WhoAsks } from "whoasks";

type Find = (path: string) => Promise<{ markdown: string } | undefined>;

// A content source answers for the pages it knows. Returning nothing lets the next renderer try.
export function contentMarkdown(find: Find): Layer {
  return {
    render: {
      markdown: async ({ ask }) => (await find(ask.url.pathname))?.markdown,
    },
  };
}

export function createSite(find: Find): WhoAsks {
  return whoasks(contentMarkdown(find));
}
content-layer.ts

find stands for the source's own lookup. It is not a real ViteHub Content function. The layer lives in the content package, not in whoasks.

Pages that find knows answer with their source Markdown. Every other page is still converted with mdream.

A renderer runs in handle only, for GET and HEAD, when the request picked its form. It receives { request, ask, next }:

FieldWhat it is
requestThe request as it arrived, twin URL included
askThe pick. ask.url is the canonical URL, ask.type the media type to send
next()The app's own response for ask.url. The app runs once however many renderers call it, and each call returns a fresh copy

A renderer returns a string, a Response, or nothing. null and undefined let the next renderer try, then the converter.

A string is sent with the picked type and Vary. A Response is sent as it is, plus Vary, so set its Content-Type from ask.type.

A form that has a renderer is offered on every page, after html and in layer order.

export function contentMarkdown(find: Find): Layer {
  return {
    render: {
      markdown: async ({ ask, next }) => {
        const page = await next();
        if (!page.ok) return undefined;
        return (await find(ask.url.pathname))?.markdown;
      },
    },
  };
}
ts

When the app answers 404 for the page, this renderer returns nothing, and the app's 404 page is converted and sent with its 404.

const cached: Layer = {
  render: {
    markdown: async ({ ask }) => {
      const source = await find(ask.url.pathname);
      if (!source) return undefined;
      return new Response(source.markdown, {
        headers: { "content-type": `${ask.type}; charset=utf-8`, "cache-control": "max-age=300" },
      });
    },
  },
};
ts

A hook runs after the rules. It gets the pick and the request, and returns the part it wants to change: form, type, vary, or nothing.

import { whoasks, type Layer } from "whoasks";

// Codex asks for Markdown with a browser-like Accept and rejects text/markdown. Send text/plain to it.
export const codexText: Layer = {
  ask(ask, request) {
    const codex = /ChatGPT-User\//.test(request.headers.get("user-agent") ?? "");
    if (codex && ask.form === "markdown") return { type: "text/plain", vary: ["User-Agent"] };
  },
};

const site = whoasks(codexText);
codex.ts

With this layer, a ChatGPT-User request that picks Markdown gets it as text/plain; charset=utf-8, with Vary: Accept, User-Agent. ask.reason becomes layer.

It names User-Agent in vary so a cache keeps the two answers apart. See Codex and twin URLs for why.

ReturnedKept when
formThe form is offered and the request permits one of its types. After a twin or ?format=, only the forced form is offered
typeIt is one of the form's types and the request permits it
form aloneThe type is then chosen by rule 5
varyAlways. The entries are appended
NothingThe pick stays

A change the request did not allow is dropped, so a hook cannot send a type the client refused. With Accept: text/html, text/markdown;q=0, a hook that returns { form: "markdown" } changes nothing.

A hook that returns the pick it already has leaves reason alone. A hook that returns nothing is a place to log:

const log: Layer = {
  ask(ask, request) {
    console.log(ask.reason, ask.form, new URL(request.url).pathname);
  },
};
ts
whoasks({ convert: false }); // no HTML to Markdown
whoasks({ strict: true }); // 406 from respond
ts

See Change the converter and Refuse with 406.

handle returns a Response, so a wrapper can add to it. site.ask(request) tells the wrapper what was picked.

import { whoasks } from "whoasks";

const site = whoasks();

// Tell people's browsers and crawlers where the Markdown twin is.
export async function withAlternate(
  request: Request,
  app: (request: Request) => Response | Promise<Response>,
): Promise<Response> {
  const response = await site.handle(request, app);
  const ask = site.ask(request);
  if (ask.form !== "html") return response;
  const path = ask.url.pathname;
  const twin = path.endsWith("/") ? `${path}index.md` : `${path}.md`;
  const copy = new Response(response.body, response);
  copy.headers.append("link", `<${twin}>; rel="alternate"; type="text/markdown"`);
  return copy;
}
alternate.ts

/docs/guide gets Link: </docs/guide.md>; rel="alternate"; type="text/markdown", and / gets </index.md>.

A request that picked Markdown gets no Link header.

This wrapper adds the header to every response of a request that picked HTML, images included. Check the response's Content-Type if you want pages only.

A generator for llms.txt or a full-text file walks its own list of pages and asks handle for each twin.

const origin = "https://example.com";
const pages = ["/docs/guide", "/docs/api"]; // your own page list
const parts: string[] = [];
for (const path of pages) {
  const response = await site.handle(new Request(origin + path + ".md"), app);
  parts.push(await response.text());
}
const full = parts.join("\n\n");
build-llms.ts

site is your site and app is the function you pass to handle as next.

whoasks has no page list and writes no file. Serving the result is a normal route in your app.

Left outHow to build it
Adapters for Hono, Next, SvelteKit, Astro, Node httpEach is site.handle(request, next) with that framework's request and next. Installation has Hono and Workers
A Nuxt moduleA Nitro middleware from whoasks/h3, plus a render.markdown layer from the content module
An agent text format, a size budgetA markdown value passed to respond
llms.txt, sitemap.mdA generator, as in the section above
A User-Agent registryA hook, as in Change the pick. It sets Vary: User-Agent itself
problem+json errorsA status in respond's init, or a problem form, as in Add a form
Link: rel="alternate" headersA wrapper, as in Wrap handle
Web Bot Auth, Markdown lint, a CLI, redirectsNot planned