@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,95 @@
1
+ generator client {
2
+ provider = "prisma-client"
3
+ runtime = "bun"
4
+ output = "../src/generated/prisma"
5
+ }
6
+
7
+ // The small query compiler trades a little speed for a Worker that fits the size limit and starts faster.
8
+ generator cloudflareClient {
9
+ provider = "prisma-client"
10
+ runtime = "cloudflare"
11
+ output = "../src/generated/prisma-cloudflare"
12
+ compilerBuild = "small"
13
+ }
14
+
15
+ datasource db {
16
+ provider = "sqlite"
17
+ }
18
+
19
+ // User through Verification follow Better Auth's core schema: keep them in step with its version.
20
+
21
+ model User {
22
+ id String @id
23
+ name String
24
+ email String
25
+ emailVerified Boolean @default(false)
26
+ image String?
27
+ createdAt DateTime @default(now())
28
+ updatedAt DateTime @updatedAt
29
+
30
+ sessions Session[]
31
+ accounts Account[]
32
+
33
+ @@unique([email])
34
+ @@map("user")
35
+ }
36
+
37
+ model Session {
38
+ id String @id
39
+ expiresAt DateTime
40
+ token String
41
+ createdAt DateTime @default(now())
42
+ updatedAt DateTime @updatedAt
43
+ ipAddress String?
44
+ userAgent String?
45
+ userId String
46
+ user User @relation(fields: [userId], references: [id], onDelete: Cascade)
47
+
48
+ @@unique([token])
49
+ @@index([userId])
50
+ @@map("session")
51
+ }
52
+
53
+ model Account {
54
+ id String @id
55
+ accountId String
56
+ providerId String
57
+ userId String
58
+ user User @relation(fields: [userId], references: [id], onDelete: Cascade)
59
+ accessToken String?
60
+ refreshToken String?
61
+ idToken String?
62
+ accessTokenExpiresAt DateTime?
63
+ refreshTokenExpiresAt DateTime?
64
+ scope String?
65
+ password String?
66
+ createdAt DateTime @default(now())
67
+ updatedAt DateTime @updatedAt
68
+
69
+ @@index([userId])
70
+ @@map("account")
71
+ }
72
+
73
+ model Verification {
74
+ id String @id
75
+ identifier String
76
+ value String
77
+ expiresAt DateTime
78
+ createdAt DateTime @default(now())
79
+ updatedAt DateTime @updatedAt
80
+
81
+ @@index([identifier])
82
+ @@map("verification")
83
+ }
84
+
85
+ /// A message sent from the public site's contact form.
86
+ model Message {
87
+ id String @id
88
+ name String
89
+ email String
90
+ body String
91
+ createdAt DateTime @default(now())
92
+
93
+ @@index([createdAt])
94
+ @@map("message")
95
+ }
@@ -0,0 +1,9 @@
1
+ import { defineConfig } from "prisma/config"
2
+
3
+ // D1 has no URL: Prisma only opens the shadow database `scripts/new-migration.ts` builds to diff against.
4
+ export default defineConfig({
5
+ datasource: {
6
+ url: process.env.MIGRATIONS_SHADOW_URL ?? "file:./.shadow.sqlite",
7
+ },
8
+ schema: "prisma/schema.prisma",
9
+ })
@@ -0,0 +1,15 @@
1
+ import {
2
+ assertMigrationAllowed,
3
+ targetOf,
4
+ wranglerTarget,
5
+ } from "../src/migration-guard"
6
+ import { BINDING, fail, wrangler } from "./wrangler"
7
+
8
+ try {
9
+ const target = targetOf(process.argv[2])
10
+
11
+ assertMigrationAllowed(target, (key) => process.env[key])
12
+ wrangler(["d1", "migrations", "apply", BINDING, ...wranglerTarget(target)])
13
+ } catch (error) {
14
+ fail(error)
15
+ }
@@ -0,0 +1,185 @@
1
+ import { Database } from "bun:sqlite"
2
+ import { spawnSync } from "node:child_process"
3
+ import {
4
+ mkdtempSync,
5
+ readdirSync,
6
+ readFileSync,
7
+ rmSync,
8
+ writeFileSync,
9
+ } from "node:fs"
10
+ import { tmpdir } from "node:os"
11
+ import path from "node:path"
12
+ import { DB_DIR, fail, MIGRATIONS_DIR } from "./wrangler"
13
+
14
+ const NAME_RE = /^[a-z0-9-]+$/
15
+
16
+ const FILE_RE = /^(\d{4})_.*\.sql$/
17
+
18
+ const FOREIGN_KEYS_PRAGMA_RE = /^PRAGMA foreign_keys=(ON|OFF);\n/gm
19
+
20
+ const DROP_TABLE_RE = /^DROP TABLE "([^"]+)";$/gm
21
+
22
+ const BARE_JSON_DEFAULT_RE = /DEFAULT (\[[^\n]*?\]|\{[^\n]*?\})(?=,?\n)/g
23
+
24
+ export function nextFileName(existing: string[], name: string): string {
25
+ const highest = Math.max(
26
+ 0,
27
+ ...existing.map((file) => Number(file.match(FILE_RE)?.[1] ?? 0))
28
+ )
29
+ const index = String(highest + 1).padStart(4, "0")
30
+
31
+ return `${index}_${name.replaceAll("-", "_")}.sql`
32
+ }
33
+
34
+ // D1 refuses to toggle foreign keys, and Prisma writes JSON defaults unquoted, which SQLite stores as unreadable text.
35
+ export function forD1(script: string): string {
36
+ return script
37
+ .replace(FOREIGN_KEYS_PRAGMA_RE, "")
38
+ .replace(
39
+ BARE_JSON_DEFAULT_RE,
40
+ (_match, json: string) => `DEFAULT '${json.replaceAll("'", "''")}'`
41
+ )
42
+ }
43
+
44
+ export function referencingTables(database: Database): Map<string, string[]> {
45
+ const rows = database
46
+ .query<{ child: string; parent: string }, []>(
47
+ `SELECT DISTINCT "table"."name" AS "child", "key"."table" AS "parent"
48
+ FROM "sqlite_master" AS "table", pragma_foreign_key_list("table"."name") AS "key"
49
+ WHERE "table"."type" = 'table'
50
+ ORDER BY "child"`
51
+ )
52
+ .all()
53
+
54
+ const references = new Map<string, string[]>()
55
+
56
+ for (const { child, parent } of rows) {
57
+ references.set(parent, [...(references.get(parent) ?? []), child])
58
+ }
59
+
60
+ return references
61
+ }
62
+
63
+ // D1 keeps foreign keys on and DROP TABLE runs every ON DELETE action: a rebuilt parent wipes its children.
64
+ export function assertNoCascadingDrop(
65
+ script: string,
66
+ references: Map<string, string[]>
67
+ ): void {
68
+ const dropped = [...script.matchAll(DROP_TABLE_RE)]
69
+ .map((match) => match[1] ?? "")
70
+ .filter((table) => references.has(table))
71
+
72
+ if (dropped.length === 0) {
73
+ return
74
+ }
75
+
76
+ throw new Error(
77
+ [
78
+ ...dropped.map(
79
+ (table) =>
80
+ `Refused: this migration drops "${table}", which ${(references.get(table) ?? []).join(", ")} point at; their rows or links would be lost.`
81
+ ),
82
+ "Write it by hand in packages/db/migrations/NNNN_<name>.sql: prefer ALTER TABLE, or copy the referencing rows aside before the rebuild.",
83
+ "",
84
+ "What Prisma generated, to start from:",
85
+ "",
86
+ script,
87
+ ].join("\n")
88
+ )
89
+ }
90
+
91
+ export function migrationFiles(dir = MIGRATIONS_DIR): string[] {
92
+ return readdirSync(dir)
93
+ .filter((file) => FILE_RE.test(file))
94
+ .toSorted()
95
+ }
96
+
97
+ export function replayMigrations(
98
+ database: Database,
99
+ dir = MIGRATIONS_DIR
100
+ ): void {
101
+ for (const file of migrationFiles(dir)) {
102
+ database.exec(readFileSync(path.join(dir, file), "utf8"))
103
+ }
104
+ }
105
+
106
+ export function schemaDiff(shadow: string): string | null {
107
+ const diff = spawnSync(
108
+ "bun",
109
+ [
110
+ "x",
111
+ "prisma",
112
+ "migrate",
113
+ "diff",
114
+ "--from-config-datasource",
115
+ "--to-schema",
116
+ "prisma/schema.prisma",
117
+ "--script",
118
+ ],
119
+ {
120
+ cwd: DB_DIR,
121
+ encoding: "utf8",
122
+ env: { ...process.env, MIGRATIONS_SHADOW_URL: `file:${shadow}` },
123
+ stdio: ["inherit", "pipe", "pipe"],
124
+ }
125
+ )
126
+
127
+ if (diff.status !== 0) {
128
+ throw new Error(
129
+ `prisma migrate diff exited with ${diff.status}\n${diff.stderr}`
130
+ )
131
+ }
132
+
133
+ return diff.stdout.includes("This is an empty migration") ? null : diff.stdout
134
+ }
135
+
136
+ function main(): void {
137
+ const [, , name] = process.argv
138
+
139
+ if (!(name && NAME_RE.test(name))) {
140
+ throw new Error(
141
+ "usage: bun run db:migrate:new <name>, in lowercase and dashes"
142
+ )
143
+ }
144
+
145
+ const temp = mkdtempSync(path.join(tmpdir(), "tpl-shadow-"))
146
+ const shadow = path.join(temp, "shadow.sqlite")
147
+
148
+ try {
149
+ const database = new Database(shadow)
150
+
151
+ replayMigrations(database)
152
+
153
+ const references = referencingTables(database)
154
+
155
+ database.close()
156
+
157
+ const diff = schemaDiff(shadow)
158
+
159
+ if (diff === null) {
160
+ throw new Error("the schema and the migrations agree: nothing to write.")
161
+ }
162
+
163
+ const script = forD1(diff)
164
+
165
+ assertNoCascadingDrop(script, references)
166
+
167
+ const file = nextFileName(migrationFiles(), name)
168
+ const target = path.join(MIGRATIONS_DIR, file)
169
+
170
+ writeFileSync(target, script)
171
+ console.log(
172
+ `${path.relative(process.cwd(), target)} — read it, then bun run db:migrate`
173
+ )
174
+ } finally {
175
+ rmSync(temp, { force: true, recursive: true })
176
+ }
177
+ }
178
+
179
+ if (import.meta.main) {
180
+ try {
181
+ main()
182
+ } catch (error) {
183
+ fail(error)
184
+ }
185
+ }
@@ -0,0 +1,54 @@
1
+ import {
2
+ assertLocalOnly,
3
+ targetOf,
4
+ wranglerTarget,
5
+ } from "../src/migration-guard"
6
+ import { seed } from "./seed"
7
+ import { BINDING, fail, wrangler } from "./wrangler"
8
+
9
+ // D1 has no reset: drop every table, the migrations ledger included, then reapply.
10
+ const TABLES_SQL =
11
+ "SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' AND name NOT LIKE '_cf_%'"
12
+
13
+ interface TAnswer {
14
+ results?: { name: string }[]
15
+ }
16
+
17
+ /** Children before parents: dropping a parent first leaves its children's keys pointing nowhere. */
18
+ export function dropStatement(tables: string[]): string {
19
+ return [...tables]
20
+ .reverse()
21
+ .map((table) => `DROP TABLE IF EXISTS "${table}";`)
22
+ .join(" ")
23
+ }
24
+
25
+ try {
26
+ const target = targetOf(process.argv[2])
27
+ const where = wranglerTarget(target)
28
+
29
+ assertLocalOnly(target, "db:reset")
30
+
31
+ const listed = wrangler(
32
+ ["d1", "execute", BINDING, ...where, "--command", TABLES_SQL, "--json"],
33
+ { capture: true }
34
+ )
35
+ const tables = (JSON.parse(listed) as TAnswer[]).flatMap((answer) =>
36
+ (answer.results ?? []).map((row) => row.name)
37
+ )
38
+
39
+ if (tables.length > 0) {
40
+ wrangler([
41
+ "d1",
42
+ "execute",
43
+ BINDING,
44
+ ...where,
45
+ "--command",
46
+ `PRAGMA defer_foreign_keys = ON; ${dropStatement(tables)}`,
47
+ ])
48
+ }
49
+
50
+ wrangler(["d1", "migrations", "apply", BINDING, ...where])
51
+ seed(target)
52
+ } catch (error) {
53
+ fail(error)
54
+ }
@@ -0,0 +1,44 @@
1
+ import { mkdtempSync, rmSync, writeFileSync } from "node:fs"
2
+ import { tmpdir } from "node:os"
3
+ import path from "node:path"
4
+ import {
5
+ assertLocalOnly,
6
+ targetOf,
7
+ wranglerTarget,
8
+ } from "../src/migration-guard"
9
+ import { demoSeedSql } from "../src/seed"
10
+ import { BINDING, fail, wrangler } from "./wrangler"
11
+
12
+ /** Through a file: a seed soon outgrows what a command line allows. */
13
+ function execute(target: string, sql: string): void {
14
+ const directory = mkdtempSync(path.join(tmpdir(), "tpl-seed-"))
15
+ const file = path.join(directory, "seed.sql")
16
+
17
+ writeFileSync(file, sql)
18
+
19
+ try {
20
+ wrangler([
21
+ "d1",
22
+ "execute",
23
+ BINDING,
24
+ ...wranglerTarget(target),
25
+ "--file",
26
+ file,
27
+ ])
28
+ } finally {
29
+ rmSync(directory, { force: true, recursive: true })
30
+ }
31
+ }
32
+
33
+ export function seed(target: string): void {
34
+ assertLocalOnly(target, "db:seed")
35
+ execute(target, demoSeedSql())
36
+ }
37
+
38
+ if (import.meta.main) {
39
+ try {
40
+ seed(targetOf(process.argv[2]))
41
+ } catch (error) {
42
+ fail(error)
43
+ }
44
+ }
@@ -0,0 +1,35 @@
1
+ import { spawnSync } from "node:child_process"
2
+ import path from "node:path"
3
+
4
+ /** The D1 bindings and the migrations directory are configured in the admin app's wrangler config. */
5
+ export const ADMIN_DIR = path.resolve(import.meta.dir, "../../../apps/admin")
6
+
7
+ export const DB_DIR = path.resolve(import.meta.dir, "..")
8
+
9
+ export const MIGRATIONS_DIR = path.join(DB_DIR, "migrations")
10
+
11
+ export const BINDING = "DB"
12
+
13
+ export function wrangler(
14
+ args: string[],
15
+ options: { capture?: boolean } = {}
16
+ ): string {
17
+ const result = spawnSync("bun", ["x", "wrangler", ...args], {
18
+ cwd: ADMIN_DIR,
19
+ encoding: "utf8",
20
+ stdio: options.capture ? ["inherit", "pipe", "inherit"] : "inherit",
21
+ })
22
+
23
+ if (result.status !== 0) {
24
+ throw new Error(
25
+ `wrangler ${args.slice(0, 3).join(" ")} exited with ${result.status}`
26
+ )
27
+ }
28
+
29
+ return result.stdout ?? ""
30
+ }
31
+
32
+ export function fail(error: unknown): never {
33
+ console.error(error instanceof Error ? error.message : String(error))
34
+ process.exit(1)
35
+ }
@@ -0,0 +1,7 @@
1
+ import type { D1Database } from "@cloudflare/workers-types"
2
+ import { PrismaD1 } from "@prisma/adapter-d1"
3
+ import { PrismaClient } from "./generated/prisma-cloudflare/client"
4
+
5
+ export function createD1PrismaClient(database: D1Database): PrismaClient {
6
+ return new PrismaClient({ adapter: new PrismaD1(database) })
7
+ }
@@ -0,0 +1,43 @@
1
+ import { describe, expect, test } from "bun:test"
2
+ import {
3
+ ALLOW_FLAG,
4
+ assertLocalOnly,
5
+ assertMigrationAllowed,
6
+ MigrationGuardError,
7
+ targetOf,
8
+ wranglerTarget,
9
+ } from "./migration-guard"
10
+
11
+ describe("migration guard", () => {
12
+ test("defaults to the local database", () => {
13
+ expect(targetOf(undefined)).toBe("local")
14
+ expect(wranglerTarget("local")).toEqual(["--local"])
15
+ })
16
+
17
+ test("rejects a target that is not an environment name", () => {
18
+ expect(() => targetOf("Prod!")).toThrow(MigrationGuardError)
19
+ })
20
+
21
+ test("only touches a remote database with the flag naming it", () => {
22
+ expect(() => assertMigrationAllowed("production", () => undefined)).toThrow(
23
+ MigrationGuardError
24
+ )
25
+ expect(() =>
26
+ assertMigrationAllowed("production", (key) =>
27
+ key === ALLOW_FLAG ? "production" : undefined
28
+ )
29
+ ).not.toThrow()
30
+ expect(wranglerTarget("production")).toEqual([
31
+ "--env",
32
+ "production",
33
+ "--remote",
34
+ ])
35
+ })
36
+
37
+ test("never seeds nor resets a deployment", () => {
38
+ expect(() => assertLocalOnly("production", "db:seed")).toThrow(
39
+ MigrationGuardError
40
+ )
41
+ expect(() => assertLocalOnly("local", "db:seed")).not.toThrow()
42
+ })
43
+ })
@@ -0,0 +1,51 @@
1
+ export type TEnvGet = (key: string) => string | undefined
2
+
3
+ export class MigrationGuardError extends Error {}
4
+
5
+ export const LOCAL_TARGET = "local"
6
+
7
+ export const ALLOW_FLAG = "ALLOW_MIGRATE_ON"
8
+
9
+ // Each deployment is a Wrangler environment of apps/admin, with its own D1.
10
+ const ENVIRONMENT_RE = /^[a-z][a-z0-9-]*$/
11
+
12
+ export function targetOf(value: string | undefined): string {
13
+ const target = value ?? LOCAL_TARGET
14
+
15
+ if (!ENVIRONMENT_RE.test(target)) {
16
+ throw new MigrationGuardError(
17
+ `"${target}" is not a database: "local" or a Wrangler environment of apps/admin.`
18
+ )
19
+ }
20
+
21
+ return target
22
+ }
23
+
24
+ /** A remote database is only touched with its name repeated on the command line, never from a file. */
25
+ export function assertMigrationAllowed(target: string, get: TEnvGet): void {
26
+ if (target !== LOCAL_TARGET && get(ALLOW_FLAG) !== target) {
27
+ throw new MigrationGuardError(
28
+ [
29
+ `Refused: "${target}" is only touched with ${ALLOW_FLAG}=${target} on the command line.`,
30
+ ` → ${ALLOW_FLAG}=${target} bun run db:migrate ${target}`,
31
+ ].join("\n")
32
+ )
33
+ }
34
+ }
35
+
36
+ export function wranglerTarget(target: string): string[] {
37
+ if (target === LOCAL_TARGET) {
38
+ return ["--local"]
39
+ }
40
+
41
+ return ["--env", target, "--remote"]
42
+ }
43
+
44
+ /** Seeding and resetting are for this machine only, whatever flag is set. */
45
+ export function assertLocalOnly(target: string, command: string): void {
46
+ if (target !== LOCAL_TARGET) {
47
+ throw new MigrationGuardError(
48
+ `Refused: ${command} only runs on "${LOCAL_TARGET}". A deployment is never seeded nor reset; restore it with D1 Time Travel instead.`
49
+ )
50
+ }
51
+ }
@@ -0,0 +1,16 @@
1
+ import { describe, expect, test } from "bun:test"
2
+ import { forD1, nextFileName } from "../scripts/new-migration"
3
+
4
+ describe("new migration", () => {
5
+ test("numbers the next file after the highest one", () => {
6
+ expect(nextFileName(["0001_init.sql", "0002_x.sql"], "add-notes")).toBe(
7
+ "0003_add_notes.sql"
8
+ )
9
+ })
10
+
11
+ test("drops the foreign key pragmas D1 refuses", () => {
12
+ const script = "PRAGMA foreign_keys=OFF;\nCREATE TABLE a (id TEXT);\n"
13
+
14
+ expect(forD1(script)).toBe("CREATE TABLE a (id TEXT);\n")
15
+ })
16
+ })
@@ -0,0 +1,38 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks"
2
+ import type { PrismaClient } from "./generated/prisma-cloudflare/client"
3
+
4
+ export type WorkerPrismaClient = PrismaClient
5
+
6
+ // One client per request, so packages never see the D1 binding and tests can inject their own.
7
+ const scopes = new AsyncLocalStorage<WorkerPrismaClient>()
8
+
9
+ export function withPrismaClient<T>(
10
+ client: WorkerPrismaClient,
11
+ run: () => T | Promise<T>
12
+ ): Promise<T> {
13
+ return scopes.run(client, async () => await run())
14
+ }
15
+
16
+ export function currentPrismaClient(): WorkerPrismaClient {
17
+ const client = scopes.getStore()
18
+
19
+ if (!client) {
20
+ throw new Error(
21
+ "no Prisma client in scope: run inside withPrismaClient, or configure one."
22
+ )
23
+ }
24
+
25
+ return client
26
+ }
27
+
28
+ /** Resolved on each call, so a module built before any request can hold on to it. */
29
+ export function scopedPrismaClient(): WorkerPrismaClient {
30
+ return new Proxy({} as WorkerPrismaClient, {
31
+ get(_target, property) {
32
+ const client = currentPrismaClient()
33
+ const value = Reflect.get(client, property) as unknown
34
+
35
+ return typeof value === "function" ? value.bind(client) : value
36
+ },
37
+ })
38
+ }
@@ -0,0 +1,30 @@
1
+ import { insertSql } from "./sql"
2
+
3
+ const DEMO_MESSAGES = [
4
+ {
5
+ id: "demo-message-1",
6
+ name: "Camille Martin",
7
+ email: "camille@example.com",
8
+ body: "Bonjour, je souhaiterais un devis pour la refonte de notre site.",
9
+ hoursAgo: 2,
10
+ },
11
+ {
12
+ id: "demo-message-2",
13
+ name: "Yanis Benali",
14
+ email: "yanis@example.com",
15
+ body: "Pouvez-vous me rappeler cette semaine au sujet de votre offre ?",
16
+ hoursAgo: 26,
17
+ },
18
+ ]
19
+
20
+ const HOUR_MS = 60 * 60 * 1000
21
+
22
+ /** Example contact messages for the local database; fixed ids make it safe to run again. */
23
+ export function demoSeedSql(now: Date = new Date()): string {
24
+ return DEMO_MESSAGES.map(({ hoursAgo, ...message }) =>
25
+ insertSql("message", {
26
+ ...message,
27
+ createdAt: new Date(now.getTime() - hoursAgo * HOUR_MS),
28
+ })
29
+ ).join("\n")
30
+ }
@@ -0,0 +1,42 @@
1
+ export function sqlText(value: string): string {
2
+ return `'${value.replaceAll("'", "''")}'`
3
+ }
4
+
5
+ /** Prisma's SQLite driver adapters store `…+00:00` text, and SQLite compares dates as text. */
6
+ export function sqlDate(date: Date): string {
7
+ return sqlText(date.toISOString().replace("Z", "+00:00"))
8
+ }
9
+
10
+ export type TSqlValue = string | number | boolean | Date | null | undefined
11
+
12
+ export function sqlValue(value: TSqlValue): string {
13
+ if (value === null || value === undefined) {
14
+ return "NULL"
15
+ }
16
+
17
+ if (value instanceof Date) {
18
+ return sqlDate(value)
19
+ }
20
+
21
+ if (typeof value === "boolean") {
22
+ return value ? "1" : "0"
23
+ }
24
+
25
+ if (typeof value === "number") {
26
+ return Number.isFinite(value) ? String(value) : "NULL"
27
+ }
28
+
29
+ return sqlText(value)
30
+ }
31
+
32
+ /** One idempotent row: an existing one, possibly edited since, is left as it is. */
33
+ export function insertSql(
34
+ table: string,
35
+ row: Record<string, TSqlValue>
36
+ ): string {
37
+ const columns = Object.keys(row)
38
+ const names = columns.map((column) => `"${column}"`).join(", ")
39
+ const values = columns.map((column) => sqlValue(row[column])).join(", ")
40
+
41
+ return `INSERT INTO "${table}" (${names}) VALUES (${values}) ON CONFLICT DO NOTHING;`
42
+ }
@@ -0,0 +1,8 @@
1
+ {
2
+ "extends": "../../tsconfig.base.json",
3
+ "compilerOptions": {
4
+ "lib": ["ES2023"],
5
+ "types": ["node", "bun"]
6
+ },
7
+ "include": ["prisma.config.ts", "scripts/*.ts", "src/*.ts"]
8
+ }