@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,233 @@
1
+ import { describe, expect, test } from "bun:test"
2
+
3
+ import type { NeonDatabaseConfig } from "../config"
4
+ import { fakeRunner } from "../test-utils"
5
+ import {
6
+ devBranchForGitBranch,
7
+ devProjectName,
8
+ ensureDevBranch,
9
+ localGuardErrors,
10
+ NeonCli,
11
+ neonEndpointId,
12
+ productionConnection,
13
+ resolveDevProject,
14
+ slugifyBranch,
15
+ waitForBranch,
16
+ } from "./neon"
17
+
18
+ const NEON: NeonDatabaseConfig = {
19
+ production: {
20
+ projectId: "little-river-1",
21
+ projectName: "fabrikam",
22
+ endpointId: "ep-prod-1",
23
+ },
24
+ }
25
+
26
+ function neonRunner(
27
+ respond: (
28
+ args: string[]
29
+ ) => { stdout?: string; exitCode?: number } | undefined
30
+ ) {
31
+ return fakeRunner((command) => respond(command.slice(1)))
32
+ }
33
+
34
+ describe("branch naming", () => {
35
+ test("git main runs on development, any other branch on a feature branch", () => {
36
+ expect(devBranchForGitBranch("main")).toEqual({
37
+ branch: "development",
38
+ disposable: false,
39
+ })
40
+ expect(devBranchForGitBranch("Feat/Admin Mail")).toEqual({
41
+ branch: "feature/feat-admin-mail",
42
+ disposable: true,
43
+ })
44
+ })
45
+
46
+ test("refuses a branch with no usable characters", () => {
47
+ expect(() => slugifyBranch("///")).toThrow()
48
+ })
49
+
50
+ test("the dev project defaults to <production>-dev", () => {
51
+ expect(devProjectName(NEON)).toBe("fabrikam-dev")
52
+ expect(devProjectName({ ...NEON, devProjectName: "other-dev" })).toBe(
53
+ "other-dev"
54
+ )
55
+ })
56
+
57
+ test("reads the compute id from pooled and direct strings", () => {
58
+ expect(
59
+ neonEndpointId("postgresql://u:p@ep-a-1-pooler.c-8.aws.neon.tech/db")
60
+ ).toBe("ep-a-1")
61
+ expect(neonEndpointId("postgresql://u:p@ep-a-1.c-8.aws.neon.tech/db")).toBe(
62
+ "ep-a-1"
63
+ )
64
+ expect(neonEndpointId("postgresql://u:p@localhost/db")).toBeNull()
65
+ })
66
+ })
67
+
68
+ describe("resolveDevProject", () => {
69
+ test("finds the dev project by name", () => {
70
+ const { runner } = neonRunner(() => ({
71
+ stdout: JSON.stringify({
72
+ projects: [
73
+ { id: "prod", name: "fabrikam" },
74
+ { id: "dev", name: "fabrikam-dev" },
75
+ ],
76
+ }),
77
+ }))
78
+
79
+ expect(resolveDevProject(new NeonCli(runner), NEON).id).toBe("dev")
80
+ })
81
+
82
+ test("refuses a dev project that is the production one", () => {
83
+ const { runner } = neonRunner(() => ({
84
+ stdout: JSON.stringify([{ id: "little-river-1", name: "fabrikam-dev" }]),
85
+ }))
86
+
87
+ expect(() => resolveDevProject(new NeonCli(runner), NEON)).toThrow(
88
+ "production"
89
+ )
90
+ })
91
+ })
92
+
93
+ describe("ensureDevBranch", () => {
94
+ test("creates development from the default branch, then the feature branch with an expiry", () => {
95
+ const { runner, calls } = neonRunner((args) =>
96
+ args[0] === "branches" && args[1] === "list"
97
+ ? {
98
+ stdout: JSON.stringify([
99
+ { name: "main", current_state: "ready", default: true },
100
+ ]),
101
+ }
102
+ : undefined
103
+ )
104
+
105
+ ensureDevBranch(
106
+ new NeonCli(runner),
107
+ "dev",
108
+ { branch: "feature/x", disposable: true },
109
+ { ttlDays: 14, now: () => 0, log: () => undefined }
110
+ )
111
+
112
+ const creates = calls
113
+ .map((call) => call.command)
114
+ .filter((command) => command[2] === "create")
115
+
116
+ expect(creates[0]).toContain("development")
117
+ expect(creates[0]).toContain("main")
118
+ expect(creates[1]).toEqual(
119
+ expect.arrayContaining([
120
+ "feature/x",
121
+ "development",
122
+ "--expires-at",
123
+ "1970-01-15T00:00:00.000Z",
124
+ ])
125
+ )
126
+ })
127
+
128
+ test("reuses existing branches", () => {
129
+ const { runner, calls } = neonRunner(() => ({
130
+ stdout: JSON.stringify([
131
+ { name: "main", current_state: "ready", default: true },
132
+ { name: "development", current_state: "archived" },
133
+ ]),
134
+ }))
135
+
136
+ ensureDevBranch(
137
+ new NeonCli(runner),
138
+ "dev",
139
+ { branch: "development", disposable: false },
140
+ { log: () => undefined }
141
+ )
142
+
143
+ expect(calls.some((call) => call.command[2] === "create")).toBe(false)
144
+ })
145
+ })
146
+
147
+ describe("waitForBranch", () => {
148
+ test("accepts an archived branch without waiting", () => {
149
+ const { runner } = neonRunner(() => ({
150
+ stdout: JSON.stringify([
151
+ { name: "development", current_state: "archived" },
152
+ ]),
153
+ }))
154
+ let slept = 0
155
+
156
+ waitForBranch(new NeonCli(runner), "dev", "development", {
157
+ sleep: () => {
158
+ slept += 1
159
+ },
160
+ })
161
+
162
+ expect(slept).toBe(0)
163
+ })
164
+
165
+ test("polls while the branch initialises, then times out", () => {
166
+ const { runner } = neonRunner(() => ({
167
+ stdout: JSON.stringify([{ name: "feature/x", current_state: "init" }]),
168
+ }))
169
+ let clock = 0
170
+
171
+ expect(() =>
172
+ waitForBranch(new NeonCli(runner), "dev", "feature/x", {
173
+ timeoutMs: 10,
174
+ pollMs: 5,
175
+ now: () => clock,
176
+ sleep: (ms) => {
177
+ clock += ms
178
+ },
179
+ })
180
+ ).toThrow("Délai dépassé")
181
+ })
182
+ })
183
+
184
+ describe("productionConnection", () => {
185
+ test("returns the direct string of the production main branch", () => {
186
+ const url = "postgresql://u:p@ep-prod-1.c-8.aws.neon.tech/neondb"
187
+ const { runner, calls } = neonRunner(() => ({ stdout: url }))
188
+
189
+ expect(productionConnection(new NeonCli(runner), NEON)).toBe(url)
190
+ expect(calls[0]?.command).toEqual([
191
+ "neonctl",
192
+ "connection-string",
193
+ "main",
194
+ "--project-id",
195
+ "little-river-1",
196
+ ])
197
+ })
198
+
199
+ test("refuses a compute other than the declared one", () => {
200
+ const { runner } = neonRunner(() => ({
201
+ stdout: "postgresql://u:p@ep-other.c-8.aws.neon.tech/neondb",
202
+ }))
203
+
204
+ expect(() => productionConnection(new NeonCli(runner), NEON)).toThrow(
205
+ "ep-prod-1"
206
+ )
207
+ })
208
+ })
209
+
210
+ describe("localGuardErrors", () => {
211
+ const safe = new Map([
212
+ ["APP_ENV", "local"],
213
+ ["DATABASE_URL", "postgresql://u:p@ep-dev-pooler.c-8.aws.neon.tech/db"],
214
+ ["NEON_BRANCH", "development"],
215
+ ["NEON_PROJECT_ID", "dev"],
216
+ ["NEON_PROJECT_NAME", "fabrikam-dev"],
217
+ ])
218
+
219
+ test("accepts a dev branch", () => {
220
+ expect(localGuardErrors(safe, NEON)).toEqual([])
221
+ })
222
+
223
+ test("refuses production, the staging branch and a non-local env", () => {
224
+ const env = new Map(safe)
225
+
226
+ env.set("APP_ENV", "production")
227
+ env.set("NEON_BRANCH", "main")
228
+ env.set("NEON_PROJECT_ID", "little-river-1")
229
+ env.set("DATABASE_URL", "postgresql://u:p@ep-prod-1.c-8.aws.neon.tech/db")
230
+
231
+ expect(localGuardErrors(env, NEON)).toHaveLength(4)
232
+ })
233
+ })
@@ -0,0 +1,357 @@
1
+ import type { NeonDatabaseConfig } from "../config"
2
+ import type { Runner } from "../process"
3
+
4
+ export const STAGING_BRANCH = "main"
5
+ export const DEVELOPMENT_BRANCH = "development"
6
+ export const FEATURE_BRANCH_PREFIX = "feature"
7
+ export const DEFAULT_FEATURE_TTL_DAYS = 14
8
+
9
+ // An archived branch wakes on its first connection: it never turns "ready" on its own.
10
+ const USABLE_BRANCH_STATES = new Set(["ready", "archived"])
11
+ const NEONCTL_ENV = { BROWSER: "true" }
12
+ const DAY_MS = 24 * 60 * 60 * 1000
13
+ const POOLER_SUFFIX_RE = /-pooler$/
14
+ const UNSAFE_SLUG_CHARS_RE = /[^a-z0-9-]+/g
15
+ const REPEATED_DASH_RE = /-+/g
16
+ const BOUNDARY_DASH_RE = /^-|-$/g
17
+
18
+ export interface NeonProject {
19
+ id: string
20
+ name: string
21
+ }
22
+
23
+ export interface NeonBranch {
24
+ name: string
25
+ current_state: string
26
+ default?: boolean
27
+ }
28
+
29
+ export interface NeonConnection {
30
+ pooled: string
31
+ direct: string
32
+ }
33
+
34
+ export interface DevBranchTarget {
35
+ branch: string
36
+ disposable: boolean
37
+ }
38
+
39
+ export function devProjectName(neon: NeonDatabaseConfig): string {
40
+ return neon.devProjectName ?? `${neon.production.projectName}-dev`
41
+ }
42
+
43
+ export function slugifyBranch(branch: string): string {
44
+ const slug = branch
45
+ .toLowerCase()
46
+ .replace(UNSAFE_SLUG_CHARS_RE, "-")
47
+ .replace(REPEATED_DASH_RE, "-")
48
+ .replace(BOUNDARY_DASH_RE, "")
49
+
50
+ if (!slug) {
51
+ throw new Error(
52
+ `Impossible de dériver un nom de branche Neon de « ${branch} ».`
53
+ )
54
+ }
55
+
56
+ return slug
57
+ }
58
+
59
+ export function devBranchForGitBranch(gitBranch: string): DevBranchTarget {
60
+ if (gitBranch === "main" || gitBranch === "master") {
61
+ return { branch: DEVELOPMENT_BRANCH, disposable: false }
62
+ }
63
+
64
+ return {
65
+ branch: `${FEATURE_BRANCH_PREFIX}/${slugifyBranch(gitBranch)}`,
66
+ disposable: true,
67
+ }
68
+ }
69
+
70
+ export function neonEndpointId(connectionString: string): string | null {
71
+ let host: string
72
+
73
+ try {
74
+ host = new URL(connectionString).hostname
75
+ } catch {
76
+ return null
77
+ }
78
+
79
+ if (!host.endsWith(".neon.tech")) {
80
+ return null
81
+ }
82
+
83
+ const [endpoint] = host.split(".")
84
+
85
+ return endpoint ? endpoint.replace(POOLER_SUFFIX_RE, "") : null
86
+ }
87
+
88
+ export function directConnectionString(url: string): string {
89
+ return url.replace("-pooler.", ".")
90
+ }
91
+
92
+ export class NeonCli {
93
+ constructor(private readonly runner: Runner) {}
94
+
95
+ private text(args: string[]): string {
96
+ const result = this.runner(["neonctl", ...args], { env: NEONCTL_ENV })
97
+
98
+ if (result.exitCode !== 0) {
99
+ throw new Error(
100
+ `« neonctl ${args.join(" ")} » a échoué :\n${(result.stderr || result.stdout).trim()}`
101
+ )
102
+ }
103
+
104
+ return result.stdout.trim()
105
+ }
106
+
107
+ private json<T>(args: string[]): T {
108
+ return JSON.parse(this.text([...args, "-o", "json"])) as T
109
+ }
110
+
111
+ available(): boolean {
112
+ return (
113
+ this.runner(["neonctl", "--version"], { env: NEONCTL_ENV }).exitCode === 0
114
+ )
115
+ }
116
+
117
+ authenticated(): boolean {
118
+ return (
119
+ this.runner(["neonctl", "me", "-o", "json"], { env: NEONCTL_ENV })
120
+ .exitCode === 0
121
+ )
122
+ }
123
+
124
+ projects(): NeonProject[] {
125
+ const parsed = this.json<NeonProject[] | { projects?: NeonProject[] }>([
126
+ "projects",
127
+ "list",
128
+ ])
129
+
130
+ return Array.isArray(parsed) ? parsed : (parsed.projects ?? [])
131
+ }
132
+
133
+ branches(projectId: string): NeonBranch[] {
134
+ return this.json<NeonBranch[]>([
135
+ "branches",
136
+ "list",
137
+ "--project-id",
138
+ projectId,
139
+ ])
140
+ }
141
+
142
+ createBranch(
143
+ projectId: string,
144
+ name: string,
145
+ parent: string,
146
+ expiresAt?: string
147
+ ): void {
148
+ this.text([
149
+ "branches",
150
+ "create",
151
+ "--project-id",
152
+ projectId,
153
+ "--name",
154
+ name,
155
+ "--parent",
156
+ parent,
157
+ ...(expiresAt ? ["--expires-at", expiresAt] : []),
158
+ "-o",
159
+ "json",
160
+ ])
161
+ }
162
+
163
+ deleteBranch(projectId: string, name: string): void {
164
+ this.text(["branches", "delete", name, "--project-id", projectId])
165
+ }
166
+
167
+ connectionString(projectId: string, branch: string, pooled: boolean): string {
168
+ return this.text([
169
+ "connection-string",
170
+ branch,
171
+ "--project-id",
172
+ projectId,
173
+ ...(pooled ? ["--pooled"] : []),
174
+ ])
175
+ }
176
+
177
+ connection(projectId: string, branch: string): NeonConnection {
178
+ return {
179
+ pooled: this.connectionString(projectId, branch, true),
180
+ direct: this.connectionString(projectId, branch, false),
181
+ }
182
+ }
183
+ }
184
+
185
+ export function resolveDevProject(
186
+ cli: NeonCli,
187
+ neon: NeonDatabaseConfig
188
+ ): NeonProject {
189
+ const name = devProjectName(neon)
190
+ const matches = cli.projects().filter((project) => project.name === name)
191
+
192
+ if (matches.length !== 1) {
193
+ throw new Error(
194
+ matches.length === 0
195
+ ? `Projet Neon de dev « ${name} » introuvable pour ce compte neonctl.`
196
+ : `Plusieurs projets Neon s'appellent « ${name} » : renomme les doublons.`
197
+ )
198
+ }
199
+
200
+ const [project] = matches as [NeonProject]
201
+
202
+ if (
203
+ project.id === neon.production.projectId ||
204
+ project.name === neon.production.projectName
205
+ ) {
206
+ throw new Error(
207
+ `Le projet de dev « ${name} » est le projet de production : le développement local ne vise jamais la production.`
208
+ )
209
+ }
210
+
211
+ return project
212
+ }
213
+
214
+ export interface EnsureBranchOptions {
215
+ ttlDays?: number
216
+ now?: () => number
217
+ log?: (line: string) => void
218
+ }
219
+
220
+ function ensureBranch(
221
+ cli: NeonCli,
222
+ projectId: string,
223
+ existing: NeonBranch[],
224
+ name: string,
225
+ parent: string,
226
+ log: (line: string) => void,
227
+ expiresAt?: string
228
+ ): void {
229
+ if (existing.some((branch) => branch.name === name)) {
230
+ log(` · branche Neon ${name} réutilisée`)
231
+
232
+ return
233
+ }
234
+
235
+ cli.createBranch(projectId, name, parent, expiresAt)
236
+ log(` ✓ branche Neon ${name} créée depuis ${parent}`)
237
+ }
238
+
239
+ export function ensureDevBranch(
240
+ cli: NeonCli,
241
+ projectId: string,
242
+ target: DevBranchTarget,
243
+ options: EnsureBranchOptions = {}
244
+ ): void {
245
+ const log = options.log ?? console.log
246
+ const branches = cli.branches(projectId)
247
+ const root = branches.find((branch) => branch.default)?.name ?? STAGING_BRANCH
248
+
249
+ ensureBranch(cli, projectId, branches, DEVELOPMENT_BRANCH, root, log)
250
+
251
+ if (!target.disposable) {
252
+ return
253
+ }
254
+
255
+ const ttlDays = options.ttlDays ?? DEFAULT_FEATURE_TTL_DAYS
256
+ const expiresAt = new Date(
257
+ (options.now ?? Date.now)() + ttlDays * DAY_MS
258
+ ).toISOString()
259
+
260
+ ensureBranch(
261
+ cli,
262
+ projectId,
263
+ branches,
264
+ target.branch,
265
+ DEVELOPMENT_BRANCH,
266
+ log,
267
+ expiresAt
268
+ )
269
+ }
270
+
271
+ export interface WaitOptions {
272
+ timeoutMs?: number
273
+ pollMs?: number
274
+ now?: () => number
275
+ sleep?: (ms: number) => void
276
+ }
277
+
278
+ export function waitForBranch(
279
+ cli: NeonCli,
280
+ projectId: string,
281
+ name: string,
282
+ options: WaitOptions = {}
283
+ ): void {
284
+ const now = options.now ?? Date.now
285
+ const sleep = options.sleep ?? Bun.sleepSync
286
+ const deadline = now() + (options.timeoutMs ?? 120_000)
287
+
288
+ while (now() < deadline) {
289
+ const branch = cli.branches(projectId).find((item) => item.name === name)
290
+
291
+ if (branch && USABLE_BRANCH_STATES.has(branch.current_state)) {
292
+ return
293
+ }
294
+
295
+ sleep(options.pollMs ?? 3000)
296
+ }
297
+
298
+ throw new Error(`Délai dépassé en attendant la branche Neon ${name}.`)
299
+ }
300
+
301
+ export function productionConnection(
302
+ cli: NeonCli,
303
+ neon: NeonDatabaseConfig
304
+ ): string {
305
+ const { projectId, endpointId } = neon.production
306
+ const url = cli.connectionString(projectId, STAGING_BRANCH, false)
307
+ const actual = neonEndpointId(url)
308
+
309
+ if (endpointId && actual !== endpointId) {
310
+ throw new Error(
311
+ `La branche main du projet de production répond sur « ${actual ?? "un hôte non Neon"} », pas sur le compute attendu « ${endpointId} » : vérifie database.neon.production.endpointId.`
312
+ )
313
+ }
314
+
315
+ return url
316
+ }
317
+
318
+ export function localGuardErrors(
319
+ env: ReadonlyMap<string, string>,
320
+ neon: NeonDatabaseConfig
321
+ ): string[] {
322
+ const errors: string[] = []
323
+ const { production } = neon
324
+
325
+ if (env.get("APP_ENV") !== "local") {
326
+ errors.push(
327
+ `APP_ENV vaut « ${env.get("APP_ENV") ?? "absent"} » au lieu de « local ».`
328
+ )
329
+ }
330
+
331
+ if (!env.get("DATABASE_URL")) {
332
+ errors.push("DATABASE_URL est absente.")
333
+ }
334
+
335
+ if (env.get("NEON_BRANCH") === STAGING_BRANCH) {
336
+ errors.push(
337
+ `NEON_BRANCH vaut « ${STAGING_BRANCH} », la branche réservée à la préproduction.`
338
+ )
339
+ }
340
+
341
+ if (
342
+ env.get("NEON_PROJECT_ID") === production.projectId ||
343
+ env.get("NEON_PROJECT_NAME") === production.projectName
344
+ ) {
345
+ errors.push("le projet Neon visé est celui de PRODUCTION.")
346
+ }
347
+
348
+ const endpoints = [env.get("DATABASE_URL"), env.get("DATABASE_URL_UNPOOLED")]
349
+ .map((url) => (url ? neonEndpointId(url) : null))
350
+ .filter(Boolean)
351
+
352
+ if (production.endpointId && endpoints.includes(production.endpointId)) {
353
+ errors.push("DATABASE_URL pointe sur le compute de PRODUCTION.")
354
+ }
355
+
356
+ return errors
357
+ }
@@ -0,0 +1,54 @@
1
+ import type { LoadedConfig } from "../config"
2
+ import type { Runner } from "../process"
3
+ import {
4
+ currentGitBranch,
5
+ databaseConfigOf,
6
+ migrateCommand,
7
+ runDatabaseCommand,
8
+ targetEnv,
9
+ writeDevEnv,
10
+ } from "./index"
11
+
12
+ function errorMessage(error: unknown): string {
13
+ return error instanceof Error ? error.message : String(error)
14
+ }
15
+
16
+ export function prepareDevDatabase(
17
+ loaded: LoadedConfig,
18
+ runner: Runner,
19
+ warn: (message: string) => void = console.warn
20
+ ): boolean {
21
+ if (databaseConfigOf(loaded).provider === "neon") {
22
+ try {
23
+ const branch = writeDevEnv(loaded, {
24
+ gitBranch: currentGitBranch(loaded.root, runner),
25
+ runner,
26
+ })
27
+
28
+ console.log(` ✓ base de dev : branche Neon ${branch}`)
29
+ } catch (error) {
30
+ warn(
31
+ `Base de dev non rafraîchie : ${errorMessage(error)}\n → Les chaînes déjà présentes dans le fichier env sont gardées.`
32
+ )
33
+ }
34
+ }
35
+
36
+ try {
37
+ const exitCode = runDatabaseCommand(
38
+ loaded,
39
+ migrateCommand(loaded, "local"),
40
+ targetEnv(loaded, "local", runner),
41
+ runner
42
+ )
43
+
44
+ if (exitCode === 0) {
45
+ return true
46
+ }
47
+
48
+ warn("Migrations de dev non appliquées : voir la sortie ci-dessus.")
49
+ } catch (error) {
50
+ warn(`Migrations de dev non appliquées : ${errorMessage(error)}`)
51
+ }
52
+
53
+ return false
54
+ }