@aurabase/aurabase-js 0.3.0 → 0.4.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 (343) hide show
  1. package/README.md +26 -795
  2. package/{packages/aurabase/dist/AuraClient-DAtDbfPB.d.ts → dist/AuraClient-BcFE8u1v.d.cts} +1 -1
  3. package/{packages/aurabase/dist/AuraClient-DAtDbfPB.d.cts → dist/AuraClient-BcFE8u1v.d.ts} +1 -1
  4. package/{packages/aurabase/dist → dist}/index.d.cts +1 -1
  5. package/{packages/aurabase/dist → dist}/index.d.ts +1 -1
  6. package/{packages/aurabase/dist → dist}/ssr.d.cts +1 -1
  7. package/{packages/aurabase/dist → dist}/ssr.d.ts +1 -1
  8. package/package.json +72 -82
  9. package/.changeset/config.json +0 -11
  10. package/CHANGELOG.md +0 -30
  11. package/packages/ai/LICENSE +0 -21
  12. package/packages/ai/README.md +0 -106
  13. package/packages/ai/dist/index.cjs +0 -229
  14. package/packages/ai/dist/index.d.cts +0 -139
  15. package/packages/ai/dist/index.d.ts +0 -139
  16. package/packages/ai/dist/index.js +0 -226
  17. package/packages/ai/node_modules/.bin/esbuild +0 -19
  18. package/packages/ai/node_modules/.bin/tsc +0 -22
  19. package/packages/ai/node_modules/.bin/tsserver +0 -22
  20. package/packages/ai/node_modules/.bin/tsup +0 -22
  21. package/packages/ai/node_modules/.bin/tsup-node +0 -22
  22. package/packages/ai/node_modules/.bin/vite +0 -22
  23. package/packages/ai/node_modules/.bin/vitest +0 -22
  24. package/packages/ai/node_modules/.vite/vitest/da39a3ee5e6b4b0d3255bfef95601890afd80709/results.json +0 -1
  25. package/packages/ai/package.json +0 -61
  26. package/packages/ai/src/AiService.ts +0 -226
  27. package/packages/ai/src/index.ts +0 -18
  28. package/packages/ai/src/sse.ts +0 -141
  29. package/packages/ai/src/types.ts +0 -30
  30. package/packages/ai/tests/chat-stream.test.ts +0 -151
  31. package/packages/ai/tests/rag-namespaces.test.ts +0 -54
  32. package/packages/ai/tests/sse.test.ts +0 -69
  33. package/packages/ai/tsconfig.json +0 -5
  34. package/packages/ai/tsup.config.ts +0 -11
  35. package/packages/aurabase/LICENSE +0 -21
  36. package/packages/aurabase/README.md +0 -64
  37. package/packages/aurabase/node_modules/.bin/esbuild +0 -19
  38. package/packages/aurabase/node_modules/.bin/tsc +0 -22
  39. package/packages/aurabase/node_modules/.bin/tsserver +0 -22
  40. package/packages/aurabase/node_modules/.bin/tsup +0 -22
  41. package/packages/aurabase/node_modules/.bin/tsup-node +0 -22
  42. package/packages/aurabase/node_modules/.bin/vite +0 -22
  43. package/packages/aurabase/node_modules/.bin/vitest +0 -22
  44. package/packages/aurabase/node_modules/.vite/vitest/da39a3ee5e6b4b0d3255bfef95601890afd80709/results.json +0 -1
  45. package/packages/aurabase/package.json +0 -80
  46. package/packages/aurabase/src/AuraClient.ts +0 -237
  47. package/packages/aurabase/src/index.ts +0 -152
  48. package/packages/aurabase/src/ssr.ts +0 -156
  49. package/packages/aurabase/tests/ai-streaming-rag-e2e.test.ts +0 -82
  50. package/packages/aurabase/tests/ai.test.ts +0 -111
  51. package/packages/aurabase/tests/auth-admin.test.ts +0 -515
  52. package/packages/aurabase/tests/auth-e2e.test.ts +0 -135
  53. package/packages/aurabase/tests/auth-hardening.test.ts +0 -206
  54. package/packages/aurabase/tests/auth.test.ts +0 -947
  55. package/packages/aurabase/tests/database.test.ts +0 -230
  56. package/packages/aurabase/tests/db-types-e2e.test.ts +0 -217
  57. package/packages/aurabase/tests/dispose.test.ts +0 -23
  58. package/packages/aurabase/tests/foreign-token.e2e.test.ts +0 -129
  59. package/packages/aurabase/tests/functions.test.ts +0 -107
  60. package/packages/aurabase/tests/integration.test.ts +0 -413
  61. package/packages/aurabase/tests/live-production-validation.js +0 -241
  62. package/packages/aurabase/tests/live-sdk-production-validation.js +0 -293
  63. package/packages/aurabase/tests/mocks.ts +0 -139
  64. package/packages/aurabase/tests/notifications.test.ts +0 -314
  65. package/packages/aurabase/tests/observability-backup.test.ts +0 -186
  66. package/packages/aurabase/tests/observability-hook.test.ts +0 -130
  67. package/packages/aurabase/tests/production-robustness.test.ts +0 -268
  68. package/packages/aurabase/tests/public-api-surface.test.ts +0 -53
  69. package/packages/aurabase/tests/query-builder.test.ts +0 -329
  70. package/packages/aurabase/tests/readme-smoke-e2e.test.ts +0 -231
  71. package/packages/aurabase/tests/realtime-filter-e2e.test.ts +0 -344
  72. package/packages/aurabase/tests/refresh-locks.test.ts +0 -210
  73. package/packages/aurabase/tests/retry-option.test.ts +0 -17
  74. package/packages/aurabase/tests/rpc-e2e.test.ts +0 -254
  75. package/packages/aurabase/tests/rs256-local-e2e.test.ts +0 -114
  76. package/packages/aurabase/tests/rt-alias-public-e2e.test.ts +0 -235
  77. package/packages/aurabase/tests/rt-http-broadcast-e2e.test.ts +0 -124
  78. package/packages/aurabase/tests/service-role-guard.test.ts +0 -99
  79. package/packages/aurabase/tests/ssr.test.ts +0 -91
  80. package/packages/aurabase/tests/storage-backend-e2e.test.ts +0 -481
  81. package/packages/aurabase/tests/storage-sdk-parity-e2e.test.ts +0 -104
  82. package/packages/aurabase/tests/storage-transform-e2e.test.ts +0 -684
  83. package/packages/aurabase/tests/storage.test.ts +0 -55
  84. package/packages/aurabase/tests/types/client-generic.test-d.ts +0 -79
  85. package/packages/aurabase/tests/types/docs-snippets.test-d.ts +0 -571
  86. package/packages/aurabase/tests/types/error-code.test-d.ts +0 -53
  87. package/packages/aurabase/tsconfig.json +0 -5
  88. package/packages/aurabase/tsconfig.test-d.json +0 -5
  89. package/packages/aurabase/tsup.config.ts +0 -11
  90. package/packages/aurabase/vitest.config.ts +0 -16
  91. package/packages/aurabase/vitest.e2e.config.ts +0 -9
  92. package/packages/auth/LICENSE +0 -21
  93. package/packages/auth/README.md +0 -215
  94. package/packages/auth/dist/index.cjs +0 -1175
  95. package/packages/auth/dist/index.d.cts +0 -397
  96. package/packages/auth/dist/index.d.ts +0 -397
  97. package/packages/auth/dist/index.js +0 -1170
  98. package/packages/auth/node_modules/.bin/esbuild +0 -19
  99. package/packages/auth/node_modules/.bin/tsc +0 -22
  100. package/packages/auth/node_modules/.bin/tsserver +0 -22
  101. package/packages/auth/node_modules/.bin/tsup +0 -22
  102. package/packages/auth/node_modules/.bin/tsup-node +0 -22
  103. package/packages/auth/node_modules/.bin/vite +0 -22
  104. package/packages/auth/node_modules/.bin/vitest +0 -22
  105. package/packages/auth/node_modules/.vite/vitest/da39a3ee5e6b4b0d3255bfef95601890afd80709/results.json +0 -1
  106. package/packages/auth/package.json +0 -61
  107. package/packages/auth/src/AuthAdminService.ts +0 -149
  108. package/packages/auth/src/AuthService.ts +0 -1166
  109. package/packages/auth/src/SessionManager.ts +0 -92
  110. package/packages/auth/src/index.ts +0 -17
  111. package/packages/auth/src/jwks.ts +0 -337
  112. package/packages/auth/src/pkce.ts +0 -27
  113. package/packages/auth/src/types.ts +0 -89
  114. package/packages/auth/tests/auth-lifecycle.test.ts +0 -149
  115. package/packages/auth/tests/detect-session.test.ts +0 -361
  116. package/packages/auth/tests/getclaims.test.ts +0 -780
  117. package/packages/auth/tests/is-mfa-challenge.test.ts +0 -27
  118. package/packages/auth/tests/password-recovery.test.ts +0 -124
  119. package/packages/auth/tests/pkce.test.ts +0 -192
  120. package/packages/auth/tests/session-manager.test.ts +0 -103
  121. package/packages/auth/tests/set-session.test.ts +0 -139
  122. package/packages/auth/tests/verify-otp.test.ts +0 -153
  123. package/packages/auth/tsconfig.json +0 -5
  124. package/packages/auth/tsup.config.ts +0 -11
  125. package/packages/core/LICENSE +0 -21
  126. package/packages/core/README.md +0 -132
  127. package/packages/core/dist/index.cjs +0 -695
  128. package/packages/core/dist/index.d.cts +0 -1137
  129. package/packages/core/dist/index.d.ts +0 -1137
  130. package/packages/core/dist/index.js +0 -673
  131. package/packages/core/node_modules/.bin/esbuild +0 -22
  132. package/packages/core/node_modules/.bin/tsc +0 -22
  133. package/packages/core/node_modules/.bin/tsserver +0 -22
  134. package/packages/core/node_modules/.bin/tsup +0 -22
  135. package/packages/core/node_modules/.bin/tsup-node +0 -22
  136. package/packages/core/node_modules/.bin/vite +0 -22
  137. package/packages/core/node_modules/.bin/vitest +0 -22
  138. package/packages/core/node_modules/.vite/vitest/da39a3ee5e6b4b0d3255bfef95601890afd80709/results.json +0 -1
  139. package/packages/core/package.json +0 -57
  140. package/packages/core/src/AuraError.ts +0 -89
  141. package/packages/core/src/BaseService.ts +0 -44
  142. package/packages/core/src/client.ts +0 -34
  143. package/packages/core/src/cookie-utils.ts +0 -42
  144. package/packages/core/src/fetch.ts +0 -435
  145. package/packages/core/src/index.ts +0 -22
  146. package/packages/core/src/retry.ts +0 -63
  147. package/packages/core/src/serialize.ts +0 -6
  148. package/packages/core/src/stores/BaseAuthStore.ts +0 -164
  149. package/packages/core/src/stores/LocalAuthStore.ts +0 -199
  150. package/packages/core/src/types.ts +0 -1042
  151. package/packages/core/tests/auth-store.test.ts +0 -300
  152. package/packages/core/tests/error-code.test.ts +0 -61
  153. package/packages/core/tests/error.test.ts +0 -24
  154. package/packages/core/tests/fetch.test.ts +0 -286
  155. package/packages/core/tests/mocks.ts +0 -139
  156. package/packages/core/tests/observability.test.ts +0 -86
  157. package/packages/core/tests/refresh-hardening.test.ts +0 -164
  158. package/packages/core/tests/refresh-observability.test.ts +0 -111
  159. package/packages/core/tests/retry.test.ts +0 -106
  160. package/packages/core/tests/serialize.test.ts +0 -12
  161. package/packages/core/tests/timeout.test.ts +0 -79
  162. package/packages/core/tsconfig.json +0 -5
  163. package/packages/core/tsup.config.ts +0 -11
  164. package/packages/db/LICENSE +0 -21
  165. package/packages/db/README.md +0 -152
  166. package/packages/db/VENDORED.md +0 -93
  167. package/packages/db/dist/index.cjs +0 -544
  168. package/packages/db/dist/index.d.cts +0 -1111
  169. package/packages/db/dist/index.d.ts +0 -1111
  170. package/packages/db/dist/index.js +0 -541
  171. package/packages/db/node_modules/.bin/esbuild +0 -19
  172. package/packages/db/node_modules/.bin/tsc +0 -22
  173. package/packages/db/node_modules/.bin/tsserver +0 -22
  174. package/packages/db/node_modules/.bin/tsup +0 -22
  175. package/packages/db/node_modules/.bin/tsup-node +0 -22
  176. package/packages/db/node_modules/.bin/vite +0 -22
  177. package/packages/db/node_modules/.bin/vitest +0 -22
  178. package/packages/db/node_modules/.vite/vitest/da39a3ee5e6b4b0d3255bfef95601890afd80709/results.json +0 -1
  179. package/packages/db/package.json +0 -62
  180. package/packages/db/src/DatabaseService.ts +0 -170
  181. package/packages/db/src/QueryBuilder.ts +0 -830
  182. package/packages/db/src/index.ts +0 -2
  183. package/packages/db/src/pgrst-types/common/common.ts +0 -86
  184. package/packages/db/src/pgrst-types/common/rpc.ts +0 -151
  185. package/packages/db/src/pgrst-types/feature-flags.ts +0 -20
  186. package/packages/db/src/pgrst-types/types.ts +0 -134
  187. package/packages/db/src/select-query-parser/parser.ts +0 -479
  188. package/packages/db/src/select-query-parser/result.ts +0 -553
  189. package/packages/db/src/select-query-parser/types.ts +0 -132
  190. package/packages/db/src/select-query-parser/utils.ts +0 -707
  191. package/packages/db/tests/filters.test.ts +0 -81
  192. package/packages/db/tests/mutations-filtered.e2e.test.ts +0 -132
  193. package/packages/db/tests/mutations-filtered.test.ts +0 -188
  194. package/packages/db/tests/order.test.ts +0 -45
  195. package/packages/db/tests/rpc.test.ts +0 -41
  196. package/packages/db/tests/scale/build-large-schema.ts +0 -94
  197. package/packages/db/tests/scale/scale-compile.test.ts +0 -167
  198. package/packages/db/tests/schema.test.ts +0 -77
  199. package/packages/db/tests/single-accept.e2e.test.ts +0 -123
  200. package/packages/db/tests/single.test.ts +0 -211
  201. package/packages/db/tests/types/filters.test-d.ts +0 -52
  202. package/packages/db/tests/types/fixtures.ts +0 -40
  203. package/packages/db/tests/types/from-views.test-d.ts +0 -18
  204. package/packages/db/tests/types/mutations.test-d.ts +0 -23
  205. package/packages/db/tests/types/rpc.test-d.ts +0 -60
  206. package/packages/db/tests/types/schema-shape.test-d.ts +0 -8
  207. package/packages/db/tests/types/select-inference.test-d.ts +0 -38
  208. package/packages/db/tests/vendored/fixtures.ts +0 -83
  209. package/packages/db/tests/vendored/get-result.test-d.ts +0 -75
  210. package/packages/db/tsconfig.json +0 -5
  211. package/packages/db/tsconfig.test-d.json +0 -5
  212. package/packages/db/tsup.config.ts +0 -11
  213. package/packages/db/vitest.config.ts +0 -8
  214. package/packages/functions/LICENSE +0 -21
  215. package/packages/functions/README.md +0 -96
  216. package/packages/functions/dist/index.cjs +0 -173
  217. package/packages/functions/dist/index.d.cts +0 -81
  218. package/packages/functions/dist/index.d.ts +0 -81
  219. package/packages/functions/dist/index.js +0 -168
  220. package/packages/functions/node_modules/.bin/esbuild +0 -19
  221. package/packages/functions/node_modules/.bin/tsc +0 -22
  222. package/packages/functions/node_modules/.bin/tsserver +0 -22
  223. package/packages/functions/node_modules/.bin/tsup +0 -22
  224. package/packages/functions/node_modules/.bin/tsup-node +0 -22
  225. package/packages/functions/node_modules/.bin/vite +0 -22
  226. package/packages/functions/node_modules/.bin/vitest +0 -22
  227. package/packages/functions/node_modules/.vite/vitest/da39a3ee5e6b4b0d3255bfef95601890afd80709/results.json +0 -1
  228. package/packages/functions/package.json +0 -60
  229. package/packages/functions/src/FunctionsService.ts +0 -188
  230. package/packages/functions/src/errors.ts +0 -70
  231. package/packages/functions/src/index.ts +0 -6
  232. package/packages/functions/tests/invoke.test.ts +0 -97
  233. package/packages/functions/tests/response-type-errors.test.ts +0 -135
  234. package/packages/functions/tsconfig.json +0 -5
  235. package/packages/functions/tsup.config.ts +0 -11
  236. package/packages/gen/LICENSE +0 -21
  237. package/packages/gen/README.md +0 -84
  238. package/packages/gen/dist/cli.cjs +0 -334
  239. package/packages/gen/dist/cli.d.cts +0 -1
  240. package/packages/gen/dist/cli.d.ts +0 -1
  241. package/packages/gen/dist/cli.js +0 -332
  242. package/packages/gen/dist/index.cjs +0 -257
  243. package/packages/gen/dist/index.d.cts +0 -12
  244. package/packages/gen/dist/index.d.ts +0 -12
  245. package/packages/gen/dist/index.js +0 -255
  246. package/packages/gen/node_modules/.bin/esbuild +0 -19
  247. package/packages/gen/node_modules/.bin/tsc +0 -22
  248. package/packages/gen/node_modules/.bin/tsserver +0 -22
  249. package/packages/gen/node_modules/.bin/tsup +0 -22
  250. package/packages/gen/node_modules/.bin/tsup-node +0 -22
  251. package/packages/gen/node_modules/.bin/vite +0 -22
  252. package/packages/gen/node_modules/.bin/vitest +0 -22
  253. package/packages/gen/node_modules/.vite/vitest/da39a3ee5e6b4b0d3255bfef95601890afd80709/results.json +0 -1
  254. package/packages/gen/package.json +0 -66
  255. package/packages/gen/src/cli.ts +0 -67
  256. package/packages/gen/src/generate.ts +0 -0
  257. package/packages/gen/src/index.ts +0 -2
  258. package/packages/gen/tests/compile.test.ts +0 -213
  259. package/packages/gen/tests/e2e.test.ts +0 -130
  260. package/packages/gen/tests/generate.test.ts +0 -396
  261. package/packages/gen/tsconfig.json +0 -5
  262. package/packages/gen/tsup.config.ts +0 -11
  263. package/packages/notifications/LICENSE +0 -21
  264. package/packages/notifications/README.md +0 -134
  265. package/packages/notifications/dist/index.cjs +0 -128
  266. package/packages/notifications/dist/index.d.cts +0 -81
  267. package/packages/notifications/dist/index.d.ts +0 -81
  268. package/packages/notifications/dist/index.js +0 -125
  269. package/packages/notifications/node_modules/.bin/esbuild +0 -19
  270. package/packages/notifications/node_modules/.bin/tsc +0 -22
  271. package/packages/notifications/node_modules/.bin/tsserver +0 -22
  272. package/packages/notifications/node_modules/.bin/tsup +0 -22
  273. package/packages/notifications/node_modules/.bin/tsup-node +0 -22
  274. package/packages/notifications/node_modules/.bin/vite +0 -22
  275. package/packages/notifications/node_modules/.bin/vitest +0 -22
  276. package/packages/notifications/package.json +0 -60
  277. package/packages/notifications/src/NotificationsService.ts +0 -230
  278. package/packages/notifications/src/index.ts +0 -19
  279. package/packages/notifications/tsconfig.json +0 -5
  280. package/packages/notifications/tsup.config.ts +0 -11
  281. package/packages/realtime/LICENSE +0 -21
  282. package/packages/realtime/README.md +0 -183
  283. package/packages/realtime/dist/index.cjs +0 -977
  284. package/packages/realtime/dist/index.d.cts +0 -259
  285. package/packages/realtime/dist/index.d.ts +0 -259
  286. package/packages/realtime/dist/index.js +0 -973
  287. package/packages/realtime/node_modules/.bin/esbuild +0 -19
  288. package/packages/realtime/node_modules/.bin/tsc +0 -22
  289. package/packages/realtime/node_modules/.bin/tsserver +0 -22
  290. package/packages/realtime/node_modules/.bin/tsup +0 -22
  291. package/packages/realtime/node_modules/.bin/tsup-node +0 -22
  292. package/packages/realtime/node_modules/.bin/vite +0 -22
  293. package/packages/realtime/node_modules/.bin/vitest +0 -22
  294. package/packages/realtime/node_modules/.vite/vitest/da39a3ee5e6b4b0d3255bfef95601890afd80709/results.json +0 -1
  295. package/packages/realtime/package.json +0 -60
  296. package/packages/realtime/src/AuraChannel.ts +0 -485
  297. package/packages/realtime/src/HeartbeatManager.ts +0 -73
  298. package/packages/realtime/src/RealtimeService.ts +0 -505
  299. package/packages/realtime/src/columnFilter.ts +0 -301
  300. package/packages/realtime/src/index.ts +0 -4
  301. package/packages/realtime/tests/ack-routing.test.ts +0 -81
  302. package/packages/realtime/tests/column-filter.test.ts +0 -144
  303. package/packages/realtime/tests/dispatch.test.ts +0 -191
  304. package/packages/realtime/tests/heartbeat.test.ts +0 -67
  305. package/packages/realtime/tests/http-broadcast.test.ts +0 -68
  306. package/packages/realtime/tests/realtime-token.test.ts +0 -43
  307. package/packages/realtime/tests/reconnect-race.test.ts +0 -149
  308. package/packages/realtime/tests/ref-id.test.ts +0 -34
  309. package/packages/realtime/tests/set-auth.test.ts +0 -70
  310. package/packages/realtime/tsconfig.json +0 -5
  311. package/packages/realtime/tsup.config.ts +0 -11
  312. package/packages/storage/LICENSE +0 -21
  313. package/packages/storage/README.md +0 -141
  314. package/packages/storage/dist/index.cjs +0 -333
  315. package/packages/storage/dist/index.d.cts +0 -185
  316. package/packages/storage/dist/index.d.ts +0 -185
  317. package/packages/storage/dist/index.js +0 -329
  318. package/packages/storage/node_modules/.bin/esbuild +0 -19
  319. package/packages/storage/node_modules/.bin/tsc +0 -22
  320. package/packages/storage/node_modules/.bin/tsserver +0 -22
  321. package/packages/storage/node_modules/.bin/tsup +0 -22
  322. package/packages/storage/node_modules/.bin/tsup-node +0 -22
  323. package/packages/storage/node_modules/.bin/vite +0 -22
  324. package/packages/storage/node_modules/.bin/vitest +0 -22
  325. package/packages/storage/node_modules/.vite/vitest/da39a3ee5e6b4b0d3255bfef95601890afd80709/results.json +0 -1
  326. package/packages/storage/package.json +0 -60
  327. package/packages/storage/src/DownloadBuilder.ts +0 -60
  328. package/packages/storage/src/StorageService.ts +0 -323
  329. package/packages/storage/src/index.ts +0 -2
  330. package/packages/storage/src/path.ts +0 -35
  331. package/packages/storage/src/transform.ts +0 -15
  332. package/packages/storage/tests/download.test.ts +0 -64
  333. package/packages/storage/tests/parity.test.ts +0 -154
  334. package/packages/storage/tests/path.test.ts +0 -87
  335. package/packages/storage/tests/transform.test.ts +0 -79
  336. package/packages/storage/tsconfig.json +0 -5
  337. package/packages/storage/tsup.config.ts +0 -11
  338. package/pnpm-workspace.yaml +0 -24
  339. package/tsconfig.base.json +0 -15
  340. /package/{packages/aurabase/dist → dist}/index.cjs +0 -0
  341. /package/{packages/aurabase/dist → dist}/index.js +0 -0
  342. /package/{packages/aurabase/dist → dist}/ssr.cjs +0 -0
  343. /package/{packages/aurabase/dist → dist}/ssr.js +0 -0
@@ -1,977 +0,0 @@
1
- 'use strict';
2
-
3
- var core = require('@aurabase/core');
4
-
5
- // src/RealtimeService.ts
6
-
7
- // src/columnFilter.ts
8
- var VALID_OPS = /* @__PURE__ */ new Set([
9
- "eq",
10
- "neq",
11
- "lt",
12
- "lte",
13
- "gt",
14
- "gte",
15
- "in",
16
- "like",
17
- "ilike",
18
- "is",
19
- "match",
20
- "imatch",
21
- "isdistinct"
22
- ]);
23
- var MAX_REGEX_PATTERN_LEN = 512;
24
- var MAX_IN_VALUES = 100;
25
- function parseColumnFilter(filterStr) {
26
- const eqIdx = filterStr.indexOf("=");
27
- if (eqIdx === -1) return null;
28
- const column = filterStr.slice(0, eqIdx);
29
- if (!column) return null;
30
- let rest = filterStr.slice(eqIdx + 1);
31
- let negated = false;
32
- if (rest.startsWith("not.")) {
33
- negated = true;
34
- rest = rest.slice(4);
35
- }
36
- const dotIdx = rest.indexOf(".");
37
- if (dotIdx === -1) return null;
38
- const opStr = rest.slice(0, dotIdx);
39
- let value = rest.slice(dotIdx + 1);
40
- if (!VALID_OPS.has(opStr)) return null;
41
- const op = opStr;
42
- if (op === "in") {
43
- const stripped = value.replace(/^\(+/, "").replace(/\)+$/, "");
44
- if (stripped.split(",").length > MAX_IN_VALUES) return null;
45
- value = stripped;
46
- } else if (op === "is") {
47
- if (value !== "null" && value !== "true" && value !== "false") return null;
48
- } else if (op === "match" || op === "imatch") {
49
- if (value.length > MAX_REGEX_PATTERN_LEN) return null;
50
- try {
51
- new RegExp(value, op === "imatch" ? "i" : void 0);
52
- } catch {
53
- return null;
54
- }
55
- }
56
- return { column, op, value, negated };
57
- }
58
- function splitTopLevel(s) {
59
- const parts = [];
60
- let depth = 0;
61
- let start = 0;
62
- for (let i = 0; i < s.length; i++) {
63
- const c = s[i];
64
- if (c === "(") depth += 1;
65
- else if (c === ")") depth = Math.max(0, depth - 1);
66
- else if (c === "," && depth === 0) {
67
- parts.push(s.slice(start, i));
68
- start = i + 1;
69
- }
70
- }
71
- parts.push(s.slice(start));
72
- return parts;
73
- }
74
- function parseFilterSet(s) {
75
- const parts = splitTopLevel(s);
76
- const out = [];
77
- for (const part of parts) {
78
- const cf = parseColumnFilter(part.trim());
79
- if (!cf) return null;
80
- out.push(cf);
81
- }
82
- return out;
83
- }
84
- function jsonValueToString(field) {
85
- if (typeof field === "string") return field;
86
- if (typeof field === "number" || typeof field === "boolean") return String(field);
87
- if (field === null) return "null";
88
- try {
89
- return JSON.stringify(field) ?? "";
90
- } catch {
91
- return "";
92
- }
93
- }
94
- function parseStrictNumber(s) {
95
- if (s.trim() === "") return null;
96
- const n = Number(s);
97
- return Number.isFinite(n) ? n : null;
98
- }
99
- function compareNumeric(a, b, cmp) {
100
- const an = parseStrictNumber(a);
101
- const bn = parseStrictNumber(b);
102
- if (an === null || bn === null) return false;
103
- return cmp(an, bn);
104
- }
105
- function likeToRegExp(pattern, caseInsensitive) {
106
- let re = "^";
107
- for (const ch of pattern) {
108
- if (ch === "%") re += ".*";
109
- else if (ch === "_") re += ".";
110
- else re += ch.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
111
- }
112
- re += "$";
113
- try {
114
- return new RegExp(re, caseInsensitive ? "i" : void 0);
115
- } catch {
116
- return null;
117
- }
118
- }
119
- function matchesRaw(cf, record) {
120
- if (cf.op === "is") {
121
- const field2 = record[cf.column];
122
- switch (cf.value) {
123
- case "null":
124
- return field2 === void 0 || field2 === null;
125
- case "true":
126
- return field2 === true;
127
- case "false":
128
- return field2 === false;
129
- default:
130
- return false;
131
- }
132
- }
133
- if (cf.op === "isdistinct") {
134
- const field2 = record[cf.column];
135
- const fieldIsNull = field2 === void 0 || field2 === null;
136
- if (fieldIsNull) return true;
137
- return jsonValueToString(field2) !== cf.value;
138
- }
139
- if (!(cf.column in record) || record[cf.column] === void 0) return null;
140
- const field = record[cf.column];
141
- const fieldStr = jsonValueToString(field);
142
- switch (cf.op) {
143
- case "eq":
144
- return fieldStr === cf.value;
145
- case "neq":
146
- return fieldStr !== cf.value;
147
- case "lt":
148
- return compareNumeric(fieldStr, cf.value, (a, b) => a < b);
149
- case "lte":
150
- return compareNumeric(fieldStr, cf.value, (a, b) => a <= b);
151
- case "gt":
152
- return compareNumeric(fieldStr, cf.value, (a, b) => a > b);
153
- case "gte":
154
- return compareNumeric(fieldStr, cf.value, (a, b) => a >= b);
155
- case "in":
156
- return cf.value.split(",").map((v) => v.trim()).some((v) => v === fieldStr);
157
- case "like": {
158
- const re = likeToRegExp(cf.value, false);
159
- return re ? re.test(fieldStr) : null;
160
- }
161
- case "ilike": {
162
- const re = likeToRegExp(cf.value, true);
163
- return re ? re.test(fieldStr) : null;
164
- }
165
- case "match": {
166
- try {
167
- return new RegExp(cf.value).test(fieldStr);
168
- } catch {
169
- return null;
170
- }
171
- }
172
- case "imatch": {
173
- try {
174
- return new RegExp(cf.value, "i").test(fieldStr);
175
- } catch {
176
- return null;
177
- }
178
- }
179
- default:
180
- return null;
181
- }
182
- }
183
- function matchesSingle(cf, record) {
184
- const raw = matchesRaw(cf, record);
185
- if (raw === null) return false;
186
- return cf.negated ? !raw : raw;
187
- }
188
- function matchesColumnFilter(filter, record) {
189
- const set = parseFilterSet(filter);
190
- if (!set) return false;
191
- return set.every((cf) => matchesSingle(cf, record));
192
- }
193
-
194
- // src/AuraChannel.ts
195
- var AuraChannel = class {
196
- name;
197
- _projectId;
198
- _listeners = [];
199
- _subscribed = false;
200
- _sendFn = null;
201
- _subscribeCallback = null;
202
- _presenceState = {};
203
- _isPrivate = false;
204
- _broadcastAck = false;
205
- _broadcastSelf = false;
206
- _presenceKey = "";
207
- /** ID de subscription retourné par le serveur (utilisé pour le filtre RLS allowed_sub_ids) */
208
- _subscriptionId = null;
209
- /** Compteur pour générer des ref_id uniques par connexion */
210
- _refCounter = 0;
211
- /** Dernier event ID recu — utilise pour since_id au reconnect */
212
- _lastEventId = null;
213
- /** Pending ACK callbacks : ref_id → resolve */
214
- _pendingAcks = /* @__PURE__ */ new Map();
215
- constructor(name, projectId, options) {
216
- this.name = name;
217
- this._projectId = projectId;
218
- this._isPrivate = options?.private ?? false;
219
- this._broadcastAck = options?.broadcast?.ack ?? false;
220
- this._broadcastSelf = options?.broadcast?.self ?? false;
221
- this._presenceKey = options?.config?.presence?.key ?? "";
222
- }
223
- /** Génère un ref_id unique pour la corrélation request/response. */
224
- _nextRef() {
225
- return `${this.fullName}:r${++this._refCounter}`;
226
- }
227
- /** Full channel name with project prefix (for server protocol) */
228
- get fullName() {
229
- return `${this._projectId}:${this.name}`;
230
- }
231
- on(type, filter, callback) {
232
- this._listeners.push({ type, filter, callback });
233
- return this;
234
- }
235
- // ─── Subscribe ──────────────────────────────────────────────────────────
236
- /**
237
- * Subscribe to the channel. Sends the Subscribe message to the server
238
- * with the full config (postgres_changes, broadcast, presence).
239
- */
240
- subscribe(callback) {
241
- this._subscribeCallback = callback ?? null;
242
- this._subscribed = true;
243
- if (this._sendFn) {
244
- this._doSubscribe();
245
- }
246
- return this;
247
- }
248
- /** Called by RealtimeService once the WS connection is ready. */
249
- _bindSend(sendFn) {
250
- this._sendFn = sendFn;
251
- }
252
- /** Send the subscribe message to the server. */
253
- _doSubscribe() {
254
- if (!this._sendFn) return;
255
- const pgFilters = this._listeners.filter((l) => l.type === "postgres_changes").map((l) => l.filter);
256
- const msg = {
257
- type: "subscribe",
258
- channel: this.fullName,
259
- ref_id: this._nextRef(),
260
- since_id: this._lastEventId ?? void 0,
261
- config: {
262
- postgres_changes: pgFilters,
263
- broadcast: {
264
- self_broadcast: this._broadcastSelf,
265
- // ← depuis les options du channel
266
- ack: this._broadcastAck
267
- // ← depuis les options du channel
268
- },
269
- presence: { key: this._presenceKey },
270
- // ← depuis les options du channel
271
- private: this._isPrivate
272
- }
273
- };
274
- this._sendFn(JSON.stringify(msg));
275
- }
276
- /** Unsubscribe from the channel. */
277
- unsubscribe() {
278
- if (this._sendFn) {
279
- this._sendFn(JSON.stringify({ type: "unsubscribe", channel: this.fullName }));
280
- }
281
- this._subscribed = false;
282
- this._listeners.length = 0;
283
- this._presenceState = {};
284
- }
285
- // ─── Broadcast ──────────────────────────────────────────────────────────
286
- /**
287
- * Send a broadcast message to the channel.
288
- * If broadcast.ack=true, returns a Promise that resolves when the server ACKs.
289
- *
290
- * @example
291
- * ```ts
292
- * // Without ACK (fire & forget)
293
- * channel.send({ type: 'broadcast', event: 'cursor-pos', payload: { x: 100, y: 200 } })
294
- *
295
- * // With ACK (wait for server confirmation)
296
- * await channel.send({ type: 'broadcast', event: 'cursor-pos', payload: { x: 100 } })
297
- * ```
298
- */
299
- send(message) {
300
- return new Promise((resolve) => {
301
- if (!this._sendFn) {
302
- resolve("error");
303
- return;
304
- }
305
- const ref_id = message.ref_id ?? this._nextRef();
306
- if (this._broadcastAck) {
307
- const timer = setTimeout(() => {
308
- this._pendingAcks.delete(ref_id);
309
- resolve("timeout");
310
- }, 5e3);
311
- this._pendingAcks.set(ref_id, () => {
312
- clearTimeout(timer);
313
- resolve("ok");
314
- });
315
- } else {
316
- resolve("ok");
317
- }
318
- this._sendFn(
319
- JSON.stringify({
320
- type: "broadcast",
321
- channel: this.fullName,
322
- ref_id,
323
- payload: { event: message.event, ...message.payload }
324
- })
325
- );
326
- });
327
- }
328
- // ─── Presence ───────────────────────────────────────────────────────────
329
- /**
330
- * Track presence state for this client.
331
- * Returns a Promise that resolves with 'ok' once tracked (compatible Supabase).
332
- *
333
- * @example
334
- * ```ts
335
- * await channel.track({ user: 'user-1', online_at: new Date().toISOString() })
336
- * ```
337
- */
338
- async track(state) {
339
- if (!this._sendFn) return "error";
340
- this._sendFn(
341
- JSON.stringify({
342
- type: "presence_update",
343
- channel: this.fullName,
344
- meta: state
345
- })
346
- );
347
- return "ok";
348
- }
349
- /** Stop tracking presence. */
350
- async untrack() {
351
- return this.track({});
352
- }
353
- /** Get the current presence state for this channel. */
354
- presenceState() {
355
- return { ...this._presenceState };
356
- }
357
- // ─── Internal: dispatch server messages ──────────────────────────────────
358
- /** Called by RealtimeService when a server message arrives for this channel. */
359
- _onMessage(msg) {
360
- switch (msg.type) {
361
- case "subscribed": {
362
- const subMsg = msg;
363
- if (subMsg.subscription_id) this._subscriptionId = subMsg.subscription_id;
364
- this._subscribeCallback?.("SUBSCRIBED");
365
- break;
366
- }
367
- case "event": {
368
- const evtMsg = msg;
369
- if (evtMsg.id) {
370
- const event = {
371
- id: evtMsg.id,
372
- event: evtMsg.event,
373
- topic: evtMsg.topic,
374
- payload: evtMsg.payload,
375
- timestamp: evtMsg.timestamp,
376
- allowed_sub_ids: evtMsg.allowed_sub_ids
377
- };
378
- this._dispatchEvent(event);
379
- }
380
- break;
381
- }
382
- case "presence_state": {
383
- const presMsg = msg;
384
- if (presMsg.presences) {
385
- this._presenceState = {};
386
- for (const p of presMsg.presences) {
387
- const key = p.user_id || p.client_id;
388
- if (!this._presenceState[key]) this._presenceState[key] = [];
389
- this._presenceState[key].push(p);
390
- }
391
- for (const l of this._listeners) {
392
- if (l.type === "presence" && l.filter.event === "sync") {
393
- l.callback(this._presenceState);
394
- }
395
- }
396
- }
397
- break;
398
- }
399
- case "error": {
400
- const errMsg = msg;
401
- this._subscribeCallback?.("CHANNEL_ERROR", new Error(errMsg.message ?? "Unknown error"));
402
- break;
403
- }
404
- case "token_refreshed":
405
- break;
406
- case "broadcast_ack": {
407
- const ackMsg = msg;
408
- const refId = ackMsg.ref_id ?? ackMsg.message_id;
409
- if (refId) {
410
- const resolve = this._pendingAcks.get(refId);
411
- if (resolve) {
412
- this._pendingAcks.delete(refId);
413
- resolve();
414
- }
415
- }
416
- break;
417
- }
418
- }
419
- }
420
- /** Dispatch a RealtimeEvent to matching listeners. */
421
- _dispatchEvent(event) {
422
- if (!event) return;
423
- if (event.id) this._lastEventId = event.id;
424
- const allowed = event.allowed_sub_ids;
425
- if (allowed && this._subscriptionId && !allowed.includes(this._subscriptionId)) {
426
- return;
427
- }
428
- const eventType = event.event;
429
- if (eventType === "presence") {
430
- const payload = event.payload;
431
- const action = payload.action;
432
- const key = payload.user_id || payload.client_id;
433
- if (action === "join") {
434
- if (!this._presenceState[key]) this._presenceState[key] = [];
435
- if (!this._presenceState[key].some((p) => p.client_id === payload.client_id)) {
436
- const presenceInfo = {
437
- client_id: payload.client_id,
438
- user_id: payload.user_id ?? void 0,
439
- metadata: payload.metadata ?? payload.meta ?? {},
440
- joined_at: (/* @__PURE__ */ new Date()).toISOString(),
441
- last_seen: (/* @__PURE__ */ new Date()).toISOString()
442
- };
443
- this._presenceState[key].push(presenceInfo);
444
- }
445
- } else if (action === "leave") {
446
- const arr = this._presenceState[key];
447
- if (arr) {
448
- const idx = arr.findIndex((p) => p.client_id === payload.client_id);
449
- if (idx >= 0) arr.splice(idx, 1);
450
- if (arr.length === 0) delete this._presenceState[key];
451
- }
452
- } else if (action === "update") {
453
- const arr = this._presenceState[key];
454
- if (arr) {
455
- const idx = arr.findIndex((p) => p.client_id === payload.client_id);
456
- if (idx >= 0) {
457
- arr[idx].metadata = payload.metadata ?? payload.meta ?? {};
458
- arr[idx].last_seen = (/* @__PURE__ */ new Date()).toISOString();
459
- } else {
460
- const presenceInfo = {
461
- client_id: payload.client_id,
462
- user_id: payload.user_id ?? void 0,
463
- metadata: payload.metadata ?? payload.meta ?? {},
464
- joined_at: (/* @__PURE__ */ new Date()).toISOString(),
465
- last_seen: (/* @__PURE__ */ new Date()).toISOString()
466
- };
467
- this._presenceState[key].push(presenceInfo);
468
- }
469
- } else {
470
- this._presenceState[key] = [{
471
- client_id: payload.client_id,
472
- user_id: payload.user_id ?? void 0,
473
- metadata: payload.metadata ?? payload.meta ?? {},
474
- joined_at: (/* @__PURE__ */ new Date()).toISOString(),
475
- last_seen: (/* @__PURE__ */ new Date()).toISOString()
476
- }];
477
- }
478
- }
479
- }
480
- for (const listener of this._listeners) {
481
- if (listener.type === "postgres_changes") {
482
- const filter = listener.filter;
483
- if (eventType === "insert" || eventType === "update" || eventType === "delete") {
484
- const filterEvent = filter.event.toLowerCase();
485
- if (filterEvent === "*" || filterEvent === eventType) {
486
- const payload = event.payload;
487
- if (filter.schema && payload.schema !== filter.schema) continue;
488
- if (filter.table && payload.table !== filter.table) continue;
489
- if (filter.filter) {
490
- const target = eventType === "delete" ? payload.old_record : payload.record;
491
- if (target && typeof target === "object") {
492
- if (!matchesColumnFilter(filter.filter, target)) {
493
- continue;
494
- }
495
- }
496
- }
497
- listener.callback(event);
498
- }
499
- }
500
- } else if (listener.type === "broadcast") {
501
- if (eventType === "broadcast") {
502
- const filter = listener.filter;
503
- const payload = event.payload;
504
- if (!filter.event || payload.event === filter.event) {
505
- listener.callback(event);
506
- }
507
- }
508
- } else if (listener.type === "presence") {
509
- if (eventType === "presence") {
510
- const filter = listener.filter;
511
- const payload = event.payload;
512
- const action = payload.action;
513
- if (filter.event === "join" && action === "join") {
514
- listener.callback({
515
- key: payload.user_id || payload.client_id,
516
- newPresences: [payload]
517
- });
518
- } else if (filter.event === "leave" && action === "leave") {
519
- listener.callback({
520
- key: payload.user_id || payload.client_id,
521
- leftPresences: [payload]
522
- });
523
- } else if (filter.event === "sync") {
524
- listener.callback(this.presenceState());
525
- }
526
- }
527
- }
528
- }
529
- }
530
- /** Whether this channel has been subscribed. */
531
- get isSubscribed() {
532
- return this._subscribed;
533
- }
534
- /** Get listeners (for re-subscribe after reconnect). */
535
- _getListeners() {
536
- return this._listeners;
537
- }
538
- };
539
-
540
- // src/HeartbeatManager.ts
541
- var HeartbeatManager = class {
542
- _worker = null;
543
- _workerUrl = null;
544
- _interval = null;
545
- _sendFn = null;
546
- start(sendPing, intervalMs = 25e3) {
547
- this.stop();
548
- this._sendFn = sendPing;
549
- if (typeof Worker !== "undefined" && typeof URL !== "undefined" && typeof URL.createObjectURL === "function") {
550
- try {
551
- const code = `let i=null;onmessage=(e)=>{if(e.data.type==='start'){if(i)clearInterval(i);i=setInterval(()=>postMessage('ping'),e.data.interval||25000);}else if(e.data.type==='stop'){if(i){clearInterval(i);i=null;}}};`;
552
- const blob = new Blob([code], { type: "application/javascript" });
553
- this._workerUrl = URL.createObjectURL(blob);
554
- this._worker = new Worker(this._workerUrl);
555
- this._worker.onmessage = () => {
556
- this._sendFn?.();
557
- };
558
- this._worker.postMessage({ type: "start", interval: intervalMs });
559
- return;
560
- } catch {
561
- this._worker = null;
562
- if (this._workerUrl) {
563
- try {
564
- URL.revokeObjectURL(this._workerUrl);
565
- } catch {
566
- }
567
- this._workerUrl = null;
568
- }
569
- }
570
- }
571
- this._interval = setInterval(() => {
572
- this._sendFn?.();
573
- }, intervalMs);
574
- }
575
- stop() {
576
- if (this._worker) {
577
- try {
578
- this._worker.postMessage({ type: "stop" });
579
- this._worker.terminate();
580
- } catch {
581
- }
582
- this._worker = null;
583
- }
584
- if (this._workerUrl) {
585
- try {
586
- URL.revokeObjectURL(this._workerUrl);
587
- } catch {
588
- }
589
- this._workerUrl = null;
590
- }
591
- if (this._interval) {
592
- clearInterval(this._interval);
593
- this._interval = null;
594
- }
595
- this._sendFn = null;
596
- }
597
- get isActive() {
598
- return this._worker !== null || this._interval !== null;
599
- }
600
- };
601
-
602
- // src/RealtimeService.ts
603
- var RealtimeService = class _RealtimeService {
604
- client;
605
- _ws = null;
606
- _channels = /* @__PURE__ */ new Map();
607
- _state = "disconnected";
608
- _stateListeners = /* @__PURE__ */ new Set();
609
- // ─── Reconnection state ──────────────────────────────────────────────
610
- _autoReconnect = true;
611
- _reconnectAttempts = 0;
612
- _maxReconnectAttempts = Infinity;
613
- _reconnectTimer = null;
614
- _intentionalClose = false;
615
- _heartbeat = new HeartbeatManager();
616
- _tokenRefreshTimer = null;
617
- /** Dernier access_token propagé au serveur — évite les pushs redondants (propagation différentielle). */
618
- _lastSentToken = null;
619
- /** Backoff delays in ms: 1s, 2s, 4s, 8s, 16s, 30s (cap) */
620
- static BACKOFF_MS = [1e3, 2e3, 4e3, 8e3, 16e3, 3e4];
621
- constructor(client) {
622
- this.client = client;
623
- }
624
- /** Current connection state. */
625
- get connectionState() {
626
- return this._state;
627
- }
628
- /** Listen for connection state changes. */
629
- onStateChange(callback) {
630
- this._stateListeners.add(callback);
631
- return () => this._stateListeners.delete(callback);
632
- }
633
- _setState(state) {
634
- this._state = state;
635
- for (const cb of this._stateListeners) {
636
- try {
637
- cb(state);
638
- } catch {
639
- }
640
- }
641
- }
642
- // ─── WebSocket URL ──────────────────────────────────────────────────────
643
- get _wsUrl() {
644
- const base = this.client.baseUrl.replace(/^http/, "ws");
645
- return `${base}/v1/realtime/ws`;
646
- }
647
- // ─── Connection management ──────────────────────────────────────────────
648
- /** Ensure the WebSocket connection is open. */
649
- connect() {
650
- if (this._ws && (this._ws.readyState === WebSocket.OPEN || this._ws.readyState === WebSocket.CONNECTING)) {
651
- return;
652
- }
653
- this._intentionalClose = false;
654
- this._setState("connecting");
655
- const token = this.client.authStore.token;
656
- const params = new URLSearchParams();
657
- if (token) params.set("token", token);
658
- if (this.client.apiKey) params.set("apikey", this.client.apiKey);
659
- const url = `${this._wsUrl}?${params.toString()}`;
660
- const ws = new WebSocket(url);
661
- this._ws = ws;
662
- ws.onopen = () => {
663
- if (ws !== this._ws) {
664
- try {
665
- ws.close();
666
- } catch {
667
- }
668
- return;
669
- }
670
- this._reconnectAttempts = 0;
671
- this._setState("connected");
672
- this._heartbeat.start(() => this._send(JSON.stringify({ type: "ping" })), 25e3);
673
- this._scheduleTokenRefresh();
674
- for (const channel of this._channels.values()) {
675
- channel._bindSend((data) => this._send(data));
676
- if (channel.isSubscribed) {
677
- channel._doSubscribe();
678
- }
679
- }
680
- };
681
- ws.onmessage = (evt) => {
682
- if (ws !== this._ws) return;
683
- try {
684
- const raw = typeof evt.data === "string" ? evt.data : "";
685
- const msg = JSON.parse(raw);
686
- this._dispatch(msg);
687
- } catch (e) {
688
- if (typeof console !== "undefined") {
689
- console.warn("[aura-realtime] Failed to parse WS message:", evt.data, e);
690
- }
691
- }
692
- };
693
- ws.onclose = () => {
694
- if (ws !== this._ws) return;
695
- this._ws = null;
696
- this._lastSentToken = null;
697
- this._heartbeat.stop();
698
- if (this._intentionalClose) {
699
- this._setState("disconnected");
700
- this._intentionalClose = false;
701
- } else if (this._autoReconnect) {
702
- this._scheduleReconnect();
703
- } else {
704
- this._setState("disconnected");
705
- }
706
- };
707
- ws.onerror = (evt) => {
708
- if (ws !== this._ws) return;
709
- if (typeof console !== "undefined") {
710
- console.warn("[aura-realtime] WebSocket error", evt);
711
- }
712
- };
713
- }
714
- /** Send raw data through the WebSocket. */
715
- _send(data) {
716
- if (this._ws && this._ws.readyState === WebSocket.OPEN) {
717
- this._ws.send(data);
718
- }
719
- }
720
- /** Refresh the JWT token on an existing connection (no disconnect). */
721
- refreshToken(token) {
722
- if (token === this._lastSentToken) {
723
- this._scheduleTokenRefresh();
724
- return;
725
- }
726
- this._lastSentToken = token;
727
- this._send(JSON.stringify({ type: "access_token", token }));
728
- this._scheduleTokenRefresh();
729
- }
730
- /**
731
- * Définit/rafraîchit explicitement le token utilisé pour l'autorisation des
732
- * canaux privés et broadcast (parité `@supabase/realtime-js` `setAuth`).
733
- *
734
- * - Avec `token` : utilise ce token. Sinon, reprend `client.authStore.token`.
735
- * - Propage via le pipeline existant `refreshToken` (push
736
- * `{ type:'access_token', token }` sur une connexion ouverte, dédupliqué via
737
- * `_lastSentToken`). N'ouvre ni ne ferme aucune connexion WS.
738
- * - Hors-ligne : `connect()` lit `client.authStore.token` au moment de l'open,
739
- * donc `setAuth()` doit être appelé avec un token présent dans le store (ou
740
- * après authentification) pour prendre effet sur une future connexion.
741
- *
742
- * À appeler AVANT de s'abonner à un canal privé (`channel(name,{private:true})`).
743
- *
744
- * @example
745
- * ```ts
746
- * aura.realtime.setAuth(session.access_token)
747
- * const ch = aura.realtime.channel('secret', { private: true }).subscribe()
748
- * ```
749
- */
750
- setAuth(token) {
751
- const resolved = token ?? this.client.authStore.token;
752
- if (resolved == null) return;
753
- this.refreshToken(resolved);
754
- }
755
- /**
756
- * Envoie un broadcast par HTTP (REST), sans connexion WebSocket ouverte
757
- * (parité `@supabase/realtime-js`). Utile côté serveur/edge.
758
- *
759
- * POST `/v1/realtime/{projectId}/broadcast` avec le contrat du handler backend
760
- * (`broadcast.rs`) : `{ channel, payload }`, `channel` préfixé par le projet,
761
- * `event` replié dans `payload` (aligné sur le broadcast WS).
762
- *
763
- * @param channel Nom du canal (préfixé projet automatiquement si absent).
764
- * @param event Nom de l'événement broadcast.
765
- * @param payload Données de l'événement.
766
- * @returns `AuraResponse<null>` — `error` non nul en cas de 4xx/rate-limit.
767
- *
768
- * @example
769
- * ```ts
770
- * await aura.realtime.httpBroadcast('room-1', 'cursor', { x: 10, y: 20 })
771
- * ```
772
- */
773
- httpBroadcast(channel, event, payload = {}) {
774
- const prefix = `${this.client.projectId}:`;
775
- const fullChannel = channel.startsWith(prefix) ? channel : `${prefix}${channel}`;
776
- const body = {
777
- channel: fullChannel,
778
- payload: { event, ...payload }
779
- };
780
- return core.fetchWithAuth(
781
- `${this.client.baseUrl}/v1/realtime/${this.client.projectId}/broadcast`,
782
- { method: "POST", body },
783
- this.client
784
- );
785
- }
786
- /**
787
- * Schedule proactive token refresh at 80% of the JWT TTL.
788
- * Prevents token expiration during an active WebSocket session.
789
- */
790
- _scheduleTokenRefresh() {
791
- if (this._tokenRefreshTimer) {
792
- clearTimeout(this._tokenRefreshTimer);
793
- this._tokenRefreshTimer = null;
794
- }
795
- const token = this.client.authStore.token;
796
- if (!token) return;
797
- try {
798
- const payload = JSON.parse(atob(token.split(".")[1]));
799
- const exp = payload.exp * 1e3;
800
- const ttl = exp - Date.now();
801
- if (ttl <= 0) return;
802
- const refreshIn = ttl * 0.8;
803
- this._tokenRefreshTimer = setTimeout(async () => {
804
- this._tokenRefreshTimer = null;
805
- try {
806
- const res = await this.client.auth.refreshSession();
807
- if (res.data) {
808
- this.refreshToken(res.data.access_token);
809
- }
810
- } catch {
811
- }
812
- }, refreshIn);
813
- } catch {
814
- }
815
- }
816
- /** Schedule a reconnection attempt with exponential backoff + jitter. */
817
- _scheduleReconnect() {
818
- if (this._reconnectTimer) {
819
- clearTimeout(this._reconnectTimer);
820
- this._reconnectTimer = null;
821
- }
822
- if (this._reconnectAttempts >= this._maxReconnectAttempts) {
823
- this._setState("disconnected");
824
- return;
825
- }
826
- this._reconnectAttempts++;
827
- this._setState("reconnecting");
828
- const idx = Math.min(this._reconnectAttempts - 1, _RealtimeService.BACKOFF_MS.length - 1);
829
- const baseDelay = _RealtimeService.BACKOFF_MS[idx];
830
- const jitter = Math.random() * baseDelay * 0.25;
831
- const delay = baseDelay + jitter;
832
- this._reconnectTimer = setTimeout(() => {
833
- this._reconnectTimer = null;
834
- this.connect();
835
- }, delay);
836
- }
837
- /** Enable/disable auto-reconnect (enabled by default). */
838
- setAutoReconnect(enabled, maxAttempts) {
839
- this._autoReconnect = enabled;
840
- if (maxAttempts !== void 0) this._maxReconnectAttempts = maxAttempts;
841
- }
842
- /** Disconnect the WebSocket and clean up all channels. */
843
- disconnect() {
844
- this._intentionalClose = true;
845
- this._heartbeat.stop();
846
- if (this._tokenRefreshTimer) {
847
- clearTimeout(this._tokenRefreshTimer);
848
- this._tokenRefreshTimer = null;
849
- }
850
- if (this._reconnectTimer) {
851
- clearTimeout(this._reconnectTimer);
852
- this._reconnectTimer = null;
853
- }
854
- this._reconnectAttempts = 0;
855
- for (const channel of this._channels.values()) {
856
- channel.unsubscribe();
857
- }
858
- this._channels.clear();
859
- if (this._ws) {
860
- this._ws.close();
861
- this._ws = null;
862
- }
863
- this._setState("disconnected");
864
- this._lastSentToken = null;
865
- }
866
- // ─── Channel factory ────────────────────────────────────────────────────
867
- /**
868
- * Create or retrieve a channel by name.
869
- * Returns an `AuraChannel` with chainable `.on()` / `.subscribe()` API.
870
- *
871
- * @example
872
- * ```ts
873
- * const channel = aura.realtime.channel('room-1')
874
- * ```
875
- */
876
- channel(name, options) {
877
- const existing = this._channels.get(name);
878
- if (existing) return existing;
879
- const ch = new AuraChannel(name, this.client.projectId, options);
880
- this._channels.set(name, ch);
881
- this.connect();
882
- if (this._ws && this._ws.readyState === WebSocket.OPEN) {
883
- ch._bindSend((data) => this._send(data));
884
- }
885
- return ch;
886
- }
887
- /** Remove a channel. */
888
- removeChannel(name) {
889
- const ch = this._channels.get(name);
890
- if (ch) {
891
- ch.unsubscribe();
892
- this._channels.delete(name);
893
- }
894
- }
895
- /** List active channels. */
896
- getChannels() {
897
- return Array.from(this._channels.values());
898
- }
899
- /** Remove all channels and subscriptions. */
900
- removeAllChannels() {
901
- for (const ch of this._channels.values()) {
902
- ch.unsubscribe();
903
- }
904
- this._channels.clear();
905
- }
906
- // ─── Message dispatch ───────────────────────────────────────────────────
907
- /** Route incoming server messages to the correct channel. */
908
- _dispatch(msg) {
909
- const channelFull = "channel" in msg ? msg.channel : "topic" in msg ? msg.topic : void 0;
910
- if (channelFull) {
911
- const prefix = `${this.client.projectId}:`;
912
- const name = channelFull.startsWith(prefix) ? channelFull.slice(prefix.length) : channelFull;
913
- const ch = this._channels.get(name);
914
- if (ch) {
915
- ch._onMessage(msg);
916
- return;
917
- }
918
- for (const [, channel] of this._channels) {
919
- if (channel.fullName === channelFull || channelFull.startsWith(channel.fullName + ":")) {
920
- channel._onMessage(msg);
921
- return;
922
- }
923
- }
924
- }
925
- if (msg.type === "token_refreshed") {
926
- return;
927
- }
928
- if (msg.type === "pong") {
929
- return;
930
- }
931
- if (msg.type === "broadcast_ack") {
932
- const ack = msg;
933
- const refId = ack.ref_id ?? ack.message_id;
934
- if (refId) {
935
- const marker = refId.lastIndexOf(":r");
936
- if (marker > 0) {
937
- const fullName = refId.slice(0, marker);
938
- for (const ch of this._channels.values()) {
939
- if (ch.fullName === fullName) {
940
- ch._onMessage(msg);
941
- return;
942
- }
943
- }
944
- }
945
- }
946
- for (const ch of this._channels.values()) {
947
- ch._onMessage(msg);
948
- }
949
- return;
950
- }
951
- if (msg.type === "error") {
952
- for (const ch of this._channels.values()) {
953
- ch._onMessage(msg);
954
- }
955
- }
956
- }
957
- // ─── Backward compatibility ─────────────────────────────────────────────
958
- /**
959
- * Simple callback-based subscription (legacy API).
960
- * Prefer using `.channel().on().subscribe()` instead.
961
- *
962
- * @deprecated Use `channel().on().subscribe()` instead.
963
- */
964
- on(channelName, callback) {
965
- this.connect();
966
- const ch = this.channel(channelName);
967
- ch.on("postgres_changes", { event: "*" }, callback);
968
- ch.subscribe();
969
- return {
970
- unsubscribe: () => this.removeChannel(channelName)
971
- };
972
- }
973
- };
974
-
975
- exports.AuraChannel = AuraChannel;
976
- exports.HeartbeatManager = HeartbeatManager;
977
- exports.RealtimeService = RealtimeService;