@sdxc/kit 2026.10.16 → 2026.10.17

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.
Files changed (114) hide show
  1. package/README.md +1 -0
  2. package/changelog.jsonl +57 -0
  3. package/dist/author.d.ts +36 -0
  4. package/dist/author.js +107 -0
  5. package/dist/commands/create.js +9 -4
  6. package/dist/commands/run.d.ts +2 -2
  7. package/dist/commands/run.js +5 -3
  8. package/dist/contract.js +1 -1
  9. package/dist/create/templates.d.ts +8 -1
  10. package/dist/create/templates.js +25 -2
  11. package/dist/init.d.ts +5 -3
  12. package/dist/init.js +15 -7
  13. package/dist/make/declare.d.ts +4 -4
  14. package/dist/make/declare.js +124 -21
  15. package/dist/make/generate.js +8 -2
  16. package/dist/make/index.js +5 -1
  17. package/dist/make/kinds.d.ts +2 -1
  18. package/dist/make/kinds.js +3 -2
  19. package/dist/testing.d.ts +12 -2
  20. package/dist/testing.js +22 -3
  21. package/package.json +3 -3
  22. package/stubs/command.stub +4 -0
  23. package/stubs/command.test.stub +3 -0
  24. package/stubs/controller.api.stub +21 -0
  25. package/stubs/controller.api.test.stub +18 -0
  26. package/stubs/controller.form.stub +39 -9
  27. package/stubs/controller.form.test.stub +61 -0
  28. package/stubs/controller.stub +15 -8
  29. package/stubs/controller.test.stub +3 -0
  30. package/stubs/email.stub +12 -30
  31. package/stubs/email.test.stub +6 -1
  32. package/stubs/factory.stub +3 -0
  33. package/stubs/initializer.stub +2 -0
  34. package/stubs/initializer.test.stub +3 -0
  35. package/stubs/job.cron.stub +4 -0
  36. package/stubs/job.stub +4 -0
  37. package/stubs/job.test.stub +3 -0
  38. package/stubs/mcp.resource.stub +3 -0
  39. package/stubs/mcp.stub +3 -0
  40. package/stubs/mcp.test.stub +3 -0
  41. package/stubs/middleware.stub +6 -1
  42. package/stubs/middleware.test.stub +3 -0
  43. package/stubs/model.stub +10 -1
  44. package/stubs/model.test.stub +3 -0
  45. package/stubs/policy.stub +3 -0
  46. package/stubs/policy.test.stub +3 -0
  47. package/stubs/service.stub +4 -0
  48. package/stubs/service.test.stub +3 -0
  49. package/stubs/validator.stub +3 -0
  50. package/stubs/validator.test.stub +3 -0
  51. package/templates/app/.env.example +16 -0
  52. package/templates/app/README.md +62 -35
  53. package/templates/app/app/commands/about.test.ts +1 -1
  54. package/templates/app/app/commands/db/console.ts +6 -0
  55. package/templates/app/app/commands/db/migrate.test.ts +30 -0
  56. package/templates/app/app/commands/db/migrate.ts +55 -0
  57. package/templates/app/app/commands/index.ts +16 -0
  58. package/templates/app/app/commands/typegen.test.ts +17 -0
  59. package/templates/app/app/commands/typegen.ts +16 -0
  60. package/templates/app/app/http/controllers/api/health.tsx +15 -0
  61. package/templates/app/app/http/controllers/api/not-found.tsx +16 -0
  62. package/templates/app/app/http/controllers/api/openapi.tsx +17 -0
  63. package/templates/app/app/http/controllers/home.tsx +21 -13
  64. package/templates/app/app/http/controllers/mcp.tsx +16 -0
  65. package/templates/app/app/http/controllers/not-found.tsx +23 -18
  66. package/templates/app/app/http/controllers/robots.test.ts +18 -0
  67. package/templates/app/app/http/controllers/robots.ts +24 -0
  68. package/templates/app/app/http/controllers/sitemap.test.ts +28 -0
  69. package/templates/app/app/http/controllers/sitemap.ts +25 -0
  70. package/templates/app/app/http/middleware/api.ts +10 -0
  71. package/templates/app/app/http/middleware/page.test.ts +40 -0
  72. package/templates/app/app/http/middleware/page.ts +49 -0
  73. package/templates/app/app/http/middleware/server-timing.test.ts +15 -0
  74. package/templates/app/app/http/middleware/server-timing.ts +42 -0
  75. package/templates/app/app/initializers/assets.ts +1 -1
  76. package/templates/app/app/initializers/captcha.ts +11 -0
  77. package/templates/app/app/initializers/cli.ts +42 -2
  78. package/templates/app/app/initializers/database.test.ts +18 -0
  79. package/templates/app/app/initializers/database.ts +18 -0
  80. package/templates/app/app/initializers/dispatcher.ts +18 -0
  81. package/templates/app/app/initializers/honeypot.ts +11 -0
  82. package/templates/app/app/initializers/i18n.test.ts +16 -0
  83. package/templates/app/app/initializers/i18n.ts +28 -0
  84. package/templates/app/app/initializers/local-database.test.ts +33 -0
  85. package/templates/app/app/initializers/local-database.ts +53 -0
  86. package/templates/app/app/initializers/mail.test.ts +27 -0
  87. package/templates/app/app/initializers/mail.ts +11 -0
  88. package/templates/app/app/initializers/mcp.ts +1 -1
  89. package/templates/app/app/initializers/openapi.ts +21 -0
  90. package/templates/app/app/initializers/router.test.ts +61 -0
  91. package/templates/app/app/initializers/router.tsx +72 -26
  92. package/templates/app/app/initializers/seo.ts +15 -0
  93. package/templates/app/app/initializers/session.test.ts +34 -0
  94. package/templates/app/app/initializers/session.ts +29 -0
  95. package/templates/app/app/initializers/spam.ts +10 -0
  96. package/templates/app/app/models/index.ts +10 -0
  97. package/templates/app/app/services/migrations.test.ts +45 -0
  98. package/templates/app/app/services/migrations.ts +60 -0
  99. package/templates/app/app/test/cloudflare-workers.ts +25 -0
  100. package/templates/app/bootstrap/cli.ts +1 -1
  101. package/templates/app/bootstrap/worker.ts +4 -4
  102. package/templates/app/cloudflare.config.ts +29 -1
  103. package/templates/app/config/constants.ts +19 -0
  104. package/templates/app/config/problems.ts +24 -0
  105. package/templates/app/config/security-policy.ts +34 -0
  106. package/templates/app/config/security-txt.ts +28 -0
  107. package/templates/app/database/migrations/.gitkeep +0 -0
  108. package/templates/app/package.json +35 -5
  109. package/templates/app/resources/layouts/document.tsx +28 -7
  110. package/templates/app/resources/locales/en.json +10 -0
  111. package/templates/app/routes/api.ts +29 -0
  112. package/templates/app/routes/web.ts +6 -4
  113. package/templates/app/vite.config.ts +4 -0
  114. package/templates/app/config/router-context.d.ts +0 -20
@@ -0,0 +1,55 @@
1
+ /**
2
+ * `db migrate`: applies every migration in `database/migrations/` the database lacks. Locally it
3
+ * writes the SQLite file `bun dev` serves from; with `--remote` it runs `cf d1 migrations apply`
4
+ * against the production database. Safe to run twice: an applied migration is skipped.
5
+ */
6
+
7
+ import { readdir, readFile } from "node:fs/promises";
8
+ import { join } from "node:path";
9
+
10
+ import { createCommand, success } from "@sdxc/cli";
11
+ import { openDatabase } from "@sdxc/cloudflare-mocks/sqlite";
12
+ import { isFailure } from "@sdxc/result";
13
+
14
+ import commandset from "~/app/commands";
15
+ import { DATABASE_ID, LOCAL_DATABASE_FILE, PROJECT_ROOT } from "~/app/initializers/local-database";
16
+ import { applyMigrations } from "~/app/services/migrations";
17
+
18
+ /** The migration chain `sdxc make migration` writes into, relative to the project's root. */
19
+ const MIGRATIONS_DIRECTORY = "database/migrations";
20
+
21
+ /** Every `.sql` file in the chain, with its SQL. */
22
+ async function readMigrations() {
23
+ let directory = join(PROJECT_ROOT, MIGRATIONS_DIRECTORY);
24
+ let names = (await readdir(directory)).filter((name) => name.endsWith(".sql"));
25
+ return Promise.all(
26
+ names.map(async (name) => ({
27
+ name,
28
+ sql: await readFile(join(directory, name), "utf8"),
29
+ })),
30
+ );
31
+ }
32
+
33
+ export default createCommand(commandset.db.migrate, async (ctx) => {
34
+ if (ctx.flags.remote) {
35
+ let applied = await ctx.exec(
36
+ ["cf", "d1", "migrations", "apply", DATABASE_ID, "--dir", MIGRATIONS_DIRECTORY],
37
+ { cwd: PROJECT_ROOT },
38
+ );
39
+ return isFailure(applied) ? applied : success();
40
+ }
41
+
42
+ let database = openDatabase(LOCAL_DATABASE_FILE);
43
+ try {
44
+ let applied = applyMigrations(database, await readMigrations());
45
+ if (isFailure(applied)) return applied;
46
+ ctx.stdout(
47
+ applied.data.length === 0
48
+ ? "No migrations to apply\n"
49
+ : applied.data.map((name) => `Applied ${name}\n`).join(""),
50
+ );
51
+ return success();
52
+ } finally {
53
+ database.close();
54
+ }
55
+ });
@@ -5,6 +5,7 @@
5
5
  */
6
6
 
7
7
  import { command, commands, flag } from "@sdxc/cli";
8
+ import { DB_COMMAND } from "@sdxc/database-middleware/cli";
8
9
 
9
10
  /** The app's commands; `sdxc make command <name>` declares one here and maps its handler. */
10
11
  export default commands({
@@ -12,4 +13,19 @@ export default commands({
12
13
  description: "Print the app's name, its @sdxc/cli and remix versions, and the runtime",
13
14
  flags: { json: flag.boolean("json", { description: "Print it as JSON" }) },
14
15
  }),
16
+ db: commands({
17
+ console: DB_COMMAND,
18
+ migrate: command({
19
+ description: "Apply the migrations in database/migrations the database lacks",
20
+ flags: {
21
+ remote: flag.boolean("remote", {
22
+ description: "Apply them to the production database instead of the local copy",
23
+ }),
24
+ },
25
+ examples: ["db migrate", "db migrate --remote"],
26
+ }),
27
+ }),
28
+ typegen: command({
29
+ description: "Write the Worker's env types from cloudflare.config.ts",
30
+ }),
15
31
  });
@@ -0,0 +1,17 @@
1
+ /**
2
+ * The `typegen` command, which hands type generation to `cf` in the project's root.
3
+ */
4
+
5
+ import { invoke } from "@sdxc/cli/test";
6
+ import { describe, expect, test } from "vitest";
7
+
8
+ import { cli } from "~/app/initializers/cli";
9
+
10
+ describe("typegen", () => {
11
+ test("generates the Worker's types with cf", async () => {
12
+ let run = await invoke(cli, ["typegen"], { exec: { "cf workers types": { code: 0 } } });
13
+
14
+ expect(run.code).toBe(0);
15
+ expect(run.exec.map((call) => call.command)).toEqual([["cf", "workers", "types"]]);
16
+ });
17
+ });
@@ -0,0 +1,16 @@
1
+ /**
2
+ * `typegen`: writes the Worker's `env` types from `cloudflare.config.ts` through `cf workers
3
+ * types`. Run it after adding or changing a binding or a secret, so `env` and every handler
4
+ * type check against what the Worker receives. Safe to run twice.
5
+ */
6
+
7
+ import { createCommand, success } from "@sdxc/cli";
8
+ import { isFailure } from "@sdxc/result";
9
+
10
+ import commandset from "~/app/commands";
11
+ import { PROJECT_ROOT } from "~/app/initializers/local-database";
12
+
13
+ export default createCommand(commandset.typegen, async (ctx) => {
14
+ let generated = await ctx.exec(["cf", "workers", "types"], { cwd: PROJECT_ROOT });
15
+ return isFailure(generated) ? generated : success();
16
+ });
@@ -0,0 +1,15 @@
1
+ /**
2
+ * The health check: it answers as soon as the Worker runs, so a monitor tells a deploy that
3
+ * serves from one that fails to start.
4
+ */
5
+
6
+ import { createAction } from "remix/router";
7
+
8
+ import api from "~/app/http/middleware/api";
9
+ import routes from "~/routes/api";
10
+
11
+ export default createAction(routes.api.health, {
12
+ middleware: api,
13
+ /** GET /api/health, answered as the `health` operation documents it. */
14
+ handler: () => Response.json({ status: "ok" }),
15
+ });
@@ -0,0 +1,16 @@
1
+ /**
2
+ * The API's 404: an unknown path under `/api` answers an RFC 9457 problem document, which a
3
+ * client parses the same way as every other error the API returns.
4
+ */
5
+
6
+ import { createAction } from "remix/router";
7
+
8
+ import api from "~/app/http/middleware/api";
9
+ import problems from "~/config/problems";
10
+ import routes from "~/routes/api";
11
+
12
+ export default createAction(routes.api.notFound, {
13
+ middleware: api,
14
+ /** Any method on an unknown `/api` path answers the `notFound` problem. */
15
+ handler: () => problems.notFound(),
16
+ });
@@ -0,0 +1,17 @@
1
+ /**
2
+ * The API's OpenAPI document, served as JSON or, for `?format=yaml`, YAML. It is built from
3
+ * the operations in `routes/api.ts`, so it describes exactly what the handlers parse.
4
+ */
5
+
6
+ import { openapiHandler } from "@sdxc/openapi/router";
7
+ import { createAction } from "remix/router";
8
+
9
+ import api from "~/app/http/middleware/api";
10
+ import { createApiDocument } from "~/app/initializers/openapi";
11
+ import routes from "~/routes/api";
12
+
13
+ export default createAction(routes.api.openapi, {
14
+ middleware: api,
15
+ /** GET /api/openapi.json, naming the origin the request reached as the API's server. */
16
+ handler: (ctx) => openapiHandler(() => createApiDocument(ctx.url.origin).build())(ctx),
17
+ });
@@ -1,22 +1,30 @@
1
1
  /**
2
2
  * The home page, the first thing a visitor sees. It renders through the document layout,
3
- * which links the stylesheets and client entry the request resolved.
3
+ * which links the stylesheets and client entry the page middleware resolved.
4
4
  */
5
5
 
6
+ import { Trans } from "@sdxc/i18n/ui";
6
7
  import { createAction } from "remix/router";
7
8
 
9
+ import page from "~/app/http/middleware/page";
8
10
  import DocumentLayout from "~/resources/layouts/document";
9
11
  import routes from "~/routes/web";
10
12
 
11
- /** GET / — the welcome page. */
12
- export default createAction(routes.home, (ctx) =>
13
- ctx.render(
14
- <DocumentLayout assets={ctx.assets} title="Welcome">
15
- <h1>Welcome</h1>
16
- <p>
17
- Edit <code>app/http/controllers/home.tsx</code>, or add a page with{" "}
18
- <code>sdxc make controller &lt;name&gt;</code>.
19
- </p>
20
- </DocumentLayout>,
21
- ),
22
- );
13
+ export default createAction(routes.home, {
14
+ middleware: page,
15
+ /** GET / — the welcome page. */
16
+ handler: (ctx) =>
17
+ ctx.render(
18
+ <DocumentLayout
19
+ assets={ctx.assets}
20
+ intl={ctx.intl}
21
+ url={ctx.url}
22
+ title={ctx.intl.t("home.title")}
23
+ >
24
+ <h1>{ctx.intl.t("home.title")}</h1>
25
+ <p>
26
+ <Trans i18nKey="home.body" components={{ file: <code />, command: <code /> }} />
27
+ </p>
28
+ </DocumentLayout>,
29
+ ),
30
+ });
@@ -0,0 +1,16 @@
1
+ /**
2
+ * The MCP endpoint an agent connects to. It forwards each request to the app's MCP server,
3
+ * whose tools and resources live in `app/mcp/`.
4
+ */
5
+
6
+ import { createAction } from "remix/router";
7
+
8
+ import api from "~/app/http/middleware/api";
9
+ import mcp from "~/app/initializers/mcp";
10
+ import routes from "~/routes/api";
11
+
12
+ export default createAction(routes.mcp, {
13
+ middleware: api,
14
+ /** POST /mcp, answered over Streamable HTTP. */
15
+ handler: (ctx) => mcp.fetch(ctx),
16
+ });
@@ -1,25 +1,30 @@
1
1
  /**
2
- * The router's default handler: any request that matches no route gets the app's own 404
3
- * page, with a way back home.
2
+ * The 404 page for any path no other route claims, with a way back home. An unknown path
3
+ * under `/api` answers a problem document instead, from its own route.
4
4
  */
5
5
 
6
- import type { RequestContext } from "remix/router";
6
+ import { createAction } from "remix/router";
7
7
 
8
+ import page from "~/app/http/middleware/page";
8
9
  import DocumentLayout from "~/resources/layouts/document";
9
10
  import routes from "~/routes/web";
10
11
 
11
- /**
12
- * Renders the 404 document. It takes only the members it reads, since the router derives
13
- * `AppContext` from the options this handler is passed in.
14
- */
15
- export default function notFound(ctx: Pick<RequestContext, "assets" | "render">) {
16
- return ctx.render(
17
- <DocumentLayout assets={ctx.assets} title="Not found">
18
- <h1>Not found</h1>
19
- <p>
20
- <a href={routes.home.href()}>Back home</a>
21
- </p>
22
- </DocumentLayout>,
23
- { status: 404 },
24
- );
25
- }
12
+ export default createAction(routes.notFound, {
13
+ middleware: page,
14
+ /** Any method on an unknown path renders the 404 document. */
15
+ handler: (ctx) =>
16
+ ctx.render(
17
+ <DocumentLayout
18
+ assets={ctx.assets}
19
+ intl={ctx.intl}
20
+ url={ctx.url}
21
+ title={ctx.intl.t("notFound.title")}
22
+ >
23
+ <h1>{ctx.intl.t("notFound.title")}</h1>
24
+ <p>
25
+ <a href={routes.home.href()}>{ctx.intl.t("notFound.back")}</a>
26
+ </p>
27
+ </DocumentLayout>,
28
+ { status: 404 },
29
+ ),
30
+ });
@@ -0,0 +1,18 @@
1
+ /**
2
+ * `/robots.txt`, fetched through the app's router.
3
+ */
4
+
5
+ import { describe, expect, test } from "vitest";
6
+
7
+ import { createWebRouter } from "~/app/initializers/router";
8
+
9
+ describe("robots", () => {
10
+ test("lets every crawler in and points it at the sitemap on SITE_URL", async () => {
11
+ let response = await createWebRouter().fetch("https://preview.example.net/robots.txt");
12
+
13
+ let body = await response.text();
14
+ expect(response.headers.get("content-type")).toBe("text/plain; charset=utf-8");
15
+ expect(body).toContain("User-agent: *");
16
+ expect(body).toContain("Sitemap: https://example.com/sitemap.xml");
17
+ });
18
+ });
@@ -0,0 +1,24 @@
1
+ /**
2
+ * `/robots.txt`: every crawler may read every page, and the sitemap lists them. Add a rule here
3
+ * before a path should stay out of search results.
4
+ */
5
+
6
+ import { text } from "@sdxc/http/response";
7
+ import { stringify } from "@sdxc/robots";
8
+ import { createAction } from "remix/router";
9
+
10
+ import { seo } from "~/app/initializers/seo";
11
+ import routes from "~/routes/web";
12
+
13
+ export default createAction(routes.robots, {
14
+ /** GET /robots.txt, cached for a day since it changes only with a deploy. */
15
+ handler: () =>
16
+ text(
17
+ stringify({
18
+ groups: [{ userAgents: ["*"], rules: [{ allow: true, pattern: "/" }] }],
19
+ sitemaps: [seo.absolute(routes.sitemap.href())],
20
+ records: [],
21
+ }),
22
+ { headers: { "Cache-Control": "public, max-age=86400" } },
23
+ ),
24
+ });
@@ -0,0 +1,28 @@
1
+ /**
2
+ * `/sitemap.xml`, fetched through the app's router.
3
+ */
4
+
5
+ import { describe, expect, test } from "vitest";
6
+
7
+ import { createWebRouter } from "~/app/initializers/router";
8
+
9
+ describe("sitemap", () => {
10
+ test("lists the home page at its canonical URL, cached for an hour", async () => {
11
+ let response = await createWebRouter().fetch("https://preview.example.net/sitemap.xml");
12
+
13
+ expect(response.headers.get("content-type")).toBe("text/xml; charset=utf-8");
14
+ expect(response.headers.get("cache-control")).toBe("public, max-age=3600");
15
+ let body = await response.text();
16
+ expect(body).toContain("<loc>https://example.com/</loc>");
17
+ expect(body).toContain("<priority>1</priority>");
18
+ });
19
+
20
+ test("leaves out robots.txt and the sitemap itself", async () => {
21
+ let response = await createWebRouter().fetch("https://preview.example.net/sitemap.xml");
22
+ let body = await response.text();
23
+
24
+ expect(body).not.toContain("robots.txt");
25
+ expect(body).not.toContain("sitemap.xml");
26
+ expect(body).not.toContain("preview.example.net");
27
+ });
28
+ });
@@ -0,0 +1,25 @@
1
+ /**
2
+ * `/sitemap.xml`: every public page, at its canonical URL, for search engines to find. Every
3
+ * GET route in `routes/web.ts` needs a decision here, so a new route fails to typecheck until
4
+ * it is listed or excluded.
5
+ */
6
+
7
+ import { xml } from "@sdxc/http/response";
8
+ import { fromRoutes } from "@sdxc/sitemap/remix";
9
+ import { createAction } from "remix/router";
10
+
11
+ import { seo } from "~/app/initializers/seo";
12
+ import routes from "~/routes/web";
13
+
14
+ export default createAction(routes.sitemap, {
15
+ /** GET /sitemap.xml, cached for an hour, with URLs on `SITE_URL` whichever host served it. */
16
+ handler: () => {
17
+ let sitemap = fromRoutes(routes, seo.baseUrl, {
18
+ home: { priority: 1 },
19
+ robots: false,
20
+ sitemap: false,
21
+ notFound: false,
22
+ });
23
+ return xml(sitemap.toString(), { headers: { "Cache-Control": "public, max-age=3600" } });
24
+ },
25
+ });
@@ -0,0 +1,10 @@
1
+ /**
2
+ * The middleware every API endpoint declares: CORS, so a browser on another origin can call
3
+ * it. An endpoint reads its own body, as JSON or a form, so it is left unparsed here.
4
+ */
5
+
6
+ import { cors } from "remix/middleware/cors";
7
+ import { createMiddleware } from "remix/router";
8
+
9
+ /** Answers CORS preflights and adds the CORS headers to every endpoint's response. */
10
+ export default createMiddleware(cors());
@@ -0,0 +1,40 @@
1
+ /**
2
+ * The page chain's security headers and language, checked through the home page, since every
3
+ * page declares the same chain and so sends the same policy.
4
+ */
5
+
6
+ import { describe, expect, test } from "vitest";
7
+
8
+ import { createWebRouter } from "~/app/initializers/router";
9
+
10
+ describe("page", () => {
11
+ test("sends the Content-Security-Policy with a page", async () => {
12
+ let response = await createWebRouter().fetch("https://example.com/");
13
+
14
+ expect(response.headers.get("content-security-policy")).toContain("default-src 'self'");
15
+ expect(response.headers.get("x-frame-options")).toBe("DENY");
16
+ });
17
+
18
+ test("advertises no nonce when the page renders no inline script", async () => {
19
+ let response = await createWebRouter().fetch("https://example.com/");
20
+
21
+ expect(response.headers.get("content-security-policy")).not.toContain("'nonce-");
22
+ });
23
+
24
+ test("renders in the language the visitor asks for, or the fallback", async () => {
25
+ let response = await createWebRouter().fetch(
26
+ new Request("https://example.com/", { headers: { "accept-language": "fr-FR, en;q=0.5" } }),
27
+ );
28
+
29
+ let html = await response.text();
30
+ expect(html).toContain('<html lang="en"');
31
+ expect(html).toContain("<h1>Welcome</h1>");
32
+ expect(html).toContain("<code>app/http/controllers/home.tsx</code>");
33
+ });
34
+
35
+ test("links the canonical URL on SITE_URL, whichever host served the page", async () => {
36
+ let response = await createWebRouter().fetch("https://preview.example.net/?utm_source=mail");
37
+
38
+ expect(await response.text()).toContain('<link rel="canonical" href="https://example.com/"');
39
+ });
40
+ });
@@ -0,0 +1,49 @@
1
+ /**
2
+ * The middleware every page declares: the parsed form body, the cross-origin check a
3
+ * cookie-backed form relies on, the visitor's session and language, the honeypot every form submission must pass, the security
4
+ * headers, and the document's assets and renderer. A page controller passes it as its
5
+ * `middleware`, so only requests that render a document pay for it.
6
+ */
7
+
8
+ import { assets } from "@sdxc/assets-middleware";
9
+ import { honeypot } from "@sdxc/honeypot/middleware";
10
+ import i18n from "@sdxc/i18n/middleware";
11
+ import { securityHeaders } from "@sdxc/security-headers/middleware";
12
+ import { cop } from "remix/middleware/cop";
13
+ import { formData } from "remix/middleware/form-data";
14
+ import { render } from "remix/middleware/render";
15
+ import { session } from "remix/middleware/session";
16
+ import { createMiddleware } from "remix/router";
17
+
18
+ import { assetResolver } from "~/app/initializers/assets";
19
+ import { honeypot as trap } from "~/app/initializers/honeypot";
20
+ import { FALLBACK_LANGUAGE, RESOURCES, SUPPORTED_LANGUAGES } from "~/app/initializers/i18n";
21
+ import { sessionCookie, sessionStorage } from "~/app/initializers/session";
22
+ import { SECURITY_POLICY } from "~/config/security-policy";
23
+
24
+ /**
25
+ * Publishes `ctx.formData`, `ctx.session`, `ctx.locale`, `ctx.intl`, `ctx.honeypot`, `ctx.securityHeaders`, `ctx.assets` and
26
+ * `ctx.render` on a page's context. A POST without valid honeypot fields is refused with a 400
27
+ * before the controller runs; the security headers come right before the assets and renderer.
28
+ */
29
+ export default createMiddleware(
30
+ formData(),
31
+ cop(),
32
+ session(sessionCookie, sessionStorage),
33
+ i18n({
34
+ detection: {
35
+ supportedLanguages: SUPPORTED_LANGUAGES,
36
+ fallbackLanguage: FALLBACK_LANGUAGE,
37
+ sessionKey: "lng",
38
+ },
39
+ resources: RESOURCES,
40
+ }),
41
+ honeypot(trap),
42
+ securityHeaders(SECURITY_POLICY),
43
+ assets(assetResolver, {
44
+ stylesheets: "resources/layouts/document.tsx",
45
+ script: "bootstrap/browser.ts",
46
+ nonce: (ctx) => ctx.securityHeaders.nonce,
47
+ }),
48
+ render({ assets: assetResolver }),
49
+ );
@@ -0,0 +1,15 @@
1
+ /**
2
+ * The `Server-Timing` header every response carries, checked through the app's router.
3
+ */
4
+
5
+ import { describe, expect, test } from "vitest";
6
+
7
+ import { createWebRouter } from "~/app/initializers/router";
8
+
9
+ describe("serverTiming", () => {
10
+ test("reports how long the request took", async () => {
11
+ let response = await createWebRouter().fetch("https://example.com/api/health");
12
+
13
+ expect(response.headers.get("server-timing")).toMatch(/^app(;dur=[\d.]+)?$/);
14
+ });
15
+ });
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Publishes a `Server-Timing` collector on every request as `ctx.timing` and writes what it
3
+ * measured onto the response, so browser devtools show where a request spent its time:
4
+ * `await ctx.timing.measure("db", "listPosts", () => listPosts())`.
5
+ */
6
+
7
+ import type { Middleware } from "remix/router";
8
+
9
+ import { TimingCollector } from "@sdxc/server-timing";
10
+ import { createContextKey } from "remix/router";
11
+
12
+ declare module "remix/router" {
13
+ interface RequestContext {
14
+ /** The request's timings, sent as its `Server-Timing` header. */
15
+ timing: TimingCollector;
16
+ }
17
+ }
18
+
19
+ /** Reads the request's collector by key, for code holding a context whose chain is unknown. */
20
+ export const Timing: { defaultValue?: TimingCollector } = createContextKey<TimingCollector>();
21
+
22
+ /**
23
+ * Creates the middleware. The whole request is measured as `app`, recorded after every entry a
24
+ * handler adds; the header goes on a copy of the response, so a redirect or a proxied
25
+ * response with immutable headers carries it too.
26
+ */
27
+ export default function serverTiming(): Middleware<{
28
+ key: typeof Timing;
29
+ value: TimingCollector;
30
+ property: "timing";
31
+ }> {
32
+ return async (ctx, next) => {
33
+ let timing = new TimingCollector();
34
+ ctx.set(Timing, timing, { property: "timing" });
35
+ let response = await timing.measure("app", "", () => next());
36
+ return new Response(response.body, {
37
+ status: response.status,
38
+ statusText: response.statusText,
39
+ headers: timing.toHeaders(new Headers(response.headers)),
40
+ });
41
+ };
42
+ }
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * The asset resolver, read from the manifest the Vite plugin writes: the source files
3
- * `vite dev` serves while editing, and the hashed files `vite build` emits. The document
3
+ * `vp dev` serves while editing, and the hashed files `vp build` emits. The document
4
4
  * links what it returns, so no tag names a file the build renamed.
5
5
  */
6
6
 
@@ -0,0 +1,11 @@
1
+ /**
2
+ * The CAPTCHA a form asks a visitor to pass before its action runs: Cloudflare Turnstile,
3
+ * verified on the server with `TURNSTILE_SECRET_KEY`. A form renders the widget with
4
+ * `TURNSTILE_SITE_KEY` and its action declares `captcha(turnstile)`.
5
+ */
6
+
7
+ import { Turnstile } from "@sdxc/captcha/turnstile";
8
+ import { env } from "cloudflare:workers";
9
+
10
+ /** Verifies the token the widget writes into the form, once per submission. */
11
+ export const turnstile = new Turnstile({ secretKey: env.TURNSTILE_SECRET_KEY });
@@ -5,11 +5,21 @@
5
5
  */
6
6
 
7
7
  import { createCLI, lazy } from "@sdxc/cli";
8
+ import { models } from "@sdxc/data-model/cli";
9
+ import { Database, database } from "@sdxc/database-middleware/cli";
10
+ import i18n from "@sdxc/i18n/middleware/cli";
8
11
  import { createLogger } from "@sdxc/logger";
9
12
  import { log } from "@sdxc/logger/middleware/cli";
13
+ import mail from "@sdxc/mail/middleware/cli";
14
+ import { PrintTransport } from "@sdxc/mail/print";
15
+ import { trace } from "@sdxc/trace-context/middleware/cli";
10
16
 
11
17
  import commandset from "~/app/commands";
18
+ import { FALLBACK_LANGUAGE, RESOURCES, SUPPORTED_LANGUAGES } from "~/app/initializers/i18n";
19
+ import { openLocalDatabase } from "~/app/initializers/local-database";
12
20
  import { logger } from "~/app/initializers/logger";
21
+ import registry from "~/app/models";
22
+ import { MAIL_FROM } from "~/config/constants";
13
23
 
14
24
  import manifest from "../../package.json" with { type: "json" };
15
25
 
@@ -22,14 +32,44 @@ const COMMAND_LOGGER = createLogger({
22
32
  sink: (record) => process.stderr.write(`${JSON.stringify(record)}\n`),
23
33
  });
24
34
 
25
- /** The command line `bootstrap/cli.ts` runs and a command's test invokes. */
35
+ /**
36
+ * The command line `bootstrap/cli.ts` runs and a command's test invokes. A command reads the
37
+ * local database as `ctx.db` and its models as `ctx.models`, prints the email it sends to stderr
38
+ * through `ctx.email`, and writes its output in the language `LANG` names through `ctx.intl`.
39
+ */
26
40
  export const cli = createCLI({
27
41
  name: manifest.name,
28
42
  commands: commandset,
29
- middleware: [log(COMMAND_LOGGER)],
43
+ middleware: [
44
+ log(COMMAND_LOGGER),
45
+ trace(),
46
+ database(openLocalDatabase),
47
+ models(registry, (ctx) => ({ db: ctx.require(Database) })),
48
+ mail({
49
+ transport: (ctx) => new PrintTransport({ write: (text) => ctx.stderr(text) }),
50
+ from: MAIL_FROM,
51
+ }),
52
+ i18n({
53
+ resources: RESOURCES,
54
+ supportedLanguages: SUPPORTED_LANGUAGES,
55
+ fallbackLanguage: FALLBACK_LANGUAGE,
56
+ }),
57
+ ],
30
58
  });
31
59
 
32
60
  cli.map(
33
61
  commandset.about,
34
62
  lazy(() => import("~/app/commands/about")),
35
63
  );
64
+ cli.map(
65
+ commandset.db.console,
66
+ lazy(() => import("~/app/commands/db/console")),
67
+ );
68
+ cli.map(
69
+ commandset.db.migrate,
70
+ lazy(() => import("~/app/commands/db/migrate")),
71
+ );
72
+ cli.map(
73
+ commandset.typegen,
74
+ lazy(() => import("~/app/commands/typegen")),
75
+ );
@@ -0,0 +1,18 @@
1
+ /**
2
+ * The database the router and the job dispatcher publish as `ctx.db`, run against the
3
+ * in-memory D1 stand-in tests receive as the `DB` binding.
4
+ */
5
+
6
+ import { describe, expect, test } from "vitest";
7
+
8
+ import { openDatabase } from "~/app/initializers/database";
9
+
10
+ describe("openDatabase", () => {
11
+ test("runs SQL through the DB binding", async () => {
12
+ let db = openDatabase();
13
+
14
+ let result = await db.exec("SELECT 41 + 1 AS answer");
15
+
16
+ expect(result.rows).toEqual([{ answer: 42 }]);
17
+ });
18
+ });