@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,18 @@
1
+ /**
2
+ * The app's database: `remix/data-table` over the `DB` D1 binding. The router and the job
3
+ * dispatcher publish it as `ctx.db`, so a controller, a job and a model bound with
4
+ * `Model.bind({ db: ctx.db })` all read and write the same tables.
5
+ */
6
+
7
+ import { createD1DatabaseAdapter } from "@sdxc/data-table-d1";
8
+ import { env } from "cloudflare:workers";
9
+ import { Database } from "remix/data-table";
10
+
11
+ /**
12
+ * Opens the database over the `DB` binding. Timestamps are written as epoch milliseconds,
13
+ * since `sdxc make model` types `created_at` and `updated_at` as integer columns and D1 binds
14
+ * no `Date`.
15
+ */
16
+ export function openDatabase(): Database {
17
+ return new Database(createD1DatabaseAdapter(env.DB), { now: () => Date.now() });
18
+ }
@@ -4,15 +4,33 @@
4
4
  * loader, so a module is imported only once a message for its job arrives.
5
5
  */
6
6
 
7
+ import type { JobDispatcherContext } from "@sdxc/jobs";
8
+
9
+ import { models } from "@sdxc/data-model/jobs";
10
+ import { Database } from "@sdxc/database-middleware";
11
+ import { database } from "@sdxc/database-middleware/jobs";
7
12
  import { createJobDispatcher } from "@sdxc/jobs";
8
13
  import * as cloudflare from "@sdxc/jobs/cloudflare";
9
14
  import { env } from "cloudflare:workers";
10
15
 
16
+ import { openDatabase } from "~/app/initializers/database";
11
17
  import { logger } from "~/app/initializers/logger";
18
+ import registry from "~/app/models";
12
19
 
13
20
  /** The dispatcher `bootstrap/worker.ts` hands queue batches and cron triggers to. */
14
21
  export const dispatcher = createJobDispatcher({
15
22
  logger,
16
23
  queue: cloudflare.queue(() => env.QUEUE),
24
+ middleware: [
25
+ database(openDatabase),
26
+ models(registry, (ctx) => ({ db: ctx.require(Database) })),
27
+ ] as const,
17
28
  timeout: "5 minutes",
18
29
  });
30
+
31
+ declare module "@sdxc/jobs" {
32
+ /** Types every job handler's `ctx` with what the dispatcher's middleware publishes: `ctx.db` and `ctx.models`. */
33
+ interface JobTypes {
34
+ context: JobDispatcherContext<typeof dispatcher>;
35
+ }
36
+ }
@@ -0,0 +1,11 @@
1
+ /**
2
+ * The honeypot every page form carries: a hidden trap field a person never fills, and a token
3
+ * signing when the form was rendered. The page middleware refuses a submission that fails
4
+ * either, so a form needs only to render the fields.
5
+ */
6
+
7
+ import { Honeypot } from "@sdxc/honeypot";
8
+ import { env } from "cloudflare:workers";
9
+
10
+ /** Signs with `HONEYPOT_SECRET`; set it with `cf workers secrets update` before deploying. */
11
+ export const honeypot = new Honeypot({ secret: env.HONEYPOT_SECRET });
@@ -0,0 +1,16 @@
1
+ /**
2
+ * The translator a job or an email uses, which reads the same bundles a page does.
3
+ */
4
+
5
+ import { describe, expect, test } from "vitest";
6
+
7
+ import { translate } from "~/app/initializers/i18n";
8
+
9
+ describe("translate", () => {
10
+ test("binds the fallback language for an unsupported one", () => {
11
+ let { locale, t } = translate("fr");
12
+
13
+ expect(locale).toBe("en");
14
+ expect(t("notFound.title")).toBe("Not found");
15
+ });
16
+ });
@@ -0,0 +1,28 @@
1
+ /**
2
+ * The app's languages and message bundles, in one place so the page middleware, a job and an
3
+ * email reach the same copy. Add a language by adding its bundle under `resources/locales/` and
4
+ * listing it in {@link SUPPORTED_LANGUAGES}.
5
+ */
6
+
7
+ import { createTranslator } from "@sdxc/i18n";
8
+
9
+ import en from "~/resources/locales/en.json";
10
+
11
+ /** The languages a page can render in; a request asking for any other gets the fallback. */
12
+ export const SUPPORTED_LANGUAGES = ["en"];
13
+
14
+ /** The language that answers a request asking for none the app speaks, and any key a bundle lacks. */
15
+ export const FALLBACK_LANGUAGE = "en";
16
+
17
+ /** The message bundles, one per supported language, as MessageFormat 2 strings. */
18
+ export const RESOURCES = { en };
19
+
20
+ /**
21
+ * Translates outside a request, such as in a job or an email, into the recipient's language:
22
+ * `translate(user.language).t("home.title")`. An unsupported language binds the fallback.
23
+ */
24
+ export const translate = createTranslator({
25
+ resources: RESOURCES,
26
+ supportedLanguages: SUPPORTED_LANGUAGES,
27
+ fallbackLanguage: FALLBACK_LANGUAGE,
28
+ });
@@ -0,0 +1,33 @@
1
+ /**
2
+ * The local database a command reads as `ctx.db`, opened in memory so the test leaves the
3
+ * project's own copy untouched.
4
+ */
5
+
6
+ import { createModel } from "@sdxc/data-model";
7
+ import { unwrap } from "@sdxc/result";
8
+ import { column as c, table } from "remix/data-table";
9
+ import { describe, expect, test } from "vitest";
10
+
11
+ import { openLocalDatabase } from "~/app/initializers/local-database";
12
+
13
+ /** A table with the timestamp columns `sdxc make model` writes. */
14
+ const POSTS = table({
15
+ name: "posts",
16
+ columns: { id: c.text().primaryKey(), created_at: c.integer(), updated_at: c.integer() },
17
+ timestamps: true,
18
+ });
19
+
20
+ describe("openLocalDatabase", () => {
21
+ test("writes timestamps as epoch milliseconds, as the Worker's database does", async () => {
22
+ let db = openLocalDatabase(":memory:");
23
+ await db.exec(
24
+ "CREATE TABLE posts (id TEXT PRIMARY KEY, created_at INTEGER NOT NULL, updated_at INTEGER NOT NULL)",
25
+ );
26
+
27
+ let posts = createModel(POSTS, {}).bind({ db });
28
+
29
+ let row = unwrap(await posts.create({ id: "p1" }));
30
+
31
+ expect(typeof row.created_at).toBe("number");
32
+ });
33
+ });
@@ -0,0 +1,53 @@
1
+ /**
2
+ * The local copy of the app's D1 database, opened as the SQLite file `bun dev` keeps it in, so a
3
+ * command reads and writes the rows the dev server serves. Miniflare names that file after the
4
+ * database id in `cloudflare.config.ts`, so it is found without starting the Worker runtime.
5
+ */
6
+
7
+ import { createHmac, createHash } from "node:crypto";
8
+ import { mkdirSync } from "node:fs";
9
+ import { dirname, join } from "node:path";
10
+
11
+ import type { Database } from "remix/data-table";
12
+
13
+ import { createSqliteDatabase } from "remix/data-table/sqlite";
14
+
15
+ import config from "../../cloudflare.config";
16
+ import manifest from "../../package.json" with { type: "json" };
17
+
18
+ /** The Durable Object namespace Miniflare stores every local D1 database under. */
19
+ const NAMESPACE = "miniflare-D1DatabaseObject";
20
+
21
+ /**
22
+ * Miniflare's object id for `name`: an HMAC-SHA256 of the name and an HMAC of that, both keyed by
23
+ * the namespace's SHA-256 and cut to 16 bytes, so one database id always maps to one file.
24
+ */
25
+ function objectId(namespace: string, name: string): string {
26
+ let key = createHash("sha256").update(namespace).digest();
27
+ let id = createHmac("sha256", key).update(name).digest().subarray(0, 16);
28
+ let mac = createHmac("sha256", key).update(id).digest().subarray(0, 16);
29
+ return Buffer.concat([id, mac]).toString("hex");
30
+ }
31
+
32
+ /** The project's root, which every path a command reads is resolved against. */
33
+ export const PROJECT_ROOT = join(import.meta.dirname, "../..");
34
+
35
+ /** The `DB` binding's id, as `cloudflare.config.ts` declares it, or its name until it has one. */
36
+ export const DATABASE_ID = config.worker.env.DB.id ?? config.worker.env.DB.name ?? manifest.name;
37
+
38
+ /** The SQLite file `bun dev` and `sdxc run db migrate` use for the `DB` binding. */
39
+ export const LOCAL_DATABASE_FILE = join(
40
+ PROJECT_ROOT,
41
+ ".cloudflare/state/v3/d1",
42
+ NAMESPACE,
43
+ `${objectId(NAMESPACE, DATABASE_ID)}.sqlite`,
44
+ );
45
+
46
+ /**
47
+ * Opens the local database, creating the file where `bun dev` will find it when none exists yet.
48
+ * Timestamps are written as epoch milliseconds, as the Worker's database writes them.
49
+ */
50
+ export function openLocalDatabase(filename = LOCAL_DATABASE_FILE): Database {
51
+ if (filename !== ":memory:") mkdirSync(dirname(filename), { recursive: true });
52
+ return createSqliteDatabase({ filename }, { now: () => Date.now() });
53
+ }
@@ -0,0 +1,27 @@
1
+ /**
2
+ * The app's mail transport, delivering into the in-memory `send_email` stand-in tests receive
3
+ * as the `EMAIL` binding.
4
+ */
5
+
6
+ import { Mailer } from "@sdxc/mail";
7
+ import { env } from "cloudflare:workers";
8
+ import { describe, expect, test } from "vitest";
9
+
10
+ import { transport } from "~/app/initializers/mail";
11
+ import { MAIL_FROM } from "~/config/constants";
12
+
13
+ describe("transport", () => {
14
+ test("delivers a message through the EMAIL binding", async () => {
15
+ let mailer = new Mailer({ transport, from: MAIL_FROM });
16
+
17
+ await mailer.send({
18
+ to: { email: "ada@example.com" },
19
+ subject: "Welcome",
20
+ html: "<p>Hello.</p>",
21
+ });
22
+
23
+ expect(env.EMAIL).toMatchObject({
24
+ messages: [expect.objectContaining({ subject: "Welcome" })],
25
+ });
26
+ });
27
+ });
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Where the app's email goes: Cloudflare's `send_email` binding, which `bun dev` simulates and
3
+ * a deploy delivers through Email Routing. The router publishes a mailer over it as `ctx.email`;
4
+ * a job builds its own with `new Mailer({ transport, from: MAIL_FROM })` and awaits `send()`.
5
+ */
6
+
7
+ import { CloudflareTransport } from "@sdxc/mail/cloudflare";
8
+ import { env } from "cloudflare:workers";
9
+
10
+ /** Sends through the `EMAIL` binding, from an address on a domain Email Routing verified. */
11
+ export const transport = new CloudflareTransport(env.EMAIL);
@@ -6,7 +6,7 @@
6
6
 
7
7
  import { createHandler } from "@sdxc/mcp";
8
8
 
9
- /** The handler the `/mcp` route forwards to. */
9
+ /** The server `app/http/controllers/mcp.ts` forwards each `/mcp` request to. */
10
10
  const mcp = createHandler({
11
11
  name: "app",
12
12
  version: "1.0.0",
@@ -0,0 +1,21 @@
1
+ /**
2
+ * The API's OpenAPI document. Add each operation `routes/api.ts` declares, so
3
+ * `/api/openapi.json` lists every documented endpoint.
4
+ */
5
+
6
+ import { createDocument } from "@sdxc/openapi";
7
+
8
+ import problems from "~/config/problems";
9
+ import { HEALTH } from "~/routes/api";
10
+
11
+ /**
12
+ * Starts the document for the origin the API is served from, which OpenAPI requires as an
13
+ * absolute server URL; `build()` assembles it, failing on a contract it cannot express.
14
+ */
15
+ export function createApiDocument(origin: string) {
16
+ return createDocument({
17
+ info: { title: "App API", version: "1.0.0" },
18
+ servers: [{ url: origin }],
19
+ problems,
20
+ }).add(HEALTH);
21
+ }
@@ -0,0 +1,61 @@
1
+ /**
2
+ * The router's own middleware, checked through a request's log record: what every page and
3
+ * endpoint gets before its controller runs.
4
+ */
5
+
6
+ import { Log } from "@sdxc/logger";
7
+ import { describe, expect, test } from "vitest";
8
+
9
+ import { createWebRouter } from "~/app/initializers/router";
10
+ import { SECURITY_TXT } from "~/config/security-txt";
11
+
12
+ /** How far ahead of `Expires` security.txt must be renewed. */
13
+ const RENEWAL_WINDOW_MS = 30 * 24 * 60 * 60 * 1000;
14
+
15
+ /** Fetches `request` through the router and answers the log record it wrote. */
16
+ async function record(request: Request) {
17
+ let records: Array<Readonly<Record<string, unknown>>> = [];
18
+ let log = new Log({ kind: "request", sink: (written) => records.push(written) });
19
+ await log.run(() => createWebRouter().fetch(request));
20
+ return records[0];
21
+ }
22
+
23
+ describe("router", () => {
24
+ test("continues the caller's W3C trace", async () => {
25
+ let written = await record(
26
+ new Request("https://example.com/api/health", {
27
+ headers: { traceparent: "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01" },
28
+ }),
29
+ );
30
+
31
+ expect(written).toMatchObject({
32
+ trace_id: "4bf92f3577b34da6a3ce929d0e0e4736",
33
+ parent_span_id: "00f067aa0ba902b7",
34
+ });
35
+ });
36
+
37
+ test("redirects a path with a trailing slash to the canonical one", async () => {
38
+ let response = await createWebRouter().fetch("https://example.com/sitemap.xml/?page=2");
39
+
40
+ expect(response.status).toBe(308);
41
+ expect(response.headers.get("location")).toBe("https://example.com/sitemap.xml?page=2");
42
+ });
43
+
44
+ test("serves security.txt with its contact", async () => {
45
+ let response = await createWebRouter().fetch("https://example.com/.well-known/security.txt");
46
+
47
+ expect(response.status).toBe(200);
48
+ expect(await response.text()).toContain("Contact: mailto:security@example.com");
49
+ });
50
+
51
+ test("keeps security.txt current for at least another month", () => {
52
+ expect(SECURITY_TXT.expires.getTime() - Date.now()).toBeGreaterThan(RENEWAL_WINDOW_MS);
53
+ });
54
+
55
+ test("redirects the www. host to the apex domain", async () => {
56
+ let response = await createWebRouter().fetch("https://www.example.com/sitemap.xml");
57
+
58
+ expect(response.status).toBe(308);
59
+ expect(response.headers.get("location")).toBe("https://example.com/sitemap.xml");
60
+ });
61
+ });
@@ -1,64 +1,110 @@
1
1
  /**
2
- * The web router: the global middleware every request runs through, and every route in
3
- * `routes/web.ts` mapped onto its controller through `lazy()`, so a request imports only the
4
- * controller it reaches. `sdxc make controller` maps each new controller here.
2
+ * The router: the middleware every request runs through, and every route in `routes/web.ts`
3
+ * and `routes/api.ts` mapped onto its controller through `lazy()`, so a request imports only
4
+ * the controller it reaches. `sdxc make controller` maps each new controller here.
5
5
  */
6
6
 
7
7
  import type { RouterContext } from "remix/router";
8
8
 
9
- import { assets } from "@sdxc/assets-middleware";
9
+ import { models } from "@sdxc/data-model/router";
10
+ import { database } from "@sdxc/database-middleware";
11
+ import getClientIP from "@sdxc/get-client-ip/middleware";
10
12
  import { lazy } from "@sdxc/lazy-route";
11
13
  import { log } from "@sdxc/logger/middleware";
14
+ import mail from "@sdxc/mail/middleware";
15
+ import { noWWW } from "@sdxc/no-www-middleware";
16
+ import { addressKey, CloudflareAdapter } from "@sdxc/rate-limit";
17
+ import { rateLimit } from "@sdxc/rate-limit/middleware";
18
+ import { trace } from "@sdxc/trace-context/middleware";
19
+ import { trailingSlash } from "@sdxc/trailing-slash-middleware";
20
+ import { userAgent } from "@sdxc/user-agent/middleware";
21
+ import { wellKnown } from "@sdxc/well-known/middleware";
22
+ import { env } from "cloudflare:workers";
12
23
  import { asyncContext } from "remix/middleware/async-context";
13
- import { cop } from "remix/middleware/cop";
14
- import { formData } from "remix/middleware/form-data";
15
- import { render } from "remix/middleware/render";
16
24
  import { createRouter } from "remix/router";
17
25
 
18
- import notFound from "~/app/http/controllers/not-found";
19
- import { assetResolver } from "~/app/initializers/assets";
26
+ import serverTiming from "~/app/http/middleware/server-timing";
27
+ import { openDatabase } from "~/app/initializers/database";
20
28
  import { logger } from "~/app/initializers/logger";
21
- import routes from "~/routes/web";
29
+ import { transport } from "~/app/initializers/mail";
30
+ import registry from "~/app/models";
31
+ import { MAIL_FROM } from "~/config/constants";
32
+ import problems from "~/config/problems";
33
+ import { securityTxtEntry } from "~/config/security-txt";
34
+ import apiRoutes from "~/routes/api";
35
+ import webRoutes from "~/routes/web";
22
36
 
23
- /** The context a controller sees once the global middleware has run. */
37
+ /** The context a controller sees once the router's middleware has run. */
24
38
  export type AppContext = RouterContext<ReturnType<typeof createWebRouter>>;
25
39
 
26
40
  declare module "remix/router" {
27
- /** Types `createAction` and `createController` with the context the global chain builds. */
41
+ /** Types `createAction` and `createController` with the context the router's chain builds. */
28
42
  interface RouterTypes {
29
43
  context: AppContext;
30
44
  }
31
45
  }
32
46
 
33
47
  /**
34
- * Builds the router the Worker forwards each request to. The middleware is written inline,
35
- * so the router's type carries what each one publishes and {@link AppContext} reads it.
48
+ * Builds the router the Worker forwards each request to. Its middleware is what pages and
49
+ * endpoints both need, written inline so {@link AppContext} reads what each one publishes; a
50
+ * controller adds its contract's chain, `app/http/middleware/page.ts` or `api.ts`, itself.
36
51
  */
37
52
  export function createWebRouter() {
38
53
  let router = createRouter({
39
54
  middleware: [
40
55
  asyncContext(),
41
56
  log(logger),
42
- formData(),
43
- cop(),
44
- assets(assetResolver, {
45
- stylesheets: "resources/layouts/document.tsx",
46
- script: "bootstrap/browser.ts",
57
+ trace(),
58
+ serverTiming(),
59
+ noWWW(),
60
+ trailingSlash(),
61
+ wellKnown({ "security.txt": securityTxtEntry }),
62
+ getClientIP(),
63
+ userAgent(),
64
+ rateLimit({
65
+ adapter: new CloudflareAdapter(env.RATE_LIMITER, { limit: 100, window: "1 minute" }),
66
+ prefix: "address",
67
+ key: (ctx) => addressKey(ctx.ip),
68
+ onLimit: () => problems.tooManyRequests(),
47
69
  }),
48
- render({ assets: assetResolver }),
70
+ database(openDatabase()),
71
+ models(registry, (ctx) => ({ db: ctx.db })),
72
+ mail({ transport, from: MAIL_FROM }),
49
73
  ],
50
- defaultHandler: notFound,
51
74
  });
52
75
 
53
76
  router.map(
54
- routes.home,
77
+ webRoutes.home,
55
78
  lazy(() => import("~/app/http/controllers/home")),
56
79
  );
57
80
  router.map(
58
- routes.mcp,
59
- lazy(() =>
60
- import("~/app/initializers/mcp").then((it) => (ctx: AppContext) => it.default.fetch(ctx)),
61
- ),
81
+ webRoutes.robots,
82
+ lazy(() => import("~/app/http/controllers/robots")),
83
+ );
84
+ router.map(
85
+ webRoutes.sitemap,
86
+ lazy(() => import("~/app/http/controllers/sitemap")),
87
+ );
88
+ router.map(
89
+ webRoutes.notFound,
90
+ lazy(() => import("~/app/http/controllers/not-found")),
91
+ );
92
+
93
+ router.map(
94
+ apiRoutes.api.health,
95
+ lazy(() => import("~/app/http/controllers/api/health")),
96
+ );
97
+ router.map(
98
+ apiRoutes.api.openapi,
99
+ lazy(() => import("~/app/http/controllers/api/openapi")),
100
+ );
101
+ router.map(
102
+ apiRoutes.api.notFound,
103
+ lazy(() => import("~/app/http/controllers/api/not-found")),
104
+ );
105
+ router.map(
106
+ apiRoutes.mcp,
107
+ lazy(() => import("~/app/http/controllers/mcp")),
62
108
  );
63
109
 
64
110
  return router;
@@ -0,0 +1,15 @@
1
+ /**
2
+ * The app's SEO instance: one configuration the document layout, the sitemap and robots.txt
3
+ * resolve URLs through, so every published link names `SITE_URL` whichever host served it.
4
+ */
5
+
6
+ import { createSeo } from "@sdxc/seo";
7
+
8
+ import { SITE_DESCRIPTION, SITE_NAME, SITE_URL } from "~/config/constants";
9
+
10
+ /** Canonical URLs drop the trailing slash and tracking parameters, matching the router's redirects. */
11
+ export const seo = createSeo({
12
+ baseUrl: SITE_URL,
13
+ siteName: SITE_NAME,
14
+ defaultDescription: SITE_DESCRIPTION,
15
+ });
@@ -0,0 +1,34 @@
1
+ /**
2
+ * The session the page middleware loads, carried across requests by its cookie and kept in the
3
+ * in-memory KV store tests receive as the `SESSIONS` binding.
4
+ */
5
+
6
+ import { session } from "remix/middleware/session";
7
+ import { createRouter } from "remix/router";
8
+ import { describe, expect, test } from "vitest";
9
+
10
+ import { sessionCookie, sessionStorage } from "~/app/initializers/session";
11
+
12
+ /** A router that counts each visitor's requests in their session. */
13
+ function createCounter() {
14
+ let router = createRouter({ middleware: [session(sessionCookie, sessionStorage)] });
15
+ router.get("/", (ctx) => {
16
+ let count = Number(ctx.session.get("count") ?? 0) + 1;
17
+ ctx.session.set("count", count);
18
+ return Response.json({ count });
19
+ });
20
+ return router;
21
+ }
22
+
23
+ describe("session", () => {
24
+ test("keeps a value from one request to the next", async () => {
25
+ let router = createCounter();
26
+
27
+ let first = await router.fetch("https://example.com/");
28
+ let cookie = first.headers.get("set-cookie")?.split(";")[0] ?? "";
29
+ let second = await router.fetch(new Request("https://example.com/", { headers: { cookie } }));
30
+
31
+ expect(first.headers.get("set-cookie")).toContain("HttpOnly");
32
+ expect(await second.json()).toEqual({ count: 2 });
33
+ });
34
+ });
@@ -0,0 +1,29 @@
1
+ /**
2
+ * The visitor's session: a signed, httpOnly cookie naming a record in the `SESSIONS` KV store.
3
+ * The page middleware loads it as `ctx.session` and saves it after the controller runs, so a
4
+ * page reads and writes values, flash messages included, without touching the cookie.
5
+ */
6
+
7
+ import { KVSessionStorage } from "@sdxc/session-storage-kv";
8
+ import { env } from "cloudflare:workers";
9
+ import { createCookie } from "remix/cookie";
10
+
11
+ /** How long a session lasts after its last change, as both the cookie's and the record's lifetime. */
12
+ const SESSION_TTL_SECONDS = 60 * 60 * 24 * 30;
13
+
14
+ /**
15
+ * Signed with `SESSION_SECRET`; set it with `cf workers secrets update` before deploying.
16
+ * `Secure` follows the request's scheme, so the cookie also works over `http://localhost`.
17
+ */
18
+ export const sessionCookie = createCookie("__session", {
19
+ path: "/",
20
+ httpOnly: true,
21
+ sameSite: "Lax",
22
+ maxAge: SESSION_TTL_SECONDS,
23
+ secrets: [env.SESSION_SECRET],
24
+ });
25
+
26
+ /** Session records, under `session:<id>` keys that expire with the cookie. */
27
+ export const sessionStorage = new KVSessionStorage(env.SESSIONS, {
28
+ ttlSeconds: SESSION_TTL_SECONDS,
29
+ });
@@ -0,0 +1,10 @@
1
+ /**
2
+ * The spam filter a form's action scores submissions with, through `spam(spamFilter, …)` from
3
+ * `@sdxc/spam/middleware`: the local rules weigh links, markup and how fast the form came back,
4
+ * with no account or network call. Add reputation checks here as the app's forms attract them.
5
+ */
6
+
7
+ import { createSpamFilter, DEFAULT_RULES } from "@sdxc/spam";
8
+
9
+ /** Scores a submission as `ham`, `unsure` or `spam`, with every signal that fired. */
10
+ export const spamFilter = createSpamFilter({ checks: DEFAULT_RULES });
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Every model the app reads and writes through, by the name a handler reaches it under:
3
+ * `ctx.models.post` on a request, a job or a command, bound to that run's database. An entry
4
+ * imports its module on first use, so a request loads only the models it touches.
5
+ */
6
+
7
+ import { createModels } from "@sdxc/data-model";
8
+
9
+ /** The app's models; `sdxc make model <name>` registers one here. */
10
+ export default createModels({});
@@ -0,0 +1,45 @@
1
+ /**
2
+ * The migration runner, on an in-memory SQLite database shaped like a local D1 copy.
3
+ */
4
+
5
+ import { openDatabase } from "@sdxc/cloudflare-mocks/sqlite";
6
+ import { isFailure, unwrap } from "@sdxc/result";
7
+ import { describe, expect, test } from "vitest";
8
+
9
+ import { applyMigrations } from "~/app/services/migrations";
10
+
11
+ /** Two migrations, given out of order to show the runner sorts them. */
12
+ const MIGRATIONS = [
13
+ { name: "0002_AddTitle.sql", sql: "ALTER TABLE posts ADD COLUMN title TEXT;" },
14
+ { name: "0001_CreatePosts.sql", sql: "CREATE TABLE posts (id TEXT PRIMARY KEY);" },
15
+ ];
16
+
17
+ describe("applyMigrations", () => {
18
+ test("applies each pending migration once, in name order", () => {
19
+ let database = openDatabase(":memory:");
20
+
21
+ let first = unwrap(applyMigrations(database, MIGRATIONS));
22
+ let second = unwrap(applyMigrations(database, MIGRATIONS));
23
+
24
+ expect(first).toEqual(["0001_CreatePosts.sql", "0002_AddTitle.sql"]);
25
+ expect(second).toEqual([]);
26
+ expect(database.query("SELECT name FROM d1_migrations ORDER BY id").all()).toEqual([
27
+ { name: "0001_CreatePosts.sql" },
28
+ { name: "0002_AddTitle.sql" },
29
+ ]);
30
+ });
31
+
32
+ test("stops at a failing migration and leaves it unrecorded", () => {
33
+ let database = openDatabase(":memory:");
34
+
35
+ let result = applyMigrations(database, [
36
+ ...MIGRATIONS,
37
+ { name: "0003_Broken.sql", sql: "CREATE TABLE posts (id TEXT);" },
38
+ ]);
39
+
40
+ expect(isFailure(result) && result.error.message).toBe("0003_Broken.sql failed");
41
+ expect(database.query("SELECT count(*) AS applied FROM d1_migrations").all()).toEqual([
42
+ { applied: 2 },
43
+ ]);
44
+ });
45
+ });