@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,106 @@
1
+ import { describe, expect, test } from "bun:test"
2
+
3
+ import {
4
+ AI_MODELS,
5
+ AiError,
6
+ aiModelOrDefault,
7
+ aiText,
8
+ askAi,
9
+ DEFAULT_AI_MODEL,
10
+ isAiModelId,
11
+ runAi,
12
+ } from "./ai.ts"
13
+
14
+ function fakeEnv(output: unknown, gateway = "tst-ai-gateway-prod") {
15
+ const calls: unknown[][] = []
16
+ const env = {
17
+ AI: {
18
+ run: async (...args: unknown[]) => {
19
+ calls.push(args)
20
+
21
+ return output
22
+ },
23
+ },
24
+ AI_GATEWAY_ID: gateway,
25
+ }
26
+
27
+ return { env, calls }
28
+ }
29
+
30
+ describe("modèles", () => {
31
+ test("Gemma 4 par défaut, DeepSeek V4.1 en alternative", () => {
32
+ expect(DEFAULT_AI_MODEL).toBe("@cf/google/gemma-4-26b-a4b-it")
33
+ expect(AI_MODELS.alternative.id).toBe(
34
+ "@cf/deepseek-ai/deepseek-v4.1-flash-1017"
35
+ )
36
+ })
37
+
38
+ test("un ancien modèle retombe sur le modèle par défaut", () => {
39
+ expect(isAiModelId("@cf/zai-org/glm-5.3-flash")).toBe(false)
40
+ expect(aiModelOrDefault("@cf/zai-org/glm-5.3-flash")).toBe(DEFAULT_AI_MODEL)
41
+ expect(aiModelOrDefault(AI_MODELS.alternative.id)).toBe(
42
+ AI_MODELS.alternative.id
43
+ )
44
+ })
45
+ })
46
+
47
+ describe("runAi", () => {
48
+ test("passe toujours par l'AI Gateway du projet", async () => {
49
+ const { env, calls } = fakeEnv({ response: "ok" })
50
+
51
+ await runAi(env, { prompt: "x" })
52
+
53
+ expect(calls).toEqual([
54
+ [
55
+ DEFAULT_AI_MODEL,
56
+ { prompt: "x" },
57
+ { gateway: { id: "tst-ai-gateway-prod" } },
58
+ ],
59
+ ])
60
+ })
61
+
62
+ test("refuse un appel sans gateway", async () => {
63
+ const { env } = fakeEnv({ response: "ok" }, " ")
64
+
65
+ await expect(runAi(env, {})).rejects.toBeInstanceOf(AiError)
66
+ })
67
+ })
68
+
69
+ describe("aiText", () => {
70
+ test("lit les deux formats de sortie", () => {
71
+ expect(aiText({ response: " a " })).toBe("a")
72
+ expect(aiText({ choices: [{ message: { content: "b\n" } }] })).toBe("b")
73
+ expect(aiText({ response: { ok: true } })).toBe('{"ok":true}')
74
+ expect(aiText(null)).toBe("")
75
+ })
76
+ })
77
+
78
+ describe("askAi", () => {
79
+ test("envoie les messages et renvoie le texte", async () => {
80
+ const { env, calls } = fakeEnv({
81
+ choices: [{ message: { content: "Bonjour" } }],
82
+ })
83
+
84
+ const text = await askAi(env, {
85
+ messages: [{ role: "user", content: "Salut" }],
86
+ model: AI_MODELS.alternative.id,
87
+ maxTokens: 50,
88
+ })
89
+
90
+ expect(text).toBe("Bonjour")
91
+ expect(calls[0]?.[0]).toBe(AI_MODELS.alternative.id)
92
+ expect(calls[0]?.[1]).toEqual({
93
+ messages: [{ role: "user", content: "Salut" }],
94
+ max_tokens: 50,
95
+ temperature: 0.2,
96
+ })
97
+ })
98
+
99
+ test("une réponse vide est une erreur", async () => {
100
+ const { env } = fakeEnv({ response: "" })
101
+
102
+ await expect(
103
+ askAi(env, { messages: [{ role: "user", content: "x" }] })
104
+ ).rejects.toBeInstanceOf(AiError)
105
+ })
106
+ })
package/runtime/ai.ts ADDED
@@ -0,0 +1,125 @@
1
+ export const AI_MODELS = {
2
+ default: {
3
+ id: "@cf/google/gemma-4-26b-a4b-it",
4
+ label: "Gemma 4 26B",
5
+ priceUsdPerMillionTokens: { input: 0.1, output: 0.3 },
6
+ },
7
+ alternative: {
8
+ id: "@cf/deepseek-ai/deepseek-v4.1-flash-1017",
9
+ label: "DeepSeek V4.1 Flash",
10
+ priceUsdPerMillionTokens: { input: 0.3, output: 1.2 },
11
+ },
12
+ } as const
13
+
14
+ export type AiModelKey = keyof typeof AI_MODELS
15
+
16
+ export type AiModelId = (typeof AI_MODELS)[AiModelKey]["id"]
17
+
18
+ export const AI_MODEL_IDS = Object.values(AI_MODELS).map(
19
+ (model) => model.id
20
+ ) as AiModelId[]
21
+
22
+ export const DEFAULT_AI_MODEL: AiModelId = AI_MODELS.default.id
23
+
24
+ export function isAiModelId(value: unknown): value is AiModelId {
25
+ return (
26
+ typeof value === "string" &&
27
+ (AI_MODEL_IDS as readonly string[]).includes(value)
28
+ )
29
+ }
30
+
31
+ export function aiModelOrDefault(value: unknown): AiModelId {
32
+ return isAiModelId(value) ? value : DEFAULT_AI_MODEL
33
+ }
34
+
35
+ export interface AiRunOptions {
36
+ gateway: { id: string }
37
+ }
38
+
39
+ export interface AiBinding {
40
+ run(model: never, inputs: never, options?: AiRunOptions): Promise<unknown>
41
+ }
42
+
43
+ export interface AiEnv {
44
+ AI: AiBinding
45
+ AI_GATEWAY_ID: string
46
+ }
47
+
48
+ export interface AiMessage {
49
+ role: "system" | "user" | "assistant"
50
+ content: string
51
+ }
52
+
53
+ export interface AskAiOptions {
54
+ messages: AiMessage[]
55
+ model?: AiModelId
56
+ maxTokens?: number
57
+ temperature?: number
58
+ }
59
+
60
+ export class AiError extends Error {}
61
+
62
+ type RunFn = (
63
+ model: string,
64
+ inputs: Record<string, unknown>,
65
+ options: AiRunOptions
66
+ ) => Promise<unknown>
67
+
68
+ export async function runAi(
69
+ env: AiEnv,
70
+ inputs: Record<string, unknown>,
71
+ model: AiModelId = DEFAULT_AI_MODEL
72
+ ): Promise<unknown> {
73
+ const gateway = env.AI_GATEWAY_ID.trim()
74
+
75
+ if (!gateway) {
76
+ throw new AiError(
77
+ "AI_GATEWAY_ID manquant : chaque appel passe par l'AI Gateway du projet."
78
+ )
79
+ }
80
+
81
+ const run = env.AI.run.bind(env.AI) as unknown as RunFn
82
+
83
+ return run(model, inputs, { gateway: { id: gateway } })
84
+ }
85
+
86
+ export function aiText(output: unknown): string {
87
+ if (typeof output === "string") {
88
+ return output.trim()
89
+ }
90
+
91
+ const record = (output ?? {}) as {
92
+ response?: unknown
93
+ choices?: { message?: { content?: unknown } }[]
94
+ }
95
+
96
+ if (typeof record.response === "string") {
97
+ return record.response.trim()
98
+ }
99
+
100
+ if (record.response && typeof record.response === "object") {
101
+ return JSON.stringify(record.response)
102
+ }
103
+
104
+ const content = record.choices?.[0]?.message?.content
105
+
106
+ return typeof content === "string" ? content.trim() : ""
107
+ }
108
+
109
+ export async function askAi(
110
+ env: AiEnv,
111
+ { messages, model, maxTokens = 1024, temperature = 0.2 }: AskAiOptions
112
+ ): Promise<string> {
113
+ const output = await runAi(
114
+ env,
115
+ { messages, max_tokens: maxTokens, temperature },
116
+ model
117
+ )
118
+ const text = aiText(output)
119
+
120
+ if (!text) {
121
+ throw new AiError("Réponse vide du modèle.")
122
+ }
123
+
124
+ return text
125
+ }
@@ -0,0 +1,42 @@
1
+ export const SERVER_ERROR_TAG_KEYS: ReadonlySet<string> = new Set([
2
+ "elysia_code",
3
+ "event",
4
+ "health_status",
5
+ "job_name",
6
+ "marker",
7
+ "method",
8
+ "module",
9
+ "provider",
10
+ "service",
11
+ "source",
12
+ "surface",
13
+ ])
14
+
15
+ export const SERVER_ERROR_CONTEXT_KEYS: ReadonlySet<string> = new Set([
16
+ "attempt",
17
+ "bucket",
18
+ "cron",
19
+ "pathname",
20
+ "reason",
21
+ "route",
22
+ "started_at",
23
+ "status",
24
+ ])
25
+
26
+ export const CLIENT_ERROR_TAG_KEYS: ReadonlySet<string> = new Set([
27
+ "front",
28
+ "surface",
29
+ ])
30
+
31
+ export const CLIENT_ERROR_CONTEXT_KEYS: ReadonlySet<string> = new Set([
32
+ "pathname",
33
+ "status",
34
+ "surface",
35
+ ])
36
+
37
+ export function withKeys(
38
+ base: ReadonlySet<string>,
39
+ extra: Iterable<string> = []
40
+ ): ReadonlySet<string> {
41
+ return new Set([...base, ...extra])
42
+ }
@@ -0,0 +1,111 @@
1
+ import { describe, expect, it } from "bun:test"
2
+ import {
3
+ anonymizeEvent,
4
+ anonymizePath,
5
+ anonymizeReferrer,
6
+ anonymizeText,
7
+ anonymizeUrl,
8
+ createAnonymousSessionId,
9
+ type TAnonymizableEvent,
10
+ } from "./anonymize"
11
+
12
+ describe("anonymizePath", () => {
13
+ it("templates identifier segments and keeps route words", () => {
14
+ expect(
15
+ anonymizePath(
16
+ "/dashboard/clients/cm1x2y3z4a5b6c7d8e9f0g1h/invoices/42/edit"
17
+ )
18
+ ).toBe("/dashboard/clients/:id/invoices/:id/edit")
19
+ expect(anonymizePath("/s/3f2b8c1e-9a4d-4e5f-8b6a-1c2d3e4f5a6b")).toBe(
20
+ "/s/:id"
21
+ )
22
+ expect(anonymizePath("/fr/legal/privacy")).toBe("/fr/legal/privacy")
23
+ })
24
+
25
+ it("hides an e-mail used as a segment", () => {
26
+ expect(anonymizePath("/u/jane.doe%40example.com")).toBe("/u/:id")
27
+ })
28
+ })
29
+
30
+ describe("anonymizeUrl", () => {
31
+ it("drops the query string and fragment", () => {
32
+ expect(
33
+ anonymizeUrl("https://www.example.com/dashboard/vault/123?q=jane#x")
34
+ ).toBe("https://www.example.com/dashboard/vault/:id")
35
+ })
36
+
37
+ it("keeps bundle paths intact for source maps", () => {
38
+ expect(
39
+ anonymizeUrl(
40
+ "https://www.example.com/_app/assets/index-a1b2c3d4e5f6g7h8.js"
41
+ )
42
+ ).toBe("https://www.example.com/_app/assets/index-a1b2c3d4e5f6g7h8.js")
43
+ })
44
+ })
45
+
46
+ describe("anonymizeReferrer", () => {
47
+ it("keeps the host only", () => {
48
+ expect(anonymizeReferrer("https://www.google.com/search?q=jane")).toBe(
49
+ "www.google.com"
50
+ )
51
+ expect(anonymizeReferrer("")).toBeNull()
52
+ })
53
+ })
54
+
55
+ describe("anonymizeText", () => {
56
+ it("masks personal data inside free text", () => {
57
+ expect(
58
+ anonymizeText(
59
+ "Failed for jane@example.com IBAN MA64011519000001205000534921 tel +212 6 14 28 58 00 order 1234567"
60
+ )
61
+ ).toBe("Failed for [email] IBAN [iban] tel [phone] order [number]")
62
+ })
63
+ })
64
+
65
+ describe("anonymizeEvent", () => {
66
+ it("keeps only allowed tags, an anonymous session and no request details", () => {
67
+ const event = anonymizeEvent(
68
+ {
69
+ breadcrumbs: [
70
+ { category: "ui.click", message: "button Jane" },
71
+ { category: "session", message: "bootstrap.session.absent" },
72
+ ],
73
+ contexts: { device: { id: "abc", model: "iPhone16,1" }, cloud: {} },
74
+ exception: { values: [{ value: "No user jane@example.com" }] },
75
+ extra: { fileName: "salaire-jane.pdf", route: "/v1/invoices/:id" },
76
+ request: {
77
+ headers: { cookie: "x" },
78
+ query_string: "q=1",
79
+ url: "https://www.example.com/dashboard/clients/123",
80
+ },
81
+ server_name: "edge",
82
+ tags: { organization_id: "org_1", surface: "api" },
83
+ user: { email: "jane@example.com", id: "user_1" },
84
+ },
85
+ {
86
+ allowedContextKeys: new Set(["route"]),
87
+ allowedTagKeys: new Set(["surface"]),
88
+ keptBreadcrumbCategories: new Set(["session"]),
89
+ sessionId: "s1",
90
+ }
91
+ )
92
+
93
+ expect(event as TAnonymizableEvent).toEqual({
94
+ breadcrumbs: [
95
+ { category: "session", message: "bootstrap.session.absent" },
96
+ ],
97
+ contexts: { device: { model: "iPhone16,1" } },
98
+ exception: { values: [{ value: "No user [email]" }] },
99
+ extra: { route: "/v1/invoices/:id" },
100
+ request: { url: "https://www.example.com/dashboard/clients/:id" },
101
+ tags: { surface: "api" },
102
+ user: { id: "s1" },
103
+ })
104
+ })
105
+ })
106
+
107
+ describe("createAnonymousSessionId", () => {
108
+ it("is random", () => {
109
+ expect(createAnonymousSessionId()).not.toBe(createAnonymousSessionId())
110
+ })
111
+ })
@@ -0,0 +1,249 @@
1
+ const ID_SEGMENT_PLACEHOLDER = ":id"
2
+
3
+ const UUID_RE = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi
4
+ const CUID_RE = /\bc[a-z0-9]{20,}\b/g
5
+ const EMAIL_RE = /[\w.%+-]+@[\w.-]+\.[a-z]{2,}/gi
6
+ const IBAN_RE = /\b[A-Z]{2}\d{2}(?:\s?[A-Z0-9]){10,30}\b/g
7
+ const PHONE_RE = /(?:\+|\b00)\d[\d\s.-]{7,}\d|\b0[5-7](?:[\s.-]?\d{2}){4}\b/g
8
+ const LONG_NUMBER_RE = /\b\d{6,}\b/g
9
+ const URL_RE = /\bhttps?:\/\/[^\s"'<>)]+/gi
10
+
11
+ const NUMERIC_SEGMENT_RE = /^\d+$/
12
+ const OPAQUE_SEGMENT_RE = /^(?=.*\d)(?=.*[a-z])[\w-]{16,}$/i
13
+ const UUID_SEGMENT_RE = new RegExp(`^${UUID_RE.source}$`, "i")
14
+ const CUID_SEGMENT_RE = /^c[a-z0-9]{20,}$/
15
+
16
+ // Stack frames point at our own bundles: their paths must stay readable for source maps.
17
+ const ASSET_PATH_RE = /\.(?:m?js|map|css)$/
18
+
19
+ export const ANONYMOUS_SESSION_ID_LENGTH = 16
20
+
21
+ function isIdentifierSegment(segment: string): boolean {
22
+ if (segment === "") {
23
+ return false
24
+ }
25
+
26
+ const decoded = safeDecode(segment)
27
+
28
+ return (
29
+ NUMERIC_SEGMENT_RE.test(decoded) ||
30
+ UUID_SEGMENT_RE.test(decoded) ||
31
+ CUID_SEGMENT_RE.test(decoded) ||
32
+ decoded.includes("@") ||
33
+ OPAQUE_SEGMENT_RE.test(decoded)
34
+ )
35
+ }
36
+
37
+ function safeDecode(segment: string): string {
38
+ try {
39
+ return decodeURIComponent(segment)
40
+ } catch {
41
+ return segment
42
+ }
43
+ }
44
+
45
+ export function anonymizePath(pathname: string): string {
46
+ return pathname
47
+ .split("/")
48
+ .map((segment) =>
49
+ isIdentifierSegment(segment) ? ID_SEGMENT_PLACEHOLDER : segment
50
+ )
51
+ .join("/")
52
+ }
53
+
54
+ export function anonymizeUrl(raw: string): string {
55
+ try {
56
+ const url = new URL(raw, "https://placeholder.invalid")
57
+ const path = ASSET_PATH_RE.test(url.pathname)
58
+ ? url.pathname
59
+ : anonymizePath(url.pathname)
60
+
61
+ if (url.origin === "https://placeholder.invalid") {
62
+ return path
63
+ }
64
+
65
+ return `${url.origin}${path}`
66
+ } catch {
67
+ return "[url]"
68
+ }
69
+ }
70
+
71
+ export function anonymizeReferrer(
72
+ raw: string | null | undefined
73
+ ): string | null {
74
+ if (!raw) {
75
+ return null
76
+ }
77
+
78
+ try {
79
+ return new URL(raw).hostname || null
80
+ } catch {
81
+ return null
82
+ }
83
+ }
84
+
85
+ export function anonymizeText(text: string): string {
86
+ return text
87
+ .replace(URL_RE, (url) => anonymizeUrl(url))
88
+ .replace(EMAIL_RE, "[email]")
89
+ .replace(UUID_RE, "[id]")
90
+ .replace(CUID_RE, "[id]")
91
+ .replace(IBAN_RE, "[iban]")
92
+ .replace(PHONE_RE, "[phone]")
93
+ .replace(LONG_NUMBER_RE, "[number]")
94
+ }
95
+
96
+ export function pickAnonymousContext(
97
+ context: Record<string, unknown> | undefined,
98
+ allowedKeys: ReadonlySet<string>
99
+ ): Record<string, string | number | boolean> {
100
+ const picked: Record<string, string | number | boolean> = {}
101
+
102
+ for (const [key, value] of Object.entries(context ?? {})) {
103
+ if (!allowedKeys.has(key)) {
104
+ continue
105
+ }
106
+
107
+ if (typeof value === "string") {
108
+ picked[key] = anonymizeText(value)
109
+ } else if (typeof value === "number" || typeof value === "boolean") {
110
+ picked[key] = value
111
+ }
112
+ }
113
+
114
+ return picked
115
+ }
116
+
117
+ // Random and held in memory only: it counts the sessions an error hits without identifying any.
118
+ export function createAnonymousSessionId(): string {
119
+ return crypto
120
+ .randomUUID()
121
+ .replaceAll("-", "")
122
+ .slice(0, ANONYMOUS_SESSION_ID_LENGTH)
123
+ }
124
+
125
+ interface TAnonymizableException {
126
+ mechanism?: unknown
127
+ stacktrace?: unknown
128
+ type?: string
129
+ value?: string
130
+ }
131
+
132
+ interface TAnonymizableBreadcrumb {
133
+ category?: string
134
+ message?: string
135
+ data?: unknown
136
+ }
137
+
138
+ export interface TAnonymizableEvent {
139
+ breadcrumbs?: TAnonymizableBreadcrumb[]
140
+ contexts?: Record<string, unknown>
141
+ exception?: { values?: TAnonymizableException[] }
142
+ extra?: Record<string, unknown>
143
+ message?: string
144
+ request?: {
145
+ cookies?: unknown
146
+ data?: unknown
147
+ env?: unknown
148
+ headers?: unknown
149
+ query_string?: unknown
150
+ url?: string
151
+ }
152
+ server_name?: string
153
+ tags?: Record<string, unknown>
154
+ transaction?: string
155
+ user?: Record<string, unknown>
156
+ }
157
+
158
+ export interface TAnonymizeEventOptions {
159
+ allowedContextKeys: ReadonlySet<string>
160
+ allowedTagKeys: ReadonlySet<string>
161
+ keptBreadcrumbCategories?: ReadonlySet<string>
162
+ sessionId: string | null
163
+ }
164
+
165
+ const KEPT_CONTEXT_NAMES = new Set([
166
+ "app",
167
+ "browser",
168
+ "device",
169
+ "expo_updates",
170
+ "os",
171
+ "runtime",
172
+ ])
173
+ const DEVICE_IDENTIFYING_KEYS = new Set([
174
+ "id",
175
+ "name",
176
+ "device_unique_identifier",
177
+ ])
178
+
179
+ function anonymizeContexts(
180
+ contexts: Record<string, unknown> | undefined
181
+ ): Record<string, unknown> | undefined {
182
+ if (!contexts) {
183
+ return
184
+ }
185
+
186
+ const kept: Record<string, unknown> = {}
187
+
188
+ for (const [name, value] of Object.entries(contexts)) {
189
+ if (!KEPT_CONTEXT_NAMES.has(name) || typeof value !== "object" || !value) {
190
+ continue
191
+ }
192
+
193
+ const copy = Object.entries(value as Record<string, unknown>)
194
+
195
+ kept[name] =
196
+ name === "device"
197
+ ? Object.fromEntries(
198
+ copy.filter(([key]) => !DEVICE_IDENTIFYING_KEYS.has(key))
199
+ )
200
+ : Object.fromEntries(copy)
201
+ }
202
+
203
+ return kept
204
+ }
205
+
206
+ export function anonymizeEvent<TEvent extends TAnonymizableEvent>(
207
+ event: TEvent,
208
+ options: TAnonymizeEventOptions
209
+ ): TEvent {
210
+ if (event.message) {
211
+ event.message = anonymizeText(event.message)
212
+ }
213
+
214
+ for (const exception of event.exception?.values ?? []) {
215
+ if (exception.value) {
216
+ exception.value = anonymizeText(exception.value)
217
+ }
218
+ }
219
+
220
+ if (event.transaction) {
221
+ event.transaction = anonymizeText(event.transaction)
222
+ }
223
+
224
+ if (event.request) {
225
+ event.request = event.request.url
226
+ ? { url: anonymizeUrl(event.request.url) }
227
+ : {}
228
+ }
229
+
230
+ event.user = options.sessionId ? { id: options.sessionId } : {}
231
+ event.tags = pickAnonymousContext(event.tags, options.allowedTagKeys)
232
+ event.extra = pickAnonymousContext(event.extra, options.allowedContextKeys)
233
+ event.contexts = anonymizeContexts(event.contexts)
234
+
235
+ const keptCategories = options.keptBreadcrumbCategories
236
+
237
+ event.breadcrumbs = keptCategories
238
+ ? (event.breadcrumbs ?? [])
239
+ .filter((crumb) => crumb.category && keptCategories.has(crumb.category))
240
+ .map((crumb) => ({
241
+ category: crumb.category,
242
+ ...(crumb.message ? { message: anonymizeText(crumb.message) } : {}),
243
+ }))
244
+ : []
245
+
246
+ event.server_name = undefined
247
+
248
+ return event
249
+ }
@@ -0,0 +1,46 @@
1
+ import { describe, expect, test } from "bun:test"
2
+ import type { TAnonymizableEvent } from "./anonymize"
3
+ import { browserErrorOptions } from "./browser"
4
+
5
+ const DSN = "https://public@o1.ingest.de.sentry.io/2"
6
+
7
+ describe("browserErrorOptions", () => {
8
+ test("sends through the same-origin tunnel with an anonymous session", () => {
9
+ const options = browserErrorOptions({ dsn: DSN, front: "web" })
10
+
11
+ expect(options.tunnel).toBe("/api/telemetry/errors")
12
+ expect(options.initialScope.tags).toEqual({ front: "web" })
13
+ expect(options.initialScope.user.id).toMatch(/^[0-9a-f]{16}$/)
14
+ })
15
+
16
+ test("drops API refusals, benign browser noise and discarded errors", () => {
17
+ const options = browserErrorOptions({
18
+ dsn: DSN,
19
+ front: "admin",
20
+ isDiscarded: (hint) => hint.originalException === "stale",
21
+ })
22
+
23
+ expect(
24
+ options.beforeSend({}, { originalException: { status: 403 } })
25
+ ).toBeNull()
26
+ expect(
27
+ options.beforeSend({ message: "ResizeObserver loop completed" }, {})
28
+ ).toBeNull()
29
+ expect(options.beforeSend({}, { originalException: "stale" })).toBeNull()
30
+ })
31
+
32
+ test("anonymizes what it keeps", () => {
33
+ const options = browserErrorOptions({ dsn: DSN, front: "admin" })
34
+ const raw: TAnonymizableEvent = {
35
+ extra: { pathname: "/clients/123", token: "secret" },
36
+ message: "Cannot load jane@example.com",
37
+ tags: { front: "admin", user_email: "jane@example.com" },
38
+ }
39
+ const event = options.beforeSend(raw, {})
40
+
41
+ expect(event?.message).toBe("Cannot load [email]")
42
+ expect(event?.extra).toEqual({ pathname: "/clients/:id" })
43
+ expect(event?.tags).toEqual({ front: "admin" })
44
+ expect(event?.user).toEqual({ id: options.initialScope.user.id })
45
+ })
46
+ })