@backendrelay/core 1.1.0 → 2.0.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 (598) hide show
  1. package/dist/standalone/index.js +1 -1
  2. package/dist/standalone/index.umd.cjs +1 -1
  3. package/node_modules/@backendrelay/admin/dist/commonjs/__types__/typeUtils.d.ts +20 -0
  4. package/node_modules/@backendrelay/admin/dist/commonjs/__types__/typeUtils.d.ts.map +1 -0
  5. package/node_modules/@backendrelay/admin/dist/commonjs/__types__/typeUtils.js +5 -0
  6. package/node_modules/@backendrelay/admin/dist/commonjs/__types__/typeUtils.js.map +1 -0
  7. package/node_modules/@backendrelay/admin/dist/commonjs/__types__/typesTests.d.ts +2 -0
  8. package/node_modules/@backendrelay/admin/dist/commonjs/__types__/typesTests.d.ts.map +1 -0
  9. package/node_modules/@backendrelay/admin/dist/commonjs/__types__/typesTests.js +88 -0
  10. package/node_modules/@backendrelay/admin/dist/commonjs/__types__/typesTests.js.map +1 -0
  11. package/node_modules/@backendrelay/admin/dist/commonjs/byop.live.e2e.test.d.ts +2 -0
  12. package/node_modules/@backendrelay/admin/dist/commonjs/byop.live.e2e.test.d.ts.map +1 -0
  13. package/node_modules/@backendrelay/admin/dist/commonjs/byop.live.e2e.test.js +131 -0
  14. package/node_modules/@backendrelay/admin/dist/commonjs/byop.live.e2e.test.js.map +1 -0
  15. package/node_modules/@backendrelay/admin/dist/commonjs/config.test.d.ts +2 -0
  16. package/node_modules/@backendrelay/admin/dist/commonjs/config.test.d.ts.map +1 -0
  17. package/node_modules/@backendrelay/admin/dist/commonjs/config.test.js +65 -0
  18. package/node_modules/@backendrelay/admin/dist/commonjs/config.test.js.map +1 -0
  19. package/node_modules/@backendrelay/admin/dist/commonjs/index.d.ts +725 -0
  20. package/node_modules/@backendrelay/admin/dist/commonjs/index.d.ts.map +1 -0
  21. package/node_modules/@backendrelay/admin/dist/commonjs/index.js +1159 -0
  22. package/node_modules/@backendrelay/admin/dist/commonjs/index.js.map +1 -0
  23. package/node_modules/@backendrelay/admin/dist/commonjs/live.e2e.test.d.ts +2 -0
  24. package/node_modules/@backendrelay/admin/dist/commonjs/live.e2e.test.d.ts.map +1 -0
  25. package/node_modules/@backendrelay/admin/dist/commonjs/live.e2e.test.js +91 -0
  26. package/node_modules/@backendrelay/admin/dist/commonjs/live.e2e.test.js.map +1 -0
  27. package/node_modules/@backendrelay/admin/dist/commonjs/package.json +3 -0
  28. package/node_modules/@backendrelay/admin/dist/commonjs/polyfill.d.ts +17 -0
  29. package/node_modules/@backendrelay/admin/dist/commonjs/polyfill.d.ts.map +1 -0
  30. package/node_modules/@backendrelay/admin/dist/commonjs/polyfill.js +26 -0
  31. package/node_modules/@backendrelay/admin/dist/commonjs/polyfill.js.map +1 -0
  32. package/node_modules/@backendrelay/admin/dist/commonjs/removed-features.test.d.ts +2 -0
  33. package/node_modules/@backendrelay/admin/dist/commonjs/removed-features.test.d.ts.map +1 -0
  34. package/node_modules/@backendrelay/admin/dist/commonjs/removed-features.test.js +50 -0
  35. package/node_modules/@backendrelay/admin/dist/commonjs/removed-features.test.js.map +1 -0
  36. package/node_modules/@backendrelay/admin/dist/commonjs/storage-upload.test.d.ts +2 -0
  37. package/node_modules/@backendrelay/admin/dist/commonjs/storage-upload.test.d.ts.map +1 -0
  38. package/node_modules/@backendrelay/admin/dist/commonjs/storage-upload.test.js +33 -0
  39. package/node_modules/@backendrelay/admin/dist/commonjs/storage-upload.test.js.map +1 -0
  40. package/node_modules/@backendrelay/admin/dist/commonjs/subscribe.d.ts +39 -0
  41. package/node_modules/@backendrelay/admin/dist/commonjs/subscribe.d.ts.map +1 -0
  42. package/node_modules/@backendrelay/admin/dist/commonjs/subscribe.js +306 -0
  43. package/node_modules/@backendrelay/admin/dist/commonjs/subscribe.js.map +1 -0
  44. package/node_modules/@backendrelay/admin/dist/commonjs/version.d.ts +3 -0
  45. package/node_modules/@backendrelay/admin/dist/commonjs/version.d.ts.map +1 -0
  46. package/node_modules/@backendrelay/admin/dist/commonjs/version.js +5 -0
  47. package/node_modules/@backendrelay/admin/dist/commonjs/version.js.map +1 -0
  48. package/node_modules/@backendrelay/admin/dist/esm/__types__/typeUtils.d.ts +20 -0
  49. package/node_modules/@backendrelay/admin/dist/esm/__types__/typeUtils.d.ts.map +1 -0
  50. package/node_modules/@backendrelay/admin/dist/esm/__types__/typeUtils.js +4 -0
  51. package/node_modules/@backendrelay/admin/dist/esm/__types__/typeUtils.js.map +1 -0
  52. package/node_modules/@backendrelay/admin/dist/esm/__types__/typesTests.d.ts +2 -0
  53. package/node_modules/@backendrelay/admin/dist/esm/__types__/typesTests.d.ts.map +1 -0
  54. package/node_modules/@backendrelay/admin/dist/esm/__types__/typesTests.js +86 -0
  55. package/node_modules/@backendrelay/admin/dist/esm/__types__/typesTests.js.map +1 -0
  56. package/node_modules/@backendrelay/admin/dist/esm/byop.live.e2e.test.d.ts +2 -0
  57. package/node_modules/@backendrelay/admin/dist/esm/byop.live.e2e.test.d.ts.map +1 -0
  58. package/node_modules/@backendrelay/admin/dist/esm/byop.live.e2e.test.js +129 -0
  59. package/node_modules/@backendrelay/admin/dist/esm/byop.live.e2e.test.js.map +1 -0
  60. package/node_modules/@backendrelay/admin/dist/esm/config.test.d.ts +2 -0
  61. package/node_modules/@backendrelay/admin/dist/esm/config.test.d.ts.map +1 -0
  62. package/node_modules/@backendrelay/admin/dist/esm/config.test.js +63 -0
  63. package/node_modules/@backendrelay/admin/dist/esm/config.test.js.map +1 -0
  64. package/node_modules/@backendrelay/admin/dist/esm/index.d.ts +725 -0
  65. package/node_modules/@backendrelay/admin/dist/esm/index.d.ts.map +1 -0
  66. package/node_modules/@backendrelay/admin/dist/esm/index.js +1146 -0
  67. package/node_modules/@backendrelay/admin/dist/esm/index.js.map +1 -0
  68. package/node_modules/@backendrelay/admin/dist/esm/live.e2e.test.d.ts +2 -0
  69. package/node_modules/@backendrelay/admin/dist/esm/live.e2e.test.d.ts.map +1 -0
  70. package/node_modules/@backendrelay/admin/dist/esm/live.e2e.test.js +89 -0
  71. package/node_modules/@backendrelay/admin/dist/esm/live.e2e.test.js.map +1 -0
  72. package/node_modules/@backendrelay/admin/dist/esm/package.json +3 -0
  73. package/node_modules/@backendrelay/admin/dist/esm/polyfill.d.ts +17 -0
  74. package/node_modules/@backendrelay/admin/dist/esm/polyfill.d.ts.map +1 -0
  75. package/node_modules/@backendrelay/admin/dist/esm/polyfill.js +22 -0
  76. package/node_modules/@backendrelay/admin/dist/esm/polyfill.js.map +1 -0
  77. package/node_modules/@backendrelay/admin/dist/esm/removed-features.test.d.ts +2 -0
  78. package/node_modules/@backendrelay/admin/dist/esm/removed-features.test.d.ts.map +1 -0
  79. package/node_modules/@backendrelay/admin/dist/esm/removed-features.test.js +48 -0
  80. package/node_modules/@backendrelay/admin/dist/esm/removed-features.test.js.map +1 -0
  81. package/node_modules/@backendrelay/admin/dist/esm/storage-upload.test.d.ts +2 -0
  82. package/node_modules/@backendrelay/admin/dist/esm/storage-upload.test.d.ts.map +1 -0
  83. package/node_modules/@backendrelay/admin/dist/esm/storage-upload.test.js +31 -0
  84. package/node_modules/@backendrelay/admin/dist/esm/storage-upload.test.js.map +1 -0
  85. package/node_modules/@backendrelay/admin/dist/esm/subscribe.d.ts +39 -0
  86. package/node_modules/@backendrelay/admin/dist/esm/subscribe.d.ts.map +1 -0
  87. package/node_modules/@backendrelay/admin/dist/esm/subscribe.js +300 -0
  88. package/node_modules/@backendrelay/admin/dist/esm/subscribe.js.map +1 -0
  89. package/node_modules/@backendrelay/admin/dist/esm/version.d.ts +3 -0
  90. package/node_modules/@backendrelay/admin/dist/esm/version.d.ts.map +1 -0
  91. package/{src/version.ts → node_modules/@backendrelay/admin/dist/esm/version.js} +1 -1
  92. package/node_modules/@backendrelay/admin/dist/esm/version.js.map +1 -0
  93. package/node_modules/@backendrelay/admin/package.json +52 -0
  94. package/node_modules/@backendrelay/functions/README.md +131 -0
  95. package/node_modules/@backendrelay/functions/dist/commonjs/__types__/typeUtils.d.ts +3 -0
  96. package/node_modules/@backendrelay/functions/dist/commonjs/__types__/typeUtils.d.ts.map +1 -0
  97. package/node_modules/@backendrelay/functions/dist/commonjs/__types__/typeUtils.js +3 -0
  98. package/node_modules/@backendrelay/functions/dist/commonjs/__types__/typeUtils.js.map +1 -0
  99. package/node_modules/@backendrelay/functions/dist/commonjs/__types__/typesTests.d.ts +2 -0
  100. package/node_modules/@backendrelay/functions/dist/commonjs/__types__/typesTests.d.ts.map +1 -0
  101. package/node_modules/@backendrelay/functions/dist/commonjs/__types__/typesTests.js +51 -0
  102. package/node_modules/@backendrelay/functions/dist/commonjs/__types__/typesTests.js.map +1 -0
  103. package/node_modules/@backendrelay/functions/dist/commonjs/index.d.ts +230 -0
  104. package/node_modules/@backendrelay/functions/dist/commonjs/index.d.ts.map +1 -0
  105. package/node_modules/@backendrelay/functions/dist/commonjs/index.js +415 -0
  106. package/node_modules/@backendrelay/functions/dist/commonjs/index.js.map +1 -0
  107. package/node_modules/@backendrelay/functions/dist/commonjs/package.json +3 -0
  108. package/node_modules/@backendrelay/functions/dist/esm/__types__/typeUtils.d.ts +3 -0
  109. package/node_modules/@backendrelay/functions/dist/esm/__types__/typeUtils.d.ts.map +1 -0
  110. package/node_modules/@backendrelay/functions/dist/esm/__types__/typeUtils.js +2 -0
  111. package/node_modules/@backendrelay/functions/dist/esm/__types__/typeUtils.js.map +1 -0
  112. package/node_modules/@backendrelay/functions/dist/esm/__types__/typesTests.d.ts +2 -0
  113. package/node_modules/@backendrelay/functions/dist/esm/__types__/typesTests.d.ts.map +1 -0
  114. package/node_modules/@backendrelay/functions/dist/esm/__types__/typesTests.js +49 -0
  115. package/node_modules/@backendrelay/functions/dist/esm/__types__/typesTests.js.map +1 -0
  116. package/node_modules/@backendrelay/functions/dist/esm/index.d.ts +230 -0
  117. package/node_modules/@backendrelay/functions/dist/esm/index.d.ts.map +1 -0
  118. package/node_modules/@backendrelay/functions/dist/esm/index.js +403 -0
  119. package/node_modules/@backendrelay/functions/dist/esm/index.js.map +1 -0
  120. package/node_modules/@backendrelay/functions/dist/esm/package.json +3 -0
  121. package/node_modules/@backendrelay/functions/package.json +49 -0
  122. package/node_modules/@backendrelay/hatchet/dist/commonjs/index.d.ts +43 -0
  123. package/node_modules/@backendrelay/hatchet/dist/commonjs/index.d.ts.map +1 -0
  124. package/node_modules/@backendrelay/hatchet/dist/commonjs/index.js +63 -0
  125. package/node_modules/@backendrelay/hatchet/dist/commonjs/index.js.map +1 -0
  126. package/node_modules/@backendrelay/hatchet/dist/commonjs/package.json +3 -0
  127. package/node_modules/@backendrelay/hatchet/dist/esm/index.d.ts +43 -0
  128. package/node_modules/@backendrelay/hatchet/dist/esm/index.d.ts.map +1 -0
  129. package/node_modules/@backendrelay/hatchet/dist/esm/index.js +59 -0
  130. package/node_modules/@backendrelay/hatchet/dist/esm/index.js.map +1 -0
  131. package/node_modules/@backendrelay/hatchet/dist/esm/package.json +3 -0
  132. package/node_modules/@backendrelay/hatchet/package.json +46 -0
  133. package/node_modules/@backendrelay/platform/dist/commonjs/ProgressPromise.d.ts +18 -0
  134. package/node_modules/@backendrelay/platform/dist/commonjs/ProgressPromise.d.ts.map +1 -0
  135. package/node_modules/@backendrelay/platform/dist/commonjs/ProgressPromise.js +77 -0
  136. package/node_modules/@backendrelay/platform/dist/commonjs/ProgressPromise.js.map +1 -0
  137. package/node_modules/@backendrelay/platform/dist/commonjs/api/apps.d.ts +99 -0
  138. package/node_modules/@backendrelay/platform/dist/commonjs/api/apps.d.ts.map +1 -0
  139. package/node_modules/@backendrelay/platform/dist/commonjs/api/apps.js +177 -0
  140. package/node_modules/@backendrelay/platform/dist/commonjs/api/apps.js.map +1 -0
  141. package/node_modules/@backendrelay/platform/dist/commonjs/api/auth.d.ts +7 -0
  142. package/node_modules/@backendrelay/platform/dist/commonjs/api/auth.d.ts.map +1 -0
  143. package/node_modules/@backendrelay/platform/dist/commonjs/api/auth.js +15 -0
  144. package/node_modules/@backendrelay/platform/dist/commonjs/api/auth.js.map +1 -0
  145. package/node_modules/@backendrelay/platform/dist/commonjs/api/http.d.ts +3 -0
  146. package/node_modules/@backendrelay/platform/dist/commonjs/api/http.d.ts.map +1 -0
  147. package/node_modules/@backendrelay/platform/dist/commonjs/api/http.js +46 -0
  148. package/node_modules/@backendrelay/platform/dist/commonjs/api/http.js.map +1 -0
  149. package/node_modules/@backendrelay/platform/dist/commonjs/api/perms.d.ts +13 -0
  150. package/node_modules/@backendrelay/platform/dist/commonjs/api/perms.d.ts.map +1 -0
  151. package/node_modules/@backendrelay/platform/dist/commonjs/api/perms.js +25 -0
  152. package/node_modules/@backendrelay/platform/dist/commonjs/api/perms.js.map +1 -0
  153. package/node_modules/@backendrelay/platform/dist/commonjs/api/platform-api.d.ts +285 -0
  154. package/node_modules/@backendrelay/platform/dist/commonjs/api/platform-api.d.ts.map +1 -0
  155. package/node_modules/@backendrelay/platform/dist/commonjs/api/platform-api.js +426 -0
  156. package/node_modules/@backendrelay/platform/dist/commonjs/api/platform-api.js.map +1 -0
  157. package/node_modules/@backendrelay/platform/dist/commonjs/api/schema-coerce.d.ts +24 -0
  158. package/node_modules/@backendrelay/platform/dist/commonjs/api/schema-coerce.d.ts.map +1 -0
  159. package/node_modules/@backendrelay/platform/dist/commonjs/api/schema-coerce.js +108 -0
  160. package/node_modules/@backendrelay/platform/dist/commonjs/api/schema-coerce.js.map +1 -0
  161. package/node_modules/@backendrelay/platform/dist/commonjs/api/schema.d.ts +188 -0
  162. package/node_modules/@backendrelay/platform/dist/commonjs/api/schema.d.ts.map +1 -0
  163. package/node_modules/@backendrelay/platform/dist/commonjs/api/schema.js +412 -0
  164. package/node_modules/@backendrelay/platform/dist/commonjs/api/schema.js.map +1 -0
  165. package/node_modules/@backendrelay/platform/dist/commonjs/api.d.ts +9 -0
  166. package/node_modules/@backendrelay/platform/dist/commonjs/api.d.ts.map +1 -0
  167. package/node_modules/@backendrelay/platform/dist/commonjs/api.js +12 -0
  168. package/node_modules/@backendrelay/platform/dist/commonjs/api.js.map +1 -0
  169. package/node_modules/@backendrelay/platform/dist/commonjs/backupDownload.d.ts +89 -0
  170. package/node_modules/@backendrelay/platform/dist/commonjs/backupDownload.d.ts.map +1 -0
  171. package/node_modules/@backendrelay/platform/dist/commonjs/backupDownload.js +357 -0
  172. package/node_modules/@backendrelay/platform/dist/commonjs/backupDownload.js.map +1 -0
  173. package/node_modules/@backendrelay/platform/dist/commonjs/backups.d.ts +146 -0
  174. package/node_modules/@backendrelay/platform/dist/commonjs/backups.d.ts.map +1 -0
  175. package/node_modules/@backendrelay/platform/dist/commonjs/backups.js +251 -0
  176. package/node_modules/@backendrelay/platform/dist/commonjs/backups.js.map +1 -0
  177. package/node_modules/@backendrelay/platform/dist/commonjs/clerk.d.ts +2 -0
  178. package/node_modules/@backendrelay/platform/dist/commonjs/clerk.d.ts.map +1 -0
  179. package/node_modules/@backendrelay/platform/dist/commonjs/clerk.js +29 -0
  180. package/node_modules/@backendrelay/platform/dist/commonjs/clerk.js.map +1 -0
  181. package/node_modules/@backendrelay/platform/dist/commonjs/consts.d.ts +11 -0
  182. package/node_modules/@backendrelay/platform/dist/commonjs/consts.d.ts.map +1 -0
  183. package/node_modules/@backendrelay/platform/dist/commonjs/consts.js +17 -0
  184. package/node_modules/@backendrelay/platform/dist/commonjs/consts.js.map +1 -0
  185. package/node_modules/@backendrelay/platform/dist/commonjs/crypto.d.ts +4 -0
  186. package/node_modules/@backendrelay/platform/dist/commonjs/crypto.d.ts.map +1 -0
  187. package/node_modules/@backendrelay/platform/dist/commonjs/crypto.js +26 -0
  188. package/node_modules/@backendrelay/platform/dist/commonjs/crypto.js.map +1 -0
  189. package/node_modules/@backendrelay/platform/dist/commonjs/index.d.ts +19 -0
  190. package/node_modules/@backendrelay/platform/dist/commonjs/index.d.ts.map +1 -0
  191. package/node_modules/@backendrelay/platform/dist/commonjs/index.js +76 -0
  192. package/node_modules/@backendrelay/platform/dist/commonjs/index.js.map +1 -0
  193. package/node_modules/@backendrelay/platform/dist/commonjs/migrationUtils.d.ts +4 -0
  194. package/node_modules/@backendrelay/platform/dist/commonjs/migrationUtils.d.ts.map +1 -0
  195. package/node_modules/@backendrelay/platform/dist/commonjs/migrationUtils.js +52 -0
  196. package/node_modules/@backendrelay/platform/dist/commonjs/migrationUtils.js.map +1 -0
  197. package/node_modules/@backendrelay/platform/dist/commonjs/migrations.d.ts +99 -0
  198. package/node_modules/@backendrelay/platform/dist/commonjs/migrations.d.ts.map +1 -0
  199. package/node_modules/@backendrelay/platform/dist/commonjs/migrations.js +597 -0
  200. package/node_modules/@backendrelay/platform/dist/commonjs/migrations.js.map +1 -0
  201. package/node_modules/@backendrelay/platform/dist/commonjs/oauth.d.ts +98 -0
  202. package/node_modules/@backendrelay/platform/dist/commonjs/oauth.d.ts.map +1 -0
  203. package/node_modules/@backendrelay/platform/dist/commonjs/oauth.js +275 -0
  204. package/node_modules/@backendrelay/platform/dist/commonjs/oauth.js.map +1 -0
  205. package/node_modules/@backendrelay/platform/dist/commonjs/oauthCommon.d.ts +12 -0
  206. package/node_modules/@backendrelay/platform/dist/commonjs/oauthCommon.d.ts.map +1 -0
  207. package/node_modules/@backendrelay/platform/dist/commonjs/oauthCommon.js +26 -0
  208. package/node_modules/@backendrelay/platform/dist/commonjs/oauthCommon.js.map +1 -0
  209. package/node_modules/@backendrelay/platform/dist/commonjs/package.json +3 -0
  210. package/node_modules/@backendrelay/platform/dist/commonjs/perms.d.ts +3 -0
  211. package/node_modules/@backendrelay/platform/dist/commonjs/perms.d.ts.map +1 -0
  212. package/node_modules/@backendrelay/platform/dist/commonjs/perms.js +66 -0
  213. package/node_modules/@backendrelay/platform/dist/commonjs/perms.js.map +1 -0
  214. package/node_modules/@backendrelay/platform/dist/commonjs/privateFields.d.ts +13 -0
  215. package/node_modules/@backendrelay/platform/dist/commonjs/privateFields.d.ts.map +1 -0
  216. package/node_modules/@backendrelay/platform/dist/commonjs/privateFields.js +31 -0
  217. package/node_modules/@backendrelay/platform/dist/commonjs/privateFields.js.map +1 -0
  218. package/node_modules/@backendrelay/platform/dist/commonjs/relationships.d.ts +7 -0
  219. package/node_modules/@backendrelay/platform/dist/commonjs/relationships.d.ts.map +1 -0
  220. package/node_modules/@backendrelay/platform/dist/commonjs/relationships.js +46 -0
  221. package/node_modules/@backendrelay/platform/dist/commonjs/relationships.js.map +1 -0
  222. package/node_modules/@backendrelay/platform/dist/commonjs/schema.d.ts +161 -0
  223. package/node_modules/@backendrelay/platform/dist/commonjs/schema.d.ts.map +1 -0
  224. package/node_modules/@backendrelay/platform/dist/commonjs/schema.js +174 -0
  225. package/node_modules/@backendrelay/platform/dist/commonjs/schema.js.map +1 -0
  226. package/node_modules/@backendrelay/platform/dist/commonjs/serverOAuth.d.ts +25 -0
  227. package/node_modules/@backendrelay/platform/dist/commonjs/serverOAuth.d.ts.map +1 -0
  228. package/node_modules/@backendrelay/platform/dist/commonjs/serverOAuth.js +68 -0
  229. package/node_modules/@backendrelay/platform/dist/commonjs/serverOAuth.js.map +1 -0
  230. package/node_modules/@backendrelay/platform/dist/commonjs/typescript-schema.d.ts +17 -0
  231. package/node_modules/@backendrelay/platform/dist/commonjs/typescript-schema.d.ts.map +1 -0
  232. package/node_modules/@backendrelay/platform/dist/commonjs/typescript-schema.js +314 -0
  233. package/node_modules/@backendrelay/platform/dist/commonjs/typescript-schema.js.map +1 -0
  234. package/node_modules/@backendrelay/platform/dist/commonjs/util.d.ts +13 -0
  235. package/node_modules/@backendrelay/platform/dist/commonjs/util.d.ts.map +1 -0
  236. package/node_modules/@backendrelay/platform/dist/commonjs/util.js +55 -0
  237. package/node_modules/@backendrelay/platform/dist/commonjs/util.js.map +1 -0
  238. package/node_modules/@backendrelay/platform/dist/commonjs/version.d.ts +3 -0
  239. package/node_modules/@backendrelay/platform/dist/commonjs/version.d.ts.map +1 -0
  240. package/node_modules/@backendrelay/platform/dist/commonjs/version.js +5 -0
  241. package/node_modules/@backendrelay/platform/dist/commonjs/version.js.map +1 -0
  242. package/node_modules/@backendrelay/platform/dist/esm/ProgressPromise.d.ts +18 -0
  243. package/node_modules/@backendrelay/platform/dist/esm/ProgressPromise.d.ts.map +1 -0
  244. package/node_modules/@backendrelay/platform/dist/esm/ProgressPromise.js +73 -0
  245. package/node_modules/@backendrelay/platform/dist/esm/ProgressPromise.js.map +1 -0
  246. package/node_modules/@backendrelay/platform/dist/esm/api/apps.d.ts +99 -0
  247. package/node_modules/@backendrelay/platform/dist/esm/api/apps.d.ts.map +1 -0
  248. package/node_modules/@backendrelay/platform/dist/esm/api/apps.js +165 -0
  249. package/node_modules/@backendrelay/platform/dist/esm/api/apps.js.map +1 -0
  250. package/node_modules/@backendrelay/platform/dist/esm/api/auth.d.ts +7 -0
  251. package/node_modules/@backendrelay/platform/dist/esm/api/auth.d.ts.map +1 -0
  252. package/node_modules/@backendrelay/platform/dist/esm/api/auth.js +12 -0
  253. package/node_modules/@backendrelay/platform/dist/esm/api/auth.js.map +1 -0
  254. package/node_modules/@backendrelay/platform/dist/esm/api/http.d.ts +3 -0
  255. package/node_modules/@backendrelay/platform/dist/esm/api/http.d.ts.map +1 -0
  256. package/node_modules/@backendrelay/platform/dist/esm/api/http.js +39 -0
  257. package/node_modules/@backendrelay/platform/dist/esm/api/http.js.map +1 -0
  258. package/node_modules/@backendrelay/platform/dist/esm/api/perms.d.ts +13 -0
  259. package/node_modules/@backendrelay/platform/dist/esm/api/perms.d.ts.map +1 -0
  260. package/node_modules/@backendrelay/platform/dist/esm/api/perms.js +21 -0
  261. package/node_modules/@backendrelay/platform/dist/esm/api/perms.js.map +1 -0
  262. package/node_modules/@backendrelay/platform/dist/esm/api/platform-api.d.ts +285 -0
  263. package/node_modules/@backendrelay/platform/dist/esm/api/platform-api.d.ts.map +1 -0
  264. package/node_modules/@backendrelay/platform/dist/esm/api/platform-api.js +421 -0
  265. package/node_modules/@backendrelay/platform/dist/esm/api/platform-api.js.map +1 -0
  266. package/node_modules/@backendrelay/platform/dist/esm/api/schema-coerce.d.ts +24 -0
  267. package/node_modules/@backendrelay/platform/dist/esm/api/schema-coerce.d.ts.map +1 -0
  268. package/node_modules/@backendrelay/platform/dist/esm/api/schema-coerce.js +99 -0
  269. package/node_modules/@backendrelay/platform/dist/esm/api/schema-coerce.js.map +1 -0
  270. package/node_modules/@backendrelay/platform/dist/esm/api/schema.d.ts +188 -0
  271. package/node_modules/@backendrelay/platform/dist/esm/api/schema.d.ts.map +1 -0
  272. package/node_modules/@backendrelay/platform/dist/esm/api/schema.js +393 -0
  273. package/node_modules/@backendrelay/platform/dist/esm/api/schema.js.map +1 -0
  274. package/node_modules/@backendrelay/platform/dist/esm/api.d.ts +9 -0
  275. package/node_modules/@backendrelay/platform/dist/esm/api.d.ts.map +1 -0
  276. package/node_modules/@backendrelay/platform/dist/esm/api.js +4 -0
  277. package/node_modules/@backendrelay/platform/dist/esm/api.js.map +1 -0
  278. package/node_modules/@backendrelay/platform/dist/esm/backupDownload.d.ts +89 -0
  279. package/node_modules/@backendrelay/platform/dist/esm/backupDownload.d.ts.map +1 -0
  280. package/node_modules/@backendrelay/platform/dist/esm/backupDownload.js +354 -0
  281. package/node_modules/@backendrelay/platform/dist/esm/backupDownload.js.map +1 -0
  282. package/node_modules/@backendrelay/platform/dist/esm/backups.d.ts +146 -0
  283. package/node_modules/@backendrelay/platform/dist/esm/backups.d.ts.map +1 -0
  284. package/node_modules/@backendrelay/platform/dist/esm/backups.js +240 -0
  285. package/node_modules/@backendrelay/platform/dist/esm/backups.js.map +1 -0
  286. package/node_modules/@backendrelay/platform/dist/esm/clerk.d.ts +2 -0
  287. package/node_modules/@backendrelay/platform/dist/esm/clerk.d.ts.map +1 -0
  288. package/node_modules/@backendrelay/platform/dist/esm/clerk.js +26 -0
  289. package/node_modules/@backendrelay/platform/dist/esm/clerk.js.map +1 -0
  290. package/node_modules/@backendrelay/platform/dist/esm/consts.d.ts +11 -0
  291. package/node_modules/@backendrelay/platform/dist/esm/consts.d.ts.map +1 -0
  292. package/node_modules/@backendrelay/platform/dist/esm/consts.js +13 -0
  293. package/node_modules/@backendrelay/platform/dist/esm/consts.js.map +1 -0
  294. package/node_modules/@backendrelay/platform/dist/esm/crypto.d.ts +4 -0
  295. package/node_modules/@backendrelay/platform/dist/esm/crypto.d.ts.map +1 -0
  296. package/node_modules/@backendrelay/platform/dist/esm/crypto.js +21 -0
  297. package/node_modules/@backendrelay/platform/dist/esm/crypto.js.map +1 -0
  298. package/node_modules/@backendrelay/platform/dist/esm/index.d.ts +19 -0
  299. package/node_modules/@backendrelay/platform/dist/esm/index.d.ts.map +1 -0
  300. package/node_modules/@backendrelay/platform/dist/esm/index.js +18 -0
  301. package/node_modules/@backendrelay/platform/dist/esm/index.js.map +1 -0
  302. package/node_modules/@backendrelay/platform/dist/esm/migrationUtils.d.ts +4 -0
  303. package/node_modules/@backendrelay/platform/dist/esm/migrationUtils.d.ts.map +1 -0
  304. package/node_modules/@backendrelay/platform/dist/esm/migrationUtils.js +47 -0
  305. package/node_modules/@backendrelay/platform/dist/esm/migrationUtils.js.map +1 -0
  306. package/node_modules/@backendrelay/platform/dist/esm/migrations.d.ts +99 -0
  307. package/node_modules/@backendrelay/platform/dist/esm/migrations.d.ts.map +1 -0
  308. package/node_modules/@backendrelay/platform/dist/esm/migrations.js +588 -0
  309. package/node_modules/@backendrelay/platform/dist/esm/migrations.js.map +1 -0
  310. package/node_modules/@backendrelay/platform/dist/esm/oauth.d.ts +98 -0
  311. package/node_modules/@backendrelay/platform/dist/esm/oauth.d.ts.map +1 -0
  312. package/node_modules/@backendrelay/platform/dist/esm/oauth.js +266 -0
  313. package/node_modules/@backendrelay/platform/dist/esm/oauth.js.map +1 -0
  314. package/node_modules/@backendrelay/platform/dist/esm/oauthCommon.d.ts +12 -0
  315. package/node_modules/@backendrelay/platform/dist/esm/oauthCommon.d.ts.map +1 -0
  316. package/node_modules/@backendrelay/platform/dist/esm/oauthCommon.js +22 -0
  317. package/node_modules/@backendrelay/platform/dist/esm/oauthCommon.js.map +1 -0
  318. package/node_modules/@backendrelay/platform/dist/esm/package.json +3 -0
  319. package/node_modules/@backendrelay/platform/dist/esm/perms.d.ts +3 -0
  320. package/node_modules/@backendrelay/platform/dist/esm/perms.d.ts.map +1 -0
  321. package/node_modules/@backendrelay/platform/dist/esm/perms.js +62 -0
  322. package/node_modules/@backendrelay/platform/dist/esm/perms.js.map +1 -0
  323. package/node_modules/@backendrelay/platform/dist/esm/privateFields.d.ts +13 -0
  324. package/node_modules/@backendrelay/platform/dist/esm/privateFields.d.ts.map +1 -0
  325. package/node_modules/@backendrelay/platform/dist/esm/privateFields.js +28 -0
  326. package/node_modules/@backendrelay/platform/dist/esm/privateFields.js.map +1 -0
  327. package/node_modules/@backendrelay/platform/dist/esm/relationships.d.ts +7 -0
  328. package/node_modules/@backendrelay/platform/dist/esm/relationships.d.ts.map +1 -0
  329. package/node_modules/@backendrelay/platform/dist/esm/relationships.js +43 -0
  330. package/node_modules/@backendrelay/platform/dist/esm/relationships.js.map +1 -0
  331. package/node_modules/@backendrelay/platform/dist/esm/schema.d.ts +161 -0
  332. package/node_modules/@backendrelay/platform/dist/esm/schema.d.ts.map +1 -0
  333. package/node_modules/@backendrelay/platform/dist/esm/schema.js +158 -0
  334. package/node_modules/@backendrelay/platform/dist/esm/schema.js.map +1 -0
  335. package/node_modules/@backendrelay/platform/dist/esm/serverOAuth.d.ts +25 -0
  336. package/node_modules/@backendrelay/platform/dist/esm/serverOAuth.d.ts.map +1 -0
  337. package/node_modules/@backendrelay/platform/dist/esm/serverOAuth.js +64 -0
  338. package/node_modules/@backendrelay/platform/dist/esm/serverOAuth.js.map +1 -0
  339. package/node_modules/@backendrelay/platform/dist/esm/typescript-schema.d.ts +17 -0
  340. package/node_modules/@backendrelay/platform/dist/esm/typescript-schema.d.ts.map +1 -0
  341. package/node_modules/@backendrelay/platform/dist/esm/typescript-schema.js +310 -0
  342. package/node_modules/@backendrelay/platform/dist/esm/typescript-schema.js.map +1 -0
  343. package/node_modules/@backendrelay/platform/dist/esm/util.d.ts +13 -0
  344. package/node_modules/@backendrelay/platform/dist/esm/util.d.ts.map +1 -0
  345. package/node_modules/@backendrelay/platform/dist/esm/util.js +46 -0
  346. package/node_modules/@backendrelay/platform/dist/esm/util.js.map +1 -0
  347. package/node_modules/@backendrelay/platform/dist/esm/version.d.ts +3 -0
  348. package/node_modules/@backendrelay/platform/dist/esm/version.d.ts.map +1 -0
  349. package/node_modules/@backendrelay/platform/dist/esm/version.js +3 -0
  350. package/node_modules/@backendrelay/platform/dist/esm/version.js.map +1 -0
  351. package/node_modules/@backendrelay/platform/dist/standalone/index.js +13738 -0
  352. package/node_modules/@backendrelay/platform/dist/standalone/index.umd.cjs +72 -0
  353. package/node_modules/@backendrelay/platform/package.json +51 -0
  354. package/node_modules/@backendrelay/resumable-stream/dist/commonjs/index.d.ts +67 -0
  355. package/node_modules/@backendrelay/resumable-stream/dist/commonjs/index.d.ts.map +1 -0
  356. package/node_modules/@backendrelay/resumable-stream/dist/commonjs/index.js +129 -0
  357. package/node_modules/@backendrelay/resumable-stream/dist/commonjs/index.js.map +1 -0
  358. package/node_modules/@backendrelay/resumable-stream/dist/commonjs/package.json +3 -0
  359. package/node_modules/@backendrelay/resumable-stream/dist/esm/index.d.ts +67 -0
  360. package/node_modules/@backendrelay/resumable-stream/dist/esm/index.d.ts.map +1 -0
  361. package/node_modules/@backendrelay/resumable-stream/dist/esm/index.js +126 -0
  362. package/node_modules/@backendrelay/resumable-stream/dist/esm/index.js.map +1 -0
  363. package/node_modules/@backendrelay/resumable-stream/dist/esm/package.json +3 -0
  364. package/node_modules/@backendrelay/resumable-stream/dist/standalone/index.js +4354 -0
  365. package/node_modules/@backendrelay/resumable-stream/dist/standalone/index.umd.cjs +6 -0
  366. package/node_modules/@backendrelay/resumable-stream/package.json +47 -0
  367. package/node_modules/@backendrelay/rules/README.md +34 -0
  368. package/node_modules/@backendrelay/rules/dist/commonjs/index.d.ts +117 -0
  369. package/node_modules/@backendrelay/rules/dist/commonjs/index.d.ts.map +1 -0
  370. package/node_modules/@backendrelay/rules/dist/commonjs/index.js +68 -0
  371. package/node_modules/@backendrelay/rules/dist/commonjs/index.js.map +1 -0
  372. package/node_modules/@backendrelay/rules/dist/commonjs/package.json +3 -0
  373. package/node_modules/@backendrelay/rules/dist/esm/index.d.ts +117 -0
  374. package/node_modules/@backendrelay/rules/dist/esm/index.d.ts.map +1 -0
  375. package/node_modules/@backendrelay/rules/dist/esm/index.js +64 -0
  376. package/node_modules/@backendrelay/rules/dist/esm/index.js.map +1 -0
  377. package/node_modules/@backendrelay/rules/dist/esm/package.json +3 -0
  378. package/node_modules/@backendrelay/rules/package.json +46 -0
  379. package/node_modules/@backendrelay/test/README.md +75 -0
  380. package/node_modules/@backendrelay/test/dist/commonjs/index.d.ts +74 -0
  381. package/node_modules/@backendrelay/test/dist/commonjs/index.d.ts.map +1 -0
  382. package/node_modules/@backendrelay/test/dist/commonjs/index.js +197 -0
  383. package/node_modules/@backendrelay/test/dist/commonjs/index.js.map +1 -0
  384. package/node_modules/@backendrelay/test/dist/commonjs/live.e2e.test.d.ts +2 -0
  385. package/node_modules/@backendrelay/test/dist/commonjs/live.e2e.test.d.ts.map +1 -0
  386. package/node_modules/@backendrelay/test/dist/commonjs/live.e2e.test.js +45 -0
  387. package/node_modules/@backendrelay/test/dist/commonjs/live.e2e.test.js.map +1 -0
  388. package/node_modules/@backendrelay/test/dist/commonjs/package.json +3 -0
  389. package/node_modules/@backendrelay/test/dist/esm/index.d.ts +74 -0
  390. package/node_modules/@backendrelay/test/dist/esm/index.d.ts.map +1 -0
  391. package/node_modules/@backendrelay/test/dist/esm/index.js +192 -0
  392. package/node_modules/@backendrelay/test/dist/esm/index.js.map +1 -0
  393. package/node_modules/@backendrelay/test/dist/esm/live.e2e.test.d.ts +2 -0
  394. package/node_modules/@backendrelay/test/dist/esm/live.e2e.test.d.ts.map +1 -0
  395. package/node_modules/@backendrelay/test/dist/esm/live.e2e.test.js +43 -0
  396. package/node_modules/@backendrelay/test/dist/esm/live.e2e.test.js.map +1 -0
  397. package/node_modules/@backendrelay/test/dist/esm/package.json +3 -0
  398. package/node_modules/@backendrelay/test/package.json +49 -0
  399. package/node_modules/@backendrelay/version/dist/commonjs/index.d.ts +3 -0
  400. package/node_modules/@backendrelay/version/dist/commonjs/index.d.ts.map +1 -0
  401. package/node_modules/@backendrelay/version/dist/commonjs/index.js +6 -0
  402. package/node_modules/@backendrelay/version/dist/commonjs/index.js.map +1 -0
  403. package/node_modules/@backendrelay/version/dist/commonjs/package.json +3 -0
  404. package/node_modules/@backendrelay/version/dist/commonjs/version.d.ts +3 -0
  405. package/node_modules/@backendrelay/version/dist/commonjs/version.d.ts.map +1 -0
  406. package/node_modules/@backendrelay/version/dist/commonjs/version.js +10 -0
  407. package/node_modules/@backendrelay/version/dist/commonjs/version.js.map +1 -0
  408. package/node_modules/@backendrelay/version/dist/esm/index.d.ts +3 -0
  409. package/node_modules/@backendrelay/version/dist/esm/index.d.ts.map +1 -0
  410. package/node_modules/@backendrelay/version/dist/esm/index.js +3 -0
  411. package/node_modules/@backendrelay/version/dist/esm/index.js.map +1 -0
  412. package/node_modules/@backendrelay/version/dist/esm/package.json +3 -0
  413. package/node_modules/@backendrelay/version/dist/esm/version.d.ts +3 -0
  414. package/node_modules/@backendrelay/version/dist/esm/version.d.ts.map +1 -0
  415. package/node_modules/@backendrelay/version/dist/esm/version.js +7 -0
  416. package/node_modules/@backendrelay/version/dist/esm/version.js.map +1 -0
  417. package/node_modules/@backendrelay/version/dist/standalone/index.js +4 -0
  418. package/node_modules/@backendrelay/version/dist/standalone/index.umd.cjs +1 -0
  419. package/node_modules/@backendrelay/version/package.json +44 -0
  420. package/node_modules/@backendrelay/webhooks/dist/commonjs/__types__/typeUtils.d.ts +12 -0
  421. package/node_modules/@backendrelay/webhooks/dist/commonjs/__types__/typeUtils.d.ts.map +1 -0
  422. package/node_modules/@backendrelay/webhooks/dist/commonjs/__types__/typeUtils.js +5 -0
  423. package/node_modules/@backendrelay/webhooks/dist/commonjs/__types__/typeUtils.js.map +1 -0
  424. package/node_modules/@backendrelay/webhooks/dist/commonjs/__types__/typesTests.d.ts +2 -0
  425. package/node_modules/@backendrelay/webhooks/dist/commonjs/__types__/typesTests.d.ts.map +1 -0
  426. package/node_modules/@backendrelay/webhooks/dist/commonjs/__types__/typesTests.js +82 -0
  427. package/node_modules/@backendrelay/webhooks/dist/commonjs/__types__/typesTests.js.map +1 -0
  428. package/node_modules/@backendrelay/webhooks/dist/commonjs/index.d.ts +607 -0
  429. package/node_modules/@backendrelay/webhooks/dist/commonjs/index.d.ts.map +1 -0
  430. package/node_modules/@backendrelay/webhooks/dist/commonjs/index.js +830 -0
  431. package/node_modules/@backendrelay/webhooks/dist/commonjs/index.js.map +1 -0
  432. package/node_modules/@backendrelay/webhooks/dist/commonjs/live.e2e.test.d.ts +2 -0
  433. package/node_modules/@backendrelay/webhooks/dist/commonjs/live.e2e.test.d.ts.map +1 -0
  434. package/node_modules/@backendrelay/webhooks/dist/commonjs/live.e2e.test.js +139 -0
  435. package/node_modules/@backendrelay/webhooks/dist/commonjs/live.e2e.test.js.map +1 -0
  436. package/node_modules/@backendrelay/webhooks/dist/commonjs/package.json +3 -0
  437. package/node_modules/@backendrelay/webhooks/dist/esm/__types__/typeUtils.d.ts +12 -0
  438. package/node_modules/@backendrelay/webhooks/dist/esm/__types__/typeUtils.d.ts.map +1 -0
  439. package/node_modules/@backendrelay/webhooks/dist/esm/__types__/typeUtils.js +4 -0
  440. package/node_modules/@backendrelay/webhooks/dist/esm/__types__/typeUtils.js.map +1 -0
  441. package/node_modules/@backendrelay/webhooks/dist/esm/__types__/typesTests.d.ts +2 -0
  442. package/node_modules/@backendrelay/webhooks/dist/esm/__types__/typesTests.d.ts.map +1 -0
  443. package/node_modules/@backendrelay/webhooks/dist/esm/__types__/typesTests.js +80 -0
  444. package/node_modules/@backendrelay/webhooks/dist/esm/__types__/typesTests.js.map +1 -0
  445. package/node_modules/@backendrelay/webhooks/dist/esm/index.d.ts +607 -0
  446. package/node_modules/@backendrelay/webhooks/dist/esm/index.d.ts.map +1 -0
  447. package/node_modules/@backendrelay/webhooks/dist/esm/index.js +825 -0
  448. package/node_modules/@backendrelay/webhooks/dist/esm/index.js.map +1 -0
  449. package/node_modules/@backendrelay/webhooks/dist/esm/live.e2e.test.d.ts +2 -0
  450. package/node_modules/@backendrelay/webhooks/dist/esm/live.e2e.test.d.ts.map +1 -0
  451. package/node_modules/@backendrelay/webhooks/dist/esm/live.e2e.test.js +137 -0
  452. package/node_modules/@backendrelay/webhooks/dist/esm/live.e2e.test.js.map +1 -0
  453. package/node_modules/@backendrelay/webhooks/dist/esm/package.json +3 -0
  454. package/node_modules/@backendrelay/webhooks/package.json +46 -0
  455. package/package.json +129 -56
  456. package/subpaths/admin/index.cjs +1 -0
  457. package/subpaths/admin/index.d.ts +1 -0
  458. package/subpaths/admin/index.mjs +3 -0
  459. package/subpaths/functions/index.cjs +1 -0
  460. package/subpaths/functions/index.d.ts +1 -0
  461. package/subpaths/functions/index.mjs +3 -0
  462. package/subpaths/hatchet/index.cjs +1 -0
  463. package/subpaths/hatchet/index.d.ts +1 -0
  464. package/subpaths/hatchet/index.mjs +3 -0
  465. package/subpaths/platform/index.cjs +1 -0
  466. package/subpaths/platform/index.d.ts +1 -0
  467. package/subpaths/platform/index.mjs +3 -0
  468. package/subpaths/resumable-stream/index.cjs +1 -0
  469. package/subpaths/resumable-stream/index.d.ts +1 -0
  470. package/subpaths/resumable-stream/index.mjs +3 -0
  471. package/subpaths/rules/index.cjs +1 -0
  472. package/subpaths/rules/index.d.ts +1 -0
  473. package/subpaths/rules/index.mjs +3 -0
  474. package/subpaths/test/index.cjs +1 -0
  475. package/subpaths/test/index.d.ts +1 -0
  476. package/subpaths/test/index.mjs +3 -0
  477. package/subpaths/version/index.cjs +1 -0
  478. package/subpaths/version/index.d.ts +1 -0
  479. package/subpaths/version/index.mjs +3 -0
  480. package/subpaths/webhooks/index.cjs +1 -0
  481. package/subpaths/webhooks/index.d.ts +1 -0
  482. package/subpaths/webhooks/index.mjs +3 -0
  483. package/.tshy/build.json +0 -8
  484. package/.tshy/commonjs.json +0 -16
  485. package/.tshy/esm.json +0 -15
  486. package/__example__/standalone.esm.html +0 -23
  487. package/__example__/standalone.umd.html +0 -21
  488. package/__tests__/src/Connection.test.ts +0 -292
  489. package/__tests__/src/IndexedDBStorage.test.ts +0 -96
  490. package/__tests__/src/Reactor.test.ts +0 -1179
  491. package/__tests__/src/auth-extra-fields.e2e.test.ts +0 -160
  492. package/__tests__/src/byop.e2e.test.ts +0 -762
  493. package/__tests__/src/config.test.ts +0 -85
  494. package/__tests__/src/cookieSync.e2e.test.ts +0 -163
  495. package/__tests__/src/data/movies/attrs.json +0 -145
  496. package/__tests__/src/data/movies/triples.json +0 -1507
  497. package/__tests__/src/data/zeneca/attrs.json +0 -251
  498. package/__tests__/src/data/zeneca/triples.json +0 -15854
  499. package/__tests__/src/datalog.test.ts +0 -175
  500. package/__tests__/src/devtool.test.ts +0 -23
  501. package/__tests__/src/framework.test.ts +0 -173
  502. package/__tests__/src/infiniteQuery.e2e.test.ts +0 -467
  503. package/__tests__/src/instaml.test.ts +0 -1593
  504. package/__tests__/src/instaql.bench.ts +0 -34
  505. package/__tests__/src/instaql.test.ts +0 -1497
  506. package/__tests__/src/instaqlInference.test.ts +0 -243
  507. package/__tests__/src/presence.test.ts +0 -49
  508. package/__tests__/src/queryValidation.test.ts +0 -1101
  509. package/__tests__/src/schema.test.ts +0 -653
  510. package/__tests__/src/serializeSchema.test.ts +0 -123
  511. package/__tests__/src/simple.e2e.test.ts +0 -133
  512. package/__tests__/src/storage-upload.test.ts +0 -37
  513. package/__tests__/src/store.test.ts +0 -960
  514. package/__tests__/src/syncTable.e2e.test.ts +0 -245
  515. package/__tests__/src/syncTable.test.ts +0 -235
  516. package/__tests__/src/transactionValidation.test.ts +0 -450
  517. package/__tests__/src/typeUtils.ts +0 -39
  518. package/__tests__/src/upstream-improvements.e2e.test.ts +0 -54
  519. package/__tests__/src/utils/MutationStorage.test.ts +0 -77
  520. package/__tests__/src/utils/PersistedObject.test.ts +0 -569
  521. package/__tests__/src/utils/dates.test.ts +0 -111
  522. package/__tests__/src/utils/e2e.ts +0 -100
  523. package/__tests__/src/utils/msw.ts +0 -3
  524. package/__tests__/src/utils/object.test.ts +0 -78
  525. package/__tests__/src/utils/weakHash.test.ts +0 -68
  526. package/__tests__/src/utils/weakHashLegacy.test.ts +0 -22
  527. package/__tests__/src/vite.env.d.ts +0 -1
  528. package/src/BackendRelayError.ts +0 -50
  529. package/src/Connection.ts +0 -361
  530. package/src/InMemoryStorage.ts +0 -34
  531. package/src/IndexedDBStorage.ts +0 -398
  532. package/src/Reactor.js +0 -1541
  533. package/src/StorageAPI.ts +0 -147
  534. package/src/Stream.ts +0 -1252
  535. package/src/SyncTable.ts +0 -750
  536. package/src/WindowNetworkListener.js +0 -19
  537. package/src/__types__/fieldsTypeTest.ts +0 -111
  538. package/src/__types__/typeUtils.ts +0 -39
  539. package/src/__types__/useDatesTypeTest.ts +0 -66
  540. package/src/attrTypes.ts +0 -37
  541. package/src/authAPI.ts +0 -205
  542. package/src/clientTypes.ts +0 -28
  543. package/src/coreTypes.ts +0 -58
  544. package/src/createRouteHandler.ts +0 -68
  545. package/src/datalog.js +0 -116
  546. package/src/devtool.ts +0 -179
  547. package/src/framework.ts +0 -450
  548. package/src/helperTypes.ts +0 -117
  549. package/src/index.ts +0 -1293
  550. package/src/infiniteQuery.ts +0 -599
  551. package/src/instaml.ts +0 -676
  552. package/src/instaql.ts +0 -999
  553. package/src/instatx.ts +0 -265
  554. package/src/model/instaqlResult.js +0 -25
  555. package/src/parseSchemaFromJSON.ts +0 -176
  556. package/src/presence.ts +0 -123
  557. package/src/presenceTypes.ts +0 -19
  558. package/src/queryTypes.ts +0 -749
  559. package/src/queryValidation.ts +0 -598
  560. package/src/reactorAuth.js +0 -236
  561. package/src/reactorEvents.js +0 -414
  562. package/src/reactorMutations.js +0 -354
  563. package/src/reactorRooms.js +0 -297
  564. package/src/reactorStorage.js +0 -180
  565. package/src/reactorSubs.js +0 -275
  566. package/src/reactorTransport.js +0 -391
  567. package/src/reactorTypes.ts +0 -41
  568. package/src/routeHandlerProtocol.ts +0 -25
  569. package/src/rulesTypes.ts +0 -132
  570. package/src/sanityCheckQueries.ts +0 -191
  571. package/src/schema.ts +0 -206
  572. package/src/schemaTypes.ts +0 -664
  573. package/src/store.ts +0 -1165
  574. package/src/transactionValidation.ts +0 -204
  575. package/src/urls.ts +0 -50
  576. package/src/utils/Deferred.ts +0 -20
  577. package/src/utils/MutationStorage.ts +0 -89
  578. package/src/utils/PersistedObject.ts +0 -612
  579. package/src/utils/dates.ts +0 -269
  580. package/src/utils/error.ts +0 -9
  581. package/src/utils/fetch.ts +0 -131
  582. package/src/utils/flags.ts +0 -14
  583. package/src/utils/id.ts +0 -28
  584. package/src/utils/linkIndex.ts +0 -33
  585. package/src/utils/log.ts +0 -23
  586. package/src/utils/object.js +0 -180
  587. package/src/utils/pgtime.ts +0 -199
  588. package/src/utils/pick.js +0 -9
  589. package/src/utils/strings.ts +0 -19
  590. package/src/utils/weakHash.ts +0 -77
  591. package/src/utils/weakHashLegacy.ts +0 -75
  592. package/src/warningToggle.ts +0 -5
  593. package/tsconfig.cjs.dev.json +0 -15
  594. package/tsconfig.dev.json +0 -14
  595. package/tsconfig.json +0 -13
  596. package/tsconfig.test.json +0 -5
  597. package/vite.config.ts +0 -19
  598. package/vitest.config.ts +0 -54
@@ -0,0 +1,4354 @@
1
+ const hn = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i;
2
+ function Re(t) {
3
+ return typeof t == "string" && hn.test(t);
4
+ }
5
+ const W = [];
6
+ for (let t = 0; t < 256; ++t)
7
+ W.push((t + 256).toString(16).slice(1));
8
+ function pn(t, e = 0) {
9
+ return (W[t[e + 0]] + W[t[e + 1]] + W[t[e + 2]] + W[t[e + 3]] + "-" + W[t[e + 4]] + W[t[e + 5]] + "-" + W[t[e + 6]] + W[t[e + 7]] + "-" + W[t[e + 8]] + W[t[e + 9]] + "-" + W[t[e + 10]] + W[t[e + 11]] + W[t[e + 12]] + W[t[e + 13]] + W[t[e + 14]] + W[t[e + 15]]).toLowerCase();
10
+ }
11
+ let Xe;
12
+ const yn = new Uint8Array(16);
13
+ function mn() {
14
+ if (!Xe) {
15
+ if (typeof crypto > "u" || !crypto.getRandomValues)
16
+ throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");
17
+ Xe = crypto.getRandomValues.bind(crypto);
18
+ }
19
+ return Xe(yn);
20
+ }
21
+ const bn = typeof crypto < "u" && crypto.randomUUID && crypto.randomUUID.bind(crypto), kt = { randomUUID: bn };
22
+ function gn(t, e, n) {
23
+ if (kt.randomUUID && !t)
24
+ return kt.randomUUID();
25
+ t = t || {};
26
+ const s = t.random ?? t.rng?.() ?? mn();
27
+ if (s.length < 16)
28
+ throw new Error("Random bytes length must be >= 16");
29
+ return s[6] = s[6] & 15 | 64, s[8] = s[8] & 63 | 128, pn(s);
30
+ }
31
+ const N = {
32
+ Remove: "remove",
33
+ Replace: "replace",
34
+ Add: "add"
35
+ }, Jt = /* @__PURE__ */ Symbol.for("__MUTATIVE_PROXY_DRAFT__"), Je = Symbol.iterator, Z = {
36
+ mutable: "mutable",
37
+ immutable: "immutable"
38
+ }, yt = {};
39
+ function Ae(t, e) {
40
+ return t instanceof Map ? t.has(e) : Object.prototype.hasOwnProperty.call(t, e);
41
+ }
42
+ function It(t, e) {
43
+ if (e in t) {
44
+ let n = Reflect.getPrototypeOf(t);
45
+ for (; n; ) {
46
+ const s = Reflect.getOwnPropertyDescriptor(n, e);
47
+ if (s)
48
+ return s;
49
+ n = Reflect.getPrototypeOf(n);
50
+ }
51
+ }
52
+ }
53
+ function qt(t) {
54
+ return Object.getPrototypeOf(t) === Set.prototype;
55
+ }
56
+ function Kt(t) {
57
+ return Object.getPrototypeOf(t) === Map.prototype;
58
+ }
59
+ function K(t) {
60
+ var e;
61
+ return (e = t.copy) !== null && e !== void 0 ? e : t.original;
62
+ }
63
+ function st(t) {
64
+ return !!O(t);
65
+ }
66
+ function O(t) {
67
+ return typeof t != "object" ? null : t?.[Jt];
68
+ }
69
+ function mt(t) {
70
+ var e;
71
+ const n = O(t);
72
+ return n ? (e = n.copy) !== null && e !== void 0 ? e : n.original : t;
73
+ }
74
+ function ge(t, e) {
75
+ if (!t || typeof t != "object")
76
+ return !1;
77
+ let n;
78
+ return Object.getPrototypeOf(t) === Object.prototype || Array.isArray(t) || t instanceof Map || t instanceof Set || !!e?.mark && ((n = e.mark(t, Z)) === Z.immutable || typeof n == "function");
79
+ }
80
+ function Ht(t, e = []) {
81
+ if (Object.hasOwnProperty.call(t, "key")) {
82
+ const n = t.parent.copy, s = O(ce(n, t.key));
83
+ if (s !== null && s?.original !== t.original)
84
+ return null;
85
+ const i = t.parent.type === 3, o = i ? Array.from(t.parent.setMap.keys()).indexOf(t.key) : t.key;
86
+ if (!(i && n.size > o || Ae(n, o)))
87
+ return null;
88
+ e.push(o);
89
+ }
90
+ if (t.parent)
91
+ return Ht(t.parent, e);
92
+ e.reverse();
93
+ try {
94
+ wn(t.copy, e);
95
+ } catch {
96
+ return null;
97
+ }
98
+ return e;
99
+ }
100
+ function Ne(t) {
101
+ return Array.isArray(t) ? 1 : t instanceof Map ? 2 : t instanceof Set ? 3 : 0;
102
+ }
103
+ function ce(t, e) {
104
+ return Ne(t) === 2 ? t.get(e) : t[e];
105
+ }
106
+ function bt(t, e, n) {
107
+ Ne(t) === 2 ? t.set(e, n) : t[e] = n;
108
+ }
109
+ function Ze(t, e) {
110
+ const n = O(t);
111
+ return (n ? K(n) : t)[e];
112
+ }
113
+ function me(t, e) {
114
+ return t === e ? t !== 0 || 1 / t === 1 / e : t !== t && e !== e;
115
+ }
116
+ function ye(t, e) {
117
+ return e ? t : [""].concat(t).map((n) => {
118
+ const s = `${n}`;
119
+ return s.indexOf("/") === -1 && s.indexOf("~") === -1 ? s : s.replace(/~/g, "~0").replace(/\//g, "~1");
120
+ }).join("/");
121
+ }
122
+ function wn(t, e) {
123
+ for (let n = 0; n < e.length - 1; n += 1) {
124
+ const s = e[n];
125
+ if (t = ce(Ne(t) === 3 ? Array.from(t) : t, s), typeof t != "object")
126
+ throw new Error(`Cannot resolve patch at '${e.join("/")}'.`);
127
+ }
128
+ return t;
129
+ }
130
+ function Sn(t) {
131
+ const e = Object.create(Object.getPrototypeOf(t));
132
+ return Reflect.ownKeys(t).forEach((n) => {
133
+ let s = Reflect.getOwnPropertyDescriptor(t, n);
134
+ if (s.enumerable && s.configurable && s.writable) {
135
+ e[n] = t[n];
136
+ return;
137
+ }
138
+ s.writable || (s.writable = !0, s.configurable = !0), (s.get || s.set) && (s = {
139
+ configurable: !0,
140
+ writable: !0,
141
+ enumerable: s.enumerable,
142
+ value: t[n]
143
+ }), Reflect.defineProperty(e, n, s);
144
+ }), e;
145
+ }
146
+ const vn = Object.prototype.propertyIsEnumerable;
147
+ function kn(t, e) {
148
+ let n;
149
+ if (Array.isArray(t))
150
+ return Array.prototype.concat.call(t);
151
+ if (t instanceof Set) {
152
+ if (!qt(t)) {
153
+ const s = Object.getPrototypeOf(t).constructor;
154
+ return new s(t.values());
155
+ }
156
+ return Set.prototype.difference ? Set.prototype.difference.call(t, /* @__PURE__ */ new Set()) : new Set(t.values());
157
+ } else if (t instanceof Map) {
158
+ if (!Kt(t)) {
159
+ const s = Object.getPrototypeOf(t).constructor;
160
+ return new s(t);
161
+ }
162
+ return new Map(t);
163
+ } else if (e?.mark && (n = e.mark(t, Z), n !== void 0) && n !== Z.mutable) {
164
+ if (n === Z.immutable)
165
+ return Sn(t);
166
+ if (typeof n == "function") {
167
+ if (e.enablePatches || e.enableAutoFreeze)
168
+ throw new Error("You can't use mark and patches or auto freeze together.");
169
+ return n();
170
+ }
171
+ throw new Error(`Unsupported mark result: ${n}`);
172
+ } else if (typeof t == "object" && Object.getPrototypeOf(t) === Object.prototype) {
173
+ const s = {};
174
+ return Object.keys(t).forEach((i) => {
175
+ s[i] = t[i];
176
+ }), Object.getOwnPropertySymbols(t).forEach((i) => {
177
+ vn.call(t, i) && (s[i] = t[i]);
178
+ }), s;
179
+ } else
180
+ throw new Error("Please check mark() to ensure that it is a stable marker draftable function.");
181
+ }
182
+ function B(t) {
183
+ t.copy || (t.copy = kn(t.original, t.options));
184
+ }
185
+ function Ce(t) {
186
+ if (!ge(t))
187
+ return mt(t);
188
+ if (Array.isArray(t))
189
+ return t.map(Ce);
190
+ if (t instanceof Map) {
191
+ const n = Array.from(t.entries()).map(([s, i]) => [
192
+ s,
193
+ Ce(i)
194
+ ]);
195
+ if (!Kt(t)) {
196
+ const s = Object.getPrototypeOf(t).constructor;
197
+ return new s(n);
198
+ }
199
+ return new Map(n);
200
+ }
201
+ if (t instanceof Set) {
202
+ const n = Array.from(t).map(Ce);
203
+ if (!qt(t)) {
204
+ const s = Object.getPrototypeOf(t).constructor;
205
+ return new s(n);
206
+ }
207
+ return new Set(n);
208
+ }
209
+ const e = Object.create(Object.getPrototypeOf(t));
210
+ for (const n in t)
211
+ e[n] = Ce(t[n]);
212
+ return e;
213
+ }
214
+ function qe(t) {
215
+ return st(t) ? Ce(t) : t;
216
+ }
217
+ function se(t) {
218
+ var e;
219
+ t.assignedMap = (e = t.assignedMap) !== null && e !== void 0 ? e : /* @__PURE__ */ new Map(), t.operated || (t.operated = !0, t.parent && se(t.parent));
220
+ }
221
+ function In(t, e) {
222
+ const n = Ne(t);
223
+ if (n === 0)
224
+ Reflect.ownKeys(t).forEach((s) => {
225
+ e(s, t[s], t);
226
+ });
227
+ else if (n === 1) {
228
+ let s = 0;
229
+ for (const i of t)
230
+ e(s, i, t), s += 1;
231
+ } else
232
+ t.forEach((s, i) => e(i, s, t));
233
+ }
234
+ function Vt(t, e, n) {
235
+ if (st(t) || !ge(t, n) || e.has(t) || Object.isFrozen(t))
236
+ return;
237
+ const s = t instanceof Set, i = s ? /* @__PURE__ */ new Map() : void 0;
238
+ if (e.add(t), In(t, (o, r) => {
239
+ var a;
240
+ if (st(r)) {
241
+ const u = O(r);
242
+ B(u);
243
+ const l = !((a = u.assignedMap) === null || a === void 0) && a.size || u.operated ? u.copy : u.original;
244
+ bt(s ? i : t, o, l);
245
+ } else
246
+ Vt(r, e, n);
247
+ }), i) {
248
+ const o = t, r = Array.from(o);
249
+ o.clear(), r.forEach((a) => {
250
+ o.add(i.has(a) ? i.get(a) : a);
251
+ });
252
+ }
253
+ }
254
+ function $n(t, e) {
255
+ const n = t.type === 3 ? t.setMap : t.copy;
256
+ t.finalities.revoke.length > 1 && t.assignedMap.get(e) && n && Vt(ce(n, e), t.finalities.handledSet, t.options);
257
+ }
258
+ function it(t) {
259
+ t.type === 3 && t.copy && (t.copy.clear(), t.setMap.forEach((e) => {
260
+ t.copy.add(mt(e));
261
+ }));
262
+ }
263
+ function rt(t, e, n, s) {
264
+ if (t.operated && t.assignedMap && t.assignedMap.size > 0 && !t.finalized) {
265
+ if (n && s) {
266
+ const o = Ht(t);
267
+ o && e(t, o, n, s);
268
+ }
269
+ t.finalized = !0;
270
+ }
271
+ }
272
+ function gt(t, e, n, s) {
273
+ const i = O(n);
274
+ i && (i.callbacks || (i.callbacks = []), i.callbacks.push((o, r) => {
275
+ var a;
276
+ const u = t.type === 3 ? t.setMap : t.copy;
277
+ if (me(ce(u, e), n)) {
278
+ let l = i.original;
279
+ i.copy && (l = i.copy), it(t), rt(t, s, o, r), t.options.enableAutoFreeze && (t.options.updatedValues = (a = t.options.updatedValues) !== null && a !== void 0 ? a : /* @__PURE__ */ new WeakMap(), t.options.updatedValues.set(l, i.original)), bt(u, e, l);
280
+ }
281
+ }), t.options.enableAutoFreeze && i.finalities !== t.finalities && (t.options.enableAutoFreeze = !1)), ge(n, t.options) && t.finalities.draft.push(() => {
282
+ const o = t.type === 3 ? t.setMap : t.copy;
283
+ me(ce(o, e), n) && $n(t, e);
284
+ });
285
+ }
286
+ function En(t, e, n, s, i) {
287
+ let { original: o, assignedMap: r, options: a } = t, u = t.copy;
288
+ u.length < o.length && ([o, u] = [u, o], [n, s] = [s, n]);
289
+ for (let l = 0; l < o.length; l += 1)
290
+ if (r.get(l.toString()) && u[l] !== o[l]) {
291
+ const f = e.concat([l]), h = ye(f, i);
292
+ n.push({
293
+ op: N.Replace,
294
+ path: h,
295
+ // If it is a draft, it needs to be deep cloned, and it may also be non-draft.
296
+ value: qe(u[l])
297
+ }), s.push({
298
+ op: N.Replace,
299
+ path: h,
300
+ // If it is a draft, it needs to be deep cloned, and it may also be non-draft.
301
+ value: qe(o[l])
302
+ });
303
+ }
304
+ for (let l = o.length; l < u.length; l += 1) {
305
+ const f = e.concat([l]), h = ye(f, i);
306
+ n.push({
307
+ op: N.Add,
308
+ path: h,
309
+ // If it is a draft, it needs to be deep cloned, and it may also be non-draft.
310
+ value: qe(u[l])
311
+ });
312
+ }
313
+ if (o.length < u.length) {
314
+ const { arrayLengthAssignment: l = !0 } = a.enablePatches;
315
+ if (l) {
316
+ const f = e.concat(["length"]), h = ye(f, i);
317
+ s.push({
318
+ op: N.Replace,
319
+ path: h,
320
+ value: o.length
321
+ });
322
+ } else
323
+ for (let f = u.length; o.length < f; f -= 1) {
324
+ const h = e.concat([f - 1]), p = ye(h, i);
325
+ s.push({
326
+ op: N.Remove,
327
+ path: p
328
+ });
329
+ }
330
+ }
331
+ }
332
+ function On({ original: t, copy: e, assignedMap: n }, s, i, o, r) {
333
+ n.forEach((a, u) => {
334
+ const l = ce(t, u), f = qe(ce(e, u)), h = a ? Ae(t, u) ? N.Replace : N.Add : N.Remove;
335
+ if (me(l, f) && h === N.Replace)
336
+ return;
337
+ const p = s.concat(u), m = ye(p, r);
338
+ i.push(h === N.Remove ? { op: h, path: m } : { op: h, path: m, value: f }), o.push(h === N.Add ? { op: N.Remove, path: m } : h === N.Remove ? { op: N.Add, path: m, value: l } : { op: N.Replace, path: m, value: l });
339
+ });
340
+ }
341
+ function _n({ original: t, copy: e }, n, s, i, o) {
342
+ let r = 0;
343
+ t.forEach((a) => {
344
+ if (!e.has(a)) {
345
+ const u = n.concat([r]), l = ye(u, o);
346
+ s.push({
347
+ op: N.Remove,
348
+ path: l,
349
+ value: a
350
+ }), i.unshift({
351
+ op: N.Add,
352
+ path: l,
353
+ value: a
354
+ });
355
+ }
356
+ r += 1;
357
+ }), r = 0, e.forEach((a) => {
358
+ if (!t.has(a)) {
359
+ const u = n.concat([r]), l = ye(u, o);
360
+ s.push({
361
+ op: N.Add,
362
+ path: l,
363
+ value: a
364
+ }), i.unshift({
365
+ op: N.Remove,
366
+ path: l,
367
+ value: a
368
+ });
369
+ }
370
+ r += 1;
371
+ });
372
+ }
373
+ function Me(t, e, n, s) {
374
+ const { pathAsArray: i = !0 } = t.options.enablePatches;
375
+ switch (t.type) {
376
+ case 0:
377
+ case 2:
378
+ return On(t, e, n, s, i);
379
+ case 1:
380
+ return En(t, e, n, s, i);
381
+ case 3:
382
+ return _n(t, e, n, s, i);
383
+ }
384
+ }
385
+ const Qe = (t, e, n = !1) => {
386
+ if (typeof t == "object" && t !== null && (!ge(t, e) || n))
387
+ throw new Error("Strict mode: Mutable data cannot be accessed directly, please use 'unsafe(callback)' wrap.");
388
+ }, ot = {
389
+ get size() {
390
+ return K(O(this)).size;
391
+ },
392
+ has(t) {
393
+ return K(O(this)).has(t);
394
+ },
395
+ set(t, e) {
396
+ const n = O(this), s = K(n);
397
+ return (!s.has(t) || !me(s.get(t), e)) && (B(n), se(n), n.assignedMap.set(t, !0), n.copy.set(t, e), gt(n, t, e, Me)), this;
398
+ },
399
+ delete(t) {
400
+ if (!this.has(t))
401
+ return !1;
402
+ const e = O(this);
403
+ return B(e), se(e), e.original.has(t) ? e.assignedMap.set(t, !1) : e.assignedMap.delete(t), e.copy.delete(t), !0;
404
+ },
405
+ clear() {
406
+ const t = O(this);
407
+ if (this.size) {
408
+ B(t), se(t), t.assignedMap = /* @__PURE__ */ new Map();
409
+ for (const [e] of t.original)
410
+ t.assignedMap.set(e, !1);
411
+ t.copy.clear();
412
+ }
413
+ },
414
+ forEach(t, e) {
415
+ const n = O(this);
416
+ K(n).forEach((s, i) => {
417
+ t.call(e, this.get(i), i, this);
418
+ });
419
+ },
420
+ get(t) {
421
+ var e, n;
422
+ const s = O(this), i = K(s).get(t), o = ((n = (e = s.options).mark) === null || n === void 0 ? void 0 : n.call(e, i, Z)) === Z.mutable;
423
+ if (s.options.strict && Qe(i, s.options, o), o || s.finalized || !ge(i, s.options) || i !== s.original.get(t))
424
+ return i;
425
+ const r = yt.createDraft({
426
+ original: i,
427
+ parentDraft: s,
428
+ key: t,
429
+ finalities: s.finalities,
430
+ options: s.options
431
+ });
432
+ return B(s), s.copy.set(t, r), r;
433
+ },
434
+ keys() {
435
+ return K(O(this)).keys();
436
+ },
437
+ values() {
438
+ const t = this.keys();
439
+ return {
440
+ [Je]: () => this.values(),
441
+ next: () => {
442
+ const e = t.next();
443
+ return e.done ? e : {
444
+ done: !1,
445
+ value: this.get(e.value)
446
+ };
447
+ }
448
+ };
449
+ },
450
+ entries() {
451
+ const t = this.keys();
452
+ return {
453
+ [Je]: () => this.entries(),
454
+ next: () => {
455
+ const e = t.next();
456
+ if (e.done)
457
+ return e;
458
+ const n = this.get(e.value);
459
+ return {
460
+ done: !1,
461
+ value: [e.value, n]
462
+ };
463
+ }
464
+ };
465
+ },
466
+ [Je]() {
467
+ return this.entries();
468
+ }
469
+ }, Rn = Reflect.ownKeys(ot), $t = (t, e, { isValuesIterator: n }) => () => {
470
+ var s, i;
471
+ const o = e.next();
472
+ if (o.done)
473
+ return o;
474
+ const r = o.value;
475
+ let a = t.setMap.get(r);
476
+ const u = O(a), l = ((i = (s = t.options).mark) === null || i === void 0 ? void 0 : i.call(s, a, Z)) === Z.mutable;
477
+ if (t.options.strict && Qe(r, t.options, l), !l && !u && ge(r, t.options) && !t.finalized && t.original.has(r)) {
478
+ const f = yt.createDraft({
479
+ original: r,
480
+ parentDraft: t,
481
+ key: r,
482
+ finalities: t.finalities,
483
+ options: t.options
484
+ });
485
+ t.setMap.set(r, f), a = f;
486
+ } else u && (a = u.proxy);
487
+ return {
488
+ done: !1,
489
+ value: n ? a : [a, a]
490
+ };
491
+ }, Ge = {
492
+ get size() {
493
+ return O(this).setMap.size;
494
+ },
495
+ has(t) {
496
+ const e = O(this);
497
+ if (e.setMap.has(t))
498
+ return !0;
499
+ B(e);
500
+ const n = O(t);
501
+ return !!(n && e.setMap.has(n.original));
502
+ },
503
+ add(t) {
504
+ const e = O(this);
505
+ return this.has(t) || (B(e), se(e), e.assignedMap.set(t, !0), e.setMap.set(t, t), gt(e, t, t, Me)), this;
506
+ },
507
+ delete(t) {
508
+ if (!this.has(t))
509
+ return !1;
510
+ const e = O(this);
511
+ B(e), se(e);
512
+ const n = O(t);
513
+ return n && e.setMap.has(n.original) ? (e.assignedMap.set(n.original, !1), e.setMap.delete(n.original)) : (!n && e.setMap.has(t) ? e.assignedMap.set(t, !1) : e.assignedMap.delete(t), e.setMap.delete(t));
514
+ },
515
+ clear() {
516
+ if (!this.size)
517
+ return;
518
+ const t = O(this);
519
+ B(t), se(t);
520
+ for (const e of t.original)
521
+ t.assignedMap.set(e, !1);
522
+ t.setMap.clear();
523
+ },
524
+ values() {
525
+ const t = O(this);
526
+ B(t);
527
+ const e = t.setMap.keys();
528
+ return {
529
+ [Symbol.iterator]: () => this.values(),
530
+ next: $t(t, e, { isValuesIterator: !0 })
531
+ };
532
+ },
533
+ entries() {
534
+ const t = O(this);
535
+ B(t);
536
+ const e = t.setMap.keys();
537
+ return {
538
+ [Symbol.iterator]: () => this.entries(),
539
+ next: $t(t, e, {
540
+ isValuesIterator: !1
541
+ })
542
+ };
543
+ },
544
+ keys() {
545
+ return this.values();
546
+ },
547
+ [Je]() {
548
+ return this.values();
549
+ },
550
+ forEach(t, e) {
551
+ const n = this.values();
552
+ let s = n.next();
553
+ for (; !s.done; )
554
+ t.call(e, s.value, s.value, this), s = n.next();
555
+ }
556
+ };
557
+ Set.prototype.difference && Object.assign(Ge, {
558
+ intersection(t) {
559
+ return Set.prototype.intersection.call(new Set(this.values()), t);
560
+ },
561
+ union(t) {
562
+ return Set.prototype.union.call(new Set(this.values()), t);
563
+ },
564
+ difference(t) {
565
+ return Set.prototype.difference.call(new Set(this.values()), t);
566
+ },
567
+ symmetricDifference(t) {
568
+ return Set.prototype.symmetricDifference.call(new Set(this.values()), t);
569
+ },
570
+ isSubsetOf(t) {
571
+ return Set.prototype.isSubsetOf.call(new Set(this.values()), t);
572
+ },
573
+ isSupersetOf(t) {
574
+ return Set.prototype.isSupersetOf.call(new Set(this.values()), t);
575
+ },
576
+ isDisjointFrom(t) {
577
+ return Set.prototype.isDisjointFrom.call(new Set(this.values()), t);
578
+ }
579
+ });
580
+ const Cn = Reflect.ownKeys(Ge), Qt = /* @__PURE__ */ new WeakSet(), Gt = {
581
+ get(t, e, n) {
582
+ var s, i;
583
+ const o = (s = t.copy) === null || s === void 0 ? void 0 : s[e];
584
+ if (o && Qt.has(o))
585
+ return o;
586
+ if (e === Jt)
587
+ return t;
588
+ let r;
589
+ if (t.options.mark) {
590
+ const l = e === "size" && (t.original instanceof Map || t.original instanceof Set) ? Reflect.get(t.original, e) : Reflect.get(t.original, e, n);
591
+ if (r = t.options.mark(l, Z), r === Z.mutable)
592
+ return t.options.strict && Qe(l, t.options, !0), l;
593
+ }
594
+ const a = K(t);
595
+ if (a instanceof Map && Rn.includes(e)) {
596
+ if (e === "size")
597
+ return Object.getOwnPropertyDescriptor(ot, "size").get.call(t.proxy);
598
+ const l = ot[e];
599
+ if (l)
600
+ return l.bind(t.proxy);
601
+ }
602
+ if (a instanceof Set && Cn.includes(e)) {
603
+ if (e === "size")
604
+ return Object.getOwnPropertyDescriptor(Ge, "size").get.call(t.proxy);
605
+ const l = Ge[e];
606
+ if (l)
607
+ return l.bind(t.proxy);
608
+ }
609
+ if (!Ae(a, e)) {
610
+ const l = It(a, e);
611
+ return l ? "value" in l ? l.value : (
612
+ // !case: support for getter
613
+ (i = l.get) === null || i === void 0 ? void 0 : i.call(t.proxy)
614
+ ) : void 0;
615
+ }
616
+ const u = a[e];
617
+ if (t.options.strict && Qe(u, t.options), t.finalized || !ge(u, t.options))
618
+ return u;
619
+ if (u === Ze(t.original, e)) {
620
+ if (B(t), t.copy[e] = Yt({
621
+ original: t.original[e],
622
+ parentDraft: t,
623
+ key: t.type === 1 ? Number(e) : e,
624
+ finalities: t.finalities,
625
+ options: t.options
626
+ }), typeof r == "function") {
627
+ const l = O(t.copy[e]);
628
+ return B(l), se(l), l.copy;
629
+ }
630
+ return t.copy[e];
631
+ }
632
+ return u;
633
+ },
634
+ set(t, e, n) {
635
+ var s;
636
+ if (t.type === 3 || t.type === 2)
637
+ throw new Error("Map/Set draft does not support any property assignment.");
638
+ let i;
639
+ if (t.type === 1 && e !== "length" && !(Number.isInteger(i = Number(e)) && i >= 0 && (e === 0 || i === 0 || String(i) === String(e))))
640
+ throw new Error("Only supports setting array indices and the 'length' property.");
641
+ const o = It(K(t), e);
642
+ if (o?.set)
643
+ return o.set.call(t.proxy, n), !0;
644
+ const r = Ze(K(t), e), a = O(r);
645
+ return a && me(a.original, n) ? (t.copy[e] = n, t.assignedMap = (s = t.assignedMap) !== null && s !== void 0 ? s : /* @__PURE__ */ new Map(), t.assignedMap.set(e, !1), !0) : (me(n, r) && (n !== void 0 || Ae(t.original, e)) || (B(t), se(t), Ae(t.original, e) && me(n, t.original[e]) ? t.assignedMap.delete(e) : t.assignedMap.set(e, !0), t.copy[e] = n, gt(t, e, n, Me)), !0);
646
+ },
647
+ has(t, e) {
648
+ return e in K(t);
649
+ },
650
+ ownKeys(t) {
651
+ return Reflect.ownKeys(K(t));
652
+ },
653
+ getOwnPropertyDescriptor(t, e) {
654
+ const n = K(t), s = Reflect.getOwnPropertyDescriptor(n, e);
655
+ return s && {
656
+ writable: !0,
657
+ configurable: t.type !== 1 || e !== "length",
658
+ enumerable: s.enumerable,
659
+ value: n[e]
660
+ };
661
+ },
662
+ getPrototypeOf(t) {
663
+ return Reflect.getPrototypeOf(t.original);
664
+ },
665
+ setPrototypeOf() {
666
+ throw new Error("Cannot call 'setPrototypeOf()' on drafts");
667
+ },
668
+ defineProperty() {
669
+ throw new Error("Cannot call 'defineProperty()' on drafts");
670
+ },
671
+ deleteProperty(t, e) {
672
+ var n;
673
+ return t.type === 1 ? Gt.set.call(this, t, e, void 0, t.proxy) : (Ze(t.original, e) !== void 0 || e in t.original ? (B(t), se(t), t.assignedMap.set(e, !1)) : (t.assignedMap = (n = t.assignedMap) !== null && n !== void 0 ? n : /* @__PURE__ */ new Map(), t.assignedMap.delete(e)), t.copy && delete t.copy[e], !0);
674
+ }
675
+ };
676
+ function Yt(t) {
677
+ const { original: e, parentDraft: n, key: s, finalities: i, options: o } = t, r = Ne(e), a = {
678
+ type: r,
679
+ finalized: !1,
680
+ parent: n,
681
+ original: e,
682
+ copy: null,
683
+ proxy: null,
684
+ finalities: i,
685
+ options: o,
686
+ // Mapping of draft Set items to their corresponding draft values.
687
+ setMap: r === 3 ? new Map(e.entries()) : void 0
688
+ };
689
+ (s || "key" in t) && (a.key = s);
690
+ const { proxy: u, revoke: l } = Proxy.revocable(r === 1 ? Object.assign([], a) : a, Gt);
691
+ if (i.revoke.push(l), Qt.add(u), a.proxy = u, n) {
692
+ const f = n;
693
+ f.finalities.draft.push((h, p) => {
694
+ var m, $;
695
+ const w = O(u);
696
+ let c = f.type === 3 ? f.setMap : f.copy;
697
+ const b = ce(c, s), S = O(b);
698
+ if (S) {
699
+ let d = S.original;
700
+ S.operated && (d = mt(b)), it(S), rt(S, Me, h, p), f.options.enableAutoFreeze && (f.options.updatedValues = (m = f.options.updatedValues) !== null && m !== void 0 ? m : /* @__PURE__ */ new WeakMap(), f.options.updatedValues.set(d, S.original)), bt(c, s, d);
701
+ }
702
+ ($ = w.callbacks) === null || $ === void 0 || $.forEach((d) => {
703
+ d(h, p);
704
+ });
705
+ });
706
+ } else {
707
+ const f = O(u);
708
+ f.finalities.draft.push((h, p) => {
709
+ it(f), rt(f, Me, h, p);
710
+ });
711
+ }
712
+ return u;
713
+ }
714
+ yt.createDraft = Yt;
715
+ Object.prototype.constructor.toString();
716
+ function xn() {
717
+ const e = {
718
+ __etype: 1,
719
+ __ops: 1,
720
+ create: 1,
721
+ update: 1,
722
+ link: 1,
723
+ unlink: 1,
724
+ delete: 1,
725
+ merge: 1,
726
+ ruleParams: 1
727
+ };
728
+ return new Set(Object.keys(e));
729
+ }
730
+ const Tn = xn();
731
+ function Ke(t, e, n) {
732
+ const s = {
733
+ __etype: t,
734
+ __ops: n
735
+ };
736
+ return new Proxy(s, {
737
+ get: (i, o) => {
738
+ if (o === "__ops")
739
+ return n;
740
+ if (o === "__etype")
741
+ return t;
742
+ if (Tn.has(o))
743
+ return (r, a) => Ke(t, e, [
744
+ ...n,
745
+ a ? [o, t, e, r, a] : [o, t, e, r]
746
+ ]);
747
+ }
748
+ });
749
+ }
750
+ function An(t, e) {
751
+ return `lookup__${t}__${JSON.stringify(e)}`;
752
+ }
753
+ function Xt(t) {
754
+ return t.startsWith("lookup__");
755
+ }
756
+ function Et(t) {
757
+ const [e, n, ...s] = t.split("__");
758
+ return [n, JSON.parse(s.join("__"))];
759
+ }
760
+ function Pn(t) {
761
+ return new Proxy({
762
+ __etype: t
763
+ }, {
764
+ get(e, n) {
765
+ if (n === "lookup")
766
+ return (i, o) => Ke(t, Et(An(i, o)), []);
767
+ if (n === "__etype")
768
+ return t;
769
+ const s = n;
770
+ return Xt(s) ? Ke(t, Et(s), []) : Ke(t, s, []);
771
+ }
772
+ });
773
+ }
774
+ function Zt() {
775
+ return new Proxy({}, {
776
+ get(t, e) {
777
+ return Pn(e);
778
+ }
779
+ });
780
+ }
781
+ Zt();
782
+ function Un(t) {
783
+ return t.__ops;
784
+ }
785
+ function Ee() {
786
+ return gn();
787
+ }
788
+ function jn(t, e) {
789
+ if (typeof t != "function")
790
+ return;
791
+ const n = e instanceof Error ? e : new R(String(e));
792
+ try {
793
+ t(n);
794
+ } catch {
795
+ }
796
+ }
797
+ class R extends Error {
798
+ hint;
799
+ traceId;
800
+ constructor(e, n, s) {
801
+ super(e), this.hint = n, s && (this.traceId = s);
802
+ const i = new.target.prototype;
803
+ Object.setPrototypeOf && Object.setPrototypeOf(this, i), Error.captureStackTrace && Error.captureStackTrace(this, R), this.name = "BackendRelayError";
804
+ }
805
+ get [Symbol.toStringTag]() {
806
+ return "BackendRelayError";
807
+ }
808
+ }
809
+ class re extends R {
810
+ body;
811
+ status;
812
+ constructor(e) {
813
+ const n = e.body?.message || `API Error (${e.status})`;
814
+ super(n, e.body.hint, e.body?.traceId || e.body["trace-id"]);
815
+ const s = new.target.prototype;
816
+ Object.setPrototypeOf && Object.setPrototypeOf(this, s), Error.captureStackTrace && Error.captureStackTrace(this, re), this.name = "BackendRelayAPIError", this.status = e.status, this.body = e.body;
817
+ }
818
+ get [Symbol.toStringTag]() {
819
+ return "BackendRelayAPIError";
820
+ }
821
+ }
822
+ typeof window < "u" && typeof window.localStorage < "u" && (window.localStorage.getItem("devBackend"), window.localStorage.getItem("__instantLogging"), window.localStorage.getItem("__devtoolLocalDash"));
823
+ const be = "v2.0.0";
824
+ class ne {
825
+ valueType;
826
+ required;
827
+ isIndexed;
828
+ config;
829
+ metadata = {};
830
+ constructor(e, n, s, i = { indexed: !1, unique: !1 }) {
831
+ this.valueType = e, this.required = n, this.isIndexed = s, this.config = i;
832
+ }
833
+ /**
834
+ * @deprecated Only use this temporarily for attributes that you want
835
+ * to treat as required in frontend code but can’t yet mark as required
836
+ * and enforced for backend
837
+ */
838
+ clientRequired() {
839
+ return new ne(this.valueType, !1, this.isIndexed, this.config);
840
+ }
841
+ optional() {
842
+ return new ne(this.valueType, !1, this.isIndexed, this.config);
843
+ }
844
+ /**
845
+ * Marks the field as private. `backendrelay-cli push` adds a field rule that
846
+ * hides it unless the app's rules allow the field explicitly.
847
+ */
848
+ private() {
849
+ return new ne(this.valueType, this.required, this.isIndexed, {
850
+ ...this.config,
851
+ private: !0
852
+ });
853
+ }
854
+ unique() {
855
+ return new ne(this.valueType, this.required, this.isIndexed, {
856
+ ...this.config,
857
+ unique: !0
858
+ });
859
+ }
860
+ indexed() {
861
+ return new ne(this.valueType, this.required, !0, {
862
+ ...this.config,
863
+ indexed: !0
864
+ });
865
+ }
866
+ }
867
+ class _ extends Error {
868
+ constructor(e, n) {
869
+ const s = n ? `At path '${n}': ${e}` : e;
870
+ super(s), this.name = "QueryValidationError";
871
+ }
872
+ }
873
+ const Ot = [
874
+ "where",
875
+ "order",
876
+ "limit",
877
+ "last",
878
+ "first",
879
+ "offset",
880
+ "after",
881
+ "afterInclusive",
882
+ "before",
883
+ "beforeInclusive",
884
+ "fields",
885
+ "aggregate"
886
+ ], Mn = (t) => t.valueType || "unknown", en = (t, e, n = !1) => {
887
+ if (n || t == null)
888
+ return !0;
889
+ switch (e) {
890
+ case "string":
891
+ return typeof t == "string";
892
+ case "number":
893
+ return typeof t == "number" && !isNaN(t);
894
+ case "boolean":
895
+ return typeof t == "boolean";
896
+ case "date":
897
+ return t instanceof Date || typeof t == "string" || typeof t == "number";
898
+ default:
899
+ return !0;
900
+ }
901
+ }, _t = (t, e, n, s, i, o, r) => {
902
+ const a = o.valueType === "json", u = (l, f, h) => {
903
+ if (!en(h, f, a))
904
+ throw new _(`Invalid value for operator '${l}' on attribute '${s}' in entity '${i}'. Expected ${f}, but received: ${typeof h}`, r);
905
+ };
906
+ switch (t) {
907
+ case "in":
908
+ case "$in":
909
+ if (!Array.isArray(e))
910
+ throw new _(`Operator '${t}' for attribute '${s}' in entity '${i}' must be an array, but received: ${typeof e}`, r);
911
+ for (const l of e)
912
+ u(t, n, l);
913
+ break;
914
+ case "$not":
915
+ case "$ne":
916
+ case "$gt":
917
+ case "$lt":
918
+ case "$gte":
919
+ case "$lte":
920
+ u(t, n, e);
921
+ break;
922
+ case "$search":
923
+ if (u(t, "string", e), o.valueType !== "string" || !o.isIndexed)
924
+ throw new _(`Operator '$search' can only be used with indexed string attributes, but '${s}' in entity '${i}' is not an indexed string`, r);
925
+ break;
926
+ case "$like":
927
+ case "$ilike":
928
+ if (u(t, "string", e), t === "$ilike" && !o.isIndexed)
929
+ throw new _(`Operator '${t}' can only be used with indexed attributes, but '${s}' in entity '${i}' is not indexed`, r);
930
+ break;
931
+ case "$isNull":
932
+ u(t, "boolean", e);
933
+ break;
934
+ case "$nearest": {
935
+ const l = Array.isArray(e) ? e : e && typeof e == "object" && Array.isArray(e.vector) ? e.vector : null;
936
+ if (l === null)
937
+ throw new _("Operator '$nearest' requires a vector array or { vector, limit } object", r);
938
+ if (l.length === 0 || l.some((f) => typeof f != "number" || !Number.isFinite(f)))
939
+ throw new _("Operator '$nearest' requires finite numbers", r);
940
+ if (!Array.isArray(e) && e && typeof e == "object" && "limit" in e && (typeof e.limit != "number" || !Number.isInteger(e.limit) || e.limit < 1))
941
+ throw new _("Operator '$nearest' limit must be a positive integer", r);
942
+ break;
943
+ }
944
+ default:
945
+ throw new _(`Unknown operator '${t}' for attribute '${s}' in entity '${i}'`, r);
946
+ }
947
+ }, Oe = (t, e, n, s, i) => {
948
+ const o = Mn(n), r = n.valueType === "json";
949
+ if (typeof t == "object" && t !== null && !Array.isArray(t)) {
950
+ const u = t;
951
+ if (r && "$nearest" in u) {
952
+ _t("$nearest", u.$nearest, o, e, s, n, `${i}.$nearest`);
953
+ return;
954
+ }
955
+ if (r)
956
+ return;
957
+ for (const [l, f] of Object.entries(u))
958
+ _t(l, f, o, e, s, n, `${i}.${l}`);
959
+ } else if (!en(t, o, r))
960
+ throw new _(`Invalid value for attribute '${e}' in entity '${s}'. Expected ${o}, but received: ${typeof t}`, i);
961
+ }, Dn = (t, e, n, s, i) => {
962
+ const o = t.split(".");
963
+ if (o.length < 2)
964
+ throw new _(`Invalid dot notation path '${t}'. Must contain at least one dot.`, i);
965
+ let r = n;
966
+ for (let f = 0; f < o.length - 1; f++) {
967
+ const h = o[f], p = s.entities[r];
968
+ if (!p)
969
+ throw new _(`Entity '${r}' does not exist in schema while traversing dot notation path '${t}'.`, i);
970
+ const m = p.links[h];
971
+ if (!m) {
972
+ const $ = Object.keys(p.links);
973
+ throw new _(`Link '${h}' does not exist on entity '${r}' in dot notation path '${t}'. Available links: ${$.length > 0 ? $.join(", ") : "none"}`, i);
974
+ }
975
+ r = m.entityName;
976
+ }
977
+ const a = o[o.length - 1], u = s.entities[r];
978
+ if (!u)
979
+ throw new _(`Target entity '${r}' does not exist in schema for dot notation path '${t}'.`, i);
980
+ if (a === "id") {
981
+ if (typeof e == "string" && !Re(e))
982
+ throw new _(`Invalid value for id field in entity '${r}'. Expected a UUID, but received: ${e}`, i);
983
+ Oe(e, t, new ne("string", !1, !0), n, i);
984
+ return;
985
+ }
986
+ const l = u.attrs[a];
987
+ if (Object.keys(u.links).includes(a)) {
988
+ if (typeof e == "string" && !Re(e))
989
+ throw new _(`Invalid value for link '${a}' in entity '${r}'. Expected a UUID, but received: ${e}`, i);
990
+ Oe(e, t, new ne("string", !1, !0), n, i);
991
+ return;
992
+ }
993
+ if (!l) {
994
+ const f = Object.keys(u.attrs);
995
+ throw new _(`Attribute '${a}' does not exist on entity '${r}' in dot notation path '${t}'. Available attributes: ${f.length > 0 ? f.join(", ") + ", id" : "id"}`, i);
996
+ }
997
+ Oe(e, t, l, n, i);
998
+ }, tn = (t, e, n, s) => {
999
+ for (const [i, o] of Object.entries(t)) {
1000
+ if (i === "or" || i === "and") {
1001
+ if (Array.isArray(o))
1002
+ for (const l of o)
1003
+ typeof l == "object" && l !== null && tn(l, e, n, `${s}.${i}[${l}]`);
1004
+ continue;
1005
+ }
1006
+ if (i === "id") {
1007
+ Oe(o, "id", new ne("string", !1, !0), e, `${s}.id`);
1008
+ continue;
1009
+ }
1010
+ if (i.includes(".")) {
1011
+ Dn(i, o, e, n, `${s}.${i}`);
1012
+ continue;
1013
+ }
1014
+ const r = n.entities[e];
1015
+ if (!r)
1016
+ continue;
1017
+ const a = r.attrs[i], u = r.links[i];
1018
+ if (!a && !u) {
1019
+ const l = Object.keys(r.attrs), f = Object.keys(r.links);
1020
+ throw new _(`Attribute or link '${i}' does not exist on entity '${e}'. Available attributes: ${l.length > 0 ? l.join(", ") : "none"}. Available links: ${f.length > 0 ? f.join(", ") : "none"}`, `${s}.${i}`);
1021
+ }
1022
+ if (a)
1023
+ Oe(o, i, a, e, `${s}.${i}`);
1024
+ else if (u) {
1025
+ if (typeof o == "string" && !Re(o))
1026
+ throw new _(`Invalid value for link '${i}' in entity '${e}'. Expected a UUID, but received: ${o}`, `${s}.${i}`);
1027
+ const l = new ne("string", !1, !0);
1028
+ Oe(o, i, l, e, `${s}.${i}`);
1029
+ }
1030
+ }
1031
+ }, Nn = (t, e, n, s, i = 0) => {
1032
+ for (const r of Object.keys(t))
1033
+ if (!Ot.includes(r))
1034
+ throw new _(`Invalid query parameter '${r}' in $ object. Valid parameters are: ${Ot.join(", ")}. Found: ${r}`, s);
1035
+ const o = [
1036
+ // 'limit', // only supported client side
1037
+ "offset",
1038
+ "before",
1039
+ "beforeInclusive",
1040
+ "after",
1041
+ "afterInclusive",
1042
+ "first",
1043
+ "last"
1044
+ ];
1045
+ for (const r of o)
1046
+ if (t[r] !== void 0 && i > 0)
1047
+ throw new _(`'${r}' can only be used on top-level namespaces. It cannot be used in nested queries.`, s);
1048
+ if (t.where && n) {
1049
+ if (typeof t.where != "object" || t.where === null)
1050
+ throw new _(`'where' clause must be an object in entity '${e}', but received: ${typeof t.where}`, s ? `${s}.where` : void 0);
1051
+ tn(t.where, e, n, s ? `${s}.where` : "where");
1052
+ }
1053
+ }, nn = (t, e, n, s, i = 0) => {
1054
+ if (!t || typeof t != "object")
1055
+ throw new _(`Query part for entity '${e}' must be an object, but received: ${typeof t}`, s);
1056
+ for (const o of Object.keys(t))
1057
+ if (o !== "$") {
1058
+ if (n && !(o in n.entities[e].links)) {
1059
+ const a = Object.keys(n.entities[e].links);
1060
+ throw new _(`Link '${o}' does not exist on entity '${e}'. Available links: ${a.length > 0 ? a.join(", ") : "none"}`, `${s}.${o}`);
1061
+ }
1062
+ const r = t[o];
1063
+ if (typeof r == "object" && r !== null) {
1064
+ const a = n?.entities[e].links[o]?.entityName;
1065
+ a && nn(r, a, n, `${s}.${o}`, i + 1);
1066
+ }
1067
+ } else {
1068
+ const r = t[o];
1069
+ if (typeof r != "object" || r === null)
1070
+ throw new _(`Query parameter '$' must be an object in entity '${e}', but received: ${typeof r}`, `${s}.$`);
1071
+ Nn(r, e, n, `${s}.$`, i);
1072
+ }
1073
+ }, Rt = (t, e) => {
1074
+ if (typeof t != "object" || t === null)
1075
+ throw new _(`Query must be an object, but received: ${typeof t}${t === null ? " (null)" : ""}`);
1076
+ if (Array.isArray(t))
1077
+ throw new _(`Query must be an object, but received: ${typeof t}`);
1078
+ const n = t;
1079
+ for (const s of Object.keys(n)) {
1080
+ if (Array.isArray(t[s]))
1081
+ throw new _(`Query keys must be strings, but found key of type: ${typeof s}`, s);
1082
+ if (typeof s != "string")
1083
+ throw new _(`Query keys must be strings, but found key of type: ${typeof s}`, s);
1084
+ if (s !== "$$ruleParams") {
1085
+ if (e && !e.entities[s]) {
1086
+ const i = Object.keys(e.entities);
1087
+ throw new _(`Entity '${s}' does not exist in schema. Available entities: ${i.length > 0 ? i.join(", ") : "none"}`, s);
1088
+ }
1089
+ nn(n[s], s, e, s, 0);
1090
+ }
1091
+ }
1092
+ }, Ct = (t) => typeof t != "string" ? !1 : Xt(t) ? !0 : Re(t);
1093
+ class V extends Error {
1094
+ constructor(e) {
1095
+ super(e), this.name = "TransactionValidationError";
1096
+ }
1097
+ }
1098
+ const sn = (t) => t.length > 0 ? t.join(", ") : "none", Ln = (t, e) => new V(`Entity '${t}' does not exist in schema. Available entities: ${sn(e)}`), Fn = {
1099
+ string: (t) => typeof t == "string",
1100
+ number: (t) => typeof t == "number" && !isNaN(t),
1101
+ boolean: (t) => typeof t == "boolean",
1102
+ date: (t) => t instanceof Date || typeof t == "string" || typeof t == "number",
1103
+ json: () => !0
1104
+ }, Wn = (t, e) => t == null ? !0 : Fn[e.valueType]?.(t) ?? !1, rn = (t, e) => {
1105
+ const n = e.entities[t];
1106
+ if (!n)
1107
+ throw Ln(t, Object.keys(e.entities));
1108
+ return n;
1109
+ }, et = (t, e, n) => {
1110
+ const s = rn(t, n);
1111
+ if (typeof e != "object" || e === null)
1112
+ throw new V(`Arguments for data operation on entity '${t}' must be an object, but received: ${typeof e}`);
1113
+ for (const [i, o] of Object.entries(e)) {
1114
+ if (i === "id")
1115
+ continue;
1116
+ const r = s.attrs[i];
1117
+ if (r && !Wn(o, r))
1118
+ throw new V(`Invalid value for attribute '${i}' in entity '${t}'. Expected ${r.valueType}, but received: ${typeof o}`);
1119
+ }
1120
+ }, xt = (t, e, n) => {
1121
+ const s = rn(t, n);
1122
+ if (typeof e != "object" || e === null)
1123
+ throw new V(`Arguments for link operation on entity '${t}' must be an object, but received: ${typeof e}`);
1124
+ for (const [i, o] of Object.entries(e)) {
1125
+ if (!s.links[i]) {
1126
+ const a = Object.keys(s.links);
1127
+ throw new V(`Link '${i}' does not exist on entity '${t}'. Available links: ${sn(a)}`);
1128
+ }
1129
+ if (o != null) {
1130
+ if (Array.isArray(o)) {
1131
+ for (const a of o)
1132
+ if (!Ct(a))
1133
+ throw new V(`Invalid entity ID in link '${i}' for entity '${t}'. Expected a UUID or a lookup, but received: ${a}`);
1134
+ } else if (!Ct(o))
1135
+ throw new V(`Invalid UUID in link '${i}' for entity '${t}'. Expected a UUID, but received: ${o}`);
1136
+ }
1137
+ }
1138
+ }, zn = {
1139
+ create: et,
1140
+ update: et,
1141
+ merge: et,
1142
+ link: xt,
1143
+ unlink: xt,
1144
+ delete: () => {
1145
+ }
1146
+ }, Bn = (t, e) => {
1147
+ if (!e)
1148
+ return;
1149
+ const [n, s, i, o] = t;
1150
+ if (!Array.isArray(i) && !Re(i))
1151
+ throw new V(`Invalid id for entity '${s}'. Expected a UUID, but received: ${i}`);
1152
+ if (typeof s != "string")
1153
+ throw new V(`Entity name must be a string, but received: ${typeof s}`);
1154
+ const r = zn[n];
1155
+ r && o !== void 0 && r(s, o, e);
1156
+ }, Jn = (t, e) => {
1157
+ const n = Array.isArray(t) ? t : [t];
1158
+ for (const s of n) {
1159
+ if (!s || typeof s != "object")
1160
+ throw new V(`Transaction chunk must be an object, but received: ${typeof s}`);
1161
+ if (!Array.isArray(s.__ops))
1162
+ throw new V(`Transaction chunk must have __ops array, but received: ${typeof s.__ops}`);
1163
+ for (const i of s.__ops) {
1164
+ if (!Array.isArray(i))
1165
+ throw new V(`Transaction operation must be an array, but received: ${typeof i}`);
1166
+ Bn(i, e);
1167
+ }
1168
+ }
1169
+ };
1170
+ class qn extends Error {
1171
+ constructor(e) {
1172
+ super(`${e} requires \`apiURI\`. Pass the BackendRelay API origin, for example init({ appId, apiURI: 'https://api.example.com' }). The SDK no longer falls back to backendrelay.com.`), this.name = "MissingApiURIError";
1173
+ }
1174
+ }
1175
+ function on(t, e = "BackendRelay") {
1176
+ const n = t?.trim();
1177
+ if (!n)
1178
+ throw new qn(e);
1179
+ let s;
1180
+ try {
1181
+ s = new URL(n);
1182
+ } catch {
1183
+ throw new Error(`${e} \`apiURI\` must be an absolute http(s) URL. Received: ${n}`);
1184
+ }
1185
+ if (s.protocol !== "http:" && s.protocol !== "https:")
1186
+ throw new Error(`${e} \`apiURI\` must use http:// or https://. Received: ${n}`);
1187
+ return n.replace(/\/+$/, "");
1188
+ }
1189
+ function Kn(t, e) {
1190
+ return t.localeCompare(e);
1191
+ }
1192
+ function Hn() {
1193
+ let t = Kn;
1194
+ if (typeof Intl == "object" && Intl.hasOwnProperty("Collator"))
1195
+ try {
1196
+ t = Intl.Collator("en-US").compare;
1197
+ } catch {
1198
+ }
1199
+ return t;
1200
+ }
1201
+ Hn();
1202
+ var Tt;
1203
+ (function(t) {
1204
+ t.InitialSyncBatch = "InitialSyncBatch", t.InitialSyncComplete = "InitialSyncComplete", t.LoadFromStorage = "LoadFromStorage", t.SyncTransaction = "SyncTransaction", t.Error = "Error";
1205
+ })(Tt || (Tt = {}));
1206
+ function Vn({ WStream: t, opts: e, startStream: n, appendStream: s, registerStream: i, persistence: o }) {
1207
+ const r = e.clientId;
1208
+ let a = null, u = null, l = null, f = Ee(), h = !1, p = !1, m = !1, $ = !1;
1209
+ const w = [], c = [], b = [];
1210
+ let S = !1, d = 0, C = 0;
1211
+ const E = [], A = new TextEncoder();
1212
+ function g() {
1213
+ o.save(r, {
1214
+ reconnectToken: f,
1215
+ ...a ? { streamId: a } : {},
1216
+ buffer: E.map((y) => ({ ...y })),
1217
+ bufferOffset: d,
1218
+ closeRequested: m
1219
+ });
1220
+ }
1221
+ async function k() {
1222
+ const y = await o.load(r);
1223
+ if (!y) {
1224
+ g();
1225
+ return;
1226
+ }
1227
+ $ = !0, f = y.reconnectToken, d = y.bufferOffset, E.push(...y.buffer), C = E.reduce((v, F) => v + F.byteLen, 0), m = y.closeRequested, h = y.closeRequested, y.streamId && j(y.streamId);
1228
+ }
1229
+ function L() {
1230
+ p = !0;
1231
+ for (const y of w)
1232
+ y(u ?? void 0);
1233
+ }
1234
+ function P(y) {
1235
+ return w.push(y), p && y(u ?? void 0), () => {
1236
+ const v = w.indexOf(y);
1237
+ v !== -1 && w.splice(v, 1);
1238
+ };
1239
+ }
1240
+ function x(y) {
1241
+ return b.push(y), () => {
1242
+ const v = b.indexOf(y);
1243
+ v !== -1 && b.splice(v, 1);
1244
+ };
1245
+ }
1246
+ e.waitUntil && e.waitUntil(new Promise((y) => {
1247
+ b.push(y);
1248
+ }));
1249
+ function M() {
1250
+ for (const y of b)
1251
+ try {
1252
+ y();
1253
+ } catch {
1254
+ }
1255
+ }
1256
+ function z(y) {
1257
+ return c.push(y), a && y(a), () => {
1258
+ const v = c.indexOf(y);
1259
+ v !== -1 && c.splice(v, 1);
1260
+ };
1261
+ }
1262
+ function j(y) {
1263
+ a = y, g();
1264
+ for (const v of c)
1265
+ v(a);
1266
+ }
1267
+ function le() {
1268
+ S = !0;
1269
+ }
1270
+ function Le(y) {
1271
+ let v = d, F = 0, H = 0;
1272
+ for (const { byteLen: Q } of E) {
1273
+ const te = v + Q;
1274
+ if (te > y)
1275
+ break;
1276
+ v = te, F++, H += Q;
1277
+ }
1278
+ F > 0 && (d += H, C -= H, E.splice(0, F), g());
1279
+ }
1280
+ function ue(y) {
1281
+ !E.length && !m || s({
1282
+ streamId: y,
1283
+ chunks: E.map((v) => v.chunk),
1284
+ offset: d,
1285
+ isDone: m
1286
+ });
1287
+ }
1288
+ function q(y, v) {
1289
+ u = v, L(), y.error(v), M();
1290
+ }
1291
+ async function ee() {
1292
+ const y = await n({
1293
+ clientId: r,
1294
+ reconnectToken: f,
1295
+ ruleParams: e.ruleParams
1296
+ });
1297
+ switch (y.type) {
1298
+ case "ok": {
1299
+ const { streamId: v, offset: F } = y;
1300
+ j(v), Le(F), i(v, Fe), ue(v), S = !1;
1301
+ break;
1302
+ }
1303
+ case "disconnect": {
1304
+ le();
1305
+ break;
1306
+ }
1307
+ case "error": {
1308
+ l && q(l, y.error);
1309
+ break;
1310
+ }
1311
+ }
1312
+ }
1313
+ function fe() {
1314
+ le(), ee();
1315
+ }
1316
+ function de({ offset: y, done: v }) {
1317
+ Le(y), v && (h = !0, o.remove(r), M());
1318
+ }
1319
+ const Fe = {
1320
+ onDisconnect: le,
1321
+ onFlush: de,
1322
+ onConnectionReconnect: ee,
1323
+ onAppendFailed: fe
1324
+ };
1325
+ function un(y) {
1326
+ return h ? (q(y, new R("Stream has been closed.")), null) : a || (q(y, new R("Stream has not been initialized.")), null);
1327
+ }
1328
+ async function fn(y) {
1329
+ l = y, await k();
1330
+ let v = !0, F = 0;
1331
+ for (; v; ) {
1332
+ let H = Date.now() + Math.min(15e3, 500 * (F - 1));
1333
+ v = !1;
1334
+ const Q = await n({
1335
+ clientId: e.clientId,
1336
+ reconnectToken: f,
1337
+ ruleParams: e.ruleParams
1338
+ });
1339
+ switch (Q.type) {
1340
+ case "ok": {
1341
+ const { streamId: te, offset: We } = Q;
1342
+ if (!$ && We !== 0) {
1343
+ const he = new R("Write stream is corrupted");
1344
+ q(y, he);
1345
+ return;
1346
+ }
1347
+ j(te), Le(We), i(te, Fe), ue(te), S = !1;
1348
+ return;
1349
+ }
1350
+ case "disconnect": {
1351
+ v = !0, le(), F++, await new Promise((te) => {
1352
+ setTimeout(te, Math.max(0, H - Date.now()));
1353
+ });
1354
+ break;
1355
+ }
1356
+ case "error": {
1357
+ q(y, Q.error);
1358
+ return;
1359
+ }
1360
+ }
1361
+ }
1362
+ }
1363
+ class dn extends t {
1364
+ constructor(v, F) {
1365
+ super(v, F);
1366
+ }
1367
+ async streamId() {
1368
+ return a || new Promise((v, F) => {
1369
+ const H = [], Q = () => {
1370
+ for (const he of H)
1371
+ he();
1372
+ }, te = (he) => {
1373
+ v(he), Q();
1374
+ }, We = (he) => {
1375
+ F(he || new R("Stream is closed.")), Q();
1376
+ };
1377
+ H.push(z(te)), H.push(P(We));
1378
+ });
1379
+ }
1380
+ }
1381
+ return {
1382
+ stream: new dn({
1383
+ async start(y) {
1384
+ try {
1385
+ await fn(y);
1386
+ } catch (v) {
1387
+ q(y, v);
1388
+ }
1389
+ },
1390
+ write(y, v) {
1391
+ const F = un(v);
1392
+ if (F) {
1393
+ const H = A.encode(y).length;
1394
+ E.push({ chunk: y, byteLen: H });
1395
+ const Q = d + C;
1396
+ C += H, g(), S || s({ streamId: F, chunks: [y], offset: Q });
1397
+ }
1398
+ },
1399
+ close() {
1400
+ m = !0, g(), a ? s({
1401
+ streamId: a,
1402
+ chunks: [],
1403
+ offset: d + C,
1404
+ isDone: !0
1405
+ }) : M(), L();
1406
+ },
1407
+ abort(y) {
1408
+ o.remove(r), a ? s({
1409
+ streamId: a,
1410
+ chunks: [],
1411
+ offset: d + C,
1412
+ isDone: !0,
1413
+ abortReason: y
1414
+ }) : M(), L();
1415
+ }
1416
+ }),
1417
+ addCompleteCb: x,
1418
+ closed() {
1419
+ return p;
1420
+ }
1421
+ };
1422
+ }
1423
+ class Qn {
1424
+ items = [];
1425
+ resolvers = [];
1426
+ isClosed = !1;
1427
+ constructor() {
1428
+ }
1429
+ push(e) {
1430
+ if (this.isClosed)
1431
+ return;
1432
+ const n = this.resolvers.shift();
1433
+ n ? n({ value: e, done: !1 }) : this.items.push(e);
1434
+ }
1435
+ close() {
1436
+ for (this.isClosed = !0; this.resolvers.length > 0; )
1437
+ this.resolvers.shift()({ value: void 0, done: !0 });
1438
+ }
1439
+ async *[Symbol.asyncIterator]() {
1440
+ for (; ; )
1441
+ if (this.items.length > 0)
1442
+ yield this.items.shift();
1443
+ else {
1444
+ if (this.isClosed)
1445
+ return;
1446
+ {
1447
+ const { value: e, done: n } = await new Promise((s) => {
1448
+ this.resolvers.push(s);
1449
+ });
1450
+ if (n || !e)
1451
+ return;
1452
+ yield e;
1453
+ }
1454
+ }
1455
+ }
1456
+ }
1457
+ function Gn({ RStream: t, opts: e, startStream: n, cancelStream: s }) {
1458
+ let i = e.byteOffset || 0, o = !1;
1459
+ const r = new TextDecoder("utf-8"), a = new TextEncoder();
1460
+ let u, l = !1;
1461
+ const f = [], h = [];
1462
+ let p = null, m = null;
1463
+ function $(g) {
1464
+ l = !0;
1465
+ for (const k of f)
1466
+ k(g);
1467
+ }
1468
+ function w(g) {
1469
+ return f.push(g), () => {
1470
+ const k = f.indexOf(g);
1471
+ k !== -1 && f.splice(k, 1);
1472
+ };
1473
+ }
1474
+ function c(g) {
1475
+ return h.push(g), p && g(p), () => {
1476
+ const k = h.indexOf(g);
1477
+ k !== -1 && h.splice(k, 1);
1478
+ };
1479
+ }
1480
+ function b(g, k) {
1481
+ m = k, g.error(k), $(k);
1482
+ }
1483
+ let S = 0;
1484
+ async function d(g, k) {
1485
+ u = Ee();
1486
+ const L = { ...g || {}, eventId: u };
1487
+ for await (const P of n(L)) {
1488
+ if (o)
1489
+ return;
1490
+ if (P.type === "reconnect")
1491
+ return { retry: !0 };
1492
+ if (P.type === "error") {
1493
+ b(k, P.error);
1494
+ return;
1495
+ }
1496
+ if (P.offset > i) {
1497
+ b(k, new R("Stream is corrupted.")), o = !0;
1498
+ return;
1499
+ }
1500
+ p = P.streamId;
1501
+ for (const M of h)
1502
+ M(p);
1503
+ let x = i - P.offset;
1504
+ if (P.files && P.files.length) {
1505
+ const M = new AbortController();
1506
+ let z = fetch(P.files[0].url, {
1507
+ signal: M.signal
1508
+ });
1509
+ for (let j = 0; j < P.files.length; j++) {
1510
+ const le = P.files[j + 1], ue = await z;
1511
+ if (le && (z = fetch(le.url, { signal: M.signal })), !ue.ok) {
1512
+ if (S++, S > 10) {
1513
+ b(k, new R("Unable to process stream."));
1514
+ return;
1515
+ }
1516
+ return { retry: !0 };
1517
+ }
1518
+ if (ue.body) {
1519
+ const q = ue.body.getReader();
1520
+ try {
1521
+ for (; ; ) {
1522
+ const { done: ee, value: fe } = await q.read();
1523
+ if (ee)
1524
+ break;
1525
+ if (o) {
1526
+ M.abort();
1527
+ return;
1528
+ }
1529
+ let de = fe;
1530
+ if (x > 0 && (de = fe.subarray(x), x -= fe.length - de.length), !de.length)
1531
+ continue;
1532
+ i += de.length;
1533
+ const Fe = r.decode(de);
1534
+ k.enqueue(Fe);
1535
+ }
1536
+ } finally {
1537
+ q.releaseLock();
1538
+ }
1539
+ } else {
1540
+ const q = await ue.arrayBuffer();
1541
+ let ee = q;
1542
+ if (o) {
1543
+ M.abort();
1544
+ return;
1545
+ }
1546
+ if (x > 0 && (ee = new Uint8Array(q).subarray(x), x -= q.byteLength - ee.length), !ee.byteLength)
1547
+ continue;
1548
+ i += ee.byteLength;
1549
+ const fe = r.decode(ee);
1550
+ k.enqueue(fe);
1551
+ }
1552
+ }
1553
+ }
1554
+ if (S = 0, P.content) {
1555
+ let M = P.content, z = a.encode(P.content);
1556
+ if (x > 0) {
1557
+ const j = z.subarray(x);
1558
+ if (x -= z.length - j.length, !j.length)
1559
+ continue;
1560
+ z = j, M = r.decode(j);
1561
+ }
1562
+ i += z.length, k.enqueue(M);
1563
+ }
1564
+ }
1565
+ }
1566
+ async function C(g) {
1567
+ let k = !0, L = 0;
1568
+ for (; k; ) {
1569
+ k = !1;
1570
+ let P = Date.now() + Math.min(15e3, 500 * (L - 1));
1571
+ (await d({ ...e, offset: i }, g))?.retry && (k = !0, L++, P < Date.now() - 3e5 && (L = 0), await new Promise((M) => {
1572
+ setTimeout(M, Math.max(0, P - Date.now()));
1573
+ }));
1574
+ }
1575
+ !o && !l && (g.close(), $());
1576
+ }
1577
+ class E extends t {
1578
+ constructor(k, L) {
1579
+ super(k, L);
1580
+ }
1581
+ async streamId() {
1582
+ if (p)
1583
+ return p;
1584
+ if (m)
1585
+ throw m;
1586
+ return new Promise((k, L) => {
1587
+ const P = [], x = () => {
1588
+ for (const j of P)
1589
+ j();
1590
+ }, M = (j) => {
1591
+ k(j), x();
1592
+ }, z = (j) => {
1593
+ L(j || new R("Stream is closed.")), x();
1594
+ };
1595
+ P.push(c(M)), P.push(w(z));
1596
+ });
1597
+ }
1598
+ }
1599
+ return {
1600
+ stream: new E({
1601
+ start(g) {
1602
+ C(g);
1603
+ },
1604
+ cancel(g) {
1605
+ o = !0, u && s({ eventId: u }), $();
1606
+ }
1607
+ }),
1608
+ addCloseCb: w,
1609
+ closed() {
1610
+ return l;
1611
+ }
1612
+ };
1613
+ }
1614
+ class Yn {
1615
+ trySend;
1616
+ WStream;
1617
+ RStream;
1618
+ writeStreams = {};
1619
+ startWriteStreamCbs = {};
1620
+ readStreamIterators = {};
1621
+ log;
1622
+ writeStreamPersistence;
1623
+ activeStreams = /* @__PURE__ */ new Set();
1624
+ constructor({ WStream: e, RStream: n, trySend: s, log: i, writeStreamPersistence: o }) {
1625
+ this.WStream = e, this.RStream = n, this.trySend = s, this.log = i, this.writeStreamPersistence = o ?? {
1626
+ load: async () => null,
1627
+ save: () => {
1628
+ },
1629
+ remove: () => {
1630
+ }
1631
+ };
1632
+ }
1633
+ createWriteStream(e) {
1634
+ const { stream: n, addCompleteCb: s } = Vn({
1635
+ WStream: this.WStream,
1636
+ startStream: this.startWriteStream.bind(this),
1637
+ appendStream: this.appendStream.bind(this),
1638
+ registerStream: this.registerWriteStream.bind(this),
1639
+ persistence: this.writeStreamPersistence,
1640
+ opts: e
1641
+ });
1642
+ return this.activeStreams.add(n), s(() => {
1643
+ this.activeStreams.delete(n);
1644
+ }), n;
1645
+ }
1646
+ createReadStream(e) {
1647
+ const { stream: n, addCloseCb: s } = Gn({
1648
+ RStream: this.RStream,
1649
+ opts: e,
1650
+ startStream: this.startReadStream.bind(this),
1651
+ cancelStream: this.cancelReadStream.bind(this)
1652
+ });
1653
+ return this.activeStreams.add(n), s(() => {
1654
+ this.activeStreams.delete(n);
1655
+ }), n;
1656
+ }
1657
+ startWriteStream(e) {
1658
+ const n = Ee();
1659
+ let s = null;
1660
+ const i = new Promise((r) => {
1661
+ s = r;
1662
+ });
1663
+ this.startWriteStreamCbs[n] = s;
1664
+ const o = {
1665
+ op: "start-stream",
1666
+ "client-id": e.clientId,
1667
+ "reconnect-token": e.reconnectToken
1668
+ };
1669
+ return e.ruleParams && (o["rule-params"] = e.ruleParams), this.trySend(n, o), i;
1670
+ }
1671
+ registerWriteStream(e, n) {
1672
+ this.writeStreams[e] = n;
1673
+ }
1674
+ appendStream({ streamId: e, chunks: n, isDone: s, offset: i, abortReason: o }) {
1675
+ const r = {
1676
+ op: "append-stream",
1677
+ "stream-id": e,
1678
+ chunks: n,
1679
+ offset: i,
1680
+ done: !!s
1681
+ };
1682
+ o && (r["abort-reason"] = o), this.trySend(Ee(), r);
1683
+ }
1684
+ onAppendFailed(e) {
1685
+ const n = this.writeStreams[e["stream-id"]];
1686
+ n && n.onAppendFailed();
1687
+ }
1688
+ onStartStreamOk(e) {
1689
+ const n = this.startWriteStreamCbs[e["client-event-id"]];
1690
+ if (!n) {
1691
+ this.log.info("No stream for start-stream-ok", e);
1692
+ return;
1693
+ }
1694
+ n({ type: "ok", streamId: e["stream-id"], offset: e.offset }), delete this.startWriteStreamCbs[e["client-event-id"]];
1695
+ }
1696
+ onStreamFlushed(e) {
1697
+ const n = e["stream-id"], s = this.writeStreams[n];
1698
+ if (!s) {
1699
+ this.log.info("No stream cbs for stream-flushed", e);
1700
+ return;
1701
+ }
1702
+ s.onFlush({ offset: e.offset, done: e.done }), e.done && delete this.writeStreams[n];
1703
+ }
1704
+ startReadStream({ eventId: e, clientId: n, streamId: s, offset: i, ruleParams: o }) {
1705
+ const r = { op: "subscribe-stream" };
1706
+ if (!s && !n)
1707
+ throw new Error("Must provide one of streamId or clientId to subscribe to the stream.");
1708
+ s && (r["stream-id"] = s), n && (r["client-id"] = n), i && (r.offset = i), o && (r["rule-params"] = o);
1709
+ const a = new Qn();
1710
+ return this.readStreamIterators[e] = a, this.trySend(e, r), a;
1711
+ }
1712
+ cancelReadStream({ eventId: e }) {
1713
+ const n = {
1714
+ op: "unsubscribe-stream",
1715
+ "subscribe-event-id": e
1716
+ };
1717
+ this.trySend(Ee(), n), delete this.readStreamIterators[e];
1718
+ }
1719
+ onStreamAppend(e) {
1720
+ const n = e["client-event-id"], s = this.readStreamIterators[n];
1721
+ if (!s) {
1722
+ this.log.info("No iterator for read stream", e);
1723
+ return;
1724
+ }
1725
+ if (e.error) {
1726
+ e.retry ? s.push({ type: "reconnect" }) : s.push({
1727
+ type: "error",
1728
+ error: new R(e.error)
1729
+ }), s.close(), delete this.readStreamIterators[n];
1730
+ return;
1731
+ }
1732
+ s.push({
1733
+ type: "append",
1734
+ offset: e.offset,
1735
+ files: e.files,
1736
+ content: e.content,
1737
+ streamId: e["stream-id"]
1738
+ }), e.done && (s.close(), delete this.readStreamIterators[n]);
1739
+ }
1740
+ onConnectionStatusChange(e) {
1741
+ for (const n of Object.values(this.startWriteStreamCbs))
1742
+ n({ type: "disconnect" });
1743
+ if (this.startWriteStreamCbs = {}, e !== Xn.AUTHENTICATED)
1744
+ for (const { onDisconnect: n } of Object.values(this.writeStreams))
1745
+ n();
1746
+ else {
1747
+ for (const { onConnectionReconnect: n } of Object.values(this.writeStreams))
1748
+ n();
1749
+ for (const n of Object.values(this.readStreamIterators))
1750
+ n.push({ type: "reconnect" }), n.close();
1751
+ this.readStreamIterators = {};
1752
+ }
1753
+ }
1754
+ onRecieveError(e) {
1755
+ const n = e["original-event"];
1756
+ switch (n.op) {
1757
+ case "append-stream": {
1758
+ const s = n["stream-id"];
1759
+ this.writeStreams[s]?.onAppendFailed();
1760
+ break;
1761
+ }
1762
+ case "start-stream": {
1763
+ const s = e["client-event-id"], i = this.startWriteStreamCbs[s];
1764
+ i && (i({
1765
+ type: "error",
1766
+ error: new R(e.message || "Unknown error", e.hint)
1767
+ }), delete this.startWriteStreamCbs[s]);
1768
+ break;
1769
+ }
1770
+ case "subscribe-stream": {
1771
+ const s = e["client-event-id"], i = this.readStreamIterators[s];
1772
+ i && (i.push({
1773
+ type: "error",
1774
+ error: new R(e.message || "Unknown error", e.hint)
1775
+ }), i.close(), delete this.readStreamIterators[s]);
1776
+ break;
1777
+ }
1778
+ }
1779
+ }
1780
+ hasActiveStreams() {
1781
+ return this.activeStreams.size > 0;
1782
+ }
1783
+ }
1784
+ const Xn = {
1785
+ AUTHENTICATED: "authenticated"
1786
+ };
1787
+ let Zn = 0;
1788
+ const es = "X-BackendRelay-SSE-Push-Format", ts = "ndjson", ns = 100, ss = 1e4;
1789
+ class is {
1790
+ type = "sse";
1791
+ initParams = null;
1792
+ sendQueue = [];
1793
+ sendPromise;
1794
+ flushScheduled = !1;
1795
+ supportsNdjson = !1;
1796
+ closeFired = !1;
1797
+ sseInitTimeout = void 0;
1798
+ pushTimeout;
1799
+ pushController = null;
1800
+ ES;
1801
+ messageUrl;
1802
+ conn;
1803
+ url;
1804
+ id;
1805
+ onopen;
1806
+ onmessage;
1807
+ onclose;
1808
+ onerror;
1809
+ constructor(e, n, s) {
1810
+ this.id = `${this.type}_${Zn++}`, this.url = n, this.messageUrl = s || this.url, this.ES = e, this.conn = new e(n), this.sseInitTimeout = setTimeout(() => {
1811
+ this.initParams || this.handleError();
1812
+ }, 1e4), this.conn.onmessage = (i) => {
1813
+ const o = JSON.parse(i.data);
1814
+ if (Array.isArray(o))
1815
+ for (const r of o)
1816
+ this.handleMessage(r);
1817
+ else
1818
+ this.handleMessage(o);
1819
+ }, this.conn.onerror = (i) => {
1820
+ this.handleError();
1821
+ };
1822
+ }
1823
+ handleMessage(e) {
1824
+ if (!this.closeFired) {
1825
+ if (e.op === "sse-init") {
1826
+ this.initParams = {
1827
+ machineId: e["machine-id"],
1828
+ sessionId: e["session-id"],
1829
+ sseToken: e["sse-token"]
1830
+ }, this.onopen && this.onopen({ target: this }), clearTimeout(this.sseInitTimeout);
1831
+ return;
1832
+ }
1833
+ this.onmessage && this.onmessage({
1834
+ target: this,
1835
+ message: e
1836
+ });
1837
+ }
1838
+ }
1839
+ // Runs the onerror and closes the connection
1840
+ handleError() {
1841
+ if (!this.closeFired)
1842
+ try {
1843
+ this.onerror && this.onerror({ target: this });
1844
+ } finally {
1845
+ this.handleClose();
1846
+ }
1847
+ }
1848
+ handleClose() {
1849
+ this.closeFired || (this.closeFired = !0, clearTimeout(this.sseInitTimeout), clearTimeout(this.pushTimeout), this.sendQueue = [], this.pushController?.abort(), this.pushController = null, this.conn.close(), this.onclose && this.onclose({ target: this }));
1850
+ }
1851
+ post(e, n, s) {
1852
+ const i = this.initParams, o = n ? [
1853
+ JSON.stringify({
1854
+ machine_id: i?.machineId,
1855
+ session_id: i?.sessionId,
1856
+ sse_token: i?.sseToken
1857
+ }),
1858
+ ...e.map((r) => JSON.stringify(r)),
1859
+ ""
1860
+ ].join(`
1861
+ `) : JSON.stringify({
1862
+ machine_id: i?.machineId,
1863
+ session_id: i?.sessionId,
1864
+ sse_token: i?.sseToken,
1865
+ messages: e
1866
+ });
1867
+ return fetch(this.messageUrl, {
1868
+ method: "POST",
1869
+ headers: {
1870
+ Accept: "application/x-ndjson, application/json",
1871
+ "Content-Type": n ? "application/x-ndjson" : "application/json"
1872
+ },
1873
+ body: o,
1874
+ signal: s
1875
+ });
1876
+ }
1877
+ async postMessages(e) {
1878
+ const n = new AbortController();
1879
+ this.pushController = n, this.pushTimeout = setTimeout(() => this.handleError(), ss);
1880
+ try {
1881
+ let s = await this.post(e, this.supportsNdjson, n.signal);
1882
+ if (this.closeFired || this.supportsNdjson && (s.status === 406 || s.status === 415) && (this.supportsNdjson = !1, s = await this.post(e, !1, n.signal), this.closeFired))
1883
+ return;
1884
+ if (!s.ok) {
1885
+ this.handleError();
1886
+ return;
1887
+ }
1888
+ this.supportsNdjson = s.headers.get(es) === ts;
1889
+ } catch {
1890
+ this.handleError();
1891
+ } finally {
1892
+ clearTimeout(this.pushTimeout), this.pushController = null;
1893
+ }
1894
+ }
1895
+ async flushQueue() {
1896
+ if (!this.isOpen() || this.sendPromise || !this.sendQueue.length)
1897
+ return;
1898
+ const e = this.sendQueue.splice(0, ns), n = this.postMessages(e);
1899
+ this.sendPromise = n, n.then(() => {
1900
+ this.sendPromise = null, this.isOpen() && this.flushQueue();
1901
+ });
1902
+ }
1903
+ scheduleFlush() {
1904
+ this.flushScheduled || (this.flushScheduled = !0, Promise.resolve().then(() => {
1905
+ this.flushScheduled = !1, this.flushQueue();
1906
+ }));
1907
+ }
1908
+ send(e) {
1909
+ if (!this.isOpen() || !this.initParams)
1910
+ throw this.isConnecting() ? new Error("Failed to execute 'send' on 'EventSource': Still in CONNECTING state.") : this.conn.readyState === this.ES.CLOSED ? new Error("EventSource is already in CLOSING or CLOSED state.") : new Error("EventSource is in invalid state.");
1911
+ this.sendQueue.push(e), this.scheduleFlush();
1912
+ }
1913
+ isOpen() {
1914
+ return !this.closeFired && this.conn.readyState === this.ES.OPEN && this.initParams !== null;
1915
+ }
1916
+ isConnecting() {
1917
+ return !this.closeFired && (this.conn.readyState === this.ES.CONNECTING || this.conn.readyState === this.ES.OPEN && this.initParams === null);
1918
+ }
1919
+ close() {
1920
+ this.handleClose();
1921
+ }
1922
+ }
1923
+ function rs() {
1924
+ return globalThis.__backendrelayDbSchemaHashStore = globalThis.__backendrelayDbSchemaHashStore ?? /* @__PURE__ */ new WeakMap(), globalThis.__backendrelayDbSchemaHashStore;
1925
+ }
1926
+ function os() {
1927
+ return globalThis.__backendrelayDbStore = globalThis.__backendrelayDbStore ?? {}, globalThis.__backendrelayDbStore;
1928
+ }
1929
+ os();
1930
+ rs();
1931
+ class At extends Error {
1932
+ constructor(e, n) {
1933
+ super(e), this.name = "ParseError", this.type = n.type, this.field = n.field, this.value = n.value, this.line = n.line;
1934
+ }
1935
+ }
1936
+ function tt(t) {
1937
+ }
1938
+ function as(t) {
1939
+ if (typeof t == "function")
1940
+ throw new TypeError(
1941
+ "`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?"
1942
+ );
1943
+ const { onEvent: e = tt, onError: n = tt, onRetry: s = tt, onComment: i } = t;
1944
+ let o = "", r = !0, a, u = "", l = "";
1945
+ function f(w) {
1946
+ const c = r ? w.replace(/^\xEF\xBB\xBF/, "") : w, [b, S] = cs(`${o}${c}`);
1947
+ for (const d of b)
1948
+ h(d);
1949
+ o = S, r = !1;
1950
+ }
1951
+ function h(w) {
1952
+ if (w === "") {
1953
+ m();
1954
+ return;
1955
+ }
1956
+ if (w.startsWith(":")) {
1957
+ i && i(w.slice(w.startsWith(": ") ? 2 : 1));
1958
+ return;
1959
+ }
1960
+ const c = w.indexOf(":");
1961
+ if (c !== -1) {
1962
+ const b = w.slice(0, c), S = w[c + 1] === " " ? 2 : 1, d = w.slice(c + S);
1963
+ p(b, d, w);
1964
+ return;
1965
+ }
1966
+ p(w, "", w);
1967
+ }
1968
+ function p(w, c, b) {
1969
+ switch (w) {
1970
+ case "event":
1971
+ l = c;
1972
+ break;
1973
+ case "data":
1974
+ u = `${u}${c}
1975
+ `;
1976
+ break;
1977
+ case "id":
1978
+ a = c.includes("\0") ? void 0 : c;
1979
+ break;
1980
+ case "retry":
1981
+ /^\d+$/.test(c) ? s(parseInt(c, 10)) : n(
1982
+ new At(`Invalid \`retry\` value: "${c}"`, {
1983
+ type: "invalid-retry",
1984
+ value: c,
1985
+ line: b
1986
+ })
1987
+ );
1988
+ break;
1989
+ default:
1990
+ n(
1991
+ new At(
1992
+ `Unknown field "${w.length > 20 ? `${w.slice(0, 20)}…` : w}"`,
1993
+ { type: "unknown-field", field: w, value: c, line: b }
1994
+ )
1995
+ );
1996
+ break;
1997
+ }
1998
+ }
1999
+ function m() {
2000
+ u.length > 0 && e({
2001
+ id: a,
2002
+ event: l || void 0,
2003
+ // If the data buffer's last character is a U+000A LINE FEED (LF) character,
2004
+ // then remove the last character from the data buffer.
2005
+ data: u.endsWith(`
2006
+ `) ? u.slice(0, -1) : u
2007
+ }), a = void 0, u = "", l = "";
2008
+ }
2009
+ function $(w = {}) {
2010
+ o && w.consume && h(o), r = !0, a = void 0, u = "", l = "", o = "";
2011
+ }
2012
+ return { feed: f, reset: $ };
2013
+ }
2014
+ function cs(t) {
2015
+ const e = [];
2016
+ let n = "", s = 0;
2017
+ for (; s < t.length; ) {
2018
+ const i = t.indexOf("\r", s), o = t.indexOf(`
2019
+ `, s);
2020
+ let r = -1;
2021
+ if (i !== -1 && o !== -1 ? r = Math.min(i, o) : i !== -1 ? i === t.length - 1 ? r = -1 : r = i : o !== -1 && (r = o), r === -1) {
2022
+ n = t.slice(s);
2023
+ break;
2024
+ } else {
2025
+ const a = t.slice(s, r);
2026
+ e.push(a), s = r + 1, t[s - 1] === "\r" && t[s] === `
2027
+ ` && s++;
2028
+ }
2029
+ }
2030
+ return [e, n];
2031
+ }
2032
+ class Pt extends Event {
2033
+ /**
2034
+ * Constructs a new `ErrorEvent` instance. This is typically not called directly,
2035
+ * but rather emitted by the `EventSource` object when an error occurs.
2036
+ *
2037
+ * @param type - The type of the event (should be "error")
2038
+ * @param errorEventInitDict - Optional properties to include in the error event
2039
+ */
2040
+ constructor(e, n) {
2041
+ var s, i;
2042
+ super(e), this.code = (s = n?.code) != null ? s : void 0, this.message = (i = n?.message) != null ? i : void 0;
2043
+ }
2044
+ /**
2045
+ * Node.js "hides" the `message` and `code` properties of the `ErrorEvent` instance,
2046
+ * when it is `console.log`'ed. This makes it harder to debug errors. To ease debugging,
2047
+ * we explicitly include the properties in the `inspect` method.
2048
+ *
2049
+ * This is automatically called by Node.js when you `console.log` an instance of this class.
2050
+ *
2051
+ * @param _depth - The current depth
2052
+ * @param options - The options passed to `util.inspect`
2053
+ * @param inspect - The inspect function to use (prevents having to import it from `util`)
2054
+ * @returns A string representation of the error
2055
+ */
2056
+ [/* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom")](e, n, s) {
2057
+ return s(Ut(this), n);
2058
+ }
2059
+ /**
2060
+ * Deno "hides" the `message` and `code` properties of the `ErrorEvent` instance,
2061
+ * when it is `console.log`'ed. This makes it harder to debug errors. To ease debugging,
2062
+ * we explicitly include the properties in the `inspect` method.
2063
+ *
2064
+ * This is automatically called by Deno when you `console.log` an instance of this class.
2065
+ *
2066
+ * @param inspect - The inspect function to use (prevents having to import it from `util`)
2067
+ * @param options - The options passed to `Deno.inspect`
2068
+ * @returns A string representation of the error
2069
+ */
2070
+ [/* @__PURE__ */ Symbol.for("Deno.customInspect")](e, n) {
2071
+ return e(Ut(this), n);
2072
+ }
2073
+ }
2074
+ function ls(t) {
2075
+ const e = globalThis.DOMException;
2076
+ return typeof e == "function" ? new e(t, "SyntaxError") : new SyntaxError(t);
2077
+ }
2078
+ function at(t) {
2079
+ return t instanceof Error ? "errors" in t && Array.isArray(t.errors) ? t.errors.map(at).join(", ") : "cause" in t && t.cause instanceof Error ? `${t}: ${at(t.cause)}` : t.message : `${t}`;
2080
+ }
2081
+ function Ut(t) {
2082
+ return {
2083
+ type: t.type,
2084
+ message: t.message,
2085
+ code: t.code,
2086
+ defaultPrevented: t.defaultPrevented,
2087
+ cancelable: t.cancelable,
2088
+ timeStamp: t.timeStamp
2089
+ };
2090
+ }
2091
+ var an = (t) => {
2092
+ throw TypeError(t);
2093
+ }, wt = (t, e, n) => e.has(t) || an("Cannot " + n), I = (t, e, n) => (wt(t, e, "read from private field"), n ? n.call(t) : e.get(t)), D = (t, e, n) => e.has(t) ? an("Cannot add the same private member more than once") : e instanceof WeakSet ? e.add(t) : e.set(t, n), U = (t, e, n, s) => (wt(t, e, "write to private field"), e.set(t, n), n), ie = (t, e, n) => (wt(t, e, "access private method"), n), J, pe, ve, He, Ye, Ve, Pe, $e, Ue, ae, ke, _e, Ie, xe, Y, ct, lt, ut, jt, ft, dt, Te, ht, pt;
2094
+ class X extends EventTarget {
2095
+ constructor(e, n) {
2096
+ var s, i, o;
2097
+ super(), D(this, Y), this.CONNECTING = 0, this.OPEN = 1, this.CLOSED = 2, D(this, J), D(this, pe), D(this, ve), D(this, He), D(this, Ye), D(this, Ve), D(this, Pe), D(this, $e), D(this, Ue, null), D(this, ae), D(this, ke), D(this, _e, null), D(this, Ie, null), D(this, xe, null), D(this, lt, async (r) => {
2098
+ var a;
2099
+ I(this, ke).reset();
2100
+ const { body: u, redirected: l, status: f, headers: h } = r;
2101
+ if (f === 204) {
2102
+ ie(this, Y, Te).call(this, "Server sent HTTP 204, not reconnecting", 204), this.close();
2103
+ return;
2104
+ }
2105
+ if (l ? U(this, ve, new URL(r.url)) : U(this, ve, void 0), f !== 200) {
2106
+ ie(this, Y, Te).call(this, `Non-200 status code (${f})`, f);
2107
+ return;
2108
+ }
2109
+ if (!(h.get("content-type") || "").startsWith("text/event-stream")) {
2110
+ ie(this, Y, Te).call(this, 'Invalid content type, expected "text/event-stream"', f);
2111
+ return;
2112
+ }
2113
+ if (I(this, J) === this.CLOSED)
2114
+ return;
2115
+ U(this, J, this.OPEN);
2116
+ const p = new Event("open");
2117
+ if ((a = I(this, xe)) == null || a.call(this, p), this.dispatchEvent(p), typeof u != "object" || !u || !("getReader" in u)) {
2118
+ ie(this, Y, Te).call(this, "Invalid response body, expected a web ReadableStream", f), this.close();
2119
+ return;
2120
+ }
2121
+ const m = new TextDecoder(), $ = u.getReader();
2122
+ let w = !0;
2123
+ do {
2124
+ const { done: c, value: b } = await $.read();
2125
+ b && I(this, ke).feed(m.decode(b, { stream: !c })), c && (w = !1, I(this, ke).reset(), ie(this, Y, ht).call(this));
2126
+ } while (w);
2127
+ }), D(this, ut, (r) => {
2128
+ U(this, ae, void 0), !(r.name === "AbortError" || r.type === "aborted") && ie(this, Y, ht).call(this, at(r));
2129
+ }), D(this, ft, (r) => {
2130
+ typeof r.id == "string" && U(this, Ue, r.id);
2131
+ const a = new (I(this, Ve))(r.event || "message", {
2132
+ data: r.data,
2133
+ origin: I(this, ve) ? I(this, ve).origin : I(this, pe).origin,
2134
+ lastEventId: r.id || ""
2135
+ });
2136
+ I(this, Ie) && (!r.event || r.event === "message") && I(this, Ie).call(this, a), this.dispatchEvent(a);
2137
+ }), D(this, dt, (r) => {
2138
+ U(this, Pe, r);
2139
+ }), D(this, pt, () => {
2140
+ U(this, $e, void 0), I(this, J) === this.CONNECTING && ie(this, Y, ct).call(this);
2141
+ });
2142
+ try {
2143
+ if (e instanceof URL)
2144
+ U(this, pe, e);
2145
+ else if (typeof e == "string")
2146
+ U(this, pe, new URL(e, us()));
2147
+ else
2148
+ throw new Error("Invalid URL");
2149
+ } catch {
2150
+ throw ls("An invalid or illegal string was specified");
2151
+ }
2152
+ U(this, ke, as({
2153
+ onEvent: I(this, ft),
2154
+ onRetry: I(this, dt)
2155
+ })), U(this, J, this.CONNECTING), U(this, Pe, 3e3), U(this, Ye, (s = n?.fetch) != null ? s : globalThis.fetch), U(this, Ve, (i = n?.messageEvent) != null ? i : globalThis.MessageEvent), U(this, He, (o = n?.withCredentials) != null ? o : !1), ie(this, Y, ct).call(this);
2156
+ }
2157
+ /**
2158
+ * Returns the state of this EventSource object's connection. It can have the values described below.
2159
+ *
2160
+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/readyState)
2161
+ *
2162
+ * Note: typed as `number` instead of `0 | 1 | 2` for compatibility with the `EventSource` interface,
2163
+ * defined in the TypeScript `dom` library.
2164
+ *
2165
+ * @public
2166
+ */
2167
+ get readyState() {
2168
+ return I(this, J);
2169
+ }
2170
+ /**
2171
+ * Returns the URL providing the event stream.
2172
+ *
2173
+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/url)
2174
+ *
2175
+ * @public
2176
+ */
2177
+ get url() {
2178
+ return I(this, pe).href;
2179
+ }
2180
+ /**
2181
+ * Returns true if the credentials mode for connection requests to the URL providing the event stream is set to "include", and false otherwise.
2182
+ *
2183
+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/withCredentials)
2184
+ */
2185
+ get withCredentials() {
2186
+ return I(this, He);
2187
+ }
2188
+ /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/error_event) */
2189
+ get onerror() {
2190
+ return I(this, _e);
2191
+ }
2192
+ set onerror(e) {
2193
+ U(this, _e, e);
2194
+ }
2195
+ /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/message_event) */
2196
+ get onmessage() {
2197
+ return I(this, Ie);
2198
+ }
2199
+ set onmessage(e) {
2200
+ U(this, Ie, e);
2201
+ }
2202
+ /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/open_event) */
2203
+ get onopen() {
2204
+ return I(this, xe);
2205
+ }
2206
+ set onopen(e) {
2207
+ U(this, xe, e);
2208
+ }
2209
+ addEventListener(e, n, s) {
2210
+ const i = n;
2211
+ super.addEventListener(e, i, s);
2212
+ }
2213
+ removeEventListener(e, n, s) {
2214
+ const i = n;
2215
+ super.removeEventListener(e, i, s);
2216
+ }
2217
+ /**
2218
+ * Aborts any instances of the fetch algorithm started for this EventSource object, and sets the readyState attribute to CLOSED.
2219
+ *
2220
+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/close)
2221
+ *
2222
+ * @public
2223
+ */
2224
+ close() {
2225
+ I(this, $e) && clearTimeout(I(this, $e)), I(this, J) !== this.CLOSED && (I(this, ae) && I(this, ae).abort(), U(this, J, this.CLOSED), U(this, ae, void 0));
2226
+ }
2227
+ }
2228
+ J = /* @__PURE__ */ new WeakMap(), pe = /* @__PURE__ */ new WeakMap(), ve = /* @__PURE__ */ new WeakMap(), He = /* @__PURE__ */ new WeakMap(), Ye = /* @__PURE__ */ new WeakMap(), Ve = /* @__PURE__ */ new WeakMap(), Pe = /* @__PURE__ */ new WeakMap(), $e = /* @__PURE__ */ new WeakMap(), Ue = /* @__PURE__ */ new WeakMap(), ae = /* @__PURE__ */ new WeakMap(), ke = /* @__PURE__ */ new WeakMap(), _e = /* @__PURE__ */ new WeakMap(), Ie = /* @__PURE__ */ new WeakMap(), xe = /* @__PURE__ */ new WeakMap(), Y = /* @__PURE__ */ new WeakSet(), /**
2229
+ * Connect to the given URL and start receiving events
2230
+ *
2231
+ * @internal
2232
+ */
2233
+ ct = function() {
2234
+ U(this, J, this.CONNECTING), U(this, ae, new AbortController()), I(this, Ye)(I(this, pe), ie(this, Y, jt).call(this)).then(I(this, lt)).catch(I(this, ut));
2235
+ }, lt = /* @__PURE__ */ new WeakMap(), ut = /* @__PURE__ */ new WeakMap(), /**
2236
+ * Get request options for the `fetch()` request
2237
+ *
2238
+ * @returns The request options
2239
+ * @internal
2240
+ */
2241
+ jt = function() {
2242
+ var t;
2243
+ const e = {
2244
+ // [spec] Let `corsAttributeState` be `Anonymous`…
2245
+ // [spec] …will have their mode set to "cors"…
2246
+ mode: "cors",
2247
+ redirect: "follow",
2248
+ headers: { Accept: "text/event-stream", ...I(this, Ue) ? { "Last-Event-ID": I(this, Ue) } : void 0 },
2249
+ cache: "no-store",
2250
+ signal: (t = I(this, ae)) == null ? void 0 : t.signal
2251
+ };
2252
+ return "window" in globalThis && (e.credentials = this.withCredentials ? "include" : "same-origin"), e;
2253
+ }, ft = /* @__PURE__ */ new WeakMap(), dt = /* @__PURE__ */ new WeakMap(), /**
2254
+ * Handles the process referred to in the EventSource specification as "failing a connection".
2255
+ *
2256
+ * @param error - The error causing the connection to fail
2257
+ * @param code - The HTTP status code, if available
2258
+ * @internal
2259
+ */
2260
+ Te = function(t, e) {
2261
+ var n;
2262
+ I(this, J) !== this.CLOSED && U(this, J, this.CLOSED);
2263
+ const s = new Pt("error", { code: e, message: t });
2264
+ (n = I(this, _e)) == null || n.call(this, s), this.dispatchEvent(s);
2265
+ }, /**
2266
+ * Schedules a reconnection attempt against the EventSource endpoint.
2267
+ *
2268
+ * @param message - The error causing the connection to fail
2269
+ * @param code - The HTTP status code, if available
2270
+ * @internal
2271
+ */
2272
+ ht = function(t, e) {
2273
+ var n;
2274
+ if (I(this, J) === this.CLOSED)
2275
+ return;
2276
+ U(this, J, this.CONNECTING);
2277
+ const s = new Pt("error", { code: e, message: t });
2278
+ (n = I(this, _e)) == null || n.call(this, s), this.dispatchEvent(s), U(this, $e, setTimeout(I(this, pt), I(this, Pe)));
2279
+ }, pt = /* @__PURE__ */ new WeakMap(), /**
2280
+ * ReadyState representing an EventSource currently trying to connect
2281
+ *
2282
+ * @public
2283
+ */
2284
+ X.CONNECTING = 0, /**
2285
+ * ReadyState representing an EventSource connection that is open (eg connected)
2286
+ *
2287
+ * @public
2288
+ */
2289
+ X.OPEN = 1, /**
2290
+ * ReadyState representing an EventSource connection that is closed (eg disconnected)
2291
+ *
2292
+ * @public
2293
+ */
2294
+ X.CLOSED = 2;
2295
+ Object.defineProperty(X, /* @__PURE__ */ Symbol.for("eventsource.supports-fetch-override"), {
2296
+ value: !0,
2297
+ writable: !1,
2298
+ configurable: !1,
2299
+ enumerable: !1
2300
+ });
2301
+ function us() {
2302
+ const t = "document" in globalThis ? globalThis.document : void 0;
2303
+ return t && typeof t == "object" && "baseURI" in t && typeof t.baseURI == "string" ? t.baseURI : void 0;
2304
+ }
2305
+ class cn extends Event {
2306
+ data;
2307
+ origin;
2308
+ lastEventId;
2309
+ source;
2310
+ ports;
2311
+ constructor(e, n) {
2312
+ super(e), this.data = n?.data ?? null, this.origin = n?.origin ?? "", this.lastEventId = n?.lastEventId ?? "", this.source = n?.source ?? null, this.ports = n?.ports ?? [];
2313
+ }
2314
+ /** @deprecated */
2315
+ initMessageEvent(e, n, s, i, o, r, a, u) {
2316
+ }
2317
+ }
2318
+ function fs(t, e, n, s) {
2319
+ let i = null, o = !1;
2320
+ const r = [], a = (h) => {
2321
+ r.push(h), r.length > 100 && r.shift(), i && (i(), i = null);
2322
+ };
2323
+ t(a);
2324
+ const u = () => (n(a), Promise.resolve({ done: !0, value: void 0 }));
2325
+ return e(() => {
2326
+ o = !0, i && i(), u();
2327
+ }), {
2328
+ next: async () => {
2329
+ for (; ; ) {
2330
+ if (s() === "closed" || o)
2331
+ return u();
2332
+ const h = r.shift();
2333
+ if (h)
2334
+ return { value: h, done: !1 };
2335
+ await new Promise((m) => {
2336
+ i = m;
2337
+ });
2338
+ }
2339
+ },
2340
+ return: u,
2341
+ throw(h) {
2342
+ return n(a), Promise.reject(h);
2343
+ },
2344
+ [Symbol.asyncIterator]() {
2345
+ return this;
2346
+ }
2347
+ };
2348
+ }
2349
+ function oe(t) {
2350
+ switch (t.readyState) {
2351
+ case t.CLOSED:
2352
+ return "closed";
2353
+ case t.CONNECTING:
2354
+ return "connecting";
2355
+ case t.OPEN:
2356
+ return "open";
2357
+ default:
2358
+ return "connecting";
2359
+ }
2360
+ }
2361
+ function ds(t) {
2362
+ let e = null;
2363
+ return {
2364
+ ...t,
2365
+ text() {
2366
+ return e || (e = t.text()), e;
2367
+ },
2368
+ json() {
2369
+ return e || (e = t.text()), e.then((n) => JSON.parse(n));
2370
+ }
2371
+ };
2372
+ }
2373
+ function Mt(t) {
2374
+ if (!t)
2375
+ return;
2376
+ const e = {};
2377
+ for (const [n, s] of Object.entries(t))
2378
+ e[n] = {
2379
+ startCursor: s["start-cursor"],
2380
+ endCursor: s["end-cursor"],
2381
+ hasNextPage: s["has-next-page?"],
2382
+ hasPreviousPage: s["has-previous-page?"]
2383
+ };
2384
+ return e;
2385
+ }
2386
+ function hs(t, e, n) {
2387
+ let s, i = !1;
2388
+ const o = Ee(), r = new X(`${n.apiURI}/admin/subscribe-query?local_connection_id=${o}`, {
2389
+ messageEvent: cn,
2390
+ fetch(c, b) {
2391
+ return s = null, fetch(c, {
2392
+ ...b,
2393
+ method: "POST",
2394
+ headers: n.headers,
2395
+ body: JSON.stringify({
2396
+ query: t,
2397
+ "inference?": n.inference,
2398
+ versions: {
2399
+ "@backendrelay/admin": be,
2400
+ "@backendrelay/core": be
2401
+ }
2402
+ })
2403
+ }).then((S) => (S.ok || (s = ds(S)), S));
2404
+ }
2405
+ }), a = [], u = [], l = (c) => {
2406
+ a.push(c);
2407
+ }, f = (c) => {
2408
+ a.splice(a.indexOf(c), 1);
2409
+ }, h = (c) => {
2410
+ u.push(c);
2411
+ };
2412
+ e && l(e);
2413
+ let p = null;
2414
+ function m(c) {
2415
+ if (!i)
2416
+ for (const b of a)
2417
+ try {
2418
+ b(c);
2419
+ } catch (S) {
2420
+ console.error("Error in subscribeQuery callback", S);
2421
+ }
2422
+ }
2423
+ function $(c) {
2424
+ switch (c.op) {
2425
+ case "sse-init": {
2426
+ const b = c["machine-id"], S = c["session-id"];
2427
+ p = { machineId: b, sessionId: S };
2428
+ break;
2429
+ }
2430
+ case "add-query-ok": {
2431
+ m({
2432
+ type: "ok",
2433
+ data: c.result,
2434
+ pageInfo: Mt(c["result-meta"]?.["page-info"]),
2435
+ sessionInfo: p
2436
+ });
2437
+ break;
2438
+ }
2439
+ case "refresh-ok": {
2440
+ c.computations.length && m({
2441
+ type: "ok",
2442
+ data: c.computations[0]["instaql-result"],
2443
+ pageInfo: Mt(c.computations[0]["result-meta"]?.["page-info"]),
2444
+ sessionInfo: p
2445
+ });
2446
+ break;
2447
+ }
2448
+ case "error": {
2449
+ m({
2450
+ type: "error",
2451
+ error: new re({ body: c, status: c.status }),
2452
+ get readyState() {
2453
+ return oe(r);
2454
+ },
2455
+ get isClosed() {
2456
+ return oe(r) === "closed";
2457
+ },
2458
+ sessionInfo: p
2459
+ });
2460
+ break;
2461
+ }
2462
+ }
2463
+ }
2464
+ return r.onerror = (c) => {
2465
+ if (s)
2466
+ s.text().then((b) => {
2467
+ let S = { type: void 0, message: b };
2468
+ try {
2469
+ S = JSON.parse(b);
2470
+ } catch {
2471
+ }
2472
+ m({
2473
+ type: "error",
2474
+ error: new re({
2475
+ status: s.status,
2476
+ body: S
2477
+ }),
2478
+ get readyState() {
2479
+ return oe(r);
2480
+ },
2481
+ get isClosed() {
2482
+ return oe(r) === "closed";
2483
+ },
2484
+ sessionInfo: p
2485
+ });
2486
+ });
2487
+ else {
2488
+ const b = () => {
2489
+ m({
2490
+ type: "error",
2491
+ error: new re({
2492
+ status: c.code || 500,
2493
+ body: {
2494
+ type: void 0,
2495
+ message: c.message || "Unknown error in subscribe query."
2496
+ }
2497
+ }),
2498
+ get readyState() {
2499
+ return oe(r);
2500
+ },
2501
+ get isClosed() {
2502
+ return oe(r) === "closed";
2503
+ },
2504
+ sessionInfo: p
2505
+ });
2506
+ };
2507
+ if (r.readyState === X.CLOSED) {
2508
+ b();
2509
+ return;
2510
+ }
2511
+ setTimeout(() => {
2512
+ r.readyState !== X.OPEN && b();
2513
+ }, 5e3);
2514
+ }
2515
+ }, r.onmessage = (c) => {
2516
+ $(JSON.parse(c.data));
2517
+ }, {
2518
+ close: () => {
2519
+ i = !0;
2520
+ for (const c of u)
2521
+ try {
2522
+ c();
2523
+ } catch (b) {
2524
+ console.error("Error in onClose callback", b);
2525
+ }
2526
+ r.close();
2527
+ },
2528
+ [Symbol.iterator]: () => {
2529
+ throw new Error("subscribeQuery does not support synchronous iteration. Use `for await` instead.");
2530
+ },
2531
+ get sessionInfo() {
2532
+ return p;
2533
+ },
2534
+ get readyState() {
2535
+ return oe(r);
2536
+ },
2537
+ get isClosed() {
2538
+ return oe(r) === "closed";
2539
+ },
2540
+ [Symbol.asyncIterator]: fs.bind(this, l, h, f, () => 1)
2541
+ };
2542
+ }
2543
+ var G = {}, Dt;
2544
+ function ps() {
2545
+ if (Dt) return G;
2546
+ Dt = 1, Object.defineProperty(G, "__esModule", { value: !0 }), G.parseCookie = a, G.parse = a, G.stringifyCookie = u, G.stringifySetCookie = l, G.serialize = l, G.parseSetCookie = f, G.stringifySetCookie = l, G.serialize = l;
2547
+ const t = /^[\u0021-\u003A\u003C\u003E-\u007E]+$/, e = /^[\u0021-\u003A\u003C-\u007E]*$/, n = /^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i, s = /^[\u0020-\u003A\u003D-\u007E]*$/, i = /^-?\d+$/, o = Object.prototype.toString, r = /* @__PURE__ */ (() => {
2548
+ const c = function() {
2549
+ };
2550
+ return c.prototype = /* @__PURE__ */ Object.create(null), c;
2551
+ })();
2552
+ function a(c, b) {
2553
+ const S = new r(), d = c.length;
2554
+ if (d < 2)
2555
+ return S;
2556
+ const C = b?.decode || $;
2557
+ let E = 0;
2558
+ do {
2559
+ const A = p(c, E, d);
2560
+ if (A === -1)
2561
+ break;
2562
+ const g = h(c, E, d);
2563
+ if (A > g) {
2564
+ E = c.lastIndexOf(";", A - 1) + 1;
2565
+ continue;
2566
+ }
2567
+ const k = m(c, E, A);
2568
+ S[k] === void 0 && (S[k] = C(m(c, A + 1, g))), E = g + 1;
2569
+ } while (E < d);
2570
+ return S;
2571
+ }
2572
+ function u(c, b) {
2573
+ const S = b?.encode || encodeURIComponent, d = [];
2574
+ for (const C of Object.keys(c)) {
2575
+ const E = c[C];
2576
+ if (E === void 0)
2577
+ continue;
2578
+ if (!t.test(C))
2579
+ throw new TypeError(`cookie name is invalid: ${C}`);
2580
+ const A = S(E);
2581
+ if (!e.test(A))
2582
+ throw new TypeError(`cookie val is invalid: ${E}`);
2583
+ d.push(`${C}=${A}`);
2584
+ }
2585
+ return d.join("; ");
2586
+ }
2587
+ function l(c, b, S) {
2588
+ const d = typeof c == "object" ? c : { ...S, name: c, value: String(b) }, E = (typeof b == "object" ? b : S)?.encode || encodeURIComponent;
2589
+ if (!t.test(d.name))
2590
+ throw new TypeError(`argument name is invalid: ${d.name}`);
2591
+ const A = d.value ? E(d.value) : "";
2592
+ if (!e.test(A))
2593
+ throw new TypeError(`argument val is invalid: ${d.value}`);
2594
+ let g = d.name + "=" + A;
2595
+ if (d.maxAge !== void 0) {
2596
+ if (!Number.isInteger(d.maxAge))
2597
+ throw new TypeError(`option maxAge is invalid: ${d.maxAge}`);
2598
+ g += "; Max-Age=" + d.maxAge;
2599
+ }
2600
+ if (d.domain) {
2601
+ if (!n.test(d.domain))
2602
+ throw new TypeError(`option domain is invalid: ${d.domain}`);
2603
+ g += "; Domain=" + d.domain;
2604
+ }
2605
+ if (d.path) {
2606
+ if (!s.test(d.path))
2607
+ throw new TypeError(`option path is invalid: ${d.path}`);
2608
+ g += "; Path=" + d.path;
2609
+ }
2610
+ if (d.expires) {
2611
+ if (!w(d.expires) || !Number.isFinite(d.expires.valueOf()))
2612
+ throw new TypeError(`option expires is invalid: ${d.expires}`);
2613
+ g += "; Expires=" + d.expires.toUTCString();
2614
+ }
2615
+ if (d.httpOnly && (g += "; HttpOnly"), d.secure && (g += "; Secure"), d.partitioned && (g += "; Partitioned"), d.priority)
2616
+ switch (typeof d.priority == "string" ? d.priority.toLowerCase() : void 0) {
2617
+ case "low":
2618
+ g += "; Priority=Low";
2619
+ break;
2620
+ case "medium":
2621
+ g += "; Priority=Medium";
2622
+ break;
2623
+ case "high":
2624
+ g += "; Priority=High";
2625
+ break;
2626
+ default:
2627
+ throw new TypeError(`option priority is invalid: ${d.priority}`);
2628
+ }
2629
+ if (d.sameSite)
2630
+ switch (typeof d.sameSite == "string" ? d.sameSite.toLowerCase() : d.sameSite) {
2631
+ case !0:
2632
+ case "strict":
2633
+ g += "; SameSite=Strict";
2634
+ break;
2635
+ case "lax":
2636
+ g += "; SameSite=Lax";
2637
+ break;
2638
+ case "none":
2639
+ g += "; SameSite=None";
2640
+ break;
2641
+ default:
2642
+ throw new TypeError(`option sameSite is invalid: ${d.sameSite}`);
2643
+ }
2644
+ return g;
2645
+ }
2646
+ function f(c, b) {
2647
+ const S = b?.decode || $, d = c.length, C = h(c, 0, d), E = p(c, 0, C), A = E === -1 ? { name: "", value: S(m(c, 0, C)) } : {
2648
+ name: m(c, 0, E),
2649
+ value: S(m(c, E + 1, C))
2650
+ };
2651
+ let g = C + 1;
2652
+ for (; g < d; ) {
2653
+ const k = h(c, g, d), L = p(c, g, k), P = L === -1 ? m(c, g, k) : m(c, g, L), x = L === -1 ? void 0 : m(c, L + 1, k);
2654
+ switch (P.toLowerCase()) {
2655
+ case "httponly":
2656
+ A.httpOnly = !0;
2657
+ break;
2658
+ case "secure":
2659
+ A.secure = !0;
2660
+ break;
2661
+ case "partitioned":
2662
+ A.partitioned = !0;
2663
+ break;
2664
+ case "domain":
2665
+ A.domain = x;
2666
+ break;
2667
+ case "path":
2668
+ A.path = x;
2669
+ break;
2670
+ case "max-age":
2671
+ x && i.test(x) && (A.maxAge = Number(x));
2672
+ break;
2673
+ case "expires":
2674
+ if (!x)
2675
+ break;
2676
+ const M = new Date(x);
2677
+ Number.isFinite(M.valueOf()) && (A.expires = M);
2678
+ break;
2679
+ case "priority":
2680
+ if (!x)
2681
+ break;
2682
+ const z = x.toLowerCase();
2683
+ (z === "low" || z === "medium" || z === "high") && (A.priority = z);
2684
+ break;
2685
+ case "samesite":
2686
+ if (!x)
2687
+ break;
2688
+ const j = x.toLowerCase();
2689
+ (j === "lax" || j === "strict" || j === "none") && (A.sameSite = j);
2690
+ break;
2691
+ }
2692
+ g = k + 1;
2693
+ }
2694
+ return A;
2695
+ }
2696
+ function h(c, b, S) {
2697
+ const d = c.indexOf(";", b);
2698
+ return d === -1 ? S : d;
2699
+ }
2700
+ function p(c, b, S) {
2701
+ const d = c.indexOf("=", b);
2702
+ return d < S ? d : -1;
2703
+ }
2704
+ function m(c, b, S) {
2705
+ let d = b, C = S;
2706
+ do {
2707
+ const E = c.charCodeAt(d);
2708
+ if (E !== 32 && E !== 9)
2709
+ break;
2710
+ } while (++d < C);
2711
+ for (; C > d; ) {
2712
+ const E = c.charCodeAt(C - 1);
2713
+ if (E !== 32 && E !== 9)
2714
+ break;
2715
+ C--;
2716
+ }
2717
+ return c.slice(d, C);
2718
+ }
2719
+ function $(c) {
2720
+ if (c.indexOf("%") === -1)
2721
+ return c;
2722
+ try {
2723
+ return decodeURIComponent(c);
2724
+ } catch {
2725
+ return c;
2726
+ }
2727
+ }
2728
+ function w(c) {
2729
+ return o.call(c) === "[object Date]";
2730
+ }
2731
+ return G;
2732
+ }
2733
+ var ys = /* @__PURE__ */ ps();
2734
+ const ms = {
2735
+ "https://api.backendrelay.com": {
2736
+ keys: [
2737
+ {
2738
+ kty: "OKP",
2739
+ crv: "Ed25519",
2740
+ alg: "EdDSA",
2741
+ use: "sig",
2742
+ kid: "1034696293",
2743
+ x: "N-C41432STKAKkXAWmeIOXMnZcGRR1b9u1L3bTVqI_o"
2744
+ }
2745
+ ]
2746
+ },
2747
+ "http://localhost:8888": {
2748
+ keys: [
2749
+ {
2750
+ kty: "OKP",
2751
+ crv: "Ed25519",
2752
+ alg: "EdDSA",
2753
+ use: "sig",
2754
+ kid: "503090235",
2755
+ x: "qrSkwDaMITRMF9nOgpueqxgaAiuFmJperYE3mkyl8Ow"
2756
+ }
2757
+ ]
2758
+ }
2759
+ };
2760
+ function bs(t) {
2761
+ if (t.kty === "OKP" && t.crv === "Ed25519")
2762
+ return { name: "Ed25519" };
2763
+ if (t.kty === "EC")
2764
+ return { name: "ECDSA", namedCurve: t.crv };
2765
+ if (t.kty === "RSA")
2766
+ return {
2767
+ name: "RSASSA-PKCS1-v1_5",
2768
+ hash: {
2769
+ RS256: "SHA-256",
2770
+ RS384: "SHA-384",
2771
+ RS512: "SHA-512"
2772
+ }[t.alg] || "SHA-256"
2773
+ };
2774
+ throw new Error(`Unsupported JWK configuration: kty=${t.kty}, crv=${t.crv}`);
2775
+ }
2776
+ async function gs(t) {
2777
+ const e = bs(t), n = await crypto.subtle.importKey("jwk", t, e, !1, ["verify"]);
2778
+ return { alg: e, key: n };
2779
+ }
2780
+ function ws(t, e, n, s) {
2781
+ return crypto.subtle.verify(t, e, n, s);
2782
+ }
2783
+ function Ss(t) {
2784
+ const e = new Uint8Array(Math.ceil(t.length / 2));
2785
+ for (let n = 0; n < e.length; n++)
2786
+ e[n] = parseInt(t.substring(n * 2, n * 2 + 2), 16);
2787
+ return e;
2788
+ }
2789
+ function vs(t) {
2790
+ let e, n, s;
2791
+ for (const o of t.split(",")) {
2792
+ const [r, a] = o.split("=");
2793
+ switch (r) {
2794
+ case "t": {
2795
+ e = a;
2796
+ break;
2797
+ }
2798
+ case "kid": {
2799
+ n = a;
2800
+ break;
2801
+ }
2802
+ case "v1": {
2803
+ s = a;
2804
+ break;
2805
+ }
2806
+ }
2807
+ }
2808
+ const i = [];
2809
+ if (e || i.push("t"), n || i.push("kid"), s || i.push("v1"), i.length || !e || !n || !s)
2810
+ throw new R("Invalid BackendRelay-Signature header.", {
2811
+ header: t,
2812
+ missingKeys: i
2813
+ });
2814
+ return { t: e, kid: n, v1: s };
2815
+ }
2816
+ function ks(t, e, n) {
2817
+ if (Math.floor(t.getTime() / 1e3) - parseInt(e, 10) > n)
2818
+ throw new R("Webhook signature is too old", {
2819
+ tolerance: n,
2820
+ receivedAt: t,
2821
+ t: e
2822
+ });
2823
+ }
2824
+ const je = /* @__PURE__ */ new Map(), we = /* @__PURE__ */ new Map(), Nt = 6e4, Is = 32;
2825
+ function $s(t) {
2826
+ let e = we.get(t);
2827
+ if (e ? we.delete(t) : e = { keys: null, fetchedAt: 0, failedAt: 0, inflight: null }, we.set(t, e), we.size > Is) {
2828
+ const n = we.keys().next().value;
2829
+ if (n !== void 0) {
2830
+ we.delete(n);
2831
+ const s = `${n}:`;
2832
+ for (const i of je.keys())
2833
+ i.startsWith(s) && je.delete(i);
2834
+ }
2835
+ }
2836
+ return e;
2837
+ }
2838
+ const Es = 300;
2839
+ async function Os(t, e) {
2840
+ const n = await e.text();
2841
+ try {
2842
+ const s = JSON.parse(n);
2843
+ return t(new re({ status: e.status, body: s }));
2844
+ } catch {
2845
+ return t(new re({
2846
+ status: e.status,
2847
+ body: { type: void 0, message: n }
2848
+ }));
2849
+ }
2850
+ }
2851
+ const _s = async (t, e) => {
2852
+ const n = {
2853
+ ...e?.headers || {},
2854
+ "BackendRelay-Core-Version": be
2855
+ }, s = await fetch(t, { ...e, headers: n });
2856
+ return s.status === 200 ? s.json() : Os((i) => Promise.reject(i), s);
2857
+ };
2858
+ function ln(t) {
2859
+ return t ? new Date(t) : null;
2860
+ }
2861
+ function Se(t) {
2862
+ return {
2863
+ id: t.id,
2864
+ sink: t.sink,
2865
+ namespaces: t.namespaces ?? [],
2866
+ actions: t.actions,
2867
+ status: t.status,
2868
+ disabledReason: t.disabled_reason ?? null,
2869
+ createdAt: new Date(t.created_at),
2870
+ updatedAt: new Date(t.updated_at)
2871
+ };
2872
+ }
2873
+ function Rs(t) {
2874
+ return {
2875
+ attemptAt: ln(t["attempt-at"]),
2876
+ durationMs: t["duration-ms"] ?? null,
2877
+ success: t["success?"] ?? null,
2878
+ statusCode: t["status-code"] ?? null,
2879
+ responseText: t["response-text"] ?? null,
2880
+ errorType: t["error-type"] ?? null,
2881
+ errorMessage: t["error-message"] ?? null
2882
+ };
2883
+ }
2884
+ function nt(t) {
2885
+ return {
2886
+ isn: t.isn,
2887
+ status: t.status,
2888
+ attempts: t.attempts ? t.attempts.map(Rs) : null,
2889
+ nextAttemptAfter: ln(t.next_attempt_after),
2890
+ createdAt: new Date(t.created_at),
2891
+ updatedAt: new Date(t.updated_at)
2892
+ };
2893
+ }
2894
+ class Cs {
2895
+ #e;
2896
+ #i;
2897
+ #t;
2898
+ #n;
2899
+ #r;
2900
+ constructor(e) {
2901
+ this.#e = e.appId, this.#i = e.apiURI, this.#t = e.token, this.#n = e.withAuth, this.#r = e.jsonFetch;
2902
+ }
2903
+ #s(e, n) {
2904
+ if (!this.#e)
2905
+ throw new R("appId is required to manage webhooks. Pass it to the Webhooks constructor.");
2906
+ const s = (i) => {
2907
+ const o = {
2908
+ method: n?.method,
2909
+ headers: {
2910
+ authorization: `Bearer ${i}`,
2911
+ "content-type": "application/json"
2912
+ }
2913
+ };
2914
+ return n?.body !== void 0 && (o.body = JSON.stringify(n.body)), this.#r(`${this.#i}${e}`, o);
2915
+ };
2916
+ if (this.#n)
2917
+ return this.#n(s);
2918
+ if (!this.#t)
2919
+ throw new R("A token is required to manage webhooks. Pass `adminToken` or `token` to the Webhooks constructor.");
2920
+ return s(this.#t);
2921
+ }
2922
+ /**
2923
+ * Returns every webhook configured on the app, newest first. Includes both
2924
+ * active and disabled webhooks.
2925
+ */
2926
+ async list() {
2927
+ return ((await this.#s(`/dash/apps/${this.#e}/webhooks`)).webhooks || []).map(Se);
2928
+ }
2929
+ /**
2930
+ * Creates a new webhook. The webhook is created in the `active` state and
2931
+ * starts receiving matching events immediately.
2932
+ *
2933
+ * The server rejects the request if `url` is not an HTTPS URL pointing at a
2934
+ * public host, if `namespaces` doesn't reference any entity in the app's
2935
+ * schema, if `actions` is empty, or if the app has hit its webhook limit.
2936
+ *
2937
+ * An app may have at most **100 active webhooks** at a time; {@link delete}
2938
+ * a webhook to free up a slot before creating another.
2939
+ *
2940
+ * @example
2941
+ * const webhook = await db.webhooks.manager.create({
2942
+ * url: 'https://example.com/instant',
2943
+ * namespaces: ['posts', 'comments'],
2944
+ * actions: ['create', 'update'],
2945
+ * });
2946
+ */
2947
+ async create(e) {
2948
+ const n = await this.#s(`/dash/apps/${this.#e}/webhooks`, {
2949
+ method: "POST",
2950
+ body: e
2951
+ });
2952
+ return Se(n.webhook);
2953
+ }
2954
+ /**
2955
+ * Updates a webhook's `url`, `namespaces`, and/or `actions`. Pass only the
2956
+ * fields you want to change; omitted fields keep their current value.
2957
+ *
2958
+ * Does not affect the webhook's status — use {@link enable} or
2959
+ * {@link disable} for that.
2960
+ */
2961
+ async update(e, n) {
2962
+ const s = await this.#s(`/dash/apps/${this.#e}/webhooks/${e}`, { method: "POST", body: n });
2963
+ return Se(s.webhook);
2964
+ }
2965
+ /**
2966
+ * Deletes a webhook. No further events will be queued for it. Returns the
2967
+ * webhook as it looked just before deletion.
2968
+ */
2969
+ async delete(e) {
2970
+ const n = await this.#s(`/dash/apps/${this.#e}/webhooks/${e}`, { method: "DELETE" });
2971
+ return Se(n.webhook);
2972
+ }
2973
+ /**
2974
+ * Re-enables a disabled webhook. Clears `disabledReason` and resumes
2975
+ * delivery for new events. Has no effect if the webhook is already active.
2976
+ *
2977
+ * Events that occurred while the webhook was disabled are not retroactively
2978
+ * delivered.
2979
+ */
2980
+ async enable(e) {
2981
+ const n = await this.#s(`/dash/apps/${this.#e}/webhooks/${e}/enable`, { method: "POST", body: {} });
2982
+ return Se(n.webhook);
2983
+ }
2984
+ /**
2985
+ * Disables a webhook. No new events will be queued until it is re-enabled
2986
+ * via {@link enable}. In-flight events already being processed will still
2987
+ * complete.
2988
+ *
2989
+ * @param opts.reason Optional human-readable note stored on the webhook
2990
+ * and surfaced in the dashboard.
2991
+ */
2992
+ async disable(e, n) {
2993
+ const s = n?.reason ? { reason: n.reason } : {}, i = await this.#s(`/dash/apps/${this.#e}/webhooks/${e}/disable`, { method: "POST", body: s });
2994
+ return Se(i.webhook);
2995
+ }
2996
+ /**
2997
+ * Returns a page of events for a webhook, newest first.
2998
+ *
2999
+ * Events are retained for ~60 days. To paginate, pass the previous page's
3000
+ * `pageInfo.endCursor` as `opts.after`; stop when `pageInfo.hasNextPage`
3001
+ * is `false`.
3002
+ */
3003
+ async listEvents(e, n) {
3004
+ const s = n?.after ? `?after=${encodeURIComponent(n.after)}` : "", i = await this.#s(`/dash/apps/${this.#e}/webhooks/${e}/events${s}`);
3005
+ return {
3006
+ events: (i.events || []).map(nt),
3007
+ pageInfo: {
3008
+ startCursor: i.pageInfo?.startCursor ?? null,
3009
+ endCursor: i.pageInfo?.endCursor ?? null,
3010
+ hasNextPage: !!i.pageInfo?.hasNextPage
3011
+ }
3012
+ };
3013
+ }
3014
+ /**
3015
+ * Fetches a single webhook event by its `isn`.
3016
+ */
3017
+ async getEvent(e, n) {
3018
+ const s = await this.#s(`/dash/apps/${this.#e}/webhooks/${e}/events/${n}`);
3019
+ return nt(s.event);
3020
+ }
3021
+ /** Returns the full payload for an event. */
3022
+ async getPayload(e, n) {
3023
+ return this.#s(`/webhooks/payload/${this.#e}/${e}/${n}`);
3024
+ }
3025
+ /**
3026
+ * Re-queues an event for delivery, regardless of its current status. Use
3027
+ * this to retry a `failed` event or force a redelivery of a `success` one.
3028
+ *
3029
+ * The server rate-limits resends; if the event was queued or resent very
3030
+ * recently the call will fail with a validation error asking you to try
3031
+ * again in about a minute.
3032
+ */
3033
+ async resendEvent(e, n) {
3034
+ const s = await this.#s(`/dash/apps/${this.#e}/webhooks/${e}/events/${n}`, { method: "POST", body: {} });
3035
+ return nt(s.event);
3036
+ }
3037
+ }
3038
+ class St {
3039
+ /** App this instance is bound to. */
3040
+ appId;
3041
+ /** Schema used to type webhook payloads and handler records. */
3042
+ schema;
3043
+ #e;
3044
+ /** Base URL for the BackendRelay API. */
3045
+ apiURI;
3046
+ #i;
3047
+ /** Manage webhook subscriptions and inspect delivery events. */
3048
+ manager;
3049
+ /**
3050
+ * Schema-bound helpers for building typed handler maps.
3051
+ *
3052
+ * - `typedHandlers(namespace, action, handler)` builds a single typed entry.
3053
+ * Pass `'$default'` for `namespace` to register a catch-all handler.
3054
+ * - `combineHandlers(...entries)` merges entries into a
3055
+ * {@link WebhookHandlers} object suitable for {@link processPayload} and
3056
+ * {@link processRequest}.
3057
+ *
3058
+ * If you already have a {@link Webhooks} instance, prefer the instance
3059
+ * form (`db.webhooks.helpers()`) — it infers `Schema` automatically.
3060
+ *
3061
+ * @example
3062
+ * const { typedHandlers, combineHandlers } = Webhooks.helpers<typeof schema>();
3063
+ * const handlers = combineHandlers(
3064
+ * typedHandlers('posts', 'create', (record) => { ... }),
3065
+ * typedHandlers('comments', '$default', (record) => { ... }),
3066
+ * typedHandlers('$default', (record) => { ... }),
3067
+ * );
3068
+ */
3069
+ static helpers() {
3070
+ function e(...s) {
3071
+ if (s.length === 2)
3072
+ return { $default: s[1] };
3073
+ const [i, o, r] = s;
3074
+ return { [i]: { [o]: r } };
3075
+ }
3076
+ function n(...s) {
3077
+ const i = {};
3078
+ for (const o of s)
3079
+ for (const r of Object.keys(o))
3080
+ r === "$default" ? i.$default = o.$default : i[r] = { ...i[r], ...o[r] };
3081
+ return i;
3082
+ }
3083
+ return {
3084
+ typedHandlers: e,
3085
+ combineHandlers: n
3086
+ };
3087
+ }
3088
+ /**
3089
+ * Instance form of {@link Webhooks.helpers} that infers `Schema` from this
3090
+ * instance — no `<typeof schema>` type argument required.
3091
+ *
3092
+ * @example
3093
+ * const { typedHandlers, combineHandlers } = db.webhooks.helpers();
3094
+ */
3095
+ helpers() {
3096
+ return St.helpers();
3097
+ }
3098
+ constructor(e, n) {
3099
+ this.appId = e.appId, this.schema = e.schema, this.#e = e.adminToken || e.token, this.apiURI = on(e.apiURI, "BackendRelay webhooks"), this.#i = n || _s, this.manager = new Cs({
3100
+ appId: this.appId,
3101
+ apiURI: this.apiURI,
3102
+ token: this.#e,
3103
+ withAuth: e.withAuth,
3104
+ jsonFetch: this.#i
3105
+ });
3106
+ }
3107
+ /** Fetches BackendRelay's JWK set for verifying webhook signatures. */
3108
+ async fetchJwks() {
3109
+ return await this.#i(`${this.apiURI}/.well-known/webhooks/jwks.json`);
3110
+ }
3111
+ /**
3112
+ * Resolves a `kid` to an imported {@link CryptoKey}, hitting a
3113
+ * process-wide cache on repeat calls. Falls back to {@link fetchJwks} if
3114
+ * the key isn't already known; per issuer the fetch is cached for
3115
+ * `jwksCacheTtlMs` (see {@link issuerState}).
3116
+ */
3117
+ async keyOfKid(e) {
3118
+ const n = `${this.apiURI}:${e}`, s = je.get(n);
3119
+ if (s && (s.exp === null || Date.now() < s.exp))
3120
+ return s;
3121
+ s && je.delete(n);
3122
+ const i = ms[this.apiURI]?.keys.find((a) => a.kid === e) || // An expired entry forces a fresh JWKS fetch, so a rotated key
3123
+ // replaces it right away instead of waiting out the issuer TTL.
3124
+ (await this.#t(s !== void 0)).find((a) => a.kid === e);
3125
+ if (!i)
3126
+ throw new R("Could not find matching signing key", {
3127
+ kid: e
3128
+ });
3129
+ const o = await gs(i), r = typeof i.exp == "number" ? i.exp * 1e3 : null;
3130
+ return je.set(n, { ...o, exp: r }), o;
3131
+ }
3132
+ /**
3133
+ * The issuer's signing keys from {@link fetchJwks}, through the per-issuer
3134
+ * cache: inside the TTL window a fetched set is reused, a failed fetch
3135
+ * fails fast until the window passes, and concurrent misses share one
3136
+ * request.
3137
+ */
3138
+ async #t(e = !1) {
3139
+ const n = $s(this.apiURI), s = Date.now();
3140
+ if (!e && n.keys && s - n.fetchedAt < Nt)
3141
+ return n.keys;
3142
+ if (s - n.failedAt < Nt)
3143
+ throw new R("Could not fetch issuer signing keys", {
3144
+ issuer: this.apiURI
3145
+ });
3146
+ return n.inflight || (n.inflight = this.fetchJwks().then((i) => {
3147
+ const o = i?.keys ?? [];
3148
+ return n.keys = o, n.fetchedAt = Date.now(), o;
3149
+ }).catch((i) => {
3150
+ throw n.failedAt = Date.now(), i;
3151
+ }).finally(() => {
3152
+ n.inflight = null;
3153
+ })), n.inflight;
3154
+ }
3155
+ /**
3156
+ * Verifies an `BackendRelay-Signature` header against a body and returns the
3157
+ * parsed {@link WebhookBody} (containing the `payloadUrl` and a JWT
3158
+ * `token` for fetching the records).
3159
+ *
3160
+ * Throws if the signature doesn't validate, the signature is older than
3161
+ * `opts.tolerance` (default 300 seconds), or the body doesn't decode to
3162
+ * the expected shape.
3163
+ *
3164
+ * @param body Either the raw body string, or a function returning it.
3165
+ * Use a function to defer reading the body until after the
3166
+ * header has been parsed.
3167
+ */
3168
+ async validate(e, n, s) {
3169
+ const i = s?.receivedAt || /* @__PURE__ */ new Date(), { t: o, kid: r, v1: a } = vs(e), u = s?.tolerance ?? Es;
3170
+ ks(i, o, u);
3171
+ const { alg: l, key: f } = await this.keyOfKid(r), h = typeof n == "function" ? await n() : n, p = new TextEncoder().encode(`${o}.${h}`);
3172
+ if (!await ws(l, f, Ss(a), p))
3173
+ throw new R("BackendRelay Signature did not validate", {
3174
+ header: e
3175
+ });
3176
+ const $ = JSON.parse(h);
3177
+ if (typeof $ != "object" || typeof $.payloadUrl != "string" || typeof $.token != "string")
3178
+ throw new R("Invalid webhook body, expected an object with payloadUrl and token fields", { body: $ });
3179
+ return $;
3180
+ }
3181
+ /**
3182
+ * Pulls the `BackendRelay-Signature` header and body from a `Request` and
3183
+ * delegates to {@link validate}. Throws if the header is missing.
3184
+ */
3185
+ async validateRequest(e, n) {
3186
+ const s = e.headers.get("BackendRelay-Signature");
3187
+ if (!s)
3188
+ throw new R("Request is missing BackendRelay-Signature header");
3189
+ return this.validate(s, () => e.text(), n);
3190
+ }
3191
+ /**
3192
+ * Fetches the records and `idempotencyKey` for a validated
3193
+ * {@link WebhookBody}, authenticating with the JWT `token` it carries.
3194
+ */
3195
+ fetchPayloads({ payloadUrl: e, token: n }) {
3196
+ return this.#i(e, {
3197
+ headers: { Authorization: `Bearer ${n}`, accept: "application/json" }
3198
+ });
3199
+ }
3200
+ /**
3201
+ * Dispatches each record in `payload` to its matching handler in
3202
+ * `handlers`. Resolution order per record: exact `namespace` + `action` →
3203
+ * `namespace`'s `$default` → top-level `$default`. Records with no matching
3204
+ * handler are skipped.
3205
+ *
3206
+ * Handlers run concurrently. If any handler rejects, the call rejects so
3207
+ * the caller (e.g. {@link processRequest}) can return a non-2xx response
3208
+ * and let BackendRelay retry the event.
3209
+ */
3210
+ async processPayload(e, n) {
3211
+ const s = [];
3212
+ for (const i of n.data) {
3213
+ const { namespace: o, action: r } = i, a = e?.[o]?.[r] || e?.[o]?.$default || e?.$default;
3214
+ a && s.push(a(i));
3215
+ }
3216
+ await Promise.all(s);
3217
+ }
3218
+ /**
3219
+ * The one-liner for handling webhooks. Hand it your handlers and the
3220
+ * incoming `Request` — it verifies the signature, fetches the records, and
3221
+ * dispatches each one to your code.
3222
+ *
3223
+ * Async handlers are executed in parallel, the return promise will resolve once
3224
+ * all handlers complete and will reject if any of the handlers fails.
3225
+ *
3226
+ * @example
3227
+ * const { typedHandlers, combineHandlers } = db.webhooks.helpers();
3228
+ *
3229
+ * const handlers = combineHandlers(
3230
+ * typedHandlers('posts', 'create', async (record) => {
3231
+ * await sendNewPostEmail(record.after);
3232
+ * }),
3233
+ * typedHandlers('$default', (record) => {
3234
+ * console.log('webhook event', record);
3235
+ * }),
3236
+ * );
3237
+ *
3238
+ * export async function POST(req: Request) {
3239
+ * await db.webhooks.processRequest(handlers, req);
3240
+ * return new Response('ok');
3241
+ * }
3242
+ */
3243
+ async processRequest(e, n, s) {
3244
+ const i = await this.validateRequest(n, s), o = await this.fetchPayloads(i);
3245
+ await this.processPayload(e, o);
3246
+ }
3247
+ /**
3248
+ * Adapter for frameworks that hand you a Node-style `http.IncomingMessage`
3249
+ * (Next.js Pages Router, Express, Koa, etc.) instead of a Web `Request`.
3250
+ * Wraps the request in a Web `Request` and delegates to
3251
+ * {@link processRequest}. You still send the HTTP response yourself.
3252
+ *
3253
+ * The raw body is required for signature verification. The adapter picks
3254
+ * it up from one of:
3255
+ *
3256
+ * - `req.body` if it's a `Buffer` or `Uint8Array` (set by middleware like
3257
+ * `express.raw({ type: 'application/json' })`)
3258
+ * - `req.body` if it's a string (set by middleware like `express.text()`)
3259
+ * - otherwise the unconsumed request stream
3260
+ *
3261
+ * Don't use a JSON body parser on this route — `express.json()` and
3262
+ * `bodyParser: true` in Next.js both parse the body into an object,
3263
+ * destroying the raw bytes the signature was computed over.
3264
+ *
3265
+ * @example
3266
+ * // Next.js Pages Router (`pages/api/webhooks.ts`)
3267
+ * import type { NextApiRequest, NextApiResponse } from 'next';
3268
+ *
3269
+ * export const config = { api: { bodyParser: false } };
3270
+ *
3271
+ * const { typedHandlers, combineHandlers } = db.webhooks.helpers();
3272
+ *
3273
+ * const handlers = combineHandlers(
3274
+ * typedHandlers('posts', 'create', async (record) => {
3275
+ * await sendNewPostEmail(record.after);
3276
+ * }),
3277
+ * typedHandlers('$default', (record) => {
3278
+ * console.log('unhandled record', record);
3279
+ * }),
3280
+ * );
3281
+ *
3282
+ * export default async function handler(
3283
+ * req: NextApiRequest,
3284
+ * res: NextApiResponse,
3285
+ * ) {
3286
+ * try {
3287
+ * await db.webhooks.processNodeRequest(handlers, req);
3288
+ * res.status(200).end();
3289
+ * } catch (e) {
3290
+ * res.status(400).json({ error: String(e) });
3291
+ * }
3292
+ * }
3293
+ *
3294
+ * @example
3295
+ * // Express — skip the JSON body parser on the webhook route and use
3296
+ * // `express.raw()` so `req.body` arrives as a Buffer.
3297
+ * import express from 'express';
3298
+ *
3299
+ * const app = express();
3300
+ *
3301
+ * app.use((req, res, next) => {
3302
+ * if (req.originalUrl === '/webhooks/backendrelay') return next();
3303
+ * express.json()(req, res, next);
3304
+ * });
3305
+ *
3306
+ * app.post(
3307
+ * '/webhooks/backendrelay',
3308
+ * express.raw({ type: 'application/json' }),
3309
+ * async (req, res) => {
3310
+ * try {
3311
+ * await db.webhooks.processNodeRequest(handlers, req);
3312
+ * res.status(200).end();
3313
+ * } catch (e) {
3314
+ * res.status(400).json({ error: String(e) });
3315
+ * }
3316
+ * },
3317
+ * );
3318
+ *
3319
+ * @example
3320
+ * // Koa — `ctx.req` is the raw IncomingMessage. If `koa-bodyparser` (or
3321
+ * // similar) runs on this route it consumes the stream, so either skip it
3322
+ * // here or pull the raw body yourself and shim it onto the request:
3323
+ * import Koa from 'koa';
3324
+ * import Router from '@koa/router';
3325
+ * import rawBody from 'raw-body';
3326
+ *
3327
+ * const router = new Router();
3328
+ *
3329
+ * router.post('/webhooks/backendrelay', async (ctx) => {
3330
+ * try {
3331
+ * await db.webhooks.processNodeRequest(handlers, ctx.req, {
3332
+ * body: rawBody(ctx.req), // adapter awaits the Promise
3333
+ * });
3334
+ * ctx.status = 200;
3335
+ * } catch (e) {
3336
+ * ctx.status = 400;
3337
+ * ctx.body = { error: String(e) };
3338
+ * }
3339
+ * });
3340
+ *
3341
+ * @example
3342
+ * // NestJS (Express adapter). With `rawBody: true` on the factory, Nest
3343
+ * // populates `req.rawBody` itself — just pass `req`.
3344
+ * import { Controller, Post, Req, HttpCode } from '@nestjs/common';
3345
+ * import type { Request } from 'express';
3346
+ *
3347
+ * @Controller('webhooks')
3348
+ * export class WebhooksController {
3349
+ * @Post('instant')
3350
+ * @HttpCode(200)
3351
+ * async handle(@Req() req: Request) {
3352
+ * await db.webhooks.processNodeRequest(handlers, req);
3353
+ * }
3354
+ * }
3355
+ *
3356
+ * // (Pair with `NestFactory.create(AppModule, { rawBody: true })` in main.ts.)
3357
+ */
3358
+ async processNodeRequest(e, n, s) {
3359
+ let i, o = !1, r = s?.body ?? n.rawBody ?? n.body;
3360
+ if (r != null && typeof r.then == "function" && (r = await r), typeof r == "string")
3361
+ i = r;
3362
+ else if (r instanceof Uint8Array)
3363
+ i = new TextDecoder("utf-8").decode(r);
3364
+ else if (r != null && typeof r == "object")
3365
+ try {
3366
+ i = JSON.stringify(r), o = !0;
3367
+ } catch {
3368
+ throw new R("Webhook request body has already been parsed and could not be re-serialized. Configure this route to receive the raw request body instead of parsed JSON.");
3369
+ }
3370
+ else if (n[Symbol.asyncIterator]) {
3371
+ const h = new TextEncoder(), p = [];
3372
+ for await (const c of n)
3373
+ p.push(typeof c == "string" ? h.encode(c) : c);
3374
+ let m = 0;
3375
+ for (const c of p)
3376
+ m += c.byteLength;
3377
+ const $ = new Uint8Array(m);
3378
+ let w = 0;
3379
+ for (const c of p)
3380
+ $.set(c, w), w += c.byteLength;
3381
+ i = new TextDecoder("utf-8").decode($);
3382
+ } else
3383
+ throw new R("Could not read the webhook request body. Pass a Node IncomingMessage with an unconsumed stream, or set `req.body` to the raw bytes (Buffer/Uint8Array) or string.");
3384
+ const a = typeof n.headers.host == "string" ? n.headers.host : "localhost", u = new URL(n.url ?? "/", `https://${a}`), l = new Headers();
3385
+ for (const [h, p] of Object.entries(n.headers))
3386
+ typeof p == "string" ? l.set(h, p) : Array.isArray(p) && l.set(h, p.join(", "));
3387
+ const f = new Request(u, {
3388
+ method: n.method ?? "POST",
3389
+ headers: l,
3390
+ body: i
3391
+ });
3392
+ try {
3393
+ await this.processRequest(e, f, s);
3394
+ } catch (h) {
3395
+ throw o && h instanceof R && h.message === "BackendRelay Signature did not validate" ? new R("Webhook signature did not validate. The request body was re-serialized from a parsed JSON object, which can produce different bytes than the server signed. Configure this route to receive the raw request body instead of parsed JSON.", { hint: h.hint }) : h;
3396
+ }
3397
+ }
3398
+ }
3399
+ function xs(t) {
3400
+ return {
3401
+ ...t,
3402
+ apiURI: on(t.apiURI, "BackendRelay admin SDK")
3403
+ };
3404
+ }
3405
+ function Ts(t, e) {
3406
+ return "email" in e ? t["as-email"] = e.email : "token" in e ? t["as-token"] = e.token : "guest" in e && (t["as-guest"] = "true"), t;
3407
+ }
3408
+ function As(t, e) {
3409
+ if (!(e && ("token" in e || "guest" in e)) && !t.adminToken)
3410
+ throw e && "email" in e ? new Error("Admin token required. To impersonate users with an email you must pass `adminToken` to `init`.") : new Error("Admin token required. To run this operation pass `adminToken` to `init`, or use `db.asUser`.");
3411
+ }
3412
+ function T(t, e) {
3413
+ As(t, e);
3414
+ const { adminToken: n, appId: s } = t, i = {
3415
+ "content-type": "application/json",
3416
+ "app-id": s
3417
+ };
3418
+ return n && (i.authorization = `Bearer ${n}`), t.requestId && (i["x-request-id"] = t.requestId), e ? Ts(i, e) : i;
3419
+ }
3420
+ function Ps() {
3421
+ return (
3422
+ // NextJS 13 onwards added a `__nextPatched` property to the fetch function
3423
+ fetch.__nextPatched && // NextJS 15 onwards _also_ added a global `next-patch` symbol.
3424
+ !globalThis[/* @__PURE__ */ Symbol.for("next-patch")]
3425
+ );
3426
+ }
3427
+ function Us() {
3428
+ return Ps() ? { cache: "no-store" } : {};
3429
+ }
3430
+ async function js(t, e) {
3431
+ const n = await e.text();
3432
+ try {
3433
+ const s = JSON.parse(n);
3434
+ return t(new re({ status: e.status, body: s }));
3435
+ } catch {
3436
+ return t(new re({
3437
+ status: e.status,
3438
+ body: { type: void 0, message: n }
3439
+ }));
3440
+ }
3441
+ }
3442
+ async function De(t, e, n) {
3443
+ try {
3444
+ const s = Us(), i = {
3445
+ ...e?.headers || {},
3446
+ "BackendRelay-Admin-Version": be,
3447
+ "BackendRelay-Core-Version": be
3448
+ }, o = await fetch(t, { ...s, ...e, headers: i });
3449
+ if (o.status === 200) {
3450
+ const r = await o.json();
3451
+ return Promise.resolve(r);
3452
+ }
3453
+ return await js((r) => Promise.reject(r), o);
3454
+ } catch (s) {
3455
+ throw jn(n, s), s;
3456
+ }
3457
+ }
3458
+ function Ms(t) {
3459
+ return class {
3460
+ source;
3461
+ static OPEN = X.OPEN;
3462
+ static CONNECTING = X.CONNECTING;
3463
+ static CLOSED = X.CLOSED;
3464
+ url;
3465
+ constructor(n) {
3466
+ this.url = n, this.source = this.#e(n);
3467
+ }
3468
+ get onopen() {
3469
+ return this.source.onopen;
3470
+ }
3471
+ set onopen(n) {
3472
+ this.source.onopen = n;
3473
+ }
3474
+ get onmessage() {
3475
+ return this.source.onmessage;
3476
+ }
3477
+ set onmessage(n) {
3478
+ this.source.onmessage = n;
3479
+ }
3480
+ get onerror() {
3481
+ return this.source.onerror;
3482
+ }
3483
+ set onerror(n) {
3484
+ this.source.onerror = n;
3485
+ }
3486
+ get readyState() {
3487
+ return this.source.readyState;
3488
+ }
3489
+ close() {
3490
+ this.source.close();
3491
+ }
3492
+ #e(n) {
3493
+ return new X(n, {
3494
+ messageEvent: cn,
3495
+ fetch(i, o) {
3496
+ return fetch(i, {
3497
+ ...o,
3498
+ method: "POST",
3499
+ headers: t.headers,
3500
+ body: JSON.stringify({
3501
+ "inference?": t.inference,
3502
+ versions: {
3503
+ "@backendrelay/admin": be,
3504
+ "@backendrelay/core": be
3505
+ }
3506
+ })
3507
+ });
3508
+ }
3509
+ });
3510
+ }
3511
+ };
3512
+ }
3513
+ function Ds(t) {
3514
+ (!t.appId || !Re(t.appId)) && console.warn("warning: BackendRelay Admin DB must be initialized with a valid appId. Received: " + JSON.stringify(t.appId));
3515
+ const e = {
3516
+ ...t,
3517
+ appId: t.appId?.trim(),
3518
+ adminToken: t.adminToken?.trim(),
3519
+ useDateObjects: t.useDateObjects ?? !1
3520
+ };
3521
+ return new vt(e);
3522
+ }
3523
+ function Lt(t) {
3524
+ return (Array.isArray(t) ? t : [t]).flatMap(Un);
3525
+ }
3526
+ class Ns {
3527
+ config;
3528
+ _fetch = (e, n) => De(e, n, this.config.onError);
3529
+ constructor(e) {
3530
+ this.config = e;
3531
+ }
3532
+ async getPresence(e, n) {
3533
+ return (await this._fetch(`${this.config.apiURI}/admin/rooms/presence?app_id=${this.config.appId}&room-type=${String(e)}&room-id=${n}`, {
3534
+ method: "GET",
3535
+ headers: T(this.config)
3536
+ })).sessions || {};
3537
+ }
3538
+ }
3539
+ class Ls {
3540
+ config;
3541
+ _fetch = (e, n) => De(e, n, this.config.onError);
3542
+ constructor(e) {
3543
+ this.config = e, this.createToken = this.createToken.bind(this);
3544
+ }
3545
+ /**
3546
+ * Generates a magic code for the user with the given email.
3547
+ * This is useful if you want to use your own email provider
3548
+ * to send magic codes.
3549
+ *
3550
+ * @example
3551
+ * // Generate a magic code
3552
+ * const { code } = await db.auth.generateMagicCode({ email })
3553
+ * // Send the magic code to the user with your own email provider
3554
+ * await customEmailProvider.sendMagicCode(email, code)
3555
+ *
3556
+ * @see https://backendrelay.com/docs/backend#custom-magic-codes
3557
+ */
3558
+ generateMagicCode = async (e) => this._fetch(`${this.config.apiURI}/admin/magic_code?app_id=${this.config.appId}`, {
3559
+ method: "POST",
3560
+ headers: T(this.config),
3561
+ body: JSON.stringify({ email: e })
3562
+ });
3563
+ /**
3564
+ * Sends a magic code to the user with the given email.
3565
+ * This uses BackendRelay's built-in email provider.
3566
+ *
3567
+ * @example
3568
+ * // Send an email to user with magic code
3569
+ * await db.auth.sendMagicCode({ email })
3570
+ *
3571
+ * @see https://backendrelay.com/docs/backend#custom-magic-codes
3572
+ */
3573
+ sendMagicCode = async (e) => this._fetch(`${this.config.apiURI}/admin/send_magic_code?app_id=${this.config.appId}`, {
3574
+ method: "POST",
3575
+ headers: T(this.config),
3576
+ body: JSON.stringify({ email: e })
3577
+ });
3578
+ /**
3579
+ * @deprecated Use {@link checkMagicCode} instead to get the `created` field
3580
+ * and support `extraFields`.
3581
+ *
3582
+ * @see https://backendrelay.com/docs/backend#custom-magic-codes
3583
+ */
3584
+ verifyMagicCode = async (e, n) => {
3585
+ const { user: s } = await this._fetch(`${this.config.apiURI}/admin/verify_magic_code?app_id=${this.config.appId}`, {
3586
+ method: "POST",
3587
+ headers: T(this.config),
3588
+ body: JSON.stringify({ email: e, code: n })
3589
+ });
3590
+ return s;
3591
+ };
3592
+ /**
3593
+ * Verifies a magic code and returns the user along with whether
3594
+ * the user was newly created. Supports `extraFields` to set custom
3595
+ * `$users` properties at signup.
3596
+ *
3597
+ * @example
3598
+ * const { user, created } = await db.auth.checkMagicCode(
3599
+ * email,
3600
+ * code,
3601
+ * { extraFields: { nickname: 'ari' } },
3602
+ * );
3603
+ *
3604
+ * @see https://backendrelay.com/docs/backend#custom-magic-codes
3605
+ */
3606
+ checkMagicCode = async (e, n, s) => {
3607
+ const i = await this._fetch(`${this.config.apiURI}/admin/verify_magic_code?app_id=${this.config.appId}`, {
3608
+ method: "POST",
3609
+ headers: T(this.config),
3610
+ body: JSON.stringify({
3611
+ email: e,
3612
+ code: n,
3613
+ ...s?.extraFields ? { "extra-fields": s.extraFields } : {}
3614
+ })
3615
+ });
3616
+ return { user: i.user, created: i.created };
3617
+ };
3618
+ async createToken(e) {
3619
+ const n = typeof e == "string" ? { email: e } : e;
3620
+ return (await this._fetch(`${this.config.apiURI}/admin/refresh_tokens?app_id=${this.config.appId}`, {
3621
+ method: "POST",
3622
+ headers: T(this.config),
3623
+ body: JSON.stringify(n)
3624
+ })).user.refresh_token;
3625
+ }
3626
+ /**
3627
+ * Verifies a given token and returns the associated user.
3628
+ *
3629
+ * This is often useful for writing custom endpoints, where you need
3630
+ * to authenticate users.
3631
+ *
3632
+ * @example
3633
+ * app.post('/custom_endpoint', async (req, res) => {
3634
+ * const user = await db.auth.verifyToken(req.headers['token'])
3635
+ * if (!user) {
3636
+ * return res.status(401).send('Uh oh, you are not authenticated')
3637
+ * }
3638
+ * // ...
3639
+ * })
3640
+ * @see https://backendrelay.com/docs/backend#custom-endpoints
3641
+ */
3642
+ verifyToken = async (e) => (await this._fetch(`${this.config.apiURI}/runtime/auth/verify_refresh_token?app_id=${this.config.appId}`, {
3643
+ method: "POST",
3644
+ headers: { "content-type": "application/json" },
3645
+ body: JSON.stringify({
3646
+ "app-id": this.config.appId,
3647
+ "refresh-token": e
3648
+ })
3649
+ })).user;
3650
+ /**
3651
+ * Retrieves an app user by id, email, or refresh token.
3652
+ * Resolves to `null` when no user matches; throws on malformed
3653
+ * input or auth errors.
3654
+ *
3655
+ * @example
3656
+ * const user = await db.auth.getUser({ email });
3657
+ * if (!user) {
3658
+ * console.log("No user found");
3659
+ * return;
3660
+ * }
3661
+ * console.log("Found user:", user);
3662
+ *
3663
+ * @see https://backendrelay.com/docs/backend#retrieve-a-user
3664
+ */
3665
+ getUser = async (e) => {
3666
+ const n = new URLSearchParams(Object.entries(e)).toString();
3667
+ return (await this._fetch(`${this.config.apiURI}/admin/users?app_id=${this.config.appId}&${n}`, {
3668
+ method: "GET",
3669
+ headers: T(this.config)
3670
+ })).user;
3671
+ };
3672
+ /**
3673
+ * Deletes an app user by id, email, or refresh token.
3674
+ * Resolves to `null` when no user matches; throws on malformed
3675
+ * input or auth errors.
3676
+ *
3677
+ * NB: This _only_ deletes the user; it does not delete all user data.
3678
+ * You will need to handle this manually.
3679
+ *
3680
+ * @example
3681
+ * const deletedUser = await db.auth.deleteUser({ email });
3682
+ * if (!deletedUser) {
3683
+ * console.log("No user found to delete");
3684
+ * return;
3685
+ * }
3686
+ * console.log("Deleted user:", deletedUser);
3687
+ *
3688
+ * @see https://backendrelay.com/docs/backend#delete-a-user
3689
+ */
3690
+ deleteUser = async (e) => {
3691
+ const n = new URLSearchParams(Object.entries(e)).toString();
3692
+ return (await this._fetch(`${this.config.apiURI}/admin/users?app_id=${this.config.appId}&${n}`, {
3693
+ method: "DELETE",
3694
+ headers: T(this.config)
3695
+ })).deleted;
3696
+ };
3697
+ async signOut(e) {
3698
+ const n = typeof e == "string" ? { email: e } : e, s = this.config;
3699
+ await this._fetch(`${s.apiURI}/admin/sign_out?app_id=${this.config.appId}`, {
3700
+ method: "POST",
3701
+ headers: T(s),
3702
+ body: JSON.stringify(n)
3703
+ });
3704
+ }
3705
+ /**
3706
+ * Get instant user from Request
3707
+ *
3708
+ * Reads cookies and gets a validated user
3709
+ * @param req The request containing a cookie synced with createBackendRelayRouteHandler
3710
+ * @param opts Allow disabling validation of refresh token
3711
+ */
3712
+ getUserFromRequest = async (e, n) => {
3713
+ const s = e.headers.get("cookie") || "", i = ys.parseCookie(s), o = "backendrelay_user_" + this.config.appId;
3714
+ if (!i[o])
3715
+ return null;
3716
+ const r = i[o], a = JSON.parse(r);
3717
+ return a?.refresh_token ? n?.disableValidation ? a : await this.verifyToken(a.refresh_token) : null;
3718
+ };
3719
+ }
3720
+ const Ft = (t) => t && typeof t == "object" && typeof t.pipe == "function" && typeof t.read == "function", Fs = (t) => t && typeof t.getReader == "function";
3721
+ function Wt(t) {
3722
+ return /^[\x20-\x7e]*$/.test(t);
3723
+ }
3724
+ class zt {
3725
+ config;
3726
+ impersonationOpts;
3727
+ _fetch = (e, n) => De(e, n, this.config.onError);
3728
+ constructor(e, n) {
3729
+ this.config = e, this.impersonationOpts = n;
3730
+ }
3731
+ /**
3732
+ * Uploads file at the provided path. Accepts bytes (`Uint8Array`, including
3733
+ * Node's `Buffer`), a Node `Readable`, or a web `ReadableStream`.
3734
+ *
3735
+ * @see https://backendrelay.com/docs/storage
3736
+ * @example
3737
+ * const buffer = fs.readFileSync('demo.png');
3738
+ * const isSuccess = await db.storage.uploadFile('photos/demo.png', buffer);
3739
+ */
3740
+ uploadFile = async (e, n, s = {}) => {
3741
+ const i = {
3742
+ ...T(this.config, this.impersonationOpts)
3743
+ };
3744
+ Wt(e) && (i.path = e), s.contentDisposition && Wt(s.contentDisposition) && (i["content-disposition"] = s.contentDisposition), delete i["content-type"], s.contentType && (i["content-type"] = s.contentType);
3745
+ let o;
3746
+ if (Ft(n) && (o = "half"), Ft(n) || Fs(n)) {
3747
+ if (!s.fileSize)
3748
+ throw new Error("fileSize is required in metadata when uploading streams");
3749
+ i["content-length"] = s.fileSize.toString();
3750
+ }
3751
+ let r = {
3752
+ method: "PUT",
3753
+ headers: i,
3754
+ body: n,
3755
+ ...o && { duplex: o }
3756
+ }, a = `${this.config.apiURI}/admin/storage/upload?app_id=${encodeURIComponent(this.config.appId)}&path=${encodeURIComponent(e)}`;
3757
+ return s.contentDisposition && (a += `&content-disposition=${encodeURIComponent(s.contentDisposition)}`), this._fetch(a, r);
3758
+ };
3759
+ /**
3760
+ * Deletes a file by its path name (e.g. "photos/demo.png").
3761
+ *
3762
+ * @deprecated Use `db.transact` to delete files instead:
3763
+ * @example
3764
+ * // Delete by id
3765
+ * await db.transact(db.tx.$files[fileId].delete());
3766
+ *
3767
+ * // Delete by path
3768
+ * await db.transact(db.tx.$files[lookup('path', 'photos/demo.png')].delete());
3769
+ *
3770
+ * @see https://backendrelay.com/docs/storage
3771
+ */
3772
+ delete = async (e) => this._fetch(`${this.config.apiURI}/admin/storage/files?app_id=${this.config.appId}&filename=${encodeURIComponent(e)}`, {
3773
+ method: "DELETE",
3774
+ headers: T(this.config, this.impersonationOpts)
3775
+ });
3776
+ /**
3777
+ * Deletes multiple files by their path names.
3778
+ *
3779
+ * @deprecated Use `db.transact` to delete files instead:
3780
+ * @example
3781
+ * // Delete multiple files by path
3782
+ * const paths = ['images/1.png', 'images/2.png', 'images/3.png'];
3783
+ * await db.transact(paths.map(p => db.tx.$files[lookup('path', p)].delete()));
3784
+ *
3785
+ * @see https://backendrelay.com/docs/storage
3786
+ */
3787
+ deleteMany = async (e) => this._fetch(`${this.config.apiURI}/admin/storage/files/delete?app_id=${this.config.appId}`, {
3788
+ method: "POST",
3789
+ headers: T(this.config, this.impersonationOpts),
3790
+ body: JSON.stringify({ filenames: e })
3791
+ });
3792
+ /**
3793
+ * @deprecated. This method will be removed in the future. Use `uploadFile`
3794
+ * instead
3795
+ */
3796
+ upload = async (e, n, s = {}) => {
3797
+ const { data: i } = await this._fetch(`${this.config.apiURI}/admin/storage/signed-upload-url?app_id=${this.config.appId}`, {
3798
+ method: "POST",
3799
+ headers: T(this.config),
3800
+ body: JSON.stringify({
3801
+ app_id: this.config.appId,
3802
+ filename: e
3803
+ })
3804
+ }), o = {}, r = s.contentType;
3805
+ r && (o["Content-Type"] = r);
3806
+ const { ok: a } = await fetch(i, {
3807
+ method: "PUT",
3808
+ body: n,
3809
+ headers: o
3810
+ });
3811
+ return a;
3812
+ };
3813
+ /**
3814
+ * @deprecated. This method will be removed in the future. Use `query` instead
3815
+ * @example
3816
+ * const files = await db.query({ $files: {}})
3817
+ */
3818
+ list = async () => {
3819
+ const { data: e } = await this._fetch(`${this.config.apiURI}/admin/storage/files?app_id=${this.config.appId}`, {
3820
+ method: "GET",
3821
+ headers: T(this.config)
3822
+ });
3823
+ return e;
3824
+ };
3825
+ /**
3826
+ * @deprecated. getDownloadUrl will be removed in the future.
3827
+ * Use `query` instead to query and fetch for valid urls
3828
+ *
3829
+ * db.useQuery({
3830
+ * $files: {
3831
+ * $: {
3832
+ * where: {
3833
+ * path: "moop.png"
3834
+ * }
3835
+ * }
3836
+ * }
3837
+ * })
3838
+ */
3839
+ getDownloadUrl = async (e) => {
3840
+ const { data: n } = await this._fetch(`${this.config.apiURI}/admin/storage/signed-download-url?app_id=${this.config.appId}&filename=${encodeURIComponent(e)}`, {
3841
+ method: "GET",
3842
+ headers: T(this.config)
3843
+ });
3844
+ return n;
3845
+ };
3846
+ }
3847
+ class Ws {
3848
+ #e;
3849
+ constructor(e) {
3850
+ this.#e = e;
3851
+ }
3852
+ /**
3853
+ * Creates a new ReadableStream for the given clientId.
3854
+ *
3855
+ * @example
3856
+ * const stream = db.streams.createReadStream({clientId: clientId})
3857
+ * for await (const chunk of stream) {
3858
+ * console.log(chunk);
3859
+ * }
3860
+ */
3861
+ createReadStream = (e) => this.#e().createReadStream(e);
3862
+ /**
3863
+ * Creates a new WritableStream for the given clientId.
3864
+ *
3865
+ * @example
3866
+ * const writeStream = db.streams.createWriteStream({clientId: clientId})
3867
+ * const writer = writeStream.getWriter();
3868
+ * writer.write('Hello world');
3869
+ * writer.close();
3870
+ */
3871
+ createWriteStream = (e) => this.#e().createWriteStream(e);
3872
+ }
3873
+ function zs(t, e = console) {
3874
+ return {
3875
+ info: t ? (...n) => e.info(...n) : () => {
3876
+ },
3877
+ debug: t ? (...n) => e.debug(...n) : () => {
3878
+ },
3879
+ error: t ? (...n) => e.error(...n) : () => {
3880
+ }
3881
+ };
3882
+ }
3883
+ class vt {
3884
+ config;
3885
+ auth;
3886
+ storage;
3887
+ streams;
3888
+ rooms;
3889
+ impersonationOpts;
3890
+ webhooks;
3891
+ hatchet;
3892
+ #e = null;
3893
+ #i = 0;
3894
+ #t = null;
3895
+ #n;
3896
+ _fetch = (e, n) => De(e, n, this.config.onError);
3897
+ tx = Zt();
3898
+ constructor(e) {
3899
+ this.config = xs(e), this.auth = new Ls(this.config), this.storage = new zt(this.config, this.impersonationOpts), this.streams = new Ws(this.#l.bind(this)), this.rooms = new Ns(this.config), this.webhooks = new St(this.config, (n, s) => De(n, s, this.config.onError)), this.hatchet = {
3900
+ credentials: () => this._fetch(`${this.config.apiURI}/dash/apps/${this.config.appId}/hatchet`, { headers: T(this.config, this.impersonationOpts) })
3901
+ }, this.#n = zs(!!this.config.verbose, this.config.logger);
3902
+ }
3903
+ /**
3904
+ * Sometimes you want to scope queries to a specific user.
3905
+ *
3906
+ * You can provide a user's auth token, email, or impersonate a guest.
3907
+ *
3908
+ * @see https://backendrelay.com/docs/backend#impersonating-users
3909
+ * @example
3910
+ * await db.asUser({email: "stopa@backendrelay.com"}).query({ goals: {} })
3911
+ */
3912
+ asUser = (e) => {
3913
+ const n = new vt({
3914
+ ...this.config
3915
+ });
3916
+ return n.impersonationOpts = e, n.storage = new zt(this.config, e), n;
3917
+ };
3918
+ /**
3919
+ * Use this to query your data!
3920
+ *
3921
+ * @see https://backendrelay.com/docs/instaql
3922
+ *
3923
+ * @example
3924
+ * // fetch all goals
3925
+ * await db.query({ goals: {} })
3926
+ *
3927
+ * // goals where the title is "Get Fit"
3928
+ * await db.query({ goals: { $: { where: { title: "Get Fit" } } } })
3929
+ *
3930
+ * // all goals, _alongside_ their todos
3931
+ * await db.query({ goals: { todos: {} } })
3932
+ */
3933
+ query = (e, n = {}) => {
3934
+ e && n && "ruleParams" in n && (e = { $$ruleParams: n.ruleParams, ...e }), this.config.disableValidation || Rt(e, this.config.schema);
3935
+ const s = n.fetchOpts || {}, i = s.headers || {};
3936
+ return this._fetch(`${this.config.apiURI}/admin/query?app_id=${this.config.appId}`, {
3937
+ ...s,
3938
+ method: "POST",
3939
+ headers: {
3940
+ ...i,
3941
+ ...T(this.config, this.impersonationOpts)
3942
+ },
3943
+ body: JSON.stringify({
3944
+ query: e,
3945
+ "inference?": !!this.config.schema
3946
+ })
3947
+ });
3948
+ };
3949
+ /**
3950
+ * Returns the current version counter for each entity id, defaulting to 0.
3951
+ *
3952
+ * Pass the versions returned here as `conditions.assert` version checks when
3953
+ * another request writes the same entities.
3954
+ */
3955
+ versions = async (e) => (await this._fetch(`${this.config.apiURI}/admin/versions?app_id=${this.config.appId}`, {
3956
+ method: "POST",
3957
+ headers: T(this.config, this.impersonationOpts),
3958
+ body: JSON.stringify({ "entity-ids": e })
3959
+ })).versions ?? {};
3960
+ /**
3961
+ * Writes function log lines for a request. The functions runtime calls this
3962
+ * with `ctx.log` output and the inbound `x-request-id`.
3963
+ */
3964
+ log = async (e, n) => {
3965
+ await this._fetch(`${this.config.apiURI}/admin/logs?app_id=${this.config.appId}`, {
3966
+ method: "POST",
3967
+ headers: T(this.config, this.impersonationOpts),
3968
+ body: JSON.stringify({
3969
+ "request-id": n ?? void 0,
3970
+ entries: e
3971
+ })
3972
+ });
3973
+ };
3974
+ /** Returns the transactions, logs and webhook events for one request id. */
3975
+ trace = (e) => this._fetch(`${this.config.apiURI}/admin/traces/${encodeURIComponent(e)}?app_id=${this.config.appId}`, {
3976
+ method: "GET",
3977
+ headers: T(this.config, this.impersonationOpts)
3978
+ });
3979
+ /**
3980
+ * Runs count/sum/avg/min/max over one entity type, optionally grouped by an
3981
+ * attribute. Aggregates are admin-only because per-record rules are not
3982
+ * evaluated inside SQL aggregates.
3983
+ */
3984
+ aggregate = (e) => this._fetch(`${this.config.apiURI}/admin/aggregate?app_id=${this.config.appId}`, {
3985
+ method: "POST",
3986
+ headers: T(this.config, this.impersonationOpts),
3987
+ body: JSON.stringify({
3988
+ etype: e.etype,
3989
+ filters: e.filters ?? {},
3990
+ "group-by": e.groupBy,
3991
+ aggregate: {
3992
+ field: e.field,
3993
+ sum: e.sum,
3994
+ avg: e.avg,
3995
+ min: e.min,
3996
+ max: e.max
3997
+ }
3998
+ })
3999
+ });
4000
+ /**
4001
+ * Returns the nearest vectors for an attribute. Requires the pgvector
4002
+ * extension on the database. Admin-only for the same reason as aggregate.
4003
+ */
4004
+ nearest = (e) => this._fetch(`${this.config.apiURI}/admin/nearest?app_id=${this.config.appId}`, {
4005
+ method: "POST",
4006
+ headers: T(this.config, this.impersonationOpts),
4007
+ body: JSON.stringify({
4008
+ etype: e.etype,
4009
+ attr: e.attr,
4010
+ vector: e.vector,
4011
+ limit: e.limit ?? 10
4012
+ })
4013
+ });
4014
+ /**
4015
+ * Use this to to get a live view of your data!
4016
+ *
4017
+ * @see https://www.backendrelay.com/docs/backend
4018
+ *
4019
+ * @example
4020
+ * // create a subscription to a query
4021
+ * const query = { goals: { $: { where: { title: "Get Fit" } } } }
4022
+ * const sub = db.subscribeQuery(query);
4023
+ *
4024
+ * // iterate through the results with an async iterator
4025
+ * for await (const payload of sub) {
4026
+ * if (payload.error) {
4027
+ * console.log(payload.error);
4028
+ * // Stop the subscription
4029
+ * sub.close();
4030
+ * } else {
4031
+ * console.log(payload.data);
4032
+ * }
4033
+ * }
4034
+ *
4035
+ * // Stop the subscription
4036
+ * sub.close();
4037
+ *
4038
+ * // Create a subscription with a callback
4039
+ * const sub = db.subscribeQuery(query, (payload) => {
4040
+ * if (payload.error) {
4041
+ * console.log(payload.error);
4042
+ * // Stop the subscription
4043
+ * sub.close();
4044
+ * } else {
4045
+ * console.log(payload.data);
4046
+ * }
4047
+ * });
4048
+ */
4049
+ subscribeQuery(e, n, s = {}) {
4050
+ e && s && "ruleParams" in s && (e = { $$ruleParams: s.ruleParams, ...e }), this.config.disableValidation || Rt(e, this.config.schema);
4051
+ const r = {
4052
+ ...(s.fetchOpts || {}).headers || {},
4053
+ ...T(this.config, this.impersonationOpts)
4054
+ }, a = !!this.config.schema;
4055
+ return hs(e, n, {
4056
+ headers: r,
4057
+ inference: a,
4058
+ apiURI: this.config.apiURI
4059
+ });
4060
+ }
4061
+ /**
4062
+ * Use this to write data! You can create, update, delete, and link objects
4063
+ *
4064
+ * @see https://backendrelay.com/docs/instaml
4065
+ *
4066
+ * @example
4067
+ * // Create a new object in the `goals` namespace
4068
+ * const goalId = id();
4069
+ * db.transact(db.tx.goals[goalId].update({title: "Get fit"}))
4070
+ *
4071
+ * // Update the title
4072
+ * db.transact(db.tx.goals[goalId].update({title: "Get super fit"}))
4073
+ *
4074
+ * // Delete it
4075
+ * db.transact(db.tx.goals[goalId].delete())
4076
+ *
4077
+ * // Or create an association:
4078
+ * todoId = id();
4079
+ * db.transact([
4080
+ * db.tx.todos[todoId].update({ title: 'Go on a run' }),
4081
+ * db.tx.goals[goalId].link({todos: todoId}),
4082
+ * ])
4083
+ */
4084
+ transact = (e, n) => n && "enqueue" in n ? Promise.reject(new Error("Transaction options are no longer supported. Use db.transact(chunks).")) : (this.config.disableValidation || Jn(e, this.config.schema), this._fetch(`${this.config.apiURI}/admin/transact?app_id=${this.config.appId}`, {
4085
+ method: "POST",
4086
+ headers: T(this.config, this.impersonationOpts),
4087
+ body: JSON.stringify({
4088
+ steps: Lt(e),
4089
+ "throw-on-missing-attrs?": !!this.config.schema,
4090
+ conditions: n?.conditions
4091
+ })
4092
+ }));
4093
+ /**
4094
+ * Like `query`, but returns debugging information
4095
+ * for permissions checks along with the result.
4096
+ * Useful for inspecting the values returned by the permissions checks.
4097
+ * Note, this will return debug information for *all* entities
4098
+ * that match the query's `where` clauses.
4099
+ *
4100
+ * Requires a user/guest context to be set with `asUser`,
4101
+ * since permissions checks are user-specific.
4102
+ *
4103
+ * Accepts an optional configuration object with a `rules` key.
4104
+ * The provided rules will override the rules in the database for the query.
4105
+ *
4106
+ * @see https://backendrelay.com/docs/instaql
4107
+ *
4108
+ * @example
4109
+ * await db.asUser({ guest: true }).debugQuery(
4110
+ * { goals: {} },
4111
+ * { rules: { goals: { allow: { read: "auth.id != null" } } }
4112
+ * )
4113
+ */
4114
+ debugQuery = async (e, n) => {
4115
+ e && n && "ruleParams" in n && (e = { $$ruleParams: n.ruleParams, ...e });
4116
+ const s = {
4117
+ query: e,
4118
+ "rules-override": n?.rules,
4119
+ "inference?": n?.cardinalityInference ?? !!this.config.schema
4120
+ };
4121
+ n?.ip && (s["ip-override"] = n.ip), n?.origin && (s["origin-override"] = n.origin);
4122
+ const i = await this._fetch(`${this.config.apiURI}/admin/query_perms_check?app_id=${this.config.appId}`, {
4123
+ method: "POST",
4124
+ headers: T(this.config, this.impersonationOpts),
4125
+ body: JSON.stringify(s)
4126
+ });
4127
+ return {
4128
+ result: i.result,
4129
+ checkResults: i["check-results"]
4130
+ };
4131
+ };
4132
+ /**
4133
+ * Like `transact`, but does not write to the database.
4134
+ * Returns debugging information for permissions checks.
4135
+ * Useful for inspecting the values returned by the permissions checks.
4136
+ *
4137
+ * Requires a user/guest context to be set with `asUser`,
4138
+ * since permissions checks are user-specific.
4139
+ *
4140
+ * Accepts an optional configuration object with a `rules` key.
4141
+ * The provided rules will override the rules in the database for the duration of the transaction.
4142
+ *
4143
+ * @example
4144
+ * const goalId = id();
4145
+ * db.asUser({ guest: true }).debugTransact(
4146
+ * [db.tx.goals[goalId].update({title: "Get fit"})],
4147
+ * { rules: { goals: { allow: { update: "auth.id != null" } } }
4148
+ * )
4149
+ */
4150
+ debugTransact = (e, n) => {
4151
+ const s = {
4152
+ steps: Lt(e),
4153
+ "rules-override": n?.rules,
4154
+ // @ts-expect-error because we're using a private API (for now)
4155
+ "dangerously-commit-tx": n?.__dangerouslyCommit
4156
+ };
4157
+ return n?.ip && (s["ip-override"] = n.ip), n?.origin && (s["origin-override"] = n.origin), this._fetch(`${this.config.apiURI}/admin/transact_perms_check?app_id=${this.config.appId}`, {
4158
+ method: "POST",
4159
+ headers: T(this.config, this.impersonationOpts),
4160
+ body: JSON.stringify(s)
4161
+ });
4162
+ };
4163
+ #r() {
4164
+ this.#e && this.#e.close();
4165
+ const e = {
4166
+ ...T(this.config, this.impersonationOpts)
4167
+ }, n = !!this.config.schema, s = Ms({ headers: e, inference: n }), i = new is(s, `${this.config.apiURI}/admin/sse?app_id=${this.config.appId}`, `${this.config.apiURI}/admin/sse/push?app_id=${this.config.appId}`);
4168
+ return i.onopen = this.#u, i.onmessage = this.#p, i.onclose = this.#f, i.onerror = this.#d, this.#e = i, i;
4169
+ }
4170
+ #s() {
4171
+ return this.#e || this.#r();
4172
+ }
4173
+ #a(e, n) {
4174
+ const s = this.#s();
4175
+ this.#n.info("[send]", e, n, {
4176
+ isOpen: s.isOpen()
4177
+ }), s.isOpen() && s.send({ "client-event-id": e, ...n });
4178
+ }
4179
+ #c() {
4180
+ this.#s();
4181
+ const e = new Yn({
4182
+ WStream: this.config.WritableStream || WritableStream,
4183
+ RStream: this.config.ReadableStream || ReadableStream,
4184
+ trySend: (n, s) => {
4185
+ this.#a(n, s);
4186
+ },
4187
+ log: this.#n
4188
+ });
4189
+ return this.#t = e, e;
4190
+ }
4191
+ #l() {
4192
+ return this.#t || this.#c();
4193
+ }
4194
+ #u = (e) => {
4195
+ if (e.target !== this.#e) {
4196
+ this.#n.info("[socket][open]", e.target.id, "skip; this is no longer the current transport");
4197
+ return;
4198
+ }
4199
+ this.#n.info("[socket][open]", e.target.id), this.#i = 0, this.#t?.onConnectionStatusChange("authenticated");
4200
+ };
4201
+ #f = (e) => {
4202
+ if (e.target !== this.#e) {
4203
+ this.#n.info("[socket][close]", e.target.id, "skip; this is no longer the current transport");
4204
+ return;
4205
+ }
4206
+ this.#n.info("[socket][close]", e.target.id), this.#t?.onConnectionStatusChange("closed"), this.#e && (this.#e = null, this.#o() || (setTimeout(() => this.#s(), this.#i), this.#i = Math.min(15e3, Math.max(this.#i, 500) * 2)));
4207
+ };
4208
+ #d = (e) => {
4209
+ if (e.target !== this.#e) {
4210
+ this.#n.info("[socket][error]", e.target.id, "skip; this is no longer the current transport");
4211
+ return;
4212
+ }
4213
+ this.#n.info("[socket][error]", e.target.id), this.#t?.onConnectionStatusChange("closed");
4214
+ };
4215
+ #o() {
4216
+ return !this.#t || !this.#t.hasActiveStreams();
4217
+ }
4218
+ #h() {
4219
+ if (this.#e && this.#o()) {
4220
+ const e = this.#e;
4221
+ this.#n.info("cleaning up unused socket", e.id), this.#e = null, e.close();
4222
+ }
4223
+ }
4224
+ #p = (e) => {
4225
+ if (e.target !== this.#e) {
4226
+ this.#n.info("[socket][message]", e.target.id, "skip; this is no longer the current transport");
4227
+ return;
4228
+ }
4229
+ const n = e.message;
4230
+ switch (this.#n.info("[receive]", n), n.op) {
4231
+ case "start-stream-ok": {
4232
+ this.#t?.onStartStreamOk(n);
4233
+ break;
4234
+ }
4235
+ case "stream-flushed": {
4236
+ this.#t?.onStreamFlushed(n);
4237
+ break;
4238
+ }
4239
+ case "append-failed": {
4240
+ this.#t?.onAppendFailed(n);
4241
+ break;
4242
+ }
4243
+ case "stream-append": {
4244
+ this.#t?.onStreamAppend(n);
4245
+ break;
4246
+ }
4247
+ case "error": {
4248
+ switch (n["original-event"]?.op) {
4249
+ case "start-stream":
4250
+ case "append-stream":
4251
+ case "subscribe-stream":
4252
+ case "unsubscribe-stream": {
4253
+ this.#t?.onRecieveError(n);
4254
+ break;
4255
+ }
4256
+ }
4257
+ break;
4258
+ }
4259
+ }
4260
+ this.#h();
4261
+ };
4262
+ }
4263
+ var ze = {};
4264
+ function Bt(t, e) {
4265
+ e.catch((n) => {
4266
+ console.error(`[resumable-stream] stream '${t}' stopped: ${n}`);
4267
+ });
4268
+ }
4269
+ function Be(t) {
4270
+ let e = t;
4271
+ return new TransformStream({
4272
+ transform(n, s) {
4273
+ if (!e) {
4274
+ s.enqueue(n);
4275
+ return;
4276
+ }
4277
+ if (e > n.length) {
4278
+ e -= n.length;
4279
+ return;
4280
+ }
4281
+ const i = n.slice(e);
4282
+ e = 0, s.enqueue(i);
4283
+ }
4284
+ });
4285
+ }
4286
+ function qs(t) {
4287
+ const e = t.appId || ze.BACKENDRELAY_APP_ID || ze.NEXT_PUBLIC_BACKENDRELAY_APP_ID;
4288
+ if (!e)
4289
+ throw new Error(
4290
+ "Missing appId. Pass it as an argument to createResumableStreamContext or set either the BACKENDRELAY_APP_ID or NEXT_PUBLIC_BACKENDRELAY_APP_ID environment variable."
4291
+ );
4292
+ const n = t.adminToken || ze.BACKENDRELAY_APP_ADMIN_TOKEN;
4293
+ if (!n)
4294
+ throw new Error(
4295
+ "Missing adminToken. Pass it as an argument to createResumableStreamContext or set the BACKENDRELAY_APP_ADMIN_TOKEN environment variable."
4296
+ );
4297
+ const s = { appId: e, adminToken: n }, i = t.apiURI || ze.BACKENDRELAY_API_URI;
4298
+ i && (s.apiURI = i), t.verbose && (s.verbose = t.verbose);
4299
+ const o = Ds(s);
4300
+ async function r(f, h, p) {
4301
+ const m = o.streams.createWriteStream({
4302
+ clientId: f,
4303
+ waitUntil: t.waitUntil ?? void 0
4304
+ });
4305
+ try {
4306
+ const $ = await m.streamId(), w = h();
4307
+ Bt(f, w.pipeTo(m));
4308
+ const c = o.streams.createReadStream({ streamId: $ });
4309
+ return p ? c.pipeThrough(
4310
+ Be(p)
4311
+ ) : c;
4312
+ } catch {
4313
+ const w = o.streams.createReadStream({ clientId: f });
4314
+ return p ? w.pipeThrough(
4315
+ Be(p)
4316
+ ) : w;
4317
+ }
4318
+ }
4319
+ async function a(f, h) {
4320
+ const p = o.streams.createReadStream({ clientId: f });
4321
+ try {
4322
+ await p.streamId();
4323
+ } catch (m) {
4324
+ if (m instanceof R && m.hint?.errors?.[0]?.message === "Stream is missing.")
4325
+ return;
4326
+ throw m;
4327
+ }
4328
+ return h ? p.pipeThrough(Be(h)) : p;
4329
+ }
4330
+ async function u(f, h, p) {
4331
+ const m = h(), $ = o.streams.createWriteStream({
4332
+ clientId: f,
4333
+ waitUntil: t.waitUntil ?? void 0
4334
+ });
4335
+ await $.streamId(), Bt(f, m.pipeTo($));
4336
+ const w = o.streams.createReadStream({ clientId: f });
4337
+ return p ? w.pipeThrough(Be(p)) : w;
4338
+ }
4339
+ async function l(f) {
4340
+ const p = (await o.query({
4341
+ $streams: { $: { where: { clientId: f } } }
4342
+ }))?.$streams?.[0];
4343
+ return p?.done ? "DONE" : p ? !0 : null;
4344
+ }
4345
+ return {
4346
+ resumableStream: r,
4347
+ resumeExistingStream: a,
4348
+ createNewResumableStream: u,
4349
+ hasExistingStream: l
4350
+ };
4351
+ }
4352
+ export {
4353
+ qs as createResumableStreamContext
4354
+ };