@aurabase/aurabase-js 0.3.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 (344) hide show
  1. package/.changeset/config.json +11 -0
  2. package/CHANGELOG.md +30 -0
  3. package/LICENSE +21 -0
  4. package/README.md +833 -0
  5. package/package.json +90 -0
  6. package/packages/ai/LICENSE +21 -0
  7. package/packages/ai/README.md +106 -0
  8. package/packages/ai/dist/index.cjs +229 -0
  9. package/packages/ai/dist/index.d.cts +139 -0
  10. package/packages/ai/dist/index.d.ts +139 -0
  11. package/packages/ai/dist/index.js +226 -0
  12. package/packages/ai/node_modules/.bin/esbuild +19 -0
  13. package/packages/ai/node_modules/.bin/tsc +22 -0
  14. package/packages/ai/node_modules/.bin/tsserver +22 -0
  15. package/packages/ai/node_modules/.bin/tsup +22 -0
  16. package/packages/ai/node_modules/.bin/tsup-node +22 -0
  17. package/packages/ai/node_modules/.bin/vite +22 -0
  18. package/packages/ai/node_modules/.bin/vitest +22 -0
  19. package/packages/ai/node_modules/.vite/vitest/da39a3ee5e6b4b0d3255bfef95601890afd80709/results.json +1 -0
  20. package/packages/ai/package.json +61 -0
  21. package/packages/ai/src/AiService.ts +226 -0
  22. package/packages/ai/src/index.ts +18 -0
  23. package/packages/ai/src/sse.ts +141 -0
  24. package/packages/ai/src/types.ts +30 -0
  25. package/packages/ai/tests/chat-stream.test.ts +151 -0
  26. package/packages/ai/tests/rag-namespaces.test.ts +54 -0
  27. package/packages/ai/tests/sse.test.ts +69 -0
  28. package/packages/ai/tsconfig.json +5 -0
  29. package/packages/ai/tsup.config.ts +11 -0
  30. package/packages/aurabase/LICENSE +21 -0
  31. package/packages/aurabase/README.md +64 -0
  32. package/packages/aurabase/dist/AuraClient-DAtDbfPB.d.cts +77 -0
  33. package/packages/aurabase/dist/AuraClient-DAtDbfPB.d.ts +77 -0
  34. package/packages/aurabase/dist/index.cjs +237 -0
  35. package/packages/aurabase/dist/index.d.cts +46 -0
  36. package/packages/aurabase/dist/index.d.ts +46 -0
  37. package/packages/aurabase/dist/index.js +177 -0
  38. package/packages/aurabase/dist/ssr.cjs +224 -0
  39. package/packages/aurabase/dist/ssr.d.cts +65 -0
  40. package/packages/aurabase/dist/ssr.d.ts +65 -0
  41. package/packages/aurabase/dist/ssr.js +214 -0
  42. package/packages/aurabase/node_modules/.bin/esbuild +19 -0
  43. package/packages/aurabase/node_modules/.bin/tsc +22 -0
  44. package/packages/aurabase/node_modules/.bin/tsserver +22 -0
  45. package/packages/aurabase/node_modules/.bin/tsup +22 -0
  46. package/packages/aurabase/node_modules/.bin/tsup-node +22 -0
  47. package/packages/aurabase/node_modules/.bin/vite +22 -0
  48. package/packages/aurabase/node_modules/.bin/vitest +22 -0
  49. package/packages/aurabase/node_modules/.vite/vitest/da39a3ee5e6b4b0d3255bfef95601890afd80709/results.json +1 -0
  50. package/packages/aurabase/package.json +80 -0
  51. package/packages/aurabase/src/AuraClient.ts +237 -0
  52. package/packages/aurabase/src/index.ts +152 -0
  53. package/packages/aurabase/src/ssr.ts +156 -0
  54. package/packages/aurabase/tests/ai-streaming-rag-e2e.test.ts +82 -0
  55. package/packages/aurabase/tests/ai.test.ts +111 -0
  56. package/packages/aurabase/tests/auth-admin.test.ts +515 -0
  57. package/packages/aurabase/tests/auth-e2e.test.ts +135 -0
  58. package/packages/aurabase/tests/auth-hardening.test.ts +206 -0
  59. package/packages/aurabase/tests/auth.test.ts +947 -0
  60. package/packages/aurabase/tests/database.test.ts +230 -0
  61. package/packages/aurabase/tests/db-types-e2e.test.ts +217 -0
  62. package/packages/aurabase/tests/dispose.test.ts +23 -0
  63. package/packages/aurabase/tests/foreign-token.e2e.test.ts +129 -0
  64. package/packages/aurabase/tests/functions.test.ts +107 -0
  65. package/packages/aurabase/tests/integration.test.ts +413 -0
  66. package/packages/aurabase/tests/live-production-validation.js +241 -0
  67. package/packages/aurabase/tests/live-sdk-production-validation.js +293 -0
  68. package/packages/aurabase/tests/mocks.ts +139 -0
  69. package/packages/aurabase/tests/notifications.test.ts +314 -0
  70. package/packages/aurabase/tests/observability-backup.test.ts +186 -0
  71. package/packages/aurabase/tests/observability-hook.test.ts +130 -0
  72. package/packages/aurabase/tests/production-robustness.test.ts +268 -0
  73. package/packages/aurabase/tests/public-api-surface.test.ts +53 -0
  74. package/packages/aurabase/tests/query-builder.test.ts +329 -0
  75. package/packages/aurabase/tests/readme-smoke-e2e.test.ts +231 -0
  76. package/packages/aurabase/tests/realtime-filter-e2e.test.ts +344 -0
  77. package/packages/aurabase/tests/refresh-locks.test.ts +210 -0
  78. package/packages/aurabase/tests/retry-option.test.ts +17 -0
  79. package/packages/aurabase/tests/rpc-e2e.test.ts +254 -0
  80. package/packages/aurabase/tests/rs256-local-e2e.test.ts +114 -0
  81. package/packages/aurabase/tests/rt-alias-public-e2e.test.ts +235 -0
  82. package/packages/aurabase/tests/rt-http-broadcast-e2e.test.ts +124 -0
  83. package/packages/aurabase/tests/service-role-guard.test.ts +99 -0
  84. package/packages/aurabase/tests/ssr.test.ts +91 -0
  85. package/packages/aurabase/tests/storage-backend-e2e.test.ts +481 -0
  86. package/packages/aurabase/tests/storage-sdk-parity-e2e.test.ts +104 -0
  87. package/packages/aurabase/tests/storage-transform-e2e.test.ts +684 -0
  88. package/packages/aurabase/tests/storage.test.ts +55 -0
  89. package/packages/aurabase/tests/types/client-generic.test-d.ts +79 -0
  90. package/packages/aurabase/tests/types/docs-snippets.test-d.ts +571 -0
  91. package/packages/aurabase/tests/types/error-code.test-d.ts +53 -0
  92. package/packages/aurabase/tsconfig.json +5 -0
  93. package/packages/aurabase/tsconfig.test-d.json +5 -0
  94. package/packages/aurabase/tsup.config.ts +11 -0
  95. package/packages/aurabase/vitest.config.ts +16 -0
  96. package/packages/aurabase/vitest.e2e.config.ts +9 -0
  97. package/packages/auth/LICENSE +21 -0
  98. package/packages/auth/README.md +215 -0
  99. package/packages/auth/dist/index.cjs +1175 -0
  100. package/packages/auth/dist/index.d.cts +397 -0
  101. package/packages/auth/dist/index.d.ts +397 -0
  102. package/packages/auth/dist/index.js +1170 -0
  103. package/packages/auth/node_modules/.bin/esbuild +19 -0
  104. package/packages/auth/node_modules/.bin/tsc +22 -0
  105. package/packages/auth/node_modules/.bin/tsserver +22 -0
  106. package/packages/auth/node_modules/.bin/tsup +22 -0
  107. package/packages/auth/node_modules/.bin/tsup-node +22 -0
  108. package/packages/auth/node_modules/.bin/vite +22 -0
  109. package/packages/auth/node_modules/.bin/vitest +22 -0
  110. package/packages/auth/node_modules/.vite/vitest/da39a3ee5e6b4b0d3255bfef95601890afd80709/results.json +1 -0
  111. package/packages/auth/package.json +61 -0
  112. package/packages/auth/src/AuthAdminService.ts +149 -0
  113. package/packages/auth/src/AuthService.ts +1166 -0
  114. package/packages/auth/src/SessionManager.ts +92 -0
  115. package/packages/auth/src/index.ts +17 -0
  116. package/packages/auth/src/jwks.ts +337 -0
  117. package/packages/auth/src/pkce.ts +27 -0
  118. package/packages/auth/src/types.ts +89 -0
  119. package/packages/auth/tests/auth-lifecycle.test.ts +149 -0
  120. package/packages/auth/tests/detect-session.test.ts +361 -0
  121. package/packages/auth/tests/getclaims.test.ts +780 -0
  122. package/packages/auth/tests/is-mfa-challenge.test.ts +27 -0
  123. package/packages/auth/tests/password-recovery.test.ts +124 -0
  124. package/packages/auth/tests/pkce.test.ts +192 -0
  125. package/packages/auth/tests/session-manager.test.ts +103 -0
  126. package/packages/auth/tests/set-session.test.ts +139 -0
  127. package/packages/auth/tests/verify-otp.test.ts +153 -0
  128. package/packages/auth/tsconfig.json +5 -0
  129. package/packages/auth/tsup.config.ts +11 -0
  130. package/packages/core/LICENSE +21 -0
  131. package/packages/core/README.md +132 -0
  132. package/packages/core/dist/index.cjs +695 -0
  133. package/packages/core/dist/index.d.cts +1137 -0
  134. package/packages/core/dist/index.d.ts +1137 -0
  135. package/packages/core/dist/index.js +673 -0
  136. package/packages/core/node_modules/.bin/esbuild +22 -0
  137. package/packages/core/node_modules/.bin/tsc +22 -0
  138. package/packages/core/node_modules/.bin/tsserver +22 -0
  139. package/packages/core/node_modules/.bin/tsup +22 -0
  140. package/packages/core/node_modules/.bin/tsup-node +22 -0
  141. package/packages/core/node_modules/.bin/vite +22 -0
  142. package/packages/core/node_modules/.bin/vitest +22 -0
  143. package/packages/core/node_modules/.vite/vitest/da39a3ee5e6b4b0d3255bfef95601890afd80709/results.json +1 -0
  144. package/packages/core/package.json +57 -0
  145. package/packages/core/src/AuraError.ts +89 -0
  146. package/packages/core/src/BaseService.ts +44 -0
  147. package/packages/core/src/client.ts +34 -0
  148. package/packages/core/src/cookie-utils.ts +42 -0
  149. package/packages/core/src/fetch.ts +435 -0
  150. package/packages/core/src/index.ts +22 -0
  151. package/packages/core/src/retry.ts +63 -0
  152. package/packages/core/src/serialize.ts +6 -0
  153. package/packages/core/src/stores/BaseAuthStore.ts +164 -0
  154. package/packages/core/src/stores/LocalAuthStore.ts +199 -0
  155. package/packages/core/src/types.ts +1042 -0
  156. package/packages/core/tests/auth-store.test.ts +300 -0
  157. package/packages/core/tests/error-code.test.ts +61 -0
  158. package/packages/core/tests/error.test.ts +24 -0
  159. package/packages/core/tests/fetch.test.ts +286 -0
  160. package/packages/core/tests/mocks.ts +139 -0
  161. package/packages/core/tests/observability.test.ts +86 -0
  162. package/packages/core/tests/refresh-hardening.test.ts +164 -0
  163. package/packages/core/tests/refresh-observability.test.ts +111 -0
  164. package/packages/core/tests/retry.test.ts +106 -0
  165. package/packages/core/tests/serialize.test.ts +12 -0
  166. package/packages/core/tests/timeout.test.ts +79 -0
  167. package/packages/core/tsconfig.json +5 -0
  168. package/packages/core/tsup.config.ts +11 -0
  169. package/packages/db/LICENSE +21 -0
  170. package/packages/db/README.md +152 -0
  171. package/packages/db/VENDORED.md +93 -0
  172. package/packages/db/dist/index.cjs +544 -0
  173. package/packages/db/dist/index.d.cts +1111 -0
  174. package/packages/db/dist/index.d.ts +1111 -0
  175. package/packages/db/dist/index.js +541 -0
  176. package/packages/db/node_modules/.bin/esbuild +19 -0
  177. package/packages/db/node_modules/.bin/tsc +22 -0
  178. package/packages/db/node_modules/.bin/tsserver +22 -0
  179. package/packages/db/node_modules/.bin/tsup +22 -0
  180. package/packages/db/node_modules/.bin/tsup-node +22 -0
  181. package/packages/db/node_modules/.bin/vite +22 -0
  182. package/packages/db/node_modules/.bin/vitest +22 -0
  183. package/packages/db/node_modules/.vite/vitest/da39a3ee5e6b4b0d3255bfef95601890afd80709/results.json +1 -0
  184. package/packages/db/package.json +62 -0
  185. package/packages/db/src/DatabaseService.ts +170 -0
  186. package/packages/db/src/QueryBuilder.ts +830 -0
  187. package/packages/db/src/index.ts +2 -0
  188. package/packages/db/src/pgrst-types/common/common.ts +86 -0
  189. package/packages/db/src/pgrst-types/common/rpc.ts +151 -0
  190. package/packages/db/src/pgrst-types/feature-flags.ts +20 -0
  191. package/packages/db/src/pgrst-types/types.ts +134 -0
  192. package/packages/db/src/select-query-parser/parser.ts +479 -0
  193. package/packages/db/src/select-query-parser/result.ts +553 -0
  194. package/packages/db/src/select-query-parser/types.ts +132 -0
  195. package/packages/db/src/select-query-parser/utils.ts +707 -0
  196. package/packages/db/tests/filters.test.ts +81 -0
  197. package/packages/db/tests/mutations-filtered.e2e.test.ts +132 -0
  198. package/packages/db/tests/mutations-filtered.test.ts +188 -0
  199. package/packages/db/tests/order.test.ts +45 -0
  200. package/packages/db/tests/rpc.test.ts +41 -0
  201. package/packages/db/tests/scale/build-large-schema.ts +94 -0
  202. package/packages/db/tests/scale/scale-compile.test.ts +167 -0
  203. package/packages/db/tests/schema.test.ts +77 -0
  204. package/packages/db/tests/single-accept.e2e.test.ts +123 -0
  205. package/packages/db/tests/single.test.ts +211 -0
  206. package/packages/db/tests/types/filters.test-d.ts +52 -0
  207. package/packages/db/tests/types/fixtures.ts +40 -0
  208. package/packages/db/tests/types/from-views.test-d.ts +18 -0
  209. package/packages/db/tests/types/mutations.test-d.ts +23 -0
  210. package/packages/db/tests/types/rpc.test-d.ts +60 -0
  211. package/packages/db/tests/types/schema-shape.test-d.ts +8 -0
  212. package/packages/db/tests/types/select-inference.test-d.ts +38 -0
  213. package/packages/db/tests/vendored/fixtures.ts +83 -0
  214. package/packages/db/tests/vendored/get-result.test-d.ts +75 -0
  215. package/packages/db/tsconfig.json +5 -0
  216. package/packages/db/tsconfig.test-d.json +5 -0
  217. package/packages/db/tsup.config.ts +11 -0
  218. package/packages/db/vitest.config.ts +8 -0
  219. package/packages/functions/LICENSE +21 -0
  220. package/packages/functions/README.md +96 -0
  221. package/packages/functions/dist/index.cjs +173 -0
  222. package/packages/functions/dist/index.d.cts +81 -0
  223. package/packages/functions/dist/index.d.ts +81 -0
  224. package/packages/functions/dist/index.js +168 -0
  225. package/packages/functions/node_modules/.bin/esbuild +19 -0
  226. package/packages/functions/node_modules/.bin/tsc +22 -0
  227. package/packages/functions/node_modules/.bin/tsserver +22 -0
  228. package/packages/functions/node_modules/.bin/tsup +22 -0
  229. package/packages/functions/node_modules/.bin/tsup-node +22 -0
  230. package/packages/functions/node_modules/.bin/vite +22 -0
  231. package/packages/functions/node_modules/.bin/vitest +22 -0
  232. package/packages/functions/node_modules/.vite/vitest/da39a3ee5e6b4b0d3255bfef95601890afd80709/results.json +1 -0
  233. package/packages/functions/package.json +60 -0
  234. package/packages/functions/src/FunctionsService.ts +188 -0
  235. package/packages/functions/src/errors.ts +70 -0
  236. package/packages/functions/src/index.ts +6 -0
  237. package/packages/functions/tests/invoke.test.ts +97 -0
  238. package/packages/functions/tests/response-type-errors.test.ts +135 -0
  239. package/packages/functions/tsconfig.json +5 -0
  240. package/packages/functions/tsup.config.ts +11 -0
  241. package/packages/gen/LICENSE +21 -0
  242. package/packages/gen/README.md +84 -0
  243. package/packages/gen/dist/cli.cjs +334 -0
  244. package/packages/gen/dist/cli.d.cts +1 -0
  245. package/packages/gen/dist/cli.d.ts +1 -0
  246. package/packages/gen/dist/cli.js +332 -0
  247. package/packages/gen/dist/index.cjs +257 -0
  248. package/packages/gen/dist/index.d.cts +12 -0
  249. package/packages/gen/dist/index.d.ts +12 -0
  250. package/packages/gen/dist/index.js +255 -0
  251. package/packages/gen/node_modules/.bin/esbuild +19 -0
  252. package/packages/gen/node_modules/.bin/tsc +22 -0
  253. package/packages/gen/node_modules/.bin/tsserver +22 -0
  254. package/packages/gen/node_modules/.bin/tsup +22 -0
  255. package/packages/gen/node_modules/.bin/tsup-node +22 -0
  256. package/packages/gen/node_modules/.bin/vite +22 -0
  257. package/packages/gen/node_modules/.bin/vitest +22 -0
  258. package/packages/gen/node_modules/.vite/vitest/da39a3ee5e6b4b0d3255bfef95601890afd80709/results.json +1 -0
  259. package/packages/gen/package.json +66 -0
  260. package/packages/gen/src/cli.ts +67 -0
  261. package/packages/gen/src/generate.ts +0 -0
  262. package/packages/gen/src/index.ts +2 -0
  263. package/packages/gen/tests/compile.test.ts +213 -0
  264. package/packages/gen/tests/e2e.test.ts +130 -0
  265. package/packages/gen/tests/generate.test.ts +396 -0
  266. package/packages/gen/tsconfig.json +5 -0
  267. package/packages/gen/tsup.config.ts +11 -0
  268. package/packages/notifications/LICENSE +21 -0
  269. package/packages/notifications/README.md +134 -0
  270. package/packages/notifications/dist/index.cjs +128 -0
  271. package/packages/notifications/dist/index.d.cts +81 -0
  272. package/packages/notifications/dist/index.d.ts +81 -0
  273. package/packages/notifications/dist/index.js +125 -0
  274. package/packages/notifications/node_modules/.bin/esbuild +19 -0
  275. package/packages/notifications/node_modules/.bin/tsc +22 -0
  276. package/packages/notifications/node_modules/.bin/tsserver +22 -0
  277. package/packages/notifications/node_modules/.bin/tsup +22 -0
  278. package/packages/notifications/node_modules/.bin/tsup-node +22 -0
  279. package/packages/notifications/node_modules/.bin/vite +22 -0
  280. package/packages/notifications/node_modules/.bin/vitest +22 -0
  281. package/packages/notifications/package.json +60 -0
  282. package/packages/notifications/src/NotificationsService.ts +230 -0
  283. package/packages/notifications/src/index.ts +19 -0
  284. package/packages/notifications/tsconfig.json +5 -0
  285. package/packages/notifications/tsup.config.ts +11 -0
  286. package/packages/realtime/LICENSE +21 -0
  287. package/packages/realtime/README.md +183 -0
  288. package/packages/realtime/dist/index.cjs +977 -0
  289. package/packages/realtime/dist/index.d.cts +259 -0
  290. package/packages/realtime/dist/index.d.ts +259 -0
  291. package/packages/realtime/dist/index.js +973 -0
  292. package/packages/realtime/node_modules/.bin/esbuild +19 -0
  293. package/packages/realtime/node_modules/.bin/tsc +22 -0
  294. package/packages/realtime/node_modules/.bin/tsserver +22 -0
  295. package/packages/realtime/node_modules/.bin/tsup +22 -0
  296. package/packages/realtime/node_modules/.bin/tsup-node +22 -0
  297. package/packages/realtime/node_modules/.bin/vite +22 -0
  298. package/packages/realtime/node_modules/.bin/vitest +22 -0
  299. package/packages/realtime/node_modules/.vite/vitest/da39a3ee5e6b4b0d3255bfef95601890afd80709/results.json +1 -0
  300. package/packages/realtime/package.json +60 -0
  301. package/packages/realtime/src/AuraChannel.ts +485 -0
  302. package/packages/realtime/src/HeartbeatManager.ts +73 -0
  303. package/packages/realtime/src/RealtimeService.ts +505 -0
  304. package/packages/realtime/src/columnFilter.ts +301 -0
  305. package/packages/realtime/src/index.ts +4 -0
  306. package/packages/realtime/tests/ack-routing.test.ts +81 -0
  307. package/packages/realtime/tests/column-filter.test.ts +144 -0
  308. package/packages/realtime/tests/dispatch.test.ts +191 -0
  309. package/packages/realtime/tests/heartbeat.test.ts +67 -0
  310. package/packages/realtime/tests/http-broadcast.test.ts +68 -0
  311. package/packages/realtime/tests/realtime-token.test.ts +43 -0
  312. package/packages/realtime/tests/reconnect-race.test.ts +149 -0
  313. package/packages/realtime/tests/ref-id.test.ts +34 -0
  314. package/packages/realtime/tests/set-auth.test.ts +70 -0
  315. package/packages/realtime/tsconfig.json +5 -0
  316. package/packages/realtime/tsup.config.ts +11 -0
  317. package/packages/storage/LICENSE +21 -0
  318. package/packages/storage/README.md +141 -0
  319. package/packages/storage/dist/index.cjs +333 -0
  320. package/packages/storage/dist/index.d.cts +185 -0
  321. package/packages/storage/dist/index.d.ts +185 -0
  322. package/packages/storage/dist/index.js +329 -0
  323. package/packages/storage/node_modules/.bin/esbuild +19 -0
  324. package/packages/storage/node_modules/.bin/tsc +22 -0
  325. package/packages/storage/node_modules/.bin/tsserver +22 -0
  326. package/packages/storage/node_modules/.bin/tsup +22 -0
  327. package/packages/storage/node_modules/.bin/tsup-node +22 -0
  328. package/packages/storage/node_modules/.bin/vite +22 -0
  329. package/packages/storage/node_modules/.bin/vitest +22 -0
  330. package/packages/storage/node_modules/.vite/vitest/da39a3ee5e6b4b0d3255bfef95601890afd80709/results.json +1 -0
  331. package/packages/storage/package.json +60 -0
  332. package/packages/storage/src/DownloadBuilder.ts +60 -0
  333. package/packages/storage/src/StorageService.ts +323 -0
  334. package/packages/storage/src/index.ts +2 -0
  335. package/packages/storage/src/path.ts +35 -0
  336. package/packages/storage/src/transform.ts +15 -0
  337. package/packages/storage/tests/download.test.ts +64 -0
  338. package/packages/storage/tests/parity.test.ts +154 -0
  339. package/packages/storage/tests/path.test.ts +87 -0
  340. package/packages/storage/tests/transform.test.ts +79 -0
  341. package/packages/storage/tsconfig.json +5 -0
  342. package/packages/storage/tsup.config.ts +11 -0
  343. package/pnpm-workspace.yaml +24 -0
  344. package/tsconfig.base.json +15 -0
@@ -0,0 +1,237 @@
1
+ import { BaseAuthStore, LocalAuthStore, DEFAULT_MAX_RETRIES } from '@aurabase/core'
2
+ import type { AuraClientLike, ChannelConfig, AuraClientOptions, AuraObservabilityEvent } from '@aurabase/core'
3
+ import { AuthService, AuthAdminService } from '@aurabase/auth'
4
+ import { DatabaseService } from '@aurabase/db'
5
+ import { StorageService } from '@aurabase/storage'
6
+ import { RealtimeService } from '@aurabase/realtime'
7
+ import type { AuraChannel } from '@aurabase/realtime'
8
+ import { FunctionsService } from '@aurabase/functions'
9
+ import { AiService } from '@aurabase/ai'
10
+ import { NotificationsService } from '@aurabase/notifications'
11
+
12
+ /**
13
+ * Détecte un contexte d'exécution CLIENT navigateur où une clé service_role ne doit
14
+ * jamais figurer : thread principal (`window`) ET Web Workers navigateur (dedicated/
15
+ * shared). On EXCLUT volontairement `ServiceWorkerGlobalScope` — utilisé par des
16
+ * runtimes SERVEUR/edge légitimes (Cloudflare Workers) où service_role est valide —
17
+ * pour éviter tout faux positif qui casserait un usage serveur légitime.
18
+ */
19
+ export function isBrowserContext(): boolean {
20
+ if (typeof window !== 'undefined') return true
21
+ const g = globalThis as Record<string, unknown>
22
+ if (typeof g.DedicatedWorkerGlobalScope !== 'undefined') return true
23
+ if (typeof g.SharedWorkerGlobalScope !== 'undefined') return true
24
+ return false
25
+ }
26
+
27
+ /** Préfixe des clés service_role (backend : `generate_api_key("service_role")`). */
28
+ const SERVICE_ROLE_KEY_PREFIX = 'aura_sk_'
29
+
30
+ /**
31
+ * Main Aurabase client.
32
+ *
33
+ * @example
34
+ * ```ts
35
+ * import { createClient } from 'aurabase'
36
+ * const aura = createClient('http://localhost:8080', 'my-project-id')
37
+ * const { data } = await aura.db.from('posts').eq('published', true)
38
+ * ```
39
+ */
40
+ export class AuraClient<Database = any> implements AuraClientLike {
41
+ readonly baseUrl: string
42
+ readonly projectId: string
43
+ readonly apiKey: string | null
44
+ readonly fetchFn: typeof globalThis.fetch
45
+ readonly authStore: BaseAuthStore
46
+ readonly retryConfig: { enabled: boolean; maxRetries: number }
47
+ /** Timeout par défaut (ms) des requêtes JSON sans signal. `undefined` → défaut core (30s). */
48
+ readonly requestTimeoutMs?: number
49
+ /** Hook d'observabilité (LOT 3) — voir `AuraClientOptions.onEvent`. */
50
+ readonly onEvent?: (event: AuraObservabilityEvent) => void
51
+ /** Journalise chaque `AuraObservabilityEvent` via `console.debug` — voir `AuraClientOptions.debug`. */
52
+ readonly debug?: boolean
53
+
54
+ // Lazy-initialised service instances
55
+ private _auth: AuthService | null = null
56
+ private _db: DatabaseService<Database> | null = null
57
+ private _storage: StorageService | null = null
58
+ private _realtime: RealtimeService | null = null
59
+ private _functions: FunctionsService | null = null
60
+ private _ai: AiService | null = null
61
+ private _notifications: NotificationsService | null = null
62
+ private _authAdmin: AuthAdminService | null = null
63
+ private _disposed = false
64
+ private readonly _persistSession: boolean
65
+ private readonly _autoRefresh: boolean
66
+ private readonly _detectSessionInUrl: boolean | undefined
67
+
68
+ constructor(
69
+ baseUrl: string,
70
+ projectId: string,
71
+ apiKeyOrOptions?: string | AuraClientOptions,
72
+ options?: AuraClientOptions,
73
+ ) {
74
+ // Normalise: strip trailing slash
75
+ this.baseUrl = baseUrl.replace(/\/+$/, '')
76
+ this.projectId = projectId
77
+
78
+ // Support both: createClient(url, pid, apiKey, opts?) or createClient(url, pid, opts?)
79
+ const resolvedOptions = typeof apiKeyOrOptions === 'string' ? options : apiKeyOrOptions
80
+ this.apiKey = typeof apiKeyOrOptions === 'string' ? apiKeyOrOptions : (apiKeyOrOptions?.apiKey ?? null)
81
+ this.fetchFn = resolvedOptions?.fetch ?? globalThis.fetch.bind(globalThis)
82
+
83
+ // Retry transitoire : activé par défaut, désactivable/ajustable via l'option `retry`.
84
+ const r = resolvedOptions?.retry
85
+ this.retryConfig =
86
+ r === false
87
+ ? { enabled: false, maxRetries: 0 }
88
+ : r === undefined || r === true
89
+ ? { enabled: true, maxRetries: DEFAULT_MAX_RETRIES }
90
+ : { enabled: r.enabled ?? true, maxRetries: r.maxRetries ?? DEFAULT_MAX_RETRIES }
91
+
92
+ // Timeout par défaut des requêtes (pass-through : undefined → défaut appliqué par le core).
93
+ this.requestTimeoutMs = resolvedOptions?.requestTimeoutMs
94
+
95
+ // Observabilité (LOT 3) : pass-through direct, consommé par fetchWithAuth/refreshOnce
96
+ // (core) et par AuthService (jwks-fetch-failed). `undefined` par défaut → aucune émission.
97
+ this.onEvent = resolvedOptions?.onEvent
98
+ this.debug = resolvedOptions?.debug
99
+
100
+ if (!this.apiKey && typeof console !== 'undefined') {
101
+ console.warn(
102
+ '[aurabase] No API key provided. Most operations require an API key (apikey header). ' +
103
+ 'Only public auth routes (register, login, refresh) will work without one.',
104
+ )
105
+ }
106
+
107
+ // SEC-F5 : une clé service_role (aura_sk_) embarquée côté client fuite dans le
108
+ // bundle JS = compromission totale du projet (BYPASSRLS). En contexte navigateur,
109
+ // on ÉCHOUE la construction par défaut (throw) — un simple warn se contourne/
110
+ // s'ignore. `refuseServiceRoleInBrowser: false` rétrograde en warn (échappatoire
111
+ // explicite). createAdminClient() couvre le cas serveur légitime.
112
+ if (this.apiKey?.startsWith(SERVICE_ROLE_KEY_PREFIX) && isBrowserContext()) {
113
+ const refuse = resolvedOptions?.refuseServiceRoleInBrowser ?? true
114
+ const message =
115
+ '[aurabase] SÉCURITÉ : une clé service_role (aura_sk_…) est fournie à createClient() ' +
116
+ 'dans un contexte navigateur. Cette clé à privilèges élevés NE DOIT JAMAIS être exposée ' +
117
+ 'côté client (elle fuiterait dans le bundle). Utilisez une clé anon (aura_anon_…) côté ' +
118
+ "client, et createAdminClient() côté serveur pour les opérations d'administration."
119
+ if (refuse) {
120
+ throw new Error(message)
121
+ } else if (typeof console !== 'undefined') {
122
+ console.warn(message)
123
+ }
124
+ }
125
+
126
+ // Auth store: use provided store, or LocalAuthStore in browser, or BaseAuthStore in Node
127
+ if (resolvedOptions?.auth?.storage) {
128
+ this.authStore = resolvedOptions.auth.storage
129
+ } else if (resolvedOptions?.auth?.persistSession === false) {
130
+ this.authStore = new BaseAuthStore()
131
+ } else if (typeof localStorage !== 'undefined') {
132
+ this.authStore = new LocalAuthStore()
133
+ } else {
134
+ this.authStore = new BaseAuthStore()
135
+ }
136
+ // Câble le hook d'observabilité sur le store (LOT 3) : `storage-blocked` est émis
137
+ // depuis les catch `localStorage` de `LocalAuthStore` (quota dépassé, navigation
138
+ // privée Safari, storage désactivé…). Câblé même si un store custom est fourni via
139
+ // `auth.storage` (méthode héritée de `BaseAuthStore`, no-op si jamais appelée).
140
+ this.authStore.setObservabilityHook(this.onEvent, this.debug)
141
+
142
+ this._persistSession = resolvedOptions?.auth?.persistSession !== false
143
+ this._autoRefresh = resolvedOptions?.auth?.autoRefresh ?? true
144
+ this._detectSessionInUrl = resolvedOptions?.auth?.detectSessionInUrl
145
+
146
+ // Démarre le refresh proactif sans attendre un accès à `aura.auth`.
147
+ if (this._autoRefresh && this._persistSession && typeof window !== 'undefined') {
148
+ void this.auth
149
+ }
150
+ }
151
+
152
+ /**
153
+ * Démonte le client : arrête le refresh proactif (ticker + visibilité + BroadcastChannel),
154
+ * déconnecte le realtime, vide les listeners d'auth. Idempotent. À appeler en teardown
155
+ * (React Strict Mode / HMR / tests).
156
+ */
157
+ dispose(): void {
158
+ if (this._disposed) return
159
+ this._disposed = true
160
+ this._auth?.dispose()
161
+ this._realtime?.disconnect()
162
+ }
163
+
164
+ // -- Lazy service getters ---------------------------------------------------
165
+
166
+ get auth(): AuthService {
167
+ if (!this._auth) {
168
+ this._auth = new AuthService(this, {
169
+ autoRefresh: this._autoRefresh,
170
+ persistSession: this._persistSession,
171
+ detectSessionInUrl: this._detectSessionInUrl,
172
+ })
173
+ }
174
+ return this._auth
175
+ }
176
+
177
+ get authAdmin(): AuthAdminService {
178
+ // E21 (durci) : l'API admin exige une clé à privilèges élevés (service_role).
179
+ // L'utiliser côté navigateur implique d'embarquer cette clé dans le bundle JS =
180
+ // compromission totale du projet. On THROW (plus de simple warn : un warn se
181
+ // contourne/s'ignore ; l'accès admin côté client doit échouer franchement).
182
+ if (isBrowserContext()) {
183
+ throw new Error(
184
+ '[aurabase] SÉCURITÉ : authAdmin est inaccessible dans un contexte navigateur. ' +
185
+ "L'API admin requiert une clé service_role qui ne doit JAMAIS être exposée côté " +
186
+ 'client (elle fuiterait dans le bundle). Utilisez createAdminClient() côté serveur uniquement.',
187
+ )
188
+ }
189
+ if (!this._authAdmin) this._authAdmin = new AuthAdminService(this)
190
+ return this._authAdmin
191
+ }
192
+
193
+ get db(): DatabaseService<Database> {
194
+ if (!this._db) this._db = new DatabaseService<Database>(this)
195
+ return this._db
196
+ }
197
+
198
+ get storage(): StorageService {
199
+ if (!this._storage) this._storage = new StorageService(this)
200
+ return this._storage
201
+ }
202
+
203
+ get realtime(): RealtimeService {
204
+ if (!this._realtime) this._realtime = new RealtimeService(this)
205
+ return this._realtime
206
+ }
207
+
208
+ get functions(): FunctionsService {
209
+ if (!this._functions) this._functions = new FunctionsService(this)
210
+ return this._functions
211
+ }
212
+
213
+ get ai(): AiService {
214
+ if (!this._ai) this._ai = new AiService(this)
215
+ return this._ai
216
+ }
217
+
218
+ get notifications(): NotificationsService {
219
+ if (!this._notifications) this._notifications = new NotificationsService(this)
220
+ return this._notifications
221
+ }
222
+
223
+ /**
224
+ * Shortcut: create a realtime channel with Supabase-compatible API.
225
+ * Equivalent to `aura.realtime.channel(name)`.
226
+ *
227
+ * @example
228
+ * ```ts
229
+ * const channel = aura.channel('room-1')
230
+ * .on('postgres_changes', { event: 'INSERT', schema: 'public', table: 'messages' }, cb)
231
+ * .subscribe()
232
+ * ```
233
+ */
234
+ channel(name: string, options?: ChannelConfig): AuraChannel {
235
+ return this.realtime.channel(name, options)
236
+ }
237
+ }
@@ -0,0 +1,152 @@
1
+ export { AuraClient } from './AuraClient'
2
+ export { AuraError, isAuraError } from '@aurabase/core'
3
+ export { BaseAuthStore } from '@aurabase/core'
4
+ export { LocalAuthStore } from '@aurabase/core'
5
+ export { QueryBuilder } from '@aurabase/db'
6
+
7
+ // Services (for advanced usage / typing)
8
+ export { AuthService, isMfaChallenge } from '@aurabase/auth'
9
+ export { AuthAdminService } from '@aurabase/auth'
10
+ export { DatabaseService } from '@aurabase/db'
11
+ export { StorageService } from '@aurabase/storage'
12
+ export { RealtimeService } from '@aurabase/realtime'
13
+ export { AuraChannel } from '@aurabase/realtime'
14
+ export { FunctionsService } from '@aurabase/functions'
15
+ export { AiService } from '@aurabase/ai'
16
+ export { NotificationsService, NotificationsAdminService } from '@aurabase/notifications'
17
+
18
+ // Types
19
+ export type {
20
+ AuraResponse,
21
+ AuraErrorCode,
22
+ AuraObservabilityEvent,
23
+ AuraClientOptions,
24
+ Meta,
25
+ User,
26
+ TokenPair,
27
+ LoginResponse,
28
+ MfaChallenge,
29
+ AuthEvent,
30
+ AuthChangePayload,
31
+ SignUpRequest,
32
+ SignInRequest,
33
+ MagicLinkRequest,
34
+ OAuthSignInOptions,
35
+ PasswordResetRequest,
36
+ UpdateUserRequest,
37
+ MfaEnrollResponse,
38
+ MfaVerifyRequest,
39
+ SessionInfo,
40
+ FilterOp,
41
+ QueryFilter,
42
+ CountMode,
43
+ QueryOptions,
44
+ SchemaColumn,
45
+ SchemaTable,
46
+ StorageBucket,
47
+ UploadResult,
48
+ FileEntry,
49
+ RealtimeEvent,
50
+ RealtimeListenType,
51
+ RealtimeSubscribeStatus,
52
+ PostgresChangesFilter,
53
+ BroadcastFilter,
54
+ PresenceFilter,
55
+ PresenceState,
56
+ PresenceInfo,
57
+ ChannelConfig,
58
+ BroadcastPayload,
59
+ ChatMessage,
60
+ ChatResponse,
61
+ EmbedRequest,
62
+ EmbedResponse,
63
+ RagRequest,
64
+ RagResponse,
65
+ RagIngestRequest,
66
+ RagIngestResponse,
67
+ SemanticSearchResult,
68
+ FunctionDef,
69
+ Job,
70
+ CronJob,
71
+ Notification,
72
+ NotificationTemplate,
73
+ SendNotificationRequest,
74
+ BatchSendResponse,
75
+ NotificationRule,
76
+ NotificationSettings,
77
+ NotificationStats,
78
+ NotificationAttempt,
79
+ NotificationDeadLetter,
80
+ NotificationEvent,
81
+ NotificationProviderLog,
82
+ NotificationQueueStats,
83
+ NotificationTemplatePreview,
84
+ IdentityInfo,
85
+ AdminUser,
86
+ AuditLogEntry,
87
+ AuthSettings,
88
+ EmailTemplateUpdate,
89
+ AdminCreateUserRequest,
90
+ AdminUpdateUserRequest,
91
+ } from '@aurabase/core'
92
+
93
+ import { AuraClient, isBrowserContext } from './AuraClient'
94
+ import type { AuraClientOptions } from '@aurabase/core'
95
+
96
+ /**
97
+ * Create a new Aurabase client instance.
98
+ *
99
+ * @example
100
+ * ```ts
101
+ * // With API key (recommended — like Supabase)
102
+ * const aura = createClient('http://localhost:8080', 'project-uuid', 'aura_anon_xxx')
103
+ *
104
+ * // With options
105
+ * const aura = createClient('http://localhost:8080', 'project-uuid', 'aura_anon_xxx', {
106
+ * auth: { persistSession: true }
107
+ * })
108
+ *
109
+ * // Without API key (backward compatible)
110
+ * const aura = createClient('http://localhost:8080', 'project-uuid')
111
+ * ```
112
+ */
113
+ export function createClient<Database = any>(
114
+ baseUrl: string,
115
+ projectId: string,
116
+ apiKeyOrOptions?: string | AuraClientOptions,
117
+ options?: AuraClientOptions,
118
+ ): AuraClient<Database> {
119
+ return new AuraClient<Database>(baseUrl, projectId, apiKeyOrOptions, options)
120
+ }
121
+
122
+ /**
123
+ * Crée un client à usage **SERVEUR uniquement** pour les opérations d'administration
124
+ * (`client.authAdmin` : lister/créer/bannir des utilisateurs, lire l'audit). Exige une
125
+ * clé `service_role`. Lève une erreur si appelé dans un navigateur — cette clé ne doit
126
+ * jamais être embarquée dans un bundle client (E21). Équivalent du séparateur
127
+ * Admin SDK de Firebase / `service_role` server-side de Supabase.
128
+ *
129
+ * @example
130
+ * ```ts
131
+ * // server-side only (API route, edge function, backend)
132
+ * const admin = createAdminClient(url, projectId, process.env.SERVICE_ROLE_KEY!)
133
+ * await admin.authAdmin.listUsers()
134
+ * ```
135
+ */
136
+ export function createAdminClient<Database = any>(
137
+ baseUrl: string,
138
+ projectId: string,
139
+ serviceRoleKey: string,
140
+ options?: AuraClientOptions,
141
+ ): AuraClient<Database> {
142
+ // Garde étendue au-delà de `window` : couvre aussi les Web Workers navigateur
143
+ // (dedicated/shared) via isBrowserContext(). ServiceWorkerGlobalScope (Cloudflare
144
+ // Workers = serveur) est volontairement exclu pour ne pas casser un usage serveur.
145
+ if (isBrowserContext()) {
146
+ throw new Error(
147
+ '[aurabase] createAdminClient() ne doit jamais être appelé côté navigateur : ' +
148
+ 'la clé service_role serait exposée dans le bundle. À utiliser uniquement côté serveur.',
149
+ )
150
+ }
151
+ return new AuraClient<Database>(baseUrl, projectId, serviceRoleKey, options)
152
+ }
@@ -0,0 +1,156 @@
1
+ /**
2
+ * Server-side rendering helpers for Aurabase.
3
+ *
4
+ * @example Next.js middleware
5
+ * ```ts
6
+ * import { createServerClient } from 'aurabase/ssr'
7
+ *
8
+ * export async function middleware(request) {
9
+ * let response = NextResponse.next({ request })
10
+ * const client = createServerClient(URL, PROJECT_ID, {
11
+ * cookies: {
12
+ * getAll: () => request.cookies.getAll(),
13
+ * setAll: (cookies) => {
14
+ * cookies.forEach(({ name, value, options }) => {
15
+ * request.cookies.set(name, value)
16
+ * response.cookies.set(name, value, options)
17
+ * })
18
+ * },
19
+ * },
20
+ * })
21
+ * await client.auth.getSession()
22
+ * return response
23
+ * }
24
+ * ```
25
+ *
26
+ * @module
27
+ */
28
+
29
+ import { AuraClient } from './AuraClient'
30
+ import type { AuraClientOptions } from '@aurabase/core'
31
+ import { LocalAuthStore } from '@aurabase/core'
32
+ import { parseCookieHeader, serializeCookieHeader } from '@aurabase/core'
33
+ import type { SerializeCookieOptions } from '@aurabase/core'
34
+
35
+ export interface CookieHandler {
36
+ /** Return all cookies from the incoming request. */
37
+ getAll(): Array<{ name: string; value: string }>
38
+ /** Set cookies on the outgoing response. */
39
+ setAll(
40
+ cookies: Array<{
41
+ name: string
42
+ value: string
43
+ options: SerializeCookieOptions
44
+ }>,
45
+ ): void
46
+ }
47
+
48
+ export interface ServerClientOptions {
49
+ apiKey?: string
50
+ cookies: CookieHandler
51
+ cookieOptions?: SerializeCookieOptions
52
+ }
53
+
54
+ /**
55
+ * Create an Aurabase client for server-side usage (SSR, API routes, middleware).
56
+ * Auth state is read from / written to HTTP cookies via the provided handler.
57
+ */
58
+ /**
59
+ * Taille max d'un cookie chunk. Les navigateurs limitent un cookie à ~4096 octets
60
+ * (nom + valeur + attributs) ; on garde une marge confortable, comme `@supabase/ssr`.
61
+ */
62
+ const MAX_CHUNK_SIZE = 3600
63
+
64
+ export function createServerClient<Database = any>(
65
+ baseUrl: string,
66
+ projectId: string,
67
+ options: ServerClientOptions,
68
+ ): AuraClient<Database> {
69
+ const cookieName = `aura-${projectId}-auth`
70
+ const store = new LocalAuthStore(cookieName)
71
+ // Regex des cookies chunkés `aura-<pid>-auth.<n>` (nom échappé pour la sûreté).
72
+ const idxRe = new RegExp(`^${cookieName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\.(\\d+)$`)
73
+
74
+ // ── Lecture : reconstitue la session depuis le cookie unique OU les chunks ──
75
+ const incoming = options.cookies.getAll()
76
+ const numbered = incoming
77
+ .filter((c) => idxRe.test(c.name))
78
+ .sort((a, b) => Number(a.name.match(idxRe)![1]) - Number(b.name.match(idxRe)![1]))
79
+ const base = incoming.find((c) => c.name === cookieName)
80
+ const decodedValue = numbered.length > 0 ? numbered.map((c) => c.value).join('') : base?.value
81
+ if (decodedValue) {
82
+ store.loadFromCookie(`${cookieName}=${encodeURIComponent(decodedValue)}`)
83
+ }
84
+ // Noms de cookies auth présents à l'entrée → à expirer s'ils ne sont plus utilisés.
85
+ const initialNames = incoming
86
+ .filter((c) => c.name === cookieName || idxRe.test(c.name))
87
+ .map((c) => c.name)
88
+
89
+ // Défaut `secure` calé sur le protocole : `true` en https, `false` en http (dev localhost).
90
+ // Surchargez via `cookieOptions.secure` si besoin.
91
+ const defaultCookieOpts: SerializeCookieOptions = {
92
+ path: '/',
93
+ secure: baseUrl.startsWith('https://'),
94
+ sameSite: 'Lax',
95
+ httpOnly: true,
96
+ maxAge: 60 * 60 * 24 * 30, // 30 days
97
+ ...options.cookieOptions,
98
+ }
99
+
100
+ // ── Écriture : propage les changements d'auth vers les cookies de réponse ──
101
+ store.onChange(() => {
102
+ const toSet: Array<{ name: string; value: string; options: SerializeCookieOptions }> = []
103
+ const used = new Set<string>()
104
+
105
+ if (store.token) {
106
+ // Valeur (JSON) décodée à chunker ; le framework ré-encode à la pose.
107
+ const cookieStr = store.exportToCookie()
108
+ const eqIdx = cookieStr.indexOf('=')
109
+ const rawEncoded = eqIdx >= 0 ? cookieStr.slice(eqIdx + 1).split(';')[0] : ''
110
+ const decoded = rawEncoded ? decodeURIComponent(rawEncoded) : ''
111
+
112
+ if (decoded.length <= MAX_CHUNK_SIZE) {
113
+ toSet.push({ name: cookieName, value: decoded, options: defaultCookieOpts })
114
+ used.add(cookieName)
115
+ } else {
116
+ // Fragmentation : `aura-<pid>-auth.0`, `.1`, … (anti-troncature silencieuse).
117
+ let idx = 0
118
+ for (let i = 0; i < decoded.length; i += MAX_CHUNK_SIZE, idx++) {
119
+ const name = `${cookieName}.${idx}`
120
+ toSet.push({ name, value: decoded.slice(i, i + MAX_CHUNK_SIZE), options: defaultCookieOpts })
121
+ used.add(name)
122
+ }
123
+ }
124
+ }
125
+
126
+ // Expire tout cookie auth présent avant mais désormais inutilisé (signout, ou
127
+ // passage de N chunks à moins de chunks) — évite de laisser traîner une session.
128
+ const expireOpts: SerializeCookieOptions = { ...defaultCookieOpts, maxAge: 0 }
129
+ for (const name of initialNames) {
130
+ if (!used.has(name)) toSet.push({ name, value: '', options: expireOpts })
131
+ }
132
+
133
+ if (toSet.length > 0) options.cookies.setAll(toSet)
134
+ })
135
+
136
+ return new AuraClient<Database>(baseUrl, projectId, options.apiKey, {
137
+ auth: { persistSession: false, storage: store },
138
+ })
139
+ }
140
+
141
+ /**
142
+ * Create an Aurabase client for browser usage.
143
+ * Thin wrapper around AuraClient with sensible browser defaults.
144
+ */
145
+ export function createBrowserClient<Database = any>(
146
+ baseUrl: string,
147
+ projectId: string,
148
+ apiKey?: string,
149
+ options?: AuraClientOptions,
150
+ ): AuraClient<Database> {
151
+ return new AuraClient<Database>(baseUrl, projectId, apiKey, options)
152
+ }
153
+
154
+ // Re-export cookie utilities
155
+ export { parseCookieHeader, serializeCookieHeader } from '@aurabase/core'
156
+ export type { SerializeCookieOptions } from '@aurabase/core'
@@ -0,0 +1,82 @@
1
+ // ---------------------------------------------------------------------------
2
+ // E2E réel (stack live) — Lot sdk-ai / `ai-chat-streaming` + `ai-rag-namespaces-crud`.
3
+ // Réf. : docs/superpowers/specs/2026-07-13-ai-chat-streaming-design.md
4
+ //
5
+ // Vérifie que le CHEMIN SSE de `ai.chatStream` (client.fetchFn brut + parseSSE)
6
+ // atteint le backend `/chat/stream` et livre un flux exploitable, et que le CRUD
7
+ // RAG (`listNamespaces`) est bien câblé. Tolérant à l'absence de provider LLM en
8
+ // local : distingue un flux fonctionnel / une erreur applicative (provider) d'un
9
+ // échec de ROUTE (404) ou d'un timeout, qui eux feraient échouer le test.
10
+ // ---------------------------------------------------------------------------
11
+
12
+ import { describe, it, expect } from 'vitest'
13
+ import { createAdminClient } from '../src/index'
14
+
15
+ const URL = process.env.AURA_E2E_URL
16
+ const PROJECT = process.env.AURA_E2E_PROJECT
17
+ const SERVICE = process.env.AURA_E2E_SERVICE_KEY
18
+ const RUN = Boolean(process.env.RUN_E2E && URL && PROJECT && SERVICE)
19
+ const TRANSIENT = new Set([408, 429, 502, 503, 504])
20
+
21
+ describe.runIf(RUN)('ai chatStream + RAG CRUD E2E réel', () => {
22
+ it(
23
+ 'chatStream ouvre le flux SSE via /chat/stream (deltas ou erreur applicative, pas 404/timeout)',
24
+ async () => {
25
+ const admin = createAdminClient(URL!, PROJECT!, SERVICE!)
26
+ let deltas = 0
27
+ let streamErr: { status: number; message?: string } | null = null
28
+ const ctrl = new AbortController()
29
+ const cutoff = setTimeout(() => ctrl.abort(), 20_000)
30
+
31
+ try {
32
+ for await (const chunk of admin.ai.chatStream(
33
+ [{ role: 'user', content: 'Dis simplement bonjour.' }],
34
+ { model: 'gpt-4o-mini', signal: ctrl.signal },
35
+ )) {
36
+ if (chunk.delta) deltas += 1
37
+ if (deltas >= 3) break // assez pour prouver le streaming
38
+ }
39
+ } catch (e) {
40
+ streamErr = e as { status: number; message?: string }
41
+ } finally {
42
+ clearTimeout(cutoff)
43
+ }
44
+
45
+ if (deltas > 0) {
46
+ // Streaming réel prouvé (provider présent).
47
+ expect(deltas).toBeGreaterThan(0)
48
+ } else if (streamErr) {
49
+ // Pas de provider LLM en local : on DOIT avoir atteint le backend et reçu
50
+ // une erreur APPLICATIVE (config/provider), PAS un 404 de route ni un
51
+ // échec transport — cela prouve que le chemin SSE fetchFn+parseSSE marche.
52
+ expect(
53
+ streamErr.status,
54
+ `chatStream a échoué avec un statut de ROUTE/transport (${streamErr.status}: ${streamErr.message}) — ` +
55
+ `le chemin SSE n'atteint pas le backend`,
56
+ ).not.toBe(404)
57
+ expect(TRANSIENT.has(streamErr.status), `statut transitoire ${streamErr.status}`).toBe(false)
58
+ console.warn(
59
+ `[ai-streaming-rag-e2e] chatStream : aucun delta mais erreur applicative ${streamErr.status} ` +
60
+ `(${streamErr.message}) — chemin SSE OK, provider LLM probablement non configuré en local.`,
61
+ )
62
+ } else {
63
+ console.warn('[ai-streaming-rag-e2e] chatStream : ni delta ni erreur (flux vide / annulé) — toléré.')
64
+ }
65
+ },
66
+ 45_000,
67
+ )
68
+
69
+ it('listNamespaces (RAG CRUD) est câblé et répond', async () => {
70
+ const admin = createAdminClient(URL!, PROJECT!, SERVICE!)
71
+ const res = await admin.ai.listNamespaces()
72
+ if (res.error && TRANSIENT.has(res.error.status)) {
73
+ console.warn(`[ai-streaming-rag-e2e] SKIP listNamespaces (${res.error.status}).`)
74
+ return
75
+ }
76
+ // La route doit répondre (pas de 404) et renvoyer une liste (éventuellement vide).
77
+ expect(res.error?.status, `listNamespaces route absente/erreur: ${JSON.stringify(res.error)}`).not.toBe(404)
78
+ if (!res.error) {
79
+ expect(Array.isArray(res.data), 'listNamespaces doit renvoyer un tableau').toBe(true)
80
+ }
81
+ })
82
+ })