@rsc-kit/mcp 0.17.0 → 0.18.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/recipes.js +319 -14
- package/dist/recipes.js.map +1 -1
- package/guides/api-routes.md +106 -6
- package/guides/authorization.md +39 -0
- package/guides/backend-answered-pages.md +163 -0
- package/guides/coming-from-next.md +3 -0
- package/guides/deployment.md +129 -0
- package/guides/domains.md +129 -0
- package/guides/errors.md +11 -1
- package/guides/go.md +194 -0
- package/guides/index.json +40 -0
- package/guides/installation.md +23 -4
- package/guides/instrumentation.md +91 -0
- package/guides/introduction.md +4 -0
- package/guides/laravel.md +406 -0
- package/guides/queries.md +138 -8
- package/guides/quick-start.md +31 -0
- package/guides/redirects.md +14 -0
- package/guides/response-headers.md +22 -0
- package/guides/seo-files.md +45 -0
- package/guides/typed-routes.md +17 -0
- package/guides/where-it-runs.md +155 -0
- package/guides/your-own-backend.md +238 -0
- package/package.json +2 -2
package/dist/index.js
CHANGED
|
@@ -97,7 +97,7 @@ server.registerTool('heaviest_routes', {
|
|
|
97
97
|
}));
|
|
98
98
|
server.registerTool('how_to', {
|
|
99
99
|
title: 'How to build it',
|
|
100
|
-
description: 'How to do something in an rsc-kit app — forms, prefetching, validation, the action client, data loading with TanStack Query or SWR, Suspense boundaries, offline, PWA, api routes, authorization, and why a page is dynamic. Read this BEFORE writing the code: the patterns here differ from Next and plain React in ways that compile either way. The short answer; read_guide has the full one.',
|
|
100
|
+
description: 'How to do something in an rsc-kit app — forms, prefetching, validation, the action client, data loading with TanStack Query or SWR, Suspense boundaries, offline, PWA, api routes, authorization, a Laravel or other backend, once-per-process startup, and why a page is dynamic. Read this BEFORE writing the code: the patterns here differ from Next and plain React in ways that compile either way. The short answer; read_guide has the full one.',
|
|
101
101
|
inputSchema: TOPIC_ARG,
|
|
102
102
|
annotations: { readOnlyHint: true },
|
|
103
103
|
}, (async ({ topic }) => text(howTo(topic))));
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";AACA,oDAAoD;AACpD,EAAE;AACF,kDAAkD;AAClD,EAAE;AACF,yEAAyE;AACzE,mCAAmC;AACnC,EAAE;AACF,iDAAiD;AACjD,+BAA+B;AAC/B,kCAAkC;AAClC,yCAAyC;AACzC,EAAE;AACF,4EAA4E;AAC5E,+EAA+E;AAC/E,gFAAgF;AAChF,8EAA8E;AAC9E,kEAAkE;AAClE,EAAE;AACF,gFAAgF;AAChF,8EAA8E;AAC9E,2EAA2E;AAE3E,OAAO,EAAE,SAAS,EAAE,MAAM,yCAAyC,CAAA;AACnE,OAAO,EAAE,oBAAoB,EAAE,MAAM,2CAA2C,CAAA;AAChF,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAA;AACvB,OAAO,EAAE,YAAY,EAAE,cAAc,EAAE,UAAU,EAAE,aAAa,EAAE,MAAM,cAAc,CAAA;AACtF,OAAO,EAAE,QAAQ,EAAE,UAAU,EAAE,MAAM,aAAa,CAAA;AAClD,OAAO,EAAE,KAAK,EAAE,UAAU,EAAE,MAAM,cAAc,CAAA;AAChD,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAA;AAEvE,uEAAuE;AACvE,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,OAAO,CAAC,GAAG,EAAE,CAAA;AAE7C;;;;;;GAMG;AACH,MAAM,IAAI,GAAG,GAAG,EAAE,CAAC,UAAU,CAAC,IAAI,CAAC,CAAA;AAEnC;;;;;;;GAOG;AACH,MAAM,OAAO,GAAG,EAAE,GAAG,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,uCAAuC,CAAC,EAAE,CAAA;AACrF,MAAM,SAAS,GAAG,EAAE,KAAK,EA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AAE,EAAE,CAAC,IAAI,CAAC,YAAY,CAAC,MAAM,CAAC,CAAC,CAAU,CAChF,CAAA;AAED,MAAM,MAAM,CAAC,OAAO,CAAC,IAAI,oBAAoB,EAAE,CAAC,CAAA","sourcesContent":["#!/usr/bin/env node\n// An MCP server over what an rsc-kit build decided.\n//\n// claude mcp add rsc-kit -- npx -y @rsc-kit/mcp\n//\n// Four questions, all answered from `build-report.json` and none of them\n// requiring the app to be running:\n//\n// what routes exist, and what happened to each\n// why is this one not stored\n// which ones render per request\n// which ones cost the browser the most\n//\n// Why a server rather than letting an agent read the file: the file is JSON\n// with a `type` field whose values mean nothing without the documentation, and\n// an agent reading it guesses — \"shell\" invites being treated as a failure when\n// it is the normal, correct outcome for a page with data in it. These answers\n// say what each state means, in the same words the build printed.\n//\n// Everything is read-only. There is no tool here that edits, builds or deploys,\n// deliberately: an agent already has a shell for those, and a server that can\n// change the project is one that can change it while answering a question.\n\nimport { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'\nimport { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'\nimport { z } from 'zod'\nimport { explainRoute, heaviestRoutes, listRoutes, whatIsDynamic } from './answers.js'\nimport { NoReport, loadReport } from './report.js'\nimport { howTo, listTopics } from './recipes.js'\nimport { listGuides, readGuide, searchGuides } from './bundleGuides.js'\n\n/** The project to read, from the argument or the working directory. */\nconst root = process.argv[2] ?? process.cwd()\n\n/**\n * Loaded per call, never cached.\n *\n * A build happens while this server is running — that is the normal case, not\n * the exception — and an answer from the build before it is worse than a slow\n * one. The file is small and this is not a hot path.\n */\nconst read = () => loadReport(root)\n\n/**\n * Declared once, outside the call.\n *\n * Inline, TypeScript walks the sdk's tool generics against the zod shape and\n * gives up with \"type instantiation is excessively deep\" — a compiler limit\n * rather than anything wrong with the schema. A named const with the handler's\n * argument annotated stops the inference chain before it gets there.\n */\nconst URL_ARG = { url: z.string().describe('The url, e.g. /orders or /posts/hello') }\nconst TOPIC_ARG = { topic: z.string().describe('One of the topics from list_topics, e.g. forms or validation') }\nconst SLUG_ARG = { slug: z.string().describe('One of the slugs from list_guides, e.g. forms or server-actions') }\nconst PHRASE_ARG = { phrase: z.string().describe('A word or phrase, e.g. fieldErrors or metadataBase') }\n\nconst text = (body: string) => ({ content: [{ type: 'text' as const, text: body }] })\n\n/** A missing report is an answer, not a crash: it says to run a build. */\nconst answering = (produce: () => string) => {\n try {\n return text(produce())\n } catch (error) {\n if (error instanceof NoReport) return text(error.message)\n\n throw error\n }\n}\n\n/**\n * The registration surface, named rather than inferred.\n *\n * `registerTool` is generic over the zod shape, and TypeScript walks those\n * generics until it gives up — \"type instantiation is excessively deep\", which\n * is a compiler limit rather than anything wrong with the schema. Describing\n * the one method used, with the argument type written out, stops the inference\n * before it gets there and costs nothing: the schemas below are still real zod\n * and still validate at runtime.\n */\ninterface Registrar {\n registerTool(\n name: string,\n config: {\n title?: string\n description?: string\n inputSchema?: Record<string, unknown>\n annotations?: { readOnlyHint?: boolean }\n },\n handler: (args: never) => Promise<{ content: { type: 'text'; text: string }[] }>,\n ): unknown\n connect(transport: StdioServerTransport): Promise<void>\n}\n\nconst server = new McpServer({ name: 'rsc-kit', version: '0.1.0' }) as unknown as Registrar\n\nserver.registerTool(\n 'list_routes',\n {\n title: 'List routes',\n description:\n 'Every route in this rsc-kit app, what the build did with each one, and how much javascript it ships. Start here when you need to know what exists.',\n annotations: { readOnlyHint: true },\n },\n async () =>\n answering(() => {\n const { report, builtAt } = read()\n\n return listRoutes(report, builtAt, Date.now())\n }),\n)\n\nserver.registerTool(\n 'explain_route',\n {\n title: 'Explain a route',\n description:\n 'Why one url is stored at build time or rendered per request, what renders it, and what it costs the browser. Use this before changing a page to make it faster — the reason is recorded, not guessed.',\n inputSchema: URL_ARG,\n annotations: { readOnlyHint: true },\n },\n (async ({ url }: { url: string }) =>\n answering(() => {\n const { report, builtAt } = read()\n\n return explainRoute(report, url, builtAt, Date.now())\n })) as never,\n)\n\nserver.registerTool(\n 'what_is_dynamic',\n {\n title: 'What renders per request',\n description:\n 'The routes that render per request rather than being stored, each with the reason. This is the answer to \"why is this site not static\".',\n annotations: { readOnlyHint: true },\n },\n async () =>\n answering(() => {\n const { report, builtAt } = read()\n\n return whatIsDynamic(report, builtAt, Date.now())\n }),\n)\n\nserver.registerTool(\n 'heaviest_routes',\n {\n title: 'Heaviest routes',\n description: 'The routes that make the browser download the most javascript, largest first.',\n annotations: { readOnlyHint: true },\n },\n async () =>\n answering(() => {\n const { report, builtAt } = read()\n\n return heaviestRoutes(report, builtAt, Date.now())\n }),\n)\n\nserver.registerTool(\n 'how_to',\n {\n title: 'How to build it',\n description:\n 'How to do something in an rsc-kit app — forms, prefetching, validation, the action client, data loading with TanStack Query or SWR, Suspense boundaries, offline, PWA, api routes, authorization, and why a page is dynamic. Read this BEFORE writing the code: the patterns here differ from Next and plain React in ways that compile either way. The short answer; read_guide has the full one.',\n inputSchema: TOPIC_ARG,\n annotations: { readOnlyHint: true },\n },\n (async ({ topic }: { topic: string }) => text(howTo(topic))) as never,\n)\n\nserver.registerTool(\n 'list_topics',\n {\n title: 'What this server can explain',\n description: 'Every topic how_to knows about, one line each.',\n annotations: { readOnlyHint: true },\n },\n async () => text(listTopics()),\n)\n\nserver.registerTool(\n 'list_guides',\n {\n title: 'The guides',\n description: 'Every guide from docs.rsc-kit.dev, bundled with this server — the full text behind how_to, one line each.',\n annotations: { readOnlyHint: true },\n },\n async () => text(listGuides()),\n)\n\nserver.registerTool(\n 'read_guide',\n {\n title: 'Read a guide',\n description:\n 'The complete guide for one topic, as published at docs.rsc-kit.dev — routing, forms, server-actions, validation, metadata, testing, deployment and the rest. Use it when how_to is not enough or names something it does not explain.',\n inputSchema: SLUG_ARG,\n annotations: { readOnlyHint: true },\n },\n (async ({ slug }: { slug: string }) => text(readGuide(slug))) as never,\n)\n\nserver.registerTool(\n 'search_guides',\n {\n title: 'Search the guides',\n description: 'Every line in the guides that mentions a word or phrase, with the guide it is in. Use it to find which guide covers something before reading it.',\n inputSchema: PHRASE_ARG,\n annotations: { readOnlyHint: true },\n },\n (async ({ phrase }: { phrase: string }) => text(searchGuides(phrase))) as never,\n)\n\nawait server.connect(new StdioServerTransport())\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";AACA,oDAAoD;AACpD,EAAE;AACF,kDAAkD;AAClD,EAAE;AACF,yEAAyE;AACzE,mCAAmC;AACnC,EAAE;AACF,iDAAiD;AACjD,+BAA+B;AAC/B,kCAAkC;AAClC,yCAAyC;AACzC,EAAE;AACF,4EAA4E;AAC5E,+EAA+E;AAC/E,gFAAgF;AAChF,8EAA8E;AAC9E,kEAAkE;AAClE,EAAE;AACF,gFAAgF;AAChF,8EAA8E;AAC9E,2EAA2E;AAE3E,OAAO,EAAE,SAAS,EAAE,MAAM,yCAAyC,CAAA;AACnE,OAAO,EAAE,oBAAoB,EAAE,MAAM,2CAA2C,CAAA;AAChF,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAA;AACvB,OAAO,EAAE,YAAY,EAAE,cAAc,EAAE,UAAU,EAAE,aAAa,EAAE,MAAM,cAAc,CAAA;AACtF,OAAO,EAAE,QAAQ,EAAE,UAAU,EAAE,MAAM,aAAa,CAAA;AAClD,OAAO,EAAE,KAAK,EAAE,UAAU,EAAE,MAAM,cAAc,CAAA;AAChD,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAA;AAEvE,uEAAuE;AACvE,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,OAAO,CAAC,GAAG,EAAE,CAAA;AAE7C;;;;;;GAMG;AACH,MAAM,IAAI,GAAG,GAAG,EAAE,CAAC,UAAU,CAAC,IAAI,CAAC,CAAA;AAEnC;;;;;;;GAOG;AACH,MAAM,OAAO,GAAG,EAAE,GAAG,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,uCAA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IAAI,EAAE;CACpC,EACD,CAAC,KAAK,EAAE,EAAE,MAAM,EAAsB,EAAE,EAAE,CAAC,IAAI,CAAC,YAAY,CAAC,MAAM,CAAC,CAAC,CAAU,CAChF,CAAA;AAED,MAAM,MAAM,CAAC,OAAO,CAAC,IAAI,oBAAoB,EAAE,CAAC,CAAA","sourcesContent":["#!/usr/bin/env node\n// An MCP server over what an rsc-kit build decided.\n//\n// claude mcp add rsc-kit -- npx -y @rsc-kit/mcp\n//\n// Four questions, all answered from `build-report.json` and none of them\n// requiring the app to be running:\n//\n// what routes exist, and what happened to each\n// why is this one not stored\n// which ones render per request\n// which ones cost the browser the most\n//\n// Why a server rather than letting an agent read the file: the file is JSON\n// with a `type` field whose values mean nothing without the documentation, and\n// an agent reading it guesses — \"shell\" invites being treated as a failure when\n// it is the normal, correct outcome for a page with data in it. These answers\n// say what each state means, in the same words the build printed.\n//\n// Everything is read-only. There is no tool here that edits, builds or deploys,\n// deliberately: an agent already has a shell for those, and a server that can\n// change the project is one that can change it while answering a question.\n\nimport { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'\nimport { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'\nimport { z } from 'zod'\nimport { explainRoute, heaviestRoutes, listRoutes, whatIsDynamic } from './answers.js'\nimport { NoReport, loadReport } from './report.js'\nimport { howTo, listTopics } from './recipes.js'\nimport { listGuides, readGuide, searchGuides } from './bundleGuides.js'\n\n/** The project to read, from the argument or the working directory. */\nconst root = process.argv[2] ?? process.cwd()\n\n/**\n * Loaded per call, never cached.\n *\n * A build happens while this server is running — that is the normal case, not\n * the exception — and an answer from the build before it is worse than a slow\n * one. The file is small and this is not a hot path.\n */\nconst read = () => loadReport(root)\n\n/**\n * Declared once, outside the call.\n *\n * Inline, TypeScript walks the sdk's tool generics against the zod shape and\n * gives up with \"type instantiation is excessively deep\" — a compiler limit\n * rather than anything wrong with the schema. A named const with the handler's\n * argument annotated stops the inference chain before it gets there.\n */\nconst URL_ARG = { url: z.string().describe('The url, e.g. /orders or /posts/hello') }\nconst TOPIC_ARG = { topic: z.string().describe('One of the topics from list_topics, e.g. forms or validation') }\nconst SLUG_ARG = { slug: z.string().describe('One of the slugs from list_guides, e.g. forms or server-actions') }\nconst PHRASE_ARG = { phrase: z.string().describe('A word or phrase, e.g. fieldErrors or metadataBase') }\n\nconst text = (body: string) => ({ content: [{ type: 'text' as const, text: body }] })\n\n/** A missing report is an answer, not a crash: it says to run a build. */\nconst answering = (produce: () => string) => {\n try {\n return text(produce())\n } catch (error) {\n if (error instanceof NoReport) return text(error.message)\n\n throw error\n }\n}\n\n/**\n * The registration surface, named rather than inferred.\n *\n * `registerTool` is generic over the zod shape, and TypeScript walks those\n * generics until it gives up — \"type instantiation is excessively deep\", which\n * is a compiler limit rather than anything wrong with the schema. Describing\n * the one method used, with the argument type written out, stops the inference\n * before it gets there and costs nothing: the schemas below are still real zod\n * and still validate at runtime.\n */\ninterface Registrar {\n registerTool(\n name: string,\n config: {\n title?: string\n description?: string\n inputSchema?: Record<string, unknown>\n annotations?: { readOnlyHint?: boolean }\n },\n handler: (args: never) => Promise<{ content: { type: 'text'; text: string }[] }>,\n ): unknown\n connect(transport: StdioServerTransport): Promise<void>\n}\n\nconst server = new McpServer({ name: 'rsc-kit', version: '0.1.0' }) as unknown as Registrar\n\nserver.registerTool(\n 'list_routes',\n {\n title: 'List routes',\n description:\n 'Every route in this rsc-kit app, what the build did with each one, and how much javascript it ships. Start here when you need to know what exists.',\n annotations: { readOnlyHint: true },\n },\n async () =>\n answering(() => {\n const { report, builtAt } = read()\n\n return listRoutes(report, builtAt, Date.now())\n }),\n)\n\nserver.registerTool(\n 'explain_route',\n {\n title: 'Explain a route',\n description:\n 'Why one url is stored at build time or rendered per request, what renders it, and what it costs the browser. Use this before changing a page to make it faster — the reason is recorded, not guessed.',\n inputSchema: URL_ARG,\n annotations: { readOnlyHint: true },\n },\n (async ({ url }: { url: string }) =>\n answering(() => {\n const { report, builtAt } = read()\n\n return explainRoute(report, url, builtAt, Date.now())\n })) as never,\n)\n\nserver.registerTool(\n 'what_is_dynamic',\n {\n title: 'What renders per request',\n description:\n 'The routes that render per request rather than being stored, each with the reason. This is the answer to \"why is this site not static\".',\n annotations: { readOnlyHint: true },\n },\n async () =>\n answering(() => {\n const { report, builtAt } = read()\n\n return whatIsDynamic(report, builtAt, Date.now())\n }),\n)\n\nserver.registerTool(\n 'heaviest_routes',\n {\n title: 'Heaviest routes',\n description: 'The routes that make the browser download the most javascript, largest first.',\n annotations: { readOnlyHint: true },\n },\n async () =>\n answering(() => {\n const { report, builtAt } = read()\n\n return heaviestRoutes(report, builtAt, Date.now())\n }),\n)\n\nserver.registerTool(\n 'how_to',\n {\n title: 'How to build it',\n description:\n 'How to do something in an rsc-kit app — forms, prefetching, validation, the action client, data loading with TanStack Query or SWR, Suspense boundaries, offline, PWA, api routes, authorization, a Laravel or other backend, once-per-process startup, and why a page is dynamic. Read this BEFORE writing the code: the patterns here differ from Next and plain React in ways that compile either way. The short answer; read_guide has the full one.',\n inputSchema: TOPIC_ARG,\n annotations: { readOnlyHint: true },\n },\n (async ({ topic }: { topic: string }) => text(howTo(topic))) as never,\n)\n\nserver.registerTool(\n 'list_topics',\n {\n title: 'What this server can explain',\n description: 'Every topic how_to knows about, one line each.',\n annotations: { readOnlyHint: true },\n },\n async () => text(listTopics()),\n)\n\nserver.registerTool(\n 'list_guides',\n {\n title: 'The guides',\n description: 'Every guide from docs.rsc-kit.dev, bundled with this server — the full text behind how_to, one line each.',\n annotations: { readOnlyHint: true },\n },\n async () => text(listGuides()),\n)\n\nserver.registerTool(\n 'read_guide',\n {\n title: 'Read a guide',\n description:\n 'The complete guide for one topic, as published at docs.rsc-kit.dev — routing, forms, server-actions, validation, metadata, testing, deployment and the rest. Use it when how_to is not enough or names something it does not explain.',\n inputSchema: SLUG_ARG,\n annotations: { readOnlyHint: true },\n },\n (async ({ slug }: { slug: string }) => text(readGuide(slug))) as never,\n)\n\nserver.registerTool(\n 'search_guides',\n {\n title: 'Search the guides',\n description: 'Every line in the guides that mentions a word or phrase, with the guide it is in. Use it to find which guide covers something before reading it.',\n inputSchema: PHRASE_ARG,\n annotations: { readOnlyHint: true },\n },\n (async ({ phrase }: { phrase: string }) => text(searchGuides(phrase))) as never,\n)\n\nawait server.connect(new StdioServerTransport())\n"]}
|
package/dist/recipes.js
CHANGED
|
@@ -342,20 +342,40 @@ export default function Page() {
|
|
|
342
342
|
|
|
343
343
|
Reach for this first. It is the thing RSC is for.
|
|
344
344
|
|
|
345
|
-
**When the BROWSER decides to refetch** — a filter,
|
|
346
|
-
|
|
345
|
+
**When the BROWSER decides to refetch** — a filter, another page, a refresh —
|
|
346
|
+
call fetchQuery. It is a plain async function that returns the typed answer;
|
|
347
|
+
NO library is needed:
|
|
347
348
|
|
|
349
|
+
\`\`\`tsx
|
|
350
|
+
const [listings, setListings] = useState(initial) // the server-rendered value
|
|
351
|
+
const [pending, start] = useTransition()
|
|
352
|
+
const show = (kind) => start(async () => setListings(await fetchQuery(getListings, [kind])))
|
|
353
|
+
\`\`\`
|
|
354
|
+
Works in an onClick, onSubmit, useEffect - anywhere in the browser.
|
|
355
|
+
|
|
356
|
+
**When you want CACHING** (stale-while-revalidate, dedupe, offline), hand the
|
|
357
|
+
same call to the library that holds the answer; this package ships none:
|
|
348
358
|
\`\`\`tsx
|
|
349
359
|
useQuery({ queryKey: ['posts', kind], queryFn: () => fetchQuery(getPosts, [kind]) })
|
|
350
360
|
useSWR(['posts', kind], () => fetchQuery(getPosts, [kind]))
|
|
351
361
|
\`\`\`
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
is
|
|
355
|
-
|
|
362
|
+
fetchQuery sends the read as a GET and goes to the server every time, which
|
|
363
|
+
is what a fetcher needs. It will never cache, dedupe or batch: a client
|
|
364
|
+
cache is the library's job, and a batch would lose the per-read cache key a
|
|
365
|
+
GET has. The ladder, most reads stopping on the first rung:
|
|
366
|
+
1. the value now: fetchQuery + setState
|
|
367
|
+
2. survive a reload / let a CDN serve it: query(fn, { cache: 'public', maxAge })
|
|
368
|
+
- HTTP caching, no code in the page
|
|
369
|
+
3. staleness, background refresh, optimistic updates, shared across
|
|
370
|
+
components: TanStack or SWR with fetchQuery as the fetcher
|
|
371
|
+
Do not add a cache on top of it, and do not install TanStack for a single
|
|
372
|
+
button that reads once.
|
|
356
373
|
|
|
357
374
|
Keep the arrow: TanStack calls a bare \`queryFn\` with its own context, and a
|
|
358
|
-
server function serialises whatever it is handed
|
|
375
|
+
server function serialises whatever it is handed.
|
|
376
|
+
|
|
377
|
+
A value that keeps CHANGING while someone watches - polling, SSE, realtime -
|
|
378
|
+
is how_to live-data, not this.`,
|
|
359
379
|
},
|
|
360
380
|
{
|
|
361
381
|
topic: 'suspense',
|
|
@@ -747,13 +767,15 @@ IMPORTS
|
|
|
747
767
|
useParams() -> the page's params prop, passed down
|
|
748
768
|
cookies(), headers() -> same names, from @rsc-kit/core/request
|
|
749
769
|
redirect() / notFound() -> @rsc-kit/core/redirect / @rsc-kit/core/not-found
|
|
750
|
-
revalidatePath/Tag -> revalidate('
|
|
770
|
+
revalidatePath/Tag -> revalidate('name') on a section() - targeted, rides back with the action; the
|
|
771
|
+
name is typed to the sections and slots the build found
|
|
751
772
|
Metadata -> @rsc-kit/core/metadata (metadataBase, openGraph, twitter, icons as-is)
|
|
752
773
|
app/robots.ts, app/sitemap.ts -> the same files and shapes; app/llms.ts beside them (how_to seo-files)
|
|
774
|
+
middleware.ts subdomain rewrite -> nothing: a host is a route segment (how_to domains)
|
|
753
775
|
next/font -> Fontsource (how_to fonts)
|
|
754
776
|
next/image -> unpic or vite-imagetools (how_to images)
|
|
755
777
|
next/script -> a <script> tag (how_to scripts)
|
|
756
|
-
NEXT_PUBLIC_* ->
|
|
778
|
+
NEXT_PUBLIC_* -> PUBLIC_* in src/env.ts (how_to env); server vars typed there too
|
|
757
779
|
next-safe-action -> createActionClient() (how_to action-client); returnValidationErrors -> return fieldErrors({...})
|
|
758
780
|
cache from 'react' -> cache from @rsc-kit/core/cache: React's dedupes only inside a render; this one
|
|
759
781
|
spans the request (guards, actions, api routes). The build names files still on React's
|
|
@@ -773,6 +795,11 @@ DIFFERENT ON PURPOSE
|
|
|
773
795
|
the top of each file, as shipped; without it the server evaluates the
|
|
774
796
|
library's internals for nothing.
|
|
775
797
|
|
|
798
|
+
SCAFFOLD FLAGS: --host=bun|node|worker --validation=zod|valibot|arktype|none
|
|
799
|
+
--env/--no-env (typed env vars via @t3-oss/env-core in src/env.ts, in the
|
|
800
|
+
chosen library; server vars never reach the browser, PUBLIC_ prefix for ones
|
|
801
|
+
that may). Pick the library the Next app already uses.
|
|
802
|
+
|
|
776
803
|
ORDER: scaffold -> copy src/app -> fix imports -> build (it typechecks first,
|
|
777
804
|
so a Link to a route that does not exist fails here) and READ the output: a
|
|
778
805
|
route that is not ○ names what streams and from which component (a cookies()
|
|
@@ -870,18 +897,295 @@ export default function llms(): MetadataRoute.Llms {
|
|
|
870
897
|
A relative url is made absolute with the root layout's metadataBase; without
|
|
871
898
|
one it is a build error. Any of them may return a string, served as written.
|
|
872
899
|
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
900
|
+
NO sitemap.ts? The build writes /sitemap.xml itself: every stored page and
|
|
901
|
+
every generateStaticParams url, lastModified = the build, minus guarded
|
|
902
|
+
routes (middleware.ts above them), failed pages and not-found. Needs the root
|
|
903
|
+
layout's metadataBase. Write sitemap.ts only when you need urls the build
|
|
904
|
+
cannot see or per-url changeFrequency/priority.
|
|
905
|
+
|
|
906
|
+
HOW FRESH - the function decides, the same rule every route follows:
|
|
907
|
+
write nothing -> the build's own sitemap, stored; fresh every deploy
|
|
908
|
+
sitemap.ts that reads the database -> stored at build (○); fresh every deploy
|
|
909
|
+
sitemap.ts that awaits connection() -> rendered per request (ƒ); fresh every crawl
|
|
910
|
+
\`\`\`ts
|
|
911
|
+
export default async function sitemap() {
|
|
912
|
+
await connection() // from '@rsc-kit/core/request' - per request, like a page
|
|
913
|
+
return (await db.post.findMany()).map((p) => ({ url: \`/blog/\${p.slug}\`, lastModified: p.updatedAt }))
|
|
914
|
+
}
|
|
915
|
+
\`\`\`
|
|
916
|
+
Reading the database at build is fine; the REQUEST makes it dynamic, not the
|
|
917
|
+
data. Same for robots.ts and llms.ts. No middleware runs for
|
|
876
918
|
them - a root guard must not 401 the crawler. The url is typed
|
|
877
919
|
(route('/sitemap.xml')).
|
|
878
920
|
|
|
879
921
|
A file as written beside the root layout is served at the root as it is:
|
|
880
922
|
robots.txt, sitemap.xml, sitemap-*.xml, llms.txt, llms-full.txt, humans.txt,
|
|
881
923
|
security.txt, ads.txt. A file and a function for the same url is a build
|
|
882
|
-
error. Do NOT put these in public/ and do NOT write a
|
|
924
|
+
error. Do NOT put these in public/ and do NOT write a middleware.ts for them.
|
|
883
925
|
|
|
884
926
|
Full guide: read_guide({ slug: 'seo-files' }).`,
|
|
927
|
+
},
|
|
928
|
+
{
|
|
929
|
+
topic: 'domains',
|
|
930
|
+
summary: 'Subdomains and custom domains as route segments - admin.example.com reaches app/admin, a tenant host binds [domain], no rewrite',
|
|
931
|
+
body: `A request from a host that is not the site's own is matched with the host
|
|
932
|
+
in FRONT of the path. The site's own hosts: the root layout's metadataBase,
|
|
933
|
+
www. of it, and rscKit({ hosts: [...] }) - which is ONLY for a name that is
|
|
934
|
+
neither the apex nor a subdomain of it (a staging/internal name, a second
|
|
935
|
+
brand domain); a normal setup needs no config beyond metadataBase. localhost
|
|
936
|
+
and ips are always own.
|
|
937
|
+
|
|
938
|
+
example.com/admin -> /admin app/admin/page.tsx
|
|
939
|
+
admin.example.com/ -> /admin the same file (subdomain of an own host = its label)
|
|
940
|
+
acme.example.com/settings -> /acme/settings app/[domain]/settings/page.tsx, domain "acme"
|
|
941
|
+
acme.com/settings -> /acme.com/settings the same file, domain "acme.com" (other host = whole host)
|
|
942
|
+
|
|
943
|
+
The visitor's url is untouched; only the match changes. A top-level [domain]
|
|
944
|
+
binds ONLY from a host, never from a path: example.com/nope is a 404, not a
|
|
945
|
+
tenant called "nope". Otherwise [domain] is an ordinary dynamic segment: params.domain in every page/layout under it, typed
|
|
946
|
+
route('/[domain]/settings', { domain }), loading/error files as usual. A
|
|
947
|
+
directory named for a host (app/admin/) wins over [domain].
|
|
948
|
+
|
|
949
|
+
\`\`\`tsx
|
|
950
|
+
// src/app/[domain]/layout.tsx
|
|
951
|
+
export default async function TenantLayout({ params, children }) {
|
|
952
|
+
const { domain } = await params
|
|
953
|
+
const tenant = await tenantByDomain(domain) // "acme" or "acme.com", as stored
|
|
954
|
+
if (!tenant) notFound()
|
|
955
|
+
return <TenantProvider tenant={tenant}>{children}</TenantProvider>
|
|
956
|
+
}
|
|
957
|
+
// src/app/[domain]/page.tsx - domains in a database: list them, they are stored at build
|
|
958
|
+
export async function generateStaticParams() {
|
|
959
|
+
return (await db.tenant.findMany()).map((t) => ({ domain: t.domain }))
|
|
960
|
+
}
|
|
961
|
+
\`\`\`
|
|
962
|
+
|
|
963
|
+
Only when a route could answer it (a top-level [domain] directory, or one
|
|
964
|
+
named for the host); otherwise the host is the site's own. Keep metadataBase as
|
|
965
|
+
the production host: localhost and ips are always own, so dev routes by path.
|
|
966
|
+
To try a tenant locally: curl -H 'X-Forwarded-Host: acme.example.com'
|
|
967
|
+
http://localhost:3000/ (or /etc/hosts). Behind a proxy the
|
|
968
|
+
host is X-Forwarded-Host, then Host. Not for a static export (a file server
|
|
969
|
+
sees no host). Do NOT write a middleware rewrite, do NOT
|
|
970
|
+
read the host in every page - the segment already is the host. The root layout
|
|
971
|
+
needs metadataBase (or rscKit({ hosts })) or every host is the site's own.
|
|
972
|
+
|
|
973
|
+
Full guide: read_guide({ slug: 'domains' }).`,
|
|
974
|
+
},
|
|
975
|
+
{
|
|
976
|
+
topic: 'identify',
|
|
977
|
+
summary: 'What a response says about itself - X-RSC-Kit (how it was served, always) and X-Powered-By + a generator tag (what built it, off with identify: false)',
|
|
978
|
+
body: `Every response carries X-RSC-Kit: stored | rendered | shell - a page from a
|
|
979
|
+
file the build wrote, rendered for this visitor, or a stored shell with its
|
|
980
|
+
holes rendered now. The header to read when a page is slower than expected
|
|
981
|
+
(like X-Nextjs-Cache); a CDN rule or health check can key on it. Names no
|
|
982
|
+
product; always sent.
|
|
983
|
+
|
|
984
|
+
By default a response also says what built it: X-Powered-By: rsc-kit and
|
|
985
|
+
<meta name="generator" content="rsc-kit"> in every document (BuiltWith,
|
|
986
|
+
Wappalyzer). The NAME only, never the version - a version in every response
|
|
987
|
+
is what a vulnerability scanner filters on.
|
|
988
|
+
|
|
989
|
+
rscKit({ identify: false }) turns off the name (header and tag) for a policy
|
|
990
|
+
that strips framework identifiers; X-RSC-Kit stays. Do not strip X-RSC-Kit
|
|
991
|
+
at the proxy - it is what tells you whether a stored page was served.
|
|
992
|
+
|
|
993
|
+
Full guide: read_guide({ slug: 'response-headers' }).`,
|
|
994
|
+
},
|
|
995
|
+
{
|
|
996
|
+
topic: 'backend',
|
|
997
|
+
summary: 'BAP (Backend-Answered Pages): a Laravel, Go or other backend behind the renderer - rpc() reaches it, middleware.ts names its middleware, app/Rsc/Actions are its server actions',
|
|
998
|
+
body: `The model is a BAP - Backend-Answered Pages: a page rendered in front of
|
|
999
|
+
the backend rather than by it (MPA: backend renders; SPA: browser renders and
|
|
1000
|
+
calls an API; BAP: a renderer on the server renders and calls the backend
|
|
1001
|
+
over loopback). The backend is the part that is not a page - models, session,
|
|
1002
|
+
auth, policies, jobs - answering one private endpoint, and it keeps every
|
|
1003
|
+
route of its own. The whole model, and how to build for it:
|
|
1004
|
+
read_guide({ slug: 'backend-answered-pages' }).
|
|
1005
|
+
|
|
1006
|
+
Go: in a Go module, rsc-kit init sees go.mod, writes the JS half and .env
|
|
1007
|
+
(RSC_BACKEND + a generated secret) and prints the Go wiring; go get
|
|
1008
|
+
github.com/rsc-kit/go. A new app: bun create rsc-kit --backend=<url>.
|
|
1009
|
+
|
|
1010
|
+
A backend in another language answers that ONE endpoint, POST /__rsc/host-call,
|
|
1011
|
+
and the renderer wires itself from two variables in .env: RSC_BACKEND (a
|
|
1012
|
+
Laravel app's APP_URL counts) and RSC_HOST_CALL_SECRET. Both or neither.
|
|
1013
|
+
|
|
1014
|
+
Laravel: composer require rsc-kit/laravel, then php artisan rsc:install. It
|
|
1015
|
+
runs rsc-kit init, which writes ONE vite.config.ts (laravel-vite-plugin is
|
|
1016
|
+
moved aside - the renderer owns the frontend). Source is resources/js (the route tree is resources/js/app).
|
|
1017
|
+
|
|
1018
|
+
Reach PHP from a server component - rpc() is a global, typed in
|
|
1019
|
+
.rsc-kit/rsc-env.d.ts, server render only:
|
|
1020
|
+
|
|
1021
|
+
// app/Rsc/Orders.php: public function recent(int $limit): array
|
|
1022
|
+
const orders = await rpc<Order[]>('Orders.recent', 5)
|
|
1023
|
+
|
|
1024
|
+
The call runs AS THE VISITOR (their cookie is forwarded; auth()->user() is
|
|
1025
|
+
them). Refuse with attributes: #[Authenticated], #[Can('update', Order::class)],
|
|
1026
|
+
#[Middleware('throttle:60,1')]. A ValidationException lands on the form as
|
|
1027
|
+
validationErrors; Authentication/Authorization exceptions answer 401/403.
|
|
1028
|
+
|
|
1029
|
+
Guard a route in Laravel's vocabulary, no route declared in PHP:
|
|
1030
|
+
|
|
1031
|
+
// resources/js/app/admin/middleware.ts
|
|
1032
|
+
export const middleware = ['auth', 'verified', 'can:update,post']
|
|
1033
|
+
|
|
1034
|
+
Server actions are classes in app/Rsc/Actions; \`php artisan
|
|
1035
|
+
rsc:action-manifest\` (already in the dev/build scripts) writes the map and
|
|
1036
|
+
the build writes server-actions.generated.ts beside the app - import
|
|
1037
|
+
ordersCancel from it in a client component. Rsc::revalidate('orders') in the
|
|
1038
|
+
action returns the re-rendered region with the answer.
|
|
1039
|
+
|
|
1040
|
+
php artisan serve is one worker, which deadlocks the proxy - unless
|
|
1041
|
+
PHP_CLI_SERVER_WORKERS=4 in .env AND serve --no-reload (Laravel ignores
|
|
1042
|
+
the variable otherwise). Herd, Valet, FPM, Octane are fine as they are. Production: put the renderer in front (bun
|
|
1043
|
+
.output/server/index.mjs with the app's .env), restrict /__rsc/host-call at
|
|
1044
|
+
the web server.
|
|
1045
|
+
|
|
1046
|
+
Any other language implements the same endpoint - request { function, args },
|
|
1047
|
+
reply { result | validationErrors | unauthenticated | unauthorized | redirect
|
|
1048
|
+
| error, revalidate }, answers '__rsc.middleware' with true or a refusal, and
|
|
1049
|
+
a batch { calls: [...] } with { replies: [{ status, ...reply }] } in order.
|
|
1050
|
+
Calls issued in the same render tick travel as one batch, so parallel reads
|
|
1051
|
+
are one backend request; the renderer falls back to single calls for a
|
|
1052
|
+
backend without batches.
|
|
1053
|
+
|
|
1054
|
+
Full guides: read_guide({ slug: 'backend-answered-pages' }), read_guide({ slug: 'laravel' }), read_guide({ slug: 'go' }), read_guide({ slug: 'your-own-backend' }).`,
|
|
1055
|
+
},
|
|
1056
|
+
{
|
|
1057
|
+
topic: 'startup',
|
|
1058
|
+
summary: 'Once-per-process setup - src/instrumentation.ts is imported before any page and its register() awaited before the first request',
|
|
1059
|
+
body: `Setup that belongs to the process - validating env, configuring a shared
|
|
1060
|
+
package, warming a connection - goes in src/instrumentation.ts. Do NOT import
|
|
1061
|
+
a bootstrap module from pages to get the same effect; it depends on nobody
|
|
1062
|
+
forgetting, and the failure is a page throwing "not configured" for whoever
|
|
1063
|
+
reaches it first.
|
|
1064
|
+
|
|
1065
|
+
// src/instrumentation.ts
|
|
1066
|
+
import './env' // refuses at import -> server fails at startup
|
|
1067
|
+
export async function register() { // optional; the first render waits for it
|
|
1068
|
+
await db.connect()
|
|
1069
|
+
}
|
|
1070
|
+
|
|
1071
|
+
The generated entry imports this file FIRST, so a package configured here is
|
|
1072
|
+
configured before any page module evaluates. register() is awaited by every
|
|
1073
|
+
entry point (server, dev, prerender, middleware, actions, api routes), once
|
|
1074
|
+
per process. On a server it runs at startup and a failure exits the process;
|
|
1075
|
+
on a Worker it runs at the isolate's first request.
|
|
1076
|
+
|
|
1077
|
+
Worker rule: read bindings INSIDE register(), not at the top of the module -
|
|
1078
|
+
process.env is empty until the first request arrives.
|
|
1079
|
+
|
|
1080
|
+
A scaffolded app with env validation already has this file importing ./env.
|
|
1081
|
+
Build machines without production variables: SKIP_ENV_VALIDATION=1.
|
|
1082
|
+
|
|
1083
|
+
Full guide: read_guide({ slug: 'instrumentation' }).`,
|
|
1084
|
+
},
|
|
1085
|
+
{
|
|
1086
|
+
topic: 'env',
|
|
1087
|
+
summary: 'Typed environment variables - src/env.ts with @t3-oss/env-core in the app\'s validation library; refused at startup by name',
|
|
1088
|
+
body: `A scaffolded app has src/env.ts when it said yes to typed environment
|
|
1089
|
+
variables (create-rsc-kit --env, with --validation=zod|valibot|arktype). To
|
|
1090
|
+
add it to an app without one: install @t3-oss/env-core and write the same file.
|
|
1091
|
+
|
|
1092
|
+
\`\`\`ts
|
|
1093
|
+
// src/env.ts
|
|
1094
|
+
import * as z from 'zod' // or valibot / arktype - any Standard Schema library
|
|
1095
|
+
import { createEnv } from '@t3-oss/env-core'
|
|
1096
|
+
|
|
1097
|
+
export const env = createEnv({
|
|
1098
|
+
server: {
|
|
1099
|
+
NODE_ENV: z.enum(['development', 'production', 'test']).default('development'),
|
|
1100
|
+
DATABASE_URL: z.url(),
|
|
1101
|
+
SESSION_SECRET: z.string().min(1),
|
|
1102
|
+
},
|
|
1103
|
+
clientPrefix: 'PUBLIC_',
|
|
1104
|
+
client: { PUBLIC_SITE_URL: z.url() },
|
|
1105
|
+
runtimeEnv: { ...process.env, ...import.meta.env },
|
|
1106
|
+
emptyStringAsUndefined: true,
|
|
1107
|
+
})
|
|
1108
|
+
\`\`\`
|
|
1109
|
+
|
|
1110
|
+
Read env.DATABASE_URL, never process.env.DATABASE_URL: the first is typed and
|
|
1111
|
+
was checked at startup (a missing or malformed one fails then, with its name),
|
|
1112
|
+
the second is string | undefined. A server variable never reaches the browser;
|
|
1113
|
+
a browser-readable one MUST start with PUBLIC_ and is read from import.meta.env
|
|
1114
|
+
(Vite), which is why runtimeEnv merges both. Commit .env.example, not .env.
|
|
1115
|
+
|
|
1116
|
+
Next: NEXT_PUBLIC_* becomes PUBLIC_*; @t3-oss/env-nextjs becomes
|
|
1117
|
+
@t3-oss/env-core with runtimeEnv as above (env-nextjs's experimental__runtimeEnv
|
|
1118
|
+
is not needed).`,
|
|
1119
|
+
},
|
|
1120
|
+
{
|
|
1121
|
+
topic: 'live-data',
|
|
1122
|
+
summary: 'A value that keeps changing - realtime, live updates: usePolling over a query, or server-sent events (SSE, streaming from a middleware.ts generator) with useEvents - both feed TanStack, SWR or setState',
|
|
1123
|
+
body: `Neither is part of query() - a query answers once and is cacheable.
|
|
1124
|
+
|
|
1125
|
+
POLLING - start here when you have no change feed yet. Reuses the query,
|
|
1126
|
+
goes through its Cache-Control (a CDN collapses many tabs into one origin
|
|
1127
|
+
read per interval), pauses when the tab is hidden, never overlaps two reads.
|
|
1128
|
+
\`\`\`tsx
|
|
1129
|
+
import { usePolling } from '@rsc-kit/core/usePolling'
|
|
1130
|
+
const { data, status, refresh } = usePolling(() => fetchQuery(getSeats), { every: 2_000 })
|
|
1131
|
+
\`\`\`
|
|
1132
|
+
UNTIL IT SETTLES - a job that ends. until(data) says the last read; onSettled
|
|
1133
|
+
fires once on it. The result is the DATA; what to
|
|
1134
|
+
do on settling is the page's choice:
|
|
1135
|
+
// a server-rendered list, some jobs still running: re-render through the server
|
|
1136
|
+
usePolling(() => fetchQuery(jobStatus, [id]), { every: 2_000, enabled: !isTerminal(job), until: isTerminal, onSettled: () => refresh('page') })
|
|
1137
|
+
// the page that owns the job's state machine: the value in hand
|
|
1138
|
+
const { data, status } = usePolling(read, { every: 1_500, until: isTerminal, onSettled: (f) => dispatch(f.status) })
|
|
1139
|
+
Settled = stopped until refresh() or the inputs change. status: 'reading' |
|
|
1140
|
+
'paused' | 'settled' | 'idle'.
|
|
1141
|
+
|
|
1142
|
+
SERVER-SENT EVENTS - when something can push. Better per update (bytes only
|
|
1143
|
+
on change, instant), but holds a connection per open tab (fine on Bun/Node,
|
|
1144
|
+
a limit on Workers or a small container), is uncacheable, and needs a source
|
|
1145
|
+
of change to yield from - a generator that polls the DB itself just moved the
|
|
1146
|
+
polling. An ordinary route.ts: beside its pages, runs middleware.ts above it.
|
|
1147
|
+
\`\`\`ts
|
|
1148
|
+
// src/app/api/orders/[id]/events/route.ts
|
|
1149
|
+
import { events, named } from '@rsc-kit/core/events'
|
|
1150
|
+
export const GET = events(async function* ({ params, signal }) {
|
|
1151
|
+
const { id } = await params
|
|
1152
|
+
for await (const status of orderStatus(id, { signal })) yield { status }
|
|
1153
|
+
// yield named('paid', order, { id: order.id }) names a message / gives an id
|
|
1154
|
+
})
|
|
1155
|
+
\`\`\`
|
|
1156
|
+
\`\`\`tsx
|
|
1157
|
+
import { useEvents } from '@rsc-kit/core/useEvents'
|
|
1158
|
+
const { latest, all, status, close } = useEvents<Status>(\`/api/orders/\${id}/events\`)
|
|
1159
|
+
// <Status> is the message type the route yields; a url infers nothing, so
|
|
1160
|
+
// without it latest is unknown. Declare the type beside the route, import both sides.
|
|
1161
|
+
\`\`\`
|
|
1162
|
+
events() frames JSON, sends a keepalive, sets text/event-stream + no-store,
|
|
1163
|
+
ends the generator on disconnect (signal). EventSource reconnects itself and
|
|
1164
|
+
resumes with Last-Event-ID when you yielded ids.
|
|
1165
|
+
|
|
1166
|
+
NO LIBRARY NEEDED. Both hooks ARE state: read data (polling) or latest
|
|
1167
|
+
(events) and render it. Neither needs TanStack or SWR.
|
|
1168
|
+
const { latest } = useEvents<Status>(url); const current = latest ?? initial // the server value until the first message
|
|
1169
|
+
WITH A STORE - when the value already lives somewhere, hand every value on so
|
|
1170
|
+
that stays the truth: a useState, a reducer, or a cache library:
|
|
1171
|
+
useEvents<Order>(url, { onMessage: setOrder }) // useState
|
|
1172
|
+
useEvents<Order>(url, { onMessage: (m) => dispatch({ type: 'update', m }) }) // reducer
|
|
1173
|
+
useEvents<Order>(url, { onMessage: (m) => queryClient.setQueryData(['order', id], m) }) // TanStack
|
|
1174
|
+
useEvents<Order>(url, { onMessage: (m) => mutate(['order', id], m, false) }) // SWR
|
|
1175
|
+
usePolling(read, { every, onData: setSeats })
|
|
1176
|
+
ERRORS: both hooks expose error as state AND fire onError - a failed poll read
|
|
1177
|
+
(the next interval still reads) or a dropped stream (EventSource reconnects
|
|
1178
|
+
itself). Use onError for a toast/log; do NOT watch error in a useEffect.
|
|
1179
|
+
usePolling's onError gets (error, { failures }) - failed reads in a row, reset
|
|
1180
|
+
by a success - so toast on the third, not the first.
|
|
1181
|
+
fetchQuery(query, args) types args from the query: fetchQuery(getSeats) for a
|
|
1182
|
+
query that takes nothing, fetchQuery(status, [{ id }]) refused if the query's
|
|
1183
|
+
input has no id.
|
|
1184
|
+
Do NOT put a stream on query() or on a server action, and do NOT poll from
|
|
1185
|
+
inside an events() generator.
|
|
1186
|
+
|
|
1187
|
+
Full guides: read_guide({ slug: 'queries' }) for polling, read_guide({ slug:
|
|
1188
|
+
'api-routes' }) for the streaming route.`,
|
|
885
1189
|
},
|
|
886
1190
|
{
|
|
887
1191
|
topic: 'images',
|
|
@@ -1033,7 +1337,8 @@ export function howTo(topic) {
|
|
|
1033
1337
|
// A near miss is common and worth answering rather than refusing: someone
|
|
1034
1338
|
// asks for "form" or "queries" and means the obvious thing.
|
|
1035
1339
|
RECIPES.find((r) => r.topic.startsWith(wanted) || wanted.startsWith(r.topic)) ??
|
|
1036
|
-
|
|
1340
|
+
// The summary is prose, so a multi-word ask is matched with its spaces back.
|
|
1341
|
+
RECIPES.find((r) => r.summary.toLowerCase().replace(/[-\s]+/g, ' ').includes(wanted.replace(/-/g, ' ')));
|
|
1037
1342
|
if (!found)
|
|
1038
1343
|
return `No topic "${topic}".\n\n${listTopics()}`;
|
|
1039
1344
|
return `# ${found.topic} — ${found.summary}\n\n${found.body}`;
|