@sdxc/kit 0.0.0-stage → 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 (298) hide show
  1. package/LICENSE.md +21 -0
  2. package/README.md +93 -2
  3. package/changelog.jsonl +1097 -0
  4. package/config.schema.json +89 -0
  5. package/dist/author.d.ts +36 -0
  6. package/dist/author.js +107 -0
  7. package/dist/bin.d.ts +9 -0
  8. package/dist/bin.js +10 -0
  9. package/dist/cli.d.ts +33 -0
  10. package/dist/cli.js +58 -0
  11. package/dist/commands/create.d.ts +20 -0
  12. package/dist/commands/create.js +169 -0
  13. package/dist/commands/init.d.ts +16 -0
  14. package/dist/commands/init.js +27 -0
  15. package/dist/commands/make.d.ts +335 -0
  16. package/dist/commands/make.js +152 -0
  17. package/dist/commands/run.d.ts +23 -0
  18. package/dist/commands/run.js +53 -0
  19. package/dist/commands/ui/add.d.ts +23 -0
  20. package/dist/commands/ui/add.js +50 -0
  21. package/dist/commands/ui/diff.d.ts +20 -0
  22. package/dist/commands/ui/diff.js +28 -0
  23. package/dist/commands/ui/list.d.ts +24 -0
  24. package/dist/commands/ui/list.js +45 -0
  25. package/dist/commands/ui/remove.d.ts +22 -0
  26. package/dist/commands/ui/remove.js +48 -0
  27. package/dist/commands/ui/update.d.ts +23 -0
  28. package/dist/commands/ui/update.js +37 -0
  29. package/dist/commands/upgrade.d.ts +30 -0
  30. package/dist/commands/upgrade.js +184 -0
  31. package/dist/config.d.ts +81 -0
  32. package/dist/config.js +157 -0
  33. package/dist/contract.d.ts +161 -0
  34. package/dist/contract.js +308 -0
  35. package/dist/create/github.d.ts +63 -0
  36. package/dist/create/github.js +172 -0
  37. package/dist/create/target.d.ts +31 -0
  38. package/dist/create/target.js +56 -0
  39. package/dist/create/templates.d.ts +69 -0
  40. package/dist/create/templates.js +251 -0
  41. package/dist/dependencies.d.ts +34 -0
  42. package/dist/dependencies.js +76 -0
  43. package/dist/diff.d.ts +14 -0
  44. package/dist/diff.js +103 -0
  45. package/dist/format.d.ts +21 -0
  46. package/dist/format.js +40 -0
  47. package/dist/init.d.ts +40 -0
  48. package/dist/init.js +100 -0
  49. package/dist/lock.d.ts +74 -0
  50. package/dist/lock.js +214 -0
  51. package/dist/make/declare.d.ts +54 -0
  52. package/dist/make/declare.js +598 -0
  53. package/dist/make/generate.d.ts +62 -0
  54. package/dist/make/generate.js +160 -0
  55. package/dist/make/imports.d.ts +43 -0
  56. package/dist/make/imports.js +105 -0
  57. package/dist/make/index.d.ts +43 -0
  58. package/dist/make/index.js +140 -0
  59. package/dist/make/kinds.d.ts +40 -0
  60. package/dist/make/kinds.js +96 -0
  61. package/dist/make/migrations.d.ts +41 -0
  62. package/dist/make/migrations.js +116 -0
  63. package/dist/make/names.d.ts +31 -0
  64. package/dist/make/names.js +47 -0
  65. package/dist/make/stubs.d.ts +44 -0
  66. package/dist/make/stubs.js +89 -0
  67. package/dist/middleware.d.ts +44 -0
  68. package/dist/middleware.js +49 -0
  69. package/dist/package-manager.d.ts +41 -0
  70. package/dist/package-manager.js +80 -0
  71. package/dist/project.d.ts +19 -0
  72. package/dist/project.js +42 -0
  73. package/dist/releases.d.ts +40 -0
  74. package/dist/releases.js +110 -0
  75. package/dist/testing.d.ts +60 -0
  76. package/dist/testing.js +148 -0
  77. package/dist/ui/commands.d.ts +114 -0
  78. package/dist/ui/commands.js +432 -0
  79. package/dist/ui/imports.d.ts +46 -0
  80. package/dist/ui/imports.js +160 -0
  81. package/dist/ui/layout.d.ts +48 -0
  82. package/dist/ui/layout.js +138 -0
  83. package/dist/ui/registry.d.ts +58 -0
  84. package/dist/ui/registry.js +82 -0
  85. package/dist/upgrade/changelog.d.ts +50 -0
  86. package/dist/upgrade/changelog.js +69 -0
  87. package/dist/upgrade/project.d.ts +62 -0
  88. package/dist/upgrade/project.js +132 -0
  89. package/dist/upgrade/prompt.d.ts +51 -0
  90. package/dist/upgrade/prompt.js +227 -0
  91. package/dist/upgrade/registry.d.ts +33 -0
  92. package/dist/upgrade/registry.js +50 -0
  93. package/lock.schema.json +60 -0
  94. package/package.json +44 -5
  95. package/registry/ui/accordion.json +15 -0
  96. package/registry/ui/alert-dialog.json +20 -0
  97. package/registry/ui/alert.json +15 -0
  98. package/registry/ui/aspect-ratio.json +13 -0
  99. package/registry/ui/attachment.json +15 -0
  100. package/registry/ui/avatar.json +15 -0
  101. package/registry/ui/badge.json +13 -0
  102. package/registry/ui/breadcrumbs.json +15 -0
  103. package/registry/ui/bubble.json +13 -0
  104. package/registry/ui/button.json +16 -0
  105. package/registry/ui/calendar.json +16 -0
  106. package/registry/ui/card.json +18 -0
  107. package/registry/ui/carousel.json +15 -0
  108. package/registry/ui/chart.json +13 -0
  109. package/registry/ui/checkbox-group.json +13 -0
  110. package/registry/ui/checkbox.json +16 -0
  111. package/registry/ui/color-area.json +13 -0
  112. package/registry/ui/color-field.json +20 -0
  113. package/registry/ui/color-picker.json +17 -0
  114. package/registry/ui/color-slider.json +13 -0
  115. package/registry/ui/color-swatch-picker.json +15 -0
  116. package/registry/ui/color-swatch.json +13 -0
  117. package/registry/ui/color-wheel.json +13 -0
  118. package/registry/ui/combobox.json +15 -0
  119. package/registry/ui/command.json +13 -0
  120. package/registry/ui/confirm.json +19 -0
  121. package/registry/ui/context-menu.json +16 -0
  122. package/registry/ui/date-field.json +19 -0
  123. package/registry/ui/date-picker.json +15 -0
  124. package/registry/ui/date-range-picker.json +16 -0
  125. package/registry/ui/description.json +13 -0
  126. package/registry/ui/dialog.json +19 -0
  127. package/registry/ui/disclosure.json +18 -0
  128. package/registry/ui/drawer.json +18 -0
  129. package/registry/ui/drop-indicator.json +13 -0
  130. package/registry/ui/drop-zone.json +13 -0
  131. package/registry/ui/empty.json +15 -0
  132. package/registry/ui/field-error.json +13 -0
  133. package/registry/ui/file-trigger.json +13 -0
  134. package/registry/ui/form.json +21 -0
  135. package/registry/ui/grid-list.json +18 -0
  136. package/registry/ui/group.json +13 -0
  137. package/registry/ui/header.json +13 -0
  138. package/registry/ui/heading-scope.json +20 -0
  139. package/registry/ui/heading.json +15 -0
  140. package/registry/ui/highlight.json +16 -0
  141. package/registry/ui/hover-card.json +13 -0
  142. package/registry/ui/image-placeholder.json +16 -0
  143. package/registry/ui/input.json +13 -0
  144. package/registry/ui/item.json +13 -0
  145. package/registry/ui/keyboard.json +13 -0
  146. package/registry/ui/label.json +13 -0
  147. package/registry/ui/link-button.json +16 -0
  148. package/registry/ui/link.json +13 -0
  149. package/registry/ui/listbox.json +15 -0
  150. package/registry/ui/logo.json +15 -0
  151. package/registry/ui/marker.json +13 -0
  152. package/registry/ui/menu.json +19 -0
  153. package/registry/ui/menubar.json +13 -0
  154. package/registry/ui/message-scroller.json +16 -0
  155. package/registry/ui/message.json +13 -0
  156. package/registry/ui/meter.json +13 -0
  157. package/registry/ui/modal.json +15 -0
  158. package/registry/ui/nav-link.json +13 -0
  159. package/registry/ui/navigation-menu.json +15 -0
  160. package/registry/ui/number-field.json +15 -0
  161. package/registry/ui/otp-field.json +15 -0
  162. package/registry/ui/overlay-arrow.json +13 -0
  163. package/registry/ui/pagination.json +16 -0
  164. package/registry/ui/popover.json +13 -0
  165. package/registry/ui/progress-bar.json +13 -0
  166. package/registry/ui/radio-group.json +13 -0
  167. package/registry/ui/range-calendar.json +16 -0
  168. package/registry/ui/resizable.json +13 -0
  169. package/registry/ui/scroll-area.json +13 -0
  170. package/registry/ui/search-field.json +16 -0
  171. package/registry/ui/section.json +13 -0
  172. package/registry/ui/select.json +13 -0
  173. package/registry/ui/selection-indicator.json +13 -0
  174. package/registry/ui/sentinel-row.json +16 -0
  175. package/registry/ui/separator.json +13 -0
  176. package/registry/ui/shared-element.json +13 -0
  177. package/registry/ui/sheet.json +15 -0
  178. package/registry/ui/shortcut-list.json +18 -0
  179. package/registry/ui/sidebar.json +20 -0
  180. package/registry/ui/skeleton.json +13 -0
  181. package/registry/ui/slider.json +16 -0
  182. package/registry/ui/spinner.json +13 -0
  183. package/registry/ui/switch.json +16 -0
  184. package/registry/ui/table.json +16 -0
  185. package/registry/ui/tabs.json +17 -0
  186. package/registry/ui/tag-group.json +18 -0
  187. package/registry/ui/text-field.json +19 -0
  188. package/registry/ui/text.json +13 -0
  189. package/registry/ui/textarea.json +13 -0
  190. package/registry/ui/time-field.json +19 -0
  191. package/registry/ui/toast.json +16 -0
  192. package/registry/ui/toggle-button.json +17 -0
  193. package/registry/ui/toolbar.json +13 -0
  194. package/registry/ui/tooltip.json +16 -0
  195. package/registry/ui/tree.json +18 -0
  196. package/registry/ui/typeset.json +16 -0
  197. package/registry/ui/youtube-embed.json +16 -0
  198. package/stubs/command.stub +16 -0
  199. package/stubs/command.test.stub +21 -0
  200. package/stubs/controller.api.stub +21 -0
  201. package/stubs/controller.api.test.stub +18 -0
  202. package/stubs/controller.form.stub +63 -0
  203. package/stubs/controller.form.test.stub +61 -0
  204. package/stubs/controller.stub +24 -0
  205. package/stubs/controller.test.stub +18 -0
  206. package/stubs/email.stub +26 -0
  207. package/stubs/email.test.stub +21 -0
  208. package/stubs/factory.stub +13 -0
  209. package/stubs/initializer.stub +9 -0
  210. package/stubs/initializer.test.stub +16 -0
  211. package/stubs/job.cron.stub +16 -0
  212. package/stubs/job.stub +15 -0
  213. package/stubs/job.test.stub +18 -0
  214. package/stubs/mcp.resource.stub +15 -0
  215. package/stubs/mcp.stub +13 -0
  216. package/stubs/mcp.test.stub +18 -0
  217. package/stubs/middleware.stub +16 -0
  218. package/stubs/middleware.test.stub +16 -0
  219. package/stubs/migration.stub +1 -0
  220. package/stubs/model.stub +33 -0
  221. package/stubs/model.test.stub +18 -0
  222. package/stubs/policy.stub +16 -0
  223. package/stubs/policy.test.stub +20 -0
  224. package/stubs/service.stub +17 -0
  225. package/stubs/service.test.stub +17 -0
  226. package/stubs/validator.stub +17 -0
  227. package/stubs/validator.test.stub +25 -0
  228. package/templates/app/.env.example +16 -0
  229. package/templates/app/README.md +84 -0
  230. package/templates/app/app/commands/about.test.ts +29 -0
  231. package/templates/app/app/commands/about.ts +34 -0
  232. package/templates/app/app/commands/db/console.ts +6 -0
  233. package/templates/app/app/commands/db/migrate.test.ts +30 -0
  234. package/templates/app/app/commands/db/migrate.ts +55 -0
  235. package/templates/app/app/commands/index.ts +31 -0
  236. package/templates/app/app/commands/typegen.test.ts +17 -0
  237. package/templates/app/app/commands/typegen.ts +16 -0
  238. package/templates/app/app/http/controllers/api/health.tsx +15 -0
  239. package/templates/app/app/http/controllers/api/not-found.tsx +16 -0
  240. package/templates/app/app/http/controllers/api/openapi.tsx +17 -0
  241. package/templates/app/app/http/controllers/home.tsx +30 -0
  242. package/templates/app/app/http/controllers/mcp.tsx +16 -0
  243. package/templates/app/app/http/controllers/not-found.tsx +30 -0
  244. package/templates/app/app/http/controllers/robots.test.ts +18 -0
  245. package/templates/app/app/http/controllers/robots.ts +24 -0
  246. package/templates/app/app/http/controllers/sitemap.test.ts +28 -0
  247. package/templates/app/app/http/controllers/sitemap.ts +25 -0
  248. package/templates/app/app/http/middleware/api.ts +10 -0
  249. package/templates/app/app/http/middleware/page.test.ts +40 -0
  250. package/templates/app/app/http/middleware/page.ts +49 -0
  251. package/templates/app/app/http/middleware/server-timing.test.ts +15 -0
  252. package/templates/app/app/http/middleware/server-timing.ts +42 -0
  253. package/templates/app/app/initializers/assets.ts +11 -0
  254. package/templates/app/app/initializers/captcha.ts +11 -0
  255. package/templates/app/app/initializers/cli.ts +75 -0
  256. package/templates/app/app/initializers/database.test.ts +18 -0
  257. package/templates/app/app/initializers/database.ts +18 -0
  258. package/templates/app/app/initializers/dispatcher.ts +36 -0
  259. package/templates/app/app/initializers/honeypot.ts +11 -0
  260. package/templates/app/app/initializers/i18n.test.ts +16 -0
  261. package/templates/app/app/initializers/i18n.ts +28 -0
  262. package/templates/app/app/initializers/local-database.test.ts +33 -0
  263. package/templates/app/app/initializers/local-database.ts +53 -0
  264. package/templates/app/app/initializers/logger.ts +10 -0
  265. package/templates/app/app/initializers/mail.test.ts +27 -0
  266. package/templates/app/app/initializers/mail.ts +11 -0
  267. package/templates/app/app/initializers/mcp.ts +16 -0
  268. package/templates/app/app/initializers/openapi.ts +21 -0
  269. package/templates/app/app/initializers/router.test.ts +61 -0
  270. package/templates/app/app/initializers/router.tsx +111 -0
  271. package/templates/app/app/initializers/seo.ts +15 -0
  272. package/templates/app/app/initializers/session.test.ts +34 -0
  273. package/templates/app/app/initializers/session.ts +29 -0
  274. package/templates/app/app/initializers/spam.ts +10 -0
  275. package/templates/app/app/jobs/index.ts +10 -0
  276. package/templates/app/app/mcp/resources/index.ts +9 -0
  277. package/templates/app/app/mcp/tools/index.ts +10 -0
  278. package/templates/app/app/models/index.ts +10 -0
  279. package/templates/app/app/services/migrations.test.ts +45 -0
  280. package/templates/app/app/services/migrations.ts +60 -0
  281. package/templates/app/app/test/cloudflare-workers.ts +25 -0
  282. package/templates/app/bootstrap/browser.ts +27 -0
  283. package/templates/app/bootstrap/cli.ts +9 -0
  284. package/templates/app/bootstrap/worker.ts +31 -0
  285. package/templates/app/cloudflare.config.ts +56 -0
  286. package/templates/app/config/constants.ts +19 -0
  287. package/templates/app/config/problems.ts +24 -0
  288. package/templates/app/config/security-policy.ts +34 -0
  289. package/templates/app/config/security-txt.ts +28 -0
  290. package/templates/app/database/migrations/.gitkeep +0 -0
  291. package/templates/app/gitignore +9 -0
  292. package/templates/app/package.json +68 -0
  293. package/templates/app/resources/layouts/document.tsx +79 -0
  294. package/templates/app/resources/locales/en.json +10 -0
  295. package/templates/app/routes/api.ts +29 -0
  296. package/templates/app/routes/web.ts +14 -0
  297. package/templates/app/tsconfig.json +40 -0
  298. package/templates/app/vite.config.ts +44 -0
@@ -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
+ });
@@ -0,0 +1,111 @@
1
+ /**
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
+ */
6
+
7
+ import type { RouterContext } from "remix/router";
8
+
9
+ import { models } from "@sdxc/data-model/router";
10
+ import { database } from "@sdxc/database-middleware";
11
+ import getClientIP from "@sdxc/get-client-ip/middleware";
12
+ import { lazy } from "@sdxc/lazy-route";
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";
23
+ import { asyncContext } from "remix/middleware/async-context";
24
+ import { createRouter } from "remix/router";
25
+
26
+ import serverTiming from "~/app/http/middleware/server-timing";
27
+ import { openDatabase } from "~/app/initializers/database";
28
+ import { logger } from "~/app/initializers/logger";
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";
36
+
37
+ /** The context a controller sees once the router's middleware has run. */
38
+ export type AppContext = RouterContext<ReturnType<typeof createWebRouter>>;
39
+
40
+ declare module "remix/router" {
41
+ /** Types `createAction` and `createController` with the context the router's chain builds. */
42
+ interface RouterTypes {
43
+ context: AppContext;
44
+ }
45
+ }
46
+
47
+ /**
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.
51
+ */
52
+ export function createWebRouter() {
53
+ let router = createRouter({
54
+ middleware: [
55
+ asyncContext(),
56
+ log(logger),
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(),
69
+ }),
70
+ database(openDatabase()),
71
+ models(registry, (ctx) => ({ db: ctx.db })),
72
+ mail({ transport, from: MAIL_FROM }),
73
+ ],
74
+ });
75
+
76
+ router.map(
77
+ webRoutes.home,
78
+ lazy(() => import("~/app/http/controllers/home")),
79
+ );
80
+ router.map(
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")),
108
+ );
109
+
110
+ return router;
111
+ }
@@ -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 background job the app runs, declared in one map: the payload each carries and the
3
+ * schedule it is enqueued on. Importing it costs the schemas alone, so a controller enqueues
4
+ * a job without loading the handler that runs it.
5
+ */
6
+
7
+ import { jobs } from "@sdxc/jobs";
8
+
9
+ /** The app's jobs; `sdxc make job <name>` declares one here and maps its handler. */
10
+ export default jobs({});
@@ -0,0 +1,9 @@
1
+ /**
2
+ * The resources the MCP server offers, each addressed by a URI pattern a client reads and a
3
+ * person attaches to a conversation. Each handler lives in its own file beside this one.
4
+ */
5
+
6
+ import { resources } from "@sdxc/mcp";
7
+
8
+ /** The app's resources; `sdxc make mcp <name> --resource` declares one here and maps it. */
9
+ export default resources({});
@@ -0,0 +1,10 @@
1
+ /**
2
+ * The tools the MCP server offers: the name a client calls, the description a model chooses
3
+ * it by, and the schema its arguments satisfy. Each handler lives in its own file beside
4
+ * this one.
5
+ */
6
+
7
+ import { tools } from "@sdxc/mcp";
8
+
9
+ /** The app's tools; `sdxc make mcp <name>` declares one here and maps its handler. */
10
+ export default tools({});
@@ -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
+ });
@@ -0,0 +1,60 @@
1
+ /**
2
+ * Applies a chain of SQL migrations the way `cf d1 migrations apply` does: in name order, each
3
+ * once, recorded in the same `d1_migrations` table, so local and remote databases agree on
4
+ * what ran whichever tool applied it.
5
+ */
6
+
7
+ import type { Result } from "@sdxc/result";
8
+
9
+ import { failure, success } from "@sdxc/result";
10
+
11
+ /** One migration file: its name, as `0001_CreatePosts.sql`, and its SQL. */
12
+ export interface Migration {
13
+ name: string;
14
+ sql: string;
15
+ }
16
+
17
+ /** The synchronous SQLite client a migration runs on; it runs several statements per call. */
18
+ export interface MigrationDatabase {
19
+ exec(sql: string): void;
20
+ query(sql: string): { all(): unknown[] };
21
+ }
22
+
23
+ /** The table D1 records applied migrations in, as Wrangler and `cf` create it. */
24
+ const JOURNAL = `CREATE TABLE IF NOT EXISTS "d1_migrations"(
25
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
26
+ name TEXT UNIQUE,
27
+ applied_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL
28
+ )`;
29
+
30
+ /**
31
+ * Runs every migration the journal lacks, each in its own transaction with its journal row, so
32
+ * a failing migration leaves the database as the previous one left it.
33
+ *
34
+ * @returns The names applied, in order; a failure names the migration that stopped the run.
35
+ */
36
+ export function applyMigrations(
37
+ database: MigrationDatabase,
38
+ migrations: readonly Migration[],
39
+ ): Result<string[], Error> {
40
+ database.exec(JOURNAL);
41
+ let rows = database.query("SELECT name FROM d1_migrations").all() as { name: string }[];
42
+ let applied = new Set(rows.map((row) => row.name));
43
+ let pending = [...migrations]
44
+ .filter((migration) => !applied.has(migration.name))
45
+ .sort((a, b) => a.name.localeCompare(b.name));
46
+
47
+ let names: string[] = [];
48
+ for (let migration of pending) {
49
+ try {
50
+ database.exec(
51
+ `BEGIN;\n${migration.sql}\n;INSERT INTO d1_migrations (name) VALUES ('${migration.name.replaceAll("'", "''")}');\nCOMMIT;`,
52
+ );
53
+ } catch (error) {
54
+ database.exec("ROLLBACK");
55
+ return failure(new Error(`${migration.name} failed`, { cause: error }));
56
+ }
57
+ names.push(migration.name);
58
+ }
59
+ return success(names);
60
+ }
@@ -0,0 +1,25 @@
1
+ /**
2
+ * The `cloudflare:workers` module under Vitest, which imports the app's modules in Node, outside
3
+ * the Worker runtime. It carries the development secrets `.env.example` lists, so a module that
4
+ * reads `env` at import loads the same way it does under `bun dev`. Its bindings are in-memory
5
+ * stand-ins that behave like Cloudflare's, so a test reads and writes real SQL through `DB`.
6
+ */
7
+
8
+ import {
9
+ createD1Database,
10
+ createKVNamespace,
11
+ createRateLimit,
12
+ createSendEmail,
13
+ } from "@sdxc/cloudflare-mocks";
14
+
15
+ /** The bindings and secrets the app reads, with the values a project starts with for development. */
16
+ export const env = {
17
+ DB: createD1Database(),
18
+ EMAIL: createSendEmail(),
19
+ RATE_LIMITER: createRateLimit(),
20
+ SESSIONS: createKVNamespace(),
21
+ SESSION_SECRET: "development-session-secret",
22
+ HONEYPOT_SECRET: "development-honeypot-secret",
23
+ TURNSTILE_SITE_KEY: "1x00000000000000000000AA",
24
+ TURNSTILE_SECRET_KEY: "1x0000000000000000000000000000000AA",
25
+ } as Partial<Cloudflare.Env> as Cloudflare.Env;
@@ -0,0 +1,27 @@
1
+ /**
2
+ * The browser's entry point: boots the Remix component runtime and resolves the island
3
+ * modules a server-rendered page hydrates. A page with no island links no script, so this
4
+ * file only runs where an island asks for it.
5
+ */
6
+
7
+ import { run } from "remix/component";
8
+
9
+ /**
10
+ * The island modules a hydration record can name, keyed by the module URL the island writes.
11
+ * Each one is listed here, so a server-rendered component never becomes a client chunk by
12
+ * sitting next to one that hydrates.
13
+ */
14
+ const CLIENT_MODULES: Record<string, () => Promise<Record<string, unknown>>> = {};
15
+
16
+ run({
17
+ /** Resolves a hydrated island's export from the module URL the server wrote. */
18
+ async loadModule(moduleUrl, exportName) {
19
+ let load = CLIENT_MODULES[moduleUrl];
20
+ if (load === undefined) throw new Error(`Unknown client entry module: ${moduleUrl}`);
21
+ let entry = (await load())[exportName];
22
+ if (typeof entry !== "function") {
23
+ throw new Error(`Missing client entry export ${exportName} in ${moduleUrl}`);
24
+ }
25
+ return entry;
26
+ },
27
+ });
@@ -0,0 +1,9 @@
1
+ /**
2
+ * The command line's entry point, started by `sdxc run`: it runs the command
3
+ * the arguments name and exits with its code. The Worker never imports it, so no command ships
4
+ * in the server build.
5
+ */
6
+
7
+ import { cli } from "~/app/initializers/cli";
8
+
9
+ process.exitCode = await cli.run(process.argv.slice(2));
@@ -0,0 +1,31 @@
1
+ /**
2
+ * The Worker's entry point. `fetch` forwards each request to the router, which serves pages
3
+ * and the API alike, and `queue` hands each delivered batch to the job dispatcher, so every
4
+ * request and every job reaches the app through the initializers that configure it.
5
+ */
6
+
7
+ import * as cloudflare from "@sdxc/jobs/cloudflare";
8
+
9
+ import { dispatcher } from "~/app/initializers/dispatcher";
10
+ import { createWebRouter } from "~/app/initializers/router";
11
+
12
+ /** The dispatcher's queue and cron handlers, bound once per isolate. */
13
+ const JOBS = cloudflare.worker(dispatcher);
14
+
15
+ export default {
16
+ /** Answers a request through the router. */
17
+ async fetch(request) {
18
+ let router = createWebRouter();
19
+ return await router.fetch(request);
20
+ },
21
+
22
+ /** Runs every job a cron trigger is the schedule for. */
23
+ async scheduled(controller) {
24
+ await JOBS.scheduled(controller);
25
+ },
26
+
27
+ /** Runs the job each queued message names, settling once every one of them has. */
28
+ async queue(batch) {
29
+ await JOBS.queue(batch);
30
+ },
31
+ } satisfies ExportedHandler<Cloudflare.Env>;
@@ -0,0 +1,56 @@
1
+ /**
2
+ * Cloudflare configuration for the Worker, read by `cf` and the Vite plugin alike. Every
3
+ * binding and trigger the app reads is declared here, so `sdxc run typegen` types `env` from
4
+ * this file and local development simulates exactly what production provides.
5
+ */
6
+
7
+ import { bindings, defineConfig, triggers } from "cf/config";
8
+
9
+ import manifest from "./package.json" with { type: "json" };
10
+
11
+ export default defineConfig({
12
+ worker: {
13
+ name: manifest.name,
14
+ compatibilityDate: "2026-09-02",
15
+ compatibilityFlags: ["nodejs_compat"],
16
+ entrypoint: "./bootstrap/worker.ts",
17
+ observability: { enabled: true },
18
+ /**
19
+ * A queue has exactly one consumer, so this Worker owns the role: every job the
20
+ * dispatcher enqueues is delivered back here and run through the same dispatcher.
21
+ */
22
+ triggers: [triggers.queue({ name: manifest.name })],
23
+ env: {
24
+ /**
25
+ * The app's database. `cf d1 create <name>` prints the id to put here, where the
26
+ * `sdxc run db` commands read it; until then, `bun dev` runs on a local copy.
27
+ */
28
+ DB: bindings.d1({ name: manifest.name, id: "00000000-0000-4000-8000-000000000000" }),
29
+ /**
30
+ * Sends the app's email. Cloudflare delivers only from an address on a domain with Email
31
+ * Routing enabled, so set `MAIL_FROM` in `config/constants.ts` to one before deploying.
32
+ */
33
+ EMAIL: bindings.sendEmail(),
34
+ /** Where the job dispatcher enqueues; `cf queues create <name>` before the first deploy. */
35
+ QUEUE: bindings.queue({ name: manifest.name }),
36
+ /**
37
+ * 100 requests per minute per client address, across every route. The router's
38
+ * adapter declares the same budget for the `RateLimit` headers; keep the two in step.
39
+ */
40
+ RATE_LIMITER: bindings.rateLimit({ namespace: "1001", simple: { limit: 100, period: 60 } }),
41
+ /**
42
+ * Visitors' sessions. `cf kv namespace create <name>` prints the id to put here; until
43
+ * then, `bun dev` keeps sessions in a local copy.
44
+ */
45
+ SESSIONS: bindings.kv({ id: "00000000000000000000000000000000" }),
46
+ /** Signs the session cookie. */
47
+ SESSION_SECRET: bindings.secret(),
48
+ /** Signs the honeypot fields every page form carries. */
49
+ HONEYPOT_SECRET: bindings.secret(),
50
+ /** The Turnstile widget's site key, which a form renders. */
51
+ TURNSTILE_SITE_KEY: bindings.secret(),
52
+ /** Verifies the Turnstile token a form submits. */
53
+ TURNSTILE_SECRET_KEY: bindings.secret(),
54
+ },
55
+ },
56
+ });
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Values the app is configured with that never change between requests. Edit them when the app
3
+ * gets its own domain, since links and identifiers built from them are published.
4
+ */
5
+
6
+ /** The origin the app is published at: canonical links, the sitemap and robots.txt name it. */
7
+ export const SITE_URL = "https://example.com";
8
+
9
+ /** The app's name, as `og:site_name` and structured data publish it. */
10
+ export const SITE_NAME = "App";
11
+
12
+ /** The description a page without its own publishes, in search results and link previews. */
13
+ export const SITE_DESCRIPTION = "A Remix app on Cloudflare Workers.";
14
+
15
+ /** Where problem `type` URIs point; each problem's slug follows it, so it ends in `/`. */
16
+ export const PROBLEMS_URL = "https://example.com/problems/";
17
+
18
+ /** Who the app's email comes from: an address on a domain Cloudflare Email Routing verified. */
19
+ export const MAIL_FROM = { email: "no-reply@example.com", name: "App" };
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Every problem the API answers with, by name. A handler returns `problems.<name>()` and the
3
+ * OpenAPI document publishes each entry, so a client branches on a `type` the server declared.
4
+ */
5
+
6
+ import * as s from "@sdxc/json-schema";
7
+ import { defineProblems, ISSUES_SCHEMA } from "@sdxc/problem";
8
+
9
+ import { PROBLEMS_URL } from "~/config/constants";
10
+
11
+ export default defineProblems(PROBLEMS_URL, {
12
+ notFound: { slug: "not-found", status: 404, title: "The resource does not exist" },
13
+ tooManyRequests: {
14
+ slug: "too-many-requests",
15
+ status: 429,
16
+ title: "Too many requests from this address",
17
+ },
18
+ validationError: {
19
+ slug: "validation-error",
20
+ status: 422,
21
+ title: "The request failed validation",
22
+ extensions: s.object({ errors: ISSUES_SCHEMA }),
23
+ },
24
+ });
@@ -0,0 +1,34 @@
1
+ /**
2
+ * The security headers every page is sent with: a Content-Security-Policy that admits this
3
+ * origin and the response's nonce, and the headers that keep the page out of frames and its
4
+ * referrer and device APIs to itself. Name an origin here before a page loads from it.
5
+ */
6
+
7
+ import type { SecurityHeaders } from "@sdxc/security-headers";
8
+
9
+ /** Where Cloudflare Turnstile loads its script and renders its challenge frame. */
10
+ const TURNSTILE_ORIGIN = "https://challenges.cloudflare.com";
11
+
12
+ /** The policy `app/http/middleware/page.ts` applies to every page response. */
13
+ export const SECURITY_POLICY: SecurityHeaders.Policy = {
14
+ contentSecurityPolicy: {
15
+ defaultSrc: ["self"],
16
+ /** The document's inline import map is admitted by the response's nonce. */
17
+ scriptSrc: ["self", "nonce", TURNSTILE_ORIGIN],
18
+ /** `css()` styles render as `<style>` elements while the page streams, before any nonce. */
19
+ styleSrc: ["self", "unsafe-inline"],
20
+ imgSrc: ["self", "data:"],
21
+ fontSrc: ["self"],
22
+ /** Same-origin requests, including the dev server's HMR socket. */
23
+ connectSrc: ["self"],
24
+ frameSrc: [TURNSTILE_ORIGIN],
25
+ formAction: ["self"],
26
+ frameAncestors: ["none"],
27
+ baseUri: ["none"],
28
+ objectSrc: ["none"],
29
+ },
30
+ strictTransportSecurity: { maxAge: 31_536_000 },
31
+ referrerPolicy: "strict-origin-when-cross-origin",
32
+ crossOriginOpenerPolicy: "same-origin",
33
+ permissionsPolicy: { camera: [], microphone: [], geolocation: [], payment: [], usb: [] },
34
+ };