@react-consulting/rc-kit 0.0.0-stage → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (337) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +94 -2
  3. package/devkit/README.md +301 -0
  4. package/devkit/cli.test.ts +211 -0
  5. package/devkit/cli.ts +120 -0
  6. package/devkit/commands/build.ts +127 -0
  7. package/devkit/commands/checks.ts +123 -0
  8. package/devkit/commands/context.ts +47 -0
  9. package/devkit/commands/db.ts +154 -0
  10. package/devkit/commands/deploy.ts +46 -0
  11. package/devkit/commands/dev.ts +191 -0
  12. package/devkit/commands/doctor.ts +25 -0
  13. package/devkit/commands/kit.ts +45 -0
  14. package/devkit/commands/new.ts +81 -0
  15. package/devkit/commands/registry.ts +20 -0
  16. package/devkit/commands/secrets.ts +254 -0
  17. package/devkit/lib/args.ts +65 -0
  18. package/devkit/lib/audit.test.ts +405 -0
  19. package/devkit/lib/audit.ts +813 -0
  20. package/devkit/lib/config.test.ts +203 -0
  21. package/devkit/lib/config.ts +417 -0
  22. package/devkit/lib/database/index.test.ts +223 -0
  23. package/devkit/lib/database/index.ts +314 -0
  24. package/devkit/lib/database/neon.test.ts +233 -0
  25. package/devkit/lib/database/neon.ts +357 -0
  26. package/devkit/lib/database/prepare.ts +54 -0
  27. package/devkit/lib/deploy-config.test.ts +217 -0
  28. package/devkit/lib/deploy-config.ts +133 -0
  29. package/devkit/lib/deploy.test.ts +275 -0
  30. package/devkit/lib/deploy.ts +177 -0
  31. package/devkit/lib/dev-gateway.test.ts +128 -0
  32. package/devkit/lib/dev-gateway.ts +162 -0
  33. package/devkit/lib/dev-menu.test.ts +114 -0
  34. package/devkit/lib/dev-menu.ts +332 -0
  35. package/devkit/lib/dev-secrets.test.ts +156 -0
  36. package/devkit/lib/dev-secrets.ts +97 -0
  37. package/devkit/lib/dev.test.ts +194 -0
  38. package/devkit/lib/dev.ts +119 -0
  39. package/devkit/lib/doctor.test.ts +144 -0
  40. package/devkit/lib/doctor.ts +264 -0
  41. package/devkit/lib/env-file.test.ts +102 -0
  42. package/devkit/lib/env-file.ts +96 -0
  43. package/devkit/lib/glob.ts +31 -0
  44. package/devkit/lib/infisical.test.ts +208 -0
  45. package/devkit/lib/infisical.ts +139 -0
  46. package/devkit/lib/json-schema.ts +220 -0
  47. package/devkit/lib/jsonc.test.ts +53 -0
  48. package/devkit/lib/jsonc.ts +93 -0
  49. package/devkit/lib/kit-migrate.test.ts +212 -0
  50. package/devkit/lib/kit-migrate.ts +617 -0
  51. package/devkit/lib/kit-package.test.ts +83 -0
  52. package/devkit/lib/kit-package.ts +57 -0
  53. package/devkit/lib/kit-version.ts +22 -0
  54. package/devkit/lib/naming.test.ts +547 -0
  55. package/devkit/lib/naming.ts +796 -0
  56. package/devkit/lib/paths.ts +7 -0
  57. package/devkit/lib/process.ts +78 -0
  58. package/devkit/lib/project-checks.ts +86 -0
  59. package/devkit/lib/scaffold.test.ts +302 -0
  60. package/devkit/lib/scaffold.ts +315 -0
  61. package/devkit/lib/secrets.test.ts +101 -0
  62. package/devkit/lib/secrets.ts +125 -0
  63. package/devkit/lib/sourcemaps.test.ts +86 -0
  64. package/devkit/lib/sourcemaps.ts +98 -0
  65. package/devkit/lib/test-utils.ts +68 -0
  66. package/devkit/lib/workspace.ts +87 -0
  67. package/devkit/lib/wrangler.ts +231 -0
  68. package/docs/rc-config.md +93 -0
  69. package/package.json +86 -4
  70. package/presets/build.d.ts +15 -0
  71. package/presets/build.js +53 -0
  72. package/presets/vite-plus.d.ts +28 -0
  73. package/presets/vite-plus.js +153 -0
  74. package/registry/README.md +294 -0
  75. package/registry/public/r/avatar-stack.json +18 -0
  76. package/registry/public/r/avatar.json +20 -0
  77. package/registry/public/r/back-link.json +21 -0
  78. package/registry/public/r/badge.json +17 -0
  79. package/registry/public/r/button.json +18 -0
  80. package/registry/public/r/calendar-days.json +14 -0
  81. package/registry/public/r/calendar-popover.json +24 -0
  82. package/registry/public/r/calendar.json +23 -0
  83. package/registry/public/r/callout.json +20 -0
  84. package/registry/public/r/card.json +18 -0
  85. package/registry/public/r/character-counter.json +17 -0
  86. package/registry/public/r/checkbox.json +22 -0
  87. package/registry/public/r/choice-cards.json +22 -0
  88. package/registry/public/r/color-tag.json +17 -0
  89. package/registry/public/r/combobox.json +24 -0
  90. package/registry/public/r/confirm-button.json +24 -0
  91. package/registry/public/r/confirm-dialog.json +23 -0
  92. package/registry/public/r/copy-button.json +24 -0
  93. package/registry/public/r/date-picker.json +24 -0
  94. package/registry/public/r/date-range-picker.json +28 -0
  95. package/registry/public/r/detail-header.json +17 -0
  96. package/registry/public/r/detail-row.json +17 -0
  97. package/registry/public/r/dev-inbox-api.json +33 -0
  98. package/registry/public/r/dev-toolbar.json +109 -0
  99. package/registry/public/r/dev-tools-contract.json +15 -0
  100. package/registry/public/r/dialog.json +23 -0
  101. package/registry/public/r/empty-state.json +20 -0
  102. package/registry/public/r/error-state.json +23 -0
  103. package/registry/public/r/eyebrow.json +17 -0
  104. package/registry/public/r/fab.json +20 -0
  105. package/registry/public/r/field-error.json +17 -0
  106. package/registry/public/r/field-grid.json +17 -0
  107. package/registry/public/r/field.json +19 -0
  108. package/registry/public/r/file-picker.json +22 -0
  109. package/registry/public/r/filter-chips.json +17 -0
  110. package/registry/public/r/form-section.json +17 -0
  111. package/registry/public/r/form-sheet.json +22 -0
  112. package/registry/public/r/icon-button.json +23 -0
  113. package/registry/public/r/input.json +18 -0
  114. package/registry/public/r/label.json +18 -0
  115. package/registry/public/r/list-row.json +17 -0
  116. package/registry/public/r/loading-state.json +18 -0
  117. package/registry/public/r/localized-field.json +23 -0
  118. package/registry/public/r/markdown-text.json +17 -0
  119. package/registry/public/r/menu.json +21 -0
  120. package/registry/public/r/money-input.json +17 -0
  121. package/registry/public/r/month-day-select.json +18 -0
  122. package/registry/public/r/numbered-step.json +20 -0
  123. package/registry/public/r/page-actions.json +14 -0
  124. package/registry/public/r/page-header.json +17 -0
  125. package/registry/public/r/pending.json +17 -0
  126. package/registry/public/r/person-option.json +21 -0
  127. package/registry/public/r/popover.json +20 -0
  128. package/registry/public/r/progress-bar.json +17 -0
  129. package/registry/public/r/query-view.json +22 -0
  130. package/registry/public/r/registry.json +1352 -0
  131. package/registry/public/r/retry-button.json +21 -0
  132. package/registry/public/r/rich-text-editor.json +32 -0
  133. package/registry/public/r/save-bar.json +22 -0
  134. package/registry/public/r/search-input.json +23 -0
  135. package/registry/public/r/search-select.json +24 -0
  136. package/registry/public/r/section-tabs.json +17 -0
  137. package/registry/public/r/segmented.json +18 -0
  138. package/registry/public/r/select.json +23 -0
  139. package/registry/public/r/sheet.json +24 -0
  140. package/registry/public/r/skeleton.json +17 -0
  141. package/registry/public/r/spinner.json +20 -0
  142. package/registry/public/r/stale-notice.json +23 -0
  143. package/registry/public/r/stat-tile.json +23 -0
  144. package/registry/public/r/stepper.json +23 -0
  145. package/registry/public/r/suggestion-strip.json +21 -0
  146. package/registry/public/r/swatch-picker.json +22 -0
  147. package/registry/public/r/switch.json +21 -0
  148. package/registry/public/r/tabs.json +20 -0
  149. package/registry/public/r/textarea.json +18 -0
  150. package/registry/public/r/theme.json +15 -0
  151. package/registry/public/r/timezone-select.json +19 -0
  152. package/registry/public/r/toaster.json +21 -0
  153. package/registry/public/r/tooltip.json +17 -0
  154. package/registry/public/r/ui-labels.json +14 -0
  155. package/registry/public/r/use-copy-to-clipboard.json +20 -0
  156. package/registry/public/r/use-online.json +14 -0
  157. package/registry/public/r/use-stale-queries.json +17 -0
  158. package/registry/public/r/utils.json +18 -0
  159. package/registry/public/r/weekday-picker.json +19 -0
  160. package/registry/public/r/yes-no.json +20 -0
  161. package/registry/serve.ts +29 -0
  162. package/rules/architecture.md +47 -0
  163. package/rules/cloudflare.md +74 -0
  164. package/rules/code.md +12 -0
  165. package/rules/git.md +10 -0
  166. package/rules/index.md +14 -0
  167. package/rules/observability.md +13 -0
  168. package/rules/performance.md +39 -0
  169. package/rules/runtime.md +9 -0
  170. package/rules/secrets.md +11 -0
  171. package/rules/stack.md +33 -0
  172. package/rules/ui.md +23 -0
  173. package/runtime/ai.test.ts +106 -0
  174. package/runtime/ai.ts +125 -0
  175. package/runtime/observability/allowlists.ts +42 -0
  176. package/runtime/observability/anonymize.test.ts +111 -0
  177. package/runtime/observability/anonymize.ts +249 -0
  178. package/runtime/observability/browser.test.ts +46 -0
  179. package/runtime/observability/browser.ts +126 -0
  180. package/runtime/observability/server.test.ts +84 -0
  181. package/runtime/observability/server.ts +152 -0
  182. package/runtime/observability/tunnel.test.ts +276 -0
  183. package/runtime/observability/tunnel.ts +360 -0
  184. package/runtime/observability/user-agent.ts +51 -0
  185. package/schema/rc.config.schema.json +333 -0
  186. package/template/.gitattributes +1 -0
  187. package/template/.github/workflows/ci.yml +64 -0
  188. package/template/CLAUDE.md +48 -0
  189. package/template/README.md +50 -0
  190. package/template/apps/admin/.dev.vars.example +5 -0
  191. package/template/apps/admin/components.json +24 -0
  192. package/template/apps/admin/package.json +48 -0
  193. package/template/apps/admin/public/favicon.svg +1 -0
  194. package/template/apps/admin/src/components/app-shell.tsx +41 -0
  195. package/template/apps/admin/src/components/dev-sign-in-links.tsx +57 -0
  196. package/template/apps/admin/src/components/dev-toolbar/dev-toolbar-context.ts +13 -0
  197. package/template/apps/admin/src/components/dev-toolbar/dev-toolbar-environment-panel.tsx +105 -0
  198. package/template/apps/admin/src/components/dev-toolbar/dev-toolbar-inbox-list.tsx +54 -0
  199. package/template/apps/admin/src/components/dev-toolbar/dev-toolbar-inbox-message.tsx +104 -0
  200. package/template/apps/admin/src/components/dev-toolbar/dev-toolbar-inbox-panel.tsx +130 -0
  201. package/template/apps/admin/src/components/dev-toolbar/dev-toolbar-launcher.tsx +45 -0
  202. package/template/apps/admin/src/components/dev-toolbar/dev-toolbar-panel.tsx +90 -0
  203. package/template/apps/admin/src/components/dev-toolbar/dev-toolbar-types.ts +11 -0
  204. package/template/apps/admin/src/components/dev-toolbar/dev-toolbar.tsx +61 -0
  205. package/template/apps/admin/src/components/dev-toolbar/development-devtools.tsx +32 -0
  206. package/template/apps/admin/src/components/login-form.tsx +115 -0
  207. package/template/apps/admin/src/components/login-sent.tsx +23 -0
  208. package/template/apps/admin/src/components/message-list.tsx +44 -0
  209. package/template/apps/admin/src/components/turnstile-challenge.tsx +140 -0
  210. package/template/apps/admin/src/components/ui/button.tsx +87 -0
  211. package/template/apps/admin/src/components/ui/callout.tsx +84 -0
  212. package/template/apps/admin/src/components/ui/card.tsx +48 -0
  213. package/template/apps/admin/src/components/ui/eyebrow.tsx +33 -0
  214. package/template/apps/admin/src/components/ui/field-error.tsx +24 -0
  215. package/template/apps/admin/src/components/ui/field.tsx +100 -0
  216. package/template/apps/admin/src/components/ui/input.tsx +73 -0
  217. package/template/apps/admin/src/components/ui/label.tsx +39 -0
  218. package/template/apps/admin/src/components/ui/skeleton.tsx +225 -0
  219. package/template/apps/admin/src/components/ui/spinner.tsx +12 -0
  220. package/template/apps/admin/src/components/ui/toaster.tsx +33 -0
  221. package/template/apps/admin/src/components/ui/tooltip.tsx +51 -0
  222. package/template/apps/admin/src/hooks/use-dev-inbox.ts +25 -0
  223. package/template/apps/admin/src/hooks/use-dev-toolbar-state.ts +48 -0
  224. package/template/apps/admin/src/lib/api.ts +39 -0
  225. package/template/apps/admin/src/lib/auth-client.ts +7 -0
  226. package/template/apps/admin/src/lib/dev-inbox-links.ts +66 -0
  227. package/template/apps/admin/src/lib/dev-tools-client.ts +54 -0
  228. package/template/apps/admin/src/lib/dev-tools-contract.ts +52 -0
  229. package/template/apps/admin/src/lib/messages.ts +5 -0
  230. package/template/apps/admin/src/lib/query-keys.ts +3 -0
  231. package/template/apps/admin/src/lib/security-headers.ts +18 -0
  232. package/template/apps/admin/src/lib/session.ts +27 -0
  233. package/template/apps/admin/src/lib/site-url.ts +7 -0
  234. package/template/apps/admin/src/lib/turnstile.ts +70 -0
  235. package/template/apps/admin/src/lib/ui-labels.tsx +182 -0
  236. package/template/apps/admin/src/lib/utils.ts +6 -0
  237. package/template/apps/admin/src/routeTree.gen.ts +109 -0
  238. package/template/apps/admin/src/router.tsx +29 -0
  239. package/template/apps/admin/src/routes/__root.tsx +56 -0
  240. package/template/apps/admin/src/routes/_app/index.tsx +38 -0
  241. package/template/apps/admin/src/routes/_app.tsx +26 -0
  242. package/template/apps/admin/src/routes/login.tsx +48 -0
  243. package/template/apps/admin/src/styles/app.css +11 -0
  244. package/template/apps/admin/src/worker.ts +88 -0
  245. package/template/apps/admin/tsconfig.json +19 -0
  246. package/template/apps/admin/vite.config.ts +69 -0
  247. package/template/apps/admin/wrangler.jsonc +92 -0
  248. package/template/apps/web/.env.example +1 -0
  249. package/template/apps/web/astro.config.ts +46 -0
  250. package/template/apps/web/package.json +33 -0
  251. package/template/apps/web/public/favicon.svg +1 -0
  252. package/template/apps/web/src/components/ContactForm.astro +78 -0
  253. package/template/apps/web/src/env.d.ts +11 -0
  254. package/template/apps/web/src/layouts/BaseLayout.astro +32 -0
  255. package/template/apps/web/src/lib/api.ts +8 -0
  256. package/template/apps/web/src/pages/api/messages.ts +32 -0
  257. package/template/apps/web/src/pages/index.astro +26 -0
  258. package/template/apps/web/src/pages/media/[...key].ts +4 -0
  259. package/template/apps/web/src/scripts/contact-form.ts +105 -0
  260. package/template/apps/web/src/scripts/error-reporting.ts +4 -0
  261. package/template/apps/web/src/scripts/turnstile.ts +177 -0
  262. package/template/apps/web/src/styles/global.css +11 -0
  263. package/template/apps/web/src/worker.ts +34 -0
  264. package/template/apps/web/tsconfig.json +11 -0
  265. package/template/apps/web/wrangler.jsonc +45 -0
  266. package/template/bun.lock +1925 -0
  267. package/template/bunfig.toml +2 -0
  268. package/template/gitignore +23 -0
  269. package/template/package.json +74 -0
  270. package/template/packages/api/components.json +21 -0
  271. package/template/packages/api/package.json +30 -0
  272. package/template/packages/api/src/client.ts +13 -0
  273. package/template/packages/api/src/cloudflare-env.d.ts +26 -0
  274. package/template/packages/api/src/emails/escape-html.ts +13 -0
  275. package/template/packages/api/src/emails/layout.ts +22 -0
  276. package/template/packages/api/src/emails/magic-link.ts +32 -0
  277. package/template/packages/api/src/emails/new-message.ts +32 -0
  278. package/template/packages/api/src/emails/send.ts +14 -0
  279. package/template/packages/api/src/lib/auth-guard.ts +16 -0
  280. package/template/packages/api/src/lib/auth.ts +108 -0
  281. package/template/packages/api/src/lib/context.ts +7 -0
  282. package/template/packages/api/src/lib/dev-inbox/routes.ts +77 -0
  283. package/template/packages/api/src/lib/dev-inbox/send.ts +57 -0
  284. package/template/packages/api/src/lib/dev-inbox/store.ts +185 -0
  285. package/template/packages/api/src/lib/dev-inbox.ts +6 -0
  286. package/template/packages/api/src/lib/dev-tools-contract.ts +52 -0
  287. package/template/packages/api/src/lib/environment.ts +17 -0
  288. package/template/packages/api/src/lib/turnstile.ts +33 -0
  289. package/template/packages/api/src/media.ts +45 -0
  290. package/template/packages/api/src/routes/admin-messages.ts +21 -0
  291. package/template/packages/api/src/routes/dev.ts +31 -0
  292. package/template/packages/api/src/routes/health.ts +7 -0
  293. package/template/packages/api/src/routes/messages.ts +58 -0
  294. package/template/packages/api/src/schemas.ts +18 -0
  295. package/template/packages/api/src/server.ts +29 -0
  296. package/template/packages/api/tsconfig.json +10 -0
  297. package/template/packages/db/migrations/0001_init.sql +79 -0
  298. package/template/packages/db/package.json +34 -0
  299. package/template/packages/db/prisma/schema.prisma +95 -0
  300. package/template/packages/db/prisma.config.ts +9 -0
  301. package/template/packages/db/scripts/migrate.ts +15 -0
  302. package/template/packages/db/scripts/new-migration.ts +185 -0
  303. package/template/packages/db/scripts/reset.ts +54 -0
  304. package/template/packages/db/scripts/seed.ts +44 -0
  305. package/template/packages/db/scripts/wrangler.ts +35 -0
  306. package/template/packages/db/src/d1.ts +7 -0
  307. package/template/packages/db/src/migration-guard.test.ts +43 -0
  308. package/template/packages/db/src/migration-guard.ts +51 -0
  309. package/template/packages/db/src/new-migration.test.ts +16 -0
  310. package/template/packages/db/src/scope.ts +38 -0
  311. package/template/packages/db/src/seed.ts +30 -0
  312. package/template/packages/db/src/sql.ts +42 -0
  313. package/template/packages/db/tsconfig.json +8 -0
  314. package/template/packages/shared/components.json +21 -0
  315. package/template/packages/shared/package.json +33 -0
  316. package/template/packages/shared/src/edge/origins.ts +20 -0
  317. package/template/packages/shared/src/edge/turnstile.ts +11 -0
  318. package/template/packages/shared/src/locales.ts +13 -0
  319. package/template/packages/shared/src/message-rules.ts +16 -0
  320. package/template/packages/shared/src/messages.test.ts +26 -0
  321. package/template/packages/shared/src/messages.ts +30 -0
  322. package/template/packages/shared/src/observability/build-release.ts +9 -0
  323. package/template/packages/shared/src/observability/error-reporting.ts +31 -0
  324. package/template/packages/shared/src/observability/error-tunnel.ts +20 -0
  325. package/template/packages/shared/src/observability/sentry-browser.ts +1 -0
  326. package/template/packages/shared/src/observability/server-errors.ts +74 -0
  327. package/template/packages/shared/src/project.ts +1 -0
  328. package/template/packages/shared/src/styles/rc-theme.css +138 -0
  329. package/template/packages/shared/src/styles/theme.css +9 -0
  330. package/template/packages/shared/tsconfig.json +10 -0
  331. package/template/rc.config.json +25 -0
  332. package/template/scripts/bootstrap-local.ts +42 -0
  333. package/template/tsconfig.base.json +20 -0
  334. package/template/tsconfig.json +8 -0
  335. package/template/tsconfig.worker.json +7 -0
  336. package/template/turbo.json +40 -0
  337. package/template/vite.config.ts +8 -0
@@ -0,0 +1,185 @@
1
+ import {
2
+ DEV_INBOX_KEY_PREFIX,
3
+ type DevInboxMessage,
4
+ type DevInboxSummary,
5
+ type OutgoingEmail,
6
+ } from "../dev-tools-contract"
7
+
8
+ export interface DevInboxStore {
9
+ clear: () => Promise<void>
10
+ list: () => Promise<DevInboxSummary[]>
11
+ markRead: (id: string) => Promise<void>
12
+ read: (id: string) => Promise<DevInboxMessage | null>
13
+ record: (message: OutgoingEmail) => Promise<DevInboxSummary>
14
+ }
15
+
16
+ /** The slice of an R2 bucket the inbox uses, so this file needs no Workers types; an `R2Bucket` fits it. */
17
+ export interface DevInboxBucket {
18
+ delete(keys: string | string[]): Promise<void>
19
+ get(key: string): Promise<{ text(): Promise<string> } | null>
20
+ list(options: {
21
+ cursor?: string
22
+ include?: ("customMetadata" | "httpMetadata")[]
23
+ prefix: string
24
+ }): Promise<{
25
+ cursor?: string
26
+ objects: { customMetadata?: Record<string, string>; key: string }[]
27
+ truncated: boolean
28
+ }>
29
+ put(
30
+ key: string,
31
+ value: string,
32
+ options?: {
33
+ customMetadata?: Record<string, string>
34
+ httpMetadata?: { contentType?: string }
35
+ }
36
+ ): Promise<unknown>
37
+ }
38
+
39
+ const MAX_MESSAGES = 100
40
+
41
+ function summaryOf(message: DevInboxMessage): DevInboxSummary {
42
+ const { id, readAt, receivedAt, subject, to } = message
43
+
44
+ return { id, readAt, receivedAt, subject, to }
45
+ }
46
+
47
+ function newestFirst(a: DevInboxSummary, b: DevInboxSummary): number {
48
+ return b.receivedAt.localeCompare(a.receivedAt)
49
+ }
50
+
51
+ function toMessage(email: OutgoingEmail): DevInboxMessage {
52
+ return {
53
+ html: email.html ?? null,
54
+ id: crypto.randomUUID(),
55
+ readAt: null,
56
+ receivedAt: new Date().toISOString(),
57
+ subject: email.subject,
58
+ text: email.text,
59
+ to: email.to,
60
+ }
61
+ }
62
+
63
+ function isSummary(value: unknown): value is DevInboxSummary {
64
+ return (
65
+ typeof value === "object" &&
66
+ value !== null &&
67
+ typeof (value as DevInboxSummary).id === "string" &&
68
+ typeof (value as DevInboxSummary).receivedAt === "string"
69
+ )
70
+ }
71
+
72
+ function parseSummary(raw: string | undefined): DevInboxSummary | null {
73
+ if (!raw) {
74
+ return null
75
+ }
76
+
77
+ try {
78
+ const parsed: unknown = JSON.parse(raw)
79
+
80
+ return isSummary(parsed) ? parsed : null
81
+ } catch {
82
+ return null
83
+ }
84
+ }
85
+
86
+ /** Local R2 (miniflare) survives dev-server restarts; the `dev-inbox/` prefix never exists outside a dev machine. */
87
+ export function createR2DevInbox(bucket: DevInboxBucket): DevInboxStore {
88
+ const keyOf = (id: string) => `${DEV_INBOX_KEY_PREFIX}${id}.json`
89
+
90
+ const write = (message: DevInboxMessage) =>
91
+ bucket.put(keyOf(message.id), JSON.stringify(message), {
92
+ customMetadata: { summary: JSON.stringify(summaryOf(message)) },
93
+ httpMetadata: { contentType: "application/json" },
94
+ })
95
+
96
+ const list = async (): Promise<DevInboxSummary[]> => {
97
+ const summaries: DevInboxSummary[] = []
98
+ let cursor: string | undefined
99
+
100
+ do {
101
+ const page = await bucket.list({
102
+ cursor,
103
+ include: ["customMetadata"],
104
+ prefix: DEV_INBOX_KEY_PREFIX,
105
+ })
106
+
107
+ for (const object of page.objects) {
108
+ const summary = parseSummary(object.customMetadata?.summary)
109
+
110
+ if (summary) {
111
+ summaries.push(summary)
112
+ }
113
+ }
114
+
115
+ cursor = page.truncated ? page.cursor : undefined
116
+ } while (cursor)
117
+
118
+ return summaries.toSorted(newestFirst)
119
+ }
120
+
121
+ const read = async (id: string): Promise<DevInboxMessage | null> => {
122
+ const object = await bucket.get(keyOf(id))
123
+
124
+ return object ? (JSON.parse(await object.text()) as DevInboxMessage) : null
125
+ }
126
+
127
+ const remove = async (summaries: DevInboxSummary[]) => {
128
+ if (summaries.length > 0) {
129
+ await bucket.delete(summaries.map((summary) => keyOf(summary.id)))
130
+ }
131
+ }
132
+
133
+ return {
134
+ clear: async () => remove(await list()),
135
+ list,
136
+ markRead: async (id) => {
137
+ const message = await read(id)
138
+
139
+ if (message && !message.readAt) {
140
+ await write({ ...message, readAt: new Date().toISOString() })
141
+ }
142
+ },
143
+ read,
144
+ record: async (email) => {
145
+ const message = toMessage(email)
146
+
147
+ await write(message)
148
+ await remove((await list()).slice(MAX_MESSAGES))
149
+
150
+ return summaryOf(message)
151
+ },
152
+ }
153
+ }
154
+
155
+ /** For `bun test` and scripts run outside workerd. */
156
+ export function createMemoryDevInbox(): DevInboxStore {
157
+ const messages = new Map<string, DevInboxMessage>()
158
+
159
+ const list = async () =>
160
+ [...messages.values()].map(summaryOf).toSorted(newestFirst)
161
+
162
+ return {
163
+ clear: async () => messages.clear(),
164
+ list,
165
+ markRead: async (id) => {
166
+ const message = messages.get(id)
167
+
168
+ if (message && !message.readAt) {
169
+ messages.set(id, { ...message, readAt: new Date().toISOString() })
170
+ }
171
+ },
172
+ read: async (id) => messages.get(id) ?? null,
173
+ record: async (email) => {
174
+ const message = toMessage(email)
175
+
176
+ messages.set(message.id, message)
177
+
178
+ for (const stale of (await list()).slice(MAX_MESSAGES)) {
179
+ messages.delete(stale.id)
180
+ }
181
+
182
+ return summaryOf(message)
183
+ },
184
+ }
185
+ }
@@ -0,0 +1,6 @@
1
+ import { env } from "./context"
2
+ import { createR2DevInbox } from "./dev-inbox/store"
3
+
4
+ export function devInbox() {
5
+ return createR2DevInbox(env.MEDIA)
6
+ }
@@ -0,0 +1,52 @@
1
+ export const DEV_API_PREFIX = "/api/dev"
2
+
3
+ export const DEV_INBOX_KEY_PREFIX = "dev-inbox/"
4
+
5
+ export const DEV_ROUTES = {
6
+ environment: "/environment",
7
+ inbox: "/inbox",
8
+ inboxMessage: (id: string) => `/inbox/${encodeURIComponent(id)}`,
9
+ inboxMessageHtml: (id: string) => `/inbox/${encodeURIComponent(id)}/html`,
10
+ inboxMessageRead: (id: string) => `/inbox/${encodeURIComponent(id)}/read`,
11
+ } as const
12
+
13
+ export interface DevInboxSummary {
14
+ id: string
15
+ readAt: string | null
16
+ receivedAt: string
17
+ subject: string
18
+ to: string
19
+ }
20
+
21
+ export interface DevInboxMessage extends DevInboxSummary {
22
+ html: string | null
23
+ text: string
24
+ }
25
+
26
+ export interface DevEnvironmentEntry {
27
+ label: string
28
+ value: string
29
+ }
30
+
31
+ export interface DevLink {
32
+ href: string
33
+ label: string
34
+ }
35
+
36
+ export interface DevEnvironment {
37
+ /** The value of `ENVIRONMENT`: always "local" when the routes answer. */
38
+ environment: string
39
+ entries: DevEnvironmentEntry[]
40
+ links: DevLink[]
41
+ }
42
+
43
+ export interface DevOk {
44
+ ok: true
45
+ }
46
+
47
+ export interface OutgoingEmail {
48
+ html?: string
49
+ subject: string
50
+ text: string
51
+ to: string
52
+ }
@@ -0,0 +1,17 @@
1
+ import { env } from "./context"
2
+
3
+ export const LOCAL_ENVIRONMENT = "local"
4
+
5
+ export function isLocalEnvironment(): boolean {
6
+ return env.ENVIRONMENT === LOCAL_ENVIRONMENT
7
+ }
8
+
9
+ export function adminEmails(): string[] {
10
+ return env.ADMIN_EMAILS.split(",")
11
+ .map((email) => email.trim().toLowerCase())
12
+ .filter(Boolean)
13
+ }
14
+
15
+ export function isAdminEmail(email: string): boolean {
16
+ return adminEmails().includes(email.trim().toLowerCase())
17
+ }
@@ -0,0 +1,33 @@
1
+ import { env } from "./context"
2
+
3
+ const SITEVERIFY_URL =
4
+ "https://challenges.cloudflare.com/turnstile/v0/siteverify"
5
+
6
+ export async function verifyTurnstile(
7
+ token: string | undefined,
8
+ remoteIp: string | null
9
+ ): Promise<boolean> {
10
+ if (!env.TURNSTILE_SECRET_KEY) {
11
+ return true
12
+ }
13
+
14
+ if (!token) {
15
+ return false
16
+ }
17
+
18
+ const form = new FormData()
19
+ form.set("secret", env.TURNSTILE_SECRET_KEY)
20
+ form.set("response", token)
21
+ if (remoteIp) {
22
+ form.set("remoteip", remoteIp)
23
+ }
24
+
25
+ const response = await fetch(SITEVERIFY_URL, { method: "POST", body: form })
26
+ if (!response.ok) {
27
+ return false
28
+ }
29
+
30
+ const result = (await response.json()) as { success?: boolean }
31
+
32
+ return result.success === true
33
+ }
@@ -0,0 +1,45 @@
1
+ import { env } from "./lib/context"
2
+ import { DEV_INBOX_KEY_PREFIX } from "./lib/dev-tools-contract"
3
+
4
+ export const MEDIA_PREFIX = "/media/"
5
+
6
+ /** Serves R2 objects under `/media/*` from the edge cache, R2 on a miss. */
7
+ export async function serveMedia(
8
+ request: Request,
9
+ ctx: ExecutionContext
10
+ ): Promise<Response> {
11
+ if (request.method !== "GET" && request.method !== "HEAD") {
12
+ return new Response("Method Not Allowed", { status: 405 })
13
+ }
14
+
15
+ const key = decodeURIComponent(
16
+ new URL(request.url).pathname.slice(MEDIA_PREFIX.length)
17
+ )
18
+
19
+ if (key.startsWith(DEV_INBOX_KEY_PREFIX)) {
20
+ return new Response("Not Found", { status: 404 })
21
+ }
22
+
23
+ // The admin's DOM lib shadows the Workers `CacheStorage`, which alone declares `default`.
24
+ const cache = (caches as unknown as { default: Cache }).default
25
+ const cached = await cache.match(request)
26
+ if (cached) {
27
+ return cached
28
+ }
29
+
30
+ const object = await env.MEDIA.get(key)
31
+
32
+ if (!object) {
33
+ return new Response("Not Found", { status: 404 })
34
+ }
35
+
36
+ const headers = new Headers()
37
+ object.writeHttpMetadata(headers)
38
+ headers.set("etag", object.httpEtag)
39
+ headers.set("cache-control", "public, max-age=31536000, immutable")
40
+
41
+ const response = new Response(object.body, { headers })
42
+ ctx.waitUntil(cache.put(request, response.clone()))
43
+
44
+ return response
45
+ }
@@ -0,0 +1,21 @@
1
+ import type { TMessageSummary } from "@tpl/shared/messages"
2
+ import { Elysia } from "elysia"
3
+ import { authGuard } from "../lib/auth-guard"
4
+ import { prisma } from "../lib/context"
5
+
6
+ const PAGE_SIZE = 200
7
+
8
+ export const adminMessageRoutes = new Elysia({ prefix: "/admin/messages" })
9
+ .use(authGuard)
10
+ .guard({ authenticated: true })
11
+ .get("/", async (): Promise<TMessageSummary[]> => {
12
+ const rows = await prisma.message.findMany({
13
+ orderBy: { createdAt: "desc" },
14
+ take: PAGE_SIZE,
15
+ })
16
+
17
+ return rows.map((row) => ({
18
+ ...row,
19
+ createdAt: row.createdAt.toISOString(),
20
+ }))
21
+ })
@@ -0,0 +1,31 @@
1
+ import { Elysia } from "elysia"
2
+ import { env } from "../lib/context"
3
+ import { devInbox } from "../lib/dev-inbox"
4
+ import { devRoutes } from "../lib/dev-inbox/routes"
5
+ import { adminEmails, isLocalEnvironment } from "../lib/environment"
6
+
7
+ const registryDevRoutes = devRoutes({
8
+ isLocal: isLocalEnvironment,
9
+ inbox: devInbox,
10
+ environment: () => ({
11
+ environment: env.ENVIRONMENT,
12
+ entries: [
13
+ { label: "Admin", value: env.ADMIN_URL },
14
+ { label: "Expéditeur", value: env.EMAIL_FROM },
15
+ ],
16
+ links: [{ label: "Ouvrir le site", href: env.PUBLIC_SITE_URL }],
17
+ }),
18
+ })
19
+
20
+ // The registry plugin's 404 guard is local to it, so the project route repeats it.
21
+ const accountRoutes = new Elysia({ prefix: "/dev" })
22
+ .onBeforeHandle(({ status }) => {
23
+ if (!isLocalEnvironment()) {
24
+ return status(404, { message: "Not Found" })
25
+ }
26
+ })
27
+ .get("/accounts", () => ({ adminEmails: adminEmails() }))
28
+
29
+ export const devRoutesWithAccounts = new Elysia()
30
+ .use(registryDevRoutes)
31
+ .use(accountRoutes)
@@ -0,0 +1,7 @@
1
+ import { Elysia } from "elysia"
2
+ import { env } from "../lib/context"
3
+
4
+ export const healthRoutes = new Elysia().get("/health", () => ({
5
+ ok: true,
6
+ environment: env.ENVIRONMENT,
7
+ }))
@@ -0,0 +1,58 @@
1
+ import { MESSAGE_ERRORS } from "@tpl/shared/message-rules"
2
+ import type { TMessageInput } from "@tpl/shared/messages"
3
+ import { Elysia } from "elysia"
4
+ import { renderNewMessageEmail } from "../emails/new-message"
5
+ import { sendEmail } from "../emails/send"
6
+ import { env, prisma } from "../lib/context"
7
+ import { adminEmails } from "../lib/environment"
8
+ import { verifyTurnstile } from "../lib/turnstile"
9
+ import { messageBody } from "../schemas"
10
+
11
+ async function notifyAdmins(message: TMessageInput): Promise<void> {
12
+ const results = await Promise.allSettled(
13
+ adminEmails().map((to) =>
14
+ sendEmail(renderNewMessageEmail({ to, message, adminUrl: env.ADMIN_URL }))
15
+ )
16
+ )
17
+
18
+ for (const result of results) {
19
+ if (result.status === "rejected") {
20
+ console.error("[messages] notification failed", result.reason)
21
+ }
22
+ }
23
+ }
24
+
25
+ export const messageRoutes = new Elysia().post(
26
+ "/messages",
27
+ async ({ body, request, status }) => {
28
+ if (body.website) {
29
+ return { ok: true }
30
+ }
31
+
32
+ const ip = request.headers.get("cf-connecting-ip")
33
+ const { success } = await env.MESSAGES_RATE_LIMITER.limit({
34
+ key: ip ?? "local",
35
+ })
36
+ if (!success) {
37
+ return status(429, { message: MESSAGE_ERRORS.rateLimited })
38
+ }
39
+
40
+ if (!(await verifyTurnstile(body.turnstileToken, ip))) {
41
+ return status(400, { message: MESSAGE_ERRORS.captcha })
42
+ }
43
+
44
+ const message = {
45
+ name: body.name.trim(),
46
+ email: body.email.trim().toLowerCase(),
47
+ body: body.body.trim(),
48
+ }
49
+
50
+ await prisma.message.create({
51
+ data: { id: crypto.randomUUID(), ...message },
52
+ })
53
+ await notifyAdmins(message)
54
+
55
+ return { ok: true }
56
+ },
57
+ { body: messageBody }
58
+ )
@@ -0,0 +1,18 @@
1
+ import { MESSAGE_LIMITS } from "@tpl/shared/message-rules"
2
+ import { t } from "elysia"
3
+
4
+ export const messageBody = t.Object({
5
+ name: t.String({
6
+ minLength: MESSAGE_LIMITS.name.min,
7
+ maxLength: MESSAGE_LIMITS.name.max,
8
+ }),
9
+ email: t.String({ format: "email", maxLength: MESSAGE_LIMITS.email.max }),
10
+ body: t.String({
11
+ minLength: MESSAGE_LIMITS.body.min,
12
+ maxLength: MESSAGE_LIMITS.body.max,
13
+ }),
14
+ turnstileToken: t.Optional(
15
+ t.String({ maxLength: MESSAGE_LIMITS.turnstileToken.max })
16
+ ),
17
+ website: t.Optional(t.String()),
18
+ })
@@ -0,0 +1,29 @@
1
+ import { reportServerError } from "@tpl/shared/observability/server-errors"
2
+ import { Elysia } from "elysia"
3
+ import { adminMessageRoutes } from "./routes/admin-messages"
4
+ import { devRoutesWithAccounts } from "./routes/dev"
5
+ import { healthRoutes } from "./routes/health"
6
+ import { messageRoutes } from "./routes/messages"
7
+
8
+ export function createApi() {
9
+ // workerd forbids `new Function` at request time, which ahead-of-time compilation relies on.
10
+ return new Elysia({ prefix: "/api", aot: false, normalize: "typebox" })
11
+ .onError(({ code, error, request }) => {
12
+ if (code === "UNKNOWN" || code === "INTERNAL_SERVER_ERROR") {
13
+ reportServerError(error, {
14
+ elysia_code: code,
15
+ method: request.method,
16
+ route: new URL(request.url).pathname,
17
+ surface: "api",
18
+ })
19
+ }
20
+ })
21
+ .use(healthRoutes)
22
+ .use(messageRoutes)
23
+ .use(adminMessageRoutes)
24
+ .use(devRoutesWithAccounts)
25
+ }
26
+
27
+ export type Api = ReturnType<typeof createApi>
28
+
29
+ export { auth, AUTH_BASE_PATH } from "./lib/auth"
@@ -0,0 +1,10 @@
1
+ {
2
+ "extends": "../../tsconfig.worker.json",
3
+ "compilerOptions": {
4
+ "types": ["@cloudflare/workers-types"],
5
+ "paths": {
6
+ "@/*": ["./src/*"]
7
+ }
8
+ },
9
+ "include": ["src/**/*.ts"]
10
+ }
@@ -0,0 +1,79 @@
1
+ -- CreateTable
2
+ CREATE TABLE "user" (
3
+ "id" TEXT NOT NULL PRIMARY KEY,
4
+ "name" TEXT NOT NULL,
5
+ "email" TEXT NOT NULL,
6
+ "emailVerified" BOOLEAN NOT NULL DEFAULT false,
7
+ "image" TEXT,
8
+ "createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
9
+ "updatedAt" DATETIME NOT NULL
10
+ );
11
+
12
+ -- CreateTable
13
+ CREATE TABLE "session" (
14
+ "id" TEXT NOT NULL PRIMARY KEY,
15
+ "expiresAt" DATETIME NOT NULL,
16
+ "token" TEXT NOT NULL,
17
+ "createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
18
+ "updatedAt" DATETIME NOT NULL,
19
+ "ipAddress" TEXT,
20
+ "userAgent" TEXT,
21
+ "userId" TEXT NOT NULL,
22
+ CONSTRAINT "session_userId_fkey" FOREIGN KEY ("userId") REFERENCES "user" ("id") ON DELETE CASCADE ON UPDATE CASCADE
23
+ );
24
+
25
+ -- CreateTable
26
+ CREATE TABLE "account" (
27
+ "id" TEXT NOT NULL PRIMARY KEY,
28
+ "accountId" TEXT NOT NULL,
29
+ "providerId" TEXT NOT NULL,
30
+ "userId" TEXT NOT NULL,
31
+ "accessToken" TEXT,
32
+ "refreshToken" TEXT,
33
+ "idToken" TEXT,
34
+ "accessTokenExpiresAt" DATETIME,
35
+ "refreshTokenExpiresAt" DATETIME,
36
+ "scope" TEXT,
37
+ "password" TEXT,
38
+ "createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
39
+ "updatedAt" DATETIME NOT NULL,
40
+ CONSTRAINT "account_userId_fkey" FOREIGN KEY ("userId") REFERENCES "user" ("id") ON DELETE CASCADE ON UPDATE CASCADE
41
+ );
42
+
43
+ -- CreateTable
44
+ CREATE TABLE "verification" (
45
+ "id" TEXT NOT NULL PRIMARY KEY,
46
+ "identifier" TEXT NOT NULL,
47
+ "value" TEXT NOT NULL,
48
+ "expiresAt" DATETIME NOT NULL,
49
+ "createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
50
+ "updatedAt" DATETIME NOT NULL
51
+ );
52
+
53
+ -- CreateTable
54
+ CREATE TABLE "message" (
55
+ "id" TEXT NOT NULL PRIMARY KEY,
56
+ "name" TEXT NOT NULL,
57
+ "email" TEXT NOT NULL,
58
+ "body" TEXT NOT NULL,
59
+ "createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
60
+ );
61
+
62
+ -- CreateIndex
63
+ CREATE UNIQUE INDEX "user_email_key" ON "user"("email");
64
+
65
+ -- CreateIndex
66
+ CREATE INDEX "session_userId_idx" ON "session"("userId");
67
+
68
+ -- CreateIndex
69
+ CREATE UNIQUE INDEX "session_token_key" ON "session"("token");
70
+
71
+ -- CreateIndex
72
+ CREATE INDEX "account_userId_idx" ON "account"("userId");
73
+
74
+ -- CreateIndex
75
+ CREATE INDEX "verification_identifier_idx" ON "verification"("identifier");
76
+
77
+ -- CreateIndex
78
+ CREATE INDEX "message_createdAt_idx" ON "message"("createdAt");
79
+
@@ -0,0 +1,34 @@
1
+ {
2
+ "name": "@tpl/db",
3
+ "version": "0.0.0",
4
+ "private": true,
5
+ "type": "module",
6
+ "exports": {
7
+ "./client": "./src/generated/prisma/client.ts",
8
+ "./cloudflare/client": "./src/generated/prisma-cloudflare/client.ts",
9
+ "./d1": "./src/d1.ts",
10
+ "./scope": "./src/scope.ts"
11
+ },
12
+ "scripts": {
13
+ "build": "bun run db:generate",
14
+ "check:types": "tsgo --noEmit --pretty false",
15
+ "db:generate": "prisma generate",
16
+ "db:migrate": "bun scripts/migrate.ts",
17
+ "db:migrate:new": "bun scripts/new-migration.ts",
18
+ "db:reset": "bun scripts/reset.ts",
19
+ "db:seed": "bun scripts/seed.ts",
20
+ "test": "bun test"
21
+ },
22
+ "dependencies": {
23
+ "@prisma/adapter-d1": "catalog:",
24
+ "@prisma/client": "catalog:"
25
+ },
26
+ "devDependencies": {
27
+ "@cloudflare/workers-types": "catalog:",
28
+ "@types/bun": "catalog:",
29
+ "@types/node": "catalog:",
30
+ "@typescript/native-preview": "catalog:",
31
+ "prisma": "catalog:",
32
+ "typescript": "catalog:"
33
+ }
34
+ }