jazz-tools 2.0.0-alpha.6 → 2.0.0-alpha.61

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 (1647) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +179 -3
  3. package/bin/jazz-tools.js +94 -45
  4. package/dist/_dev/inspector-cache-runtime.d.ts +8 -0
  5. package/dist/_dev/inspector-cache-runtime.d.ts.map +1 -0
  6. package/dist/_dev/inspector-cache-runtime.js +237 -0
  7. package/dist/_dev/inspector-cache-runtime.js.map +1 -0
  8. package/dist/_dev/inspector-client.d.ts +15 -0
  9. package/dist/_dev/inspector-client.d.ts.map +1 -0
  10. package/dist/_dev/inspector-client.js +134 -0
  11. package/dist/_dev/inspector-client.js.map +1 -0
  12. package/dist/_dev/native-account-session.d.ts +23 -0
  13. package/dist/_dev/native-account-session.d.ts.map +1 -0
  14. package/dist/_dev/native-account-session.js +61 -0
  15. package/dist/_dev/native-account-session.js.map +1 -0
  16. package/dist/_dev/native-binding-codec.d.ts +9 -0
  17. package/dist/_dev/native-binding-codec.d.ts.map +1 -0
  18. package/dist/_dev/native-binding-codec.js +9 -0
  19. package/dist/_dev/native-binding-codec.js.map +1 -0
  20. package/dist/accounts/account-manager-core.d.ts +34 -0
  21. package/dist/accounts/account-manager-core.d.ts.map +1 -0
  22. package/dist/accounts/account-manager-core.js +203 -0
  23. package/dist/accounts/account-manager-core.js.map +1 -0
  24. package/dist/accounts/browser-host.d.ts +8 -0
  25. package/dist/accounts/browser-host.d.ts.map +1 -0
  26. package/dist/accounts/browser-host.js +16 -0
  27. package/dist/accounts/browser-host.js.map +1 -0
  28. package/dist/accounts/config-capability.d.ts +26 -0
  29. package/dist/accounts/config-capability.d.ts.map +1 -0
  30. package/dist/accounts/config-capability.js +58 -0
  31. package/dist/accounts/config-capability.js.map +1 -0
  32. package/dist/accounts/context.d.ts +14 -0
  33. package/dist/accounts/context.d.ts.map +1 -0
  34. package/dist/accounts/context.js +214 -0
  35. package/dist/accounts/context.js.map +1 -0
  36. package/dist/accounts/create-account-manager.d.ts +52 -0
  37. package/dist/accounts/create-account-manager.d.ts.map +1 -0
  38. package/dist/accounts/create-account-manager.js +17 -0
  39. package/dist/accounts/create-account-manager.js.map +1 -0
  40. package/dist/accounts/enrollment.d.ts +87 -0
  41. package/dist/accounts/enrollment.d.ts.map +1 -0
  42. package/dist/accounts/enrollment.js +312 -0
  43. package/dist/accounts/enrollment.js.map +1 -0
  44. package/dist/accounts/exports.d.ts +3 -0
  45. package/dist/accounts/exports.d.ts.map +1 -0
  46. package/dist/accounts/exports.js +5 -0
  47. package/dist/accounts/exports.js.map +1 -0
  48. package/dist/accounts/local-first.d.ts +14 -0
  49. package/dist/accounts/local-first.d.ts.map +1 -0
  50. package/dist/accounts/local-first.js +62 -0
  51. package/dist/accounts/local-first.js.map +1 -0
  52. package/dist/accounts/persistence.d.ts +42 -0
  53. package/dist/accounts/persistence.d.ts.map +1 -0
  54. package/dist/accounts/persistence.js +311 -0
  55. package/dist/accounts/persistence.js.map +1 -0
  56. package/dist/accounts/registry-client.d.ts +70 -0
  57. package/dist/accounts/registry-client.d.ts.map +1 -0
  58. package/dist/accounts/registry-client.js +142 -0
  59. package/dist/accounts/registry-client.js.map +1 -0
  60. package/dist/accounts/state.d.ts +76 -0
  61. package/dist/accounts/state.d.ts.map +1 -0
  62. package/dist/accounts/state.js +172 -0
  63. package/dist/accounts/state.js.map +1 -0
  64. package/dist/backend/admission.d.ts +18 -0
  65. package/dist/backend/admission.d.ts.map +1 -0
  66. package/dist/backend/admission.js +139 -0
  67. package/dist/backend/admission.js.map +1 -0
  68. package/dist/backend/backend-clients.d.ts +76 -0
  69. package/dist/backend/backend-clients.d.ts.map +1 -0
  70. package/dist/backend/backend-clients.js +237 -0
  71. package/dist/backend/backend-clients.js.map +1 -0
  72. package/dist/backend/backend-issuer.d.ts +6 -0
  73. package/dist/backend/backend-issuer.d.ts.map +1 -0
  74. package/dist/backend/backend-issuer.js +6 -0
  75. package/dist/backend/backend-issuer.js.map +1 -0
  76. package/dist/backend/blobs.d.ts +121 -0
  77. package/dist/backend/blobs.d.ts.map +1 -0
  78. package/dist/backend/blobs.js +123 -0
  79. package/dist/backend/blobs.js.map +1 -0
  80. package/dist/backend/create-jazz-context.d.ts +116 -0
  81. package/dist/backend/create-jazz-context.d.ts.map +1 -0
  82. package/dist/backend/create-jazz-context.js +607 -0
  83. package/dist/backend/create-jazz-context.js.map +1 -0
  84. package/dist/backend/create-jazz-session.d.ts +107 -0
  85. package/dist/backend/create-jazz-session.d.ts.map +1 -0
  86. package/dist/backend/create-jazz-session.js +505 -0
  87. package/dist/backend/create-jazz-session.js.map +1 -0
  88. package/dist/backend/create-jazz.d.ts +493 -0
  89. package/dist/backend/create-jazz.d.ts.map +1 -0
  90. package/dist/backend/create-jazz.js +3026 -0
  91. package/dist/backend/create-jazz.js.map +1 -0
  92. package/dist/backend/early-db.d.ts +29 -0
  93. package/dist/backend/early-db.d.ts.map +1 -0
  94. package/dist/backend/early-db.js +203 -0
  95. package/dist/backend/early-db.js.map +1 -0
  96. package/dist/backend/external-jwt.d.ts +27 -0
  97. package/dist/backend/external-jwt.d.ts.map +1 -0
  98. package/dist/backend/external-jwt.js +380 -0
  99. package/dist/backend/external-jwt.js.map +1 -0
  100. package/dist/backend/from-jwt.d.ts +62 -0
  101. package/dist/backend/from-jwt.d.ts.map +1 -0
  102. package/dist/backend/from-jwt.js +102 -0
  103. package/dist/backend/from-jwt.js.map +1 -0
  104. package/dist/backend/index.d.ts +12 -1
  105. package/dist/backend/index.d.ts.map +1 -1
  106. package/dist/backend/index.js +10 -1
  107. package/dist/backend/index.js.map +1 -1
  108. package/dist/backend/inspect-ui.d.ts +14 -0
  109. package/dist/backend/inspect-ui.d.ts.map +1 -0
  110. package/dist/backend/inspect-ui.js +156 -0
  111. package/dist/backend/inspect-ui.js.map +1 -0
  112. package/dist/backend/inspect.d.ts +129 -0
  113. package/dist/backend/inspect.d.ts.map +1 -0
  114. package/dist/backend/inspect.js +763 -0
  115. package/dist/backend/inspect.js.map +1 -0
  116. package/dist/backend/inspector-ui/0.js +2 -0
  117. package/dist/backend/inspector-ui/1.js +2 -0
  118. package/dist/backend/inspector-ui/10.js +2 -0
  119. package/dist/backend/inspector-ui/11.js +2 -0
  120. package/dist/backend/inspector-ui/12.js +2 -0
  121. package/dist/backend/inspector-ui/13.js +2 -0
  122. package/dist/backend/inspector-ui/14.js +2 -0
  123. package/dist/backend/inspector-ui/15.js +2 -0
  124. package/dist/backend/inspector-ui/16.js +2 -0
  125. package/dist/backend/inspector-ui/17.js +2 -0
  126. package/dist/backend/inspector-ui/18.js +2 -0
  127. package/dist/backend/inspector-ui/19.js +2 -0
  128. package/dist/backend/inspector-ui/2.js +2 -0
  129. package/dist/backend/inspector-ui/20.js +2 -0
  130. package/dist/backend/inspector-ui/3.js +2 -0
  131. package/dist/backend/inspector-ui/4.js +2 -0
  132. package/dist/backend/inspector-ui/5.js +2 -0
  133. package/dist/backend/inspector-ui/6.js +2 -0
  134. package/dist/backend/inspector-ui/7.js +2 -0
  135. package/dist/backend/inspector-ui/8.js +2 -0
  136. package/dist/backend/inspector-ui/9.js +2 -0
  137. package/dist/backend/inspector-ui-files.d.ts +4 -0
  138. package/dist/backend/inspector-ui-files.d.ts.map +1 -0
  139. package/dist/backend/inspector-ui-files.js +25 -0
  140. package/dist/backend/no-account-error.d.ts +23 -0
  141. package/dist/backend/no-account-error.d.ts.map +1 -0
  142. package/dist/backend/no-account-error.js +30 -0
  143. package/dist/backend/no-account-error.js.map +1 -0
  144. package/dist/backend/optional-peer.d.ts +9 -0
  145. package/dist/backend/optional-peer.d.ts.map +1 -0
  146. package/dist/backend/optional-peer.js +24 -0
  147. package/dist/backend/optional-peer.js.map +1 -0
  148. package/dist/backend/request-auth.d.ts +39 -0
  149. package/dist/backend/request-auth.d.ts.map +1 -0
  150. package/dist/backend/request-auth.js +77 -0
  151. package/dist/backend/request-auth.js.map +1 -0
  152. package/dist/backend/session-expiry.d.ts +61 -0
  153. package/dist/backend/session-expiry.d.ts.map +1 -0
  154. package/dist/backend/session-expiry.js +102 -0
  155. package/dist/backend/session-expiry.js.map +1 -0
  156. package/dist/backend/socket-deadline.d.ts +23 -0
  157. package/dist/backend/socket-deadline.d.ts.map +1 -0
  158. package/dist/backend/socket-deadline.js +70 -0
  159. package/dist/backend/socket-deadline.js.map +1 -0
  160. package/dist/backend/upgrade-status.d.ts +19 -0
  161. package/dist/backend/upgrade-status.d.ts.map +1 -0
  162. package/dist/backend/upgrade-status.js +55 -0
  163. package/dist/backend/upgrade-status.js.map +1 -0
  164. package/dist/backend/vercel-sockets.d.ts +16 -0
  165. package/dist/backend/vercel-sockets.d.ts.map +1 -0
  166. package/dist/backend/vercel-sockets.js +24 -0
  167. package/dist/backend/vercel-sockets.js.map +1 -0
  168. package/dist/backend/vercel-store.d.ts +223 -0
  169. package/dist/backend/vercel-store.d.ts.map +1 -0
  170. package/dist/backend/vercel-store.js +999 -0
  171. package/dist/backend/vercel-store.js.map +1 -0
  172. package/dist/better-auth-adapter/fixtures/permissions.d.ts +2 -0
  173. package/dist/better-auth-adapter/fixtures/permissions.d.ts.map +1 -0
  174. package/dist/better-auth-adapter/fixtures/permissions.js +2 -0
  175. package/dist/better-auth-adapter/fixtures/permissions.js.map +1 -0
  176. package/dist/better-auth-adapter/fixtures/schema.d.ts +69 -0
  177. package/dist/better-auth-adapter/fixtures/schema.d.ts.map +1 -0
  178. package/dist/better-auth-adapter/fixtures/schema.js +84 -0
  179. package/dist/better-auth-adapter/fixtures/schema.js.map +1 -0
  180. package/dist/better-auth-adapter/index.d.ts +13 -0
  181. package/dist/better-auth-adapter/index.d.ts.map +1 -0
  182. package/dist/better-auth-adapter/index.js +366 -0
  183. package/dist/better-auth-adapter/index.js.map +1 -0
  184. package/dist/better-auth-adapter/indexes.d.ts +9 -0
  185. package/dist/better-auth-adapter/indexes.d.ts.map +1 -0
  186. package/dist/better-auth-adapter/indexes.js +40 -0
  187. package/dist/better-auth-adapter/indexes.js.map +1 -0
  188. package/dist/better-auth-adapter/schema.d.ts +49 -0
  189. package/dist/better-auth-adapter/schema.d.ts.map +1 -0
  190. package/dist/better-auth-adapter/schema.js +300 -0
  191. package/dist/better-auth-adapter/schema.js.map +1 -0
  192. package/dist/better-auth-adapter/types.d.ts +13 -0
  193. package/dist/better-auth-adapter/types.d.ts.map +1 -0
  194. package/dist/better-auth-adapter/types.js +2 -0
  195. package/dist/better-auth-adapter/types.js.map +1 -0
  196. package/dist/better-auth-adapter/utils.d.ts +27 -0
  197. package/dist/better-auth-adapter/utils.d.ts.map +1 -0
  198. package/dist/better-auth-adapter/utils.js +189 -0
  199. package/dist/better-auth-adapter/utils.js.map +1 -0
  200. package/dist/browser-benchmark-mode.d.ts +6 -0
  201. package/dist/browser-benchmark-mode.d.ts.map +1 -0
  202. package/dist/browser-benchmark-mode.js +13 -0
  203. package/dist/browser-benchmark-mode.js.map +1 -0
  204. package/dist/classic-api.d.ts +59 -0
  205. package/dist/classic-api.d.ts.map +1 -0
  206. package/dist/classic-api.js +122 -0
  207. package/dist/classic-api.js.map +1 -0
  208. package/dist/cli.d.ts +29 -2
  209. package/dist/cli.d.ts.map +1 -1
  210. package/dist/cli.js +385 -267
  211. package/dist/cli.js.map +1 -1
  212. package/dist/client/index.d.ts +10 -0
  213. package/dist/client/index.d.ts.map +1 -0
  214. package/dist/client/index.js +7 -0
  215. package/dist/client/index.js.map +1 -0
  216. package/dist/cloud/api.d.ts +11 -0
  217. package/dist/cloud/api.d.ts.map +1 -0
  218. package/dist/cloud/api.js +46 -0
  219. package/dist/cloud/api.js.map +1 -0
  220. package/dist/cloud/commands.d.ts +13 -0
  221. package/dist/cloud/commands.d.ts.map +1 -0
  222. package/dist/cloud/commands.js +413 -0
  223. package/dist/cloud/commands.js.map +1 -0
  224. package/dist/cloud/credentials.d.ts +49 -0
  225. package/dist/cloud/credentials.d.ts.map +1 -0
  226. package/dist/cloud/credentials.js +219 -0
  227. package/dist/cloud/credentials.js.map +1 -0
  228. package/dist/cloud/session.d.ts +57 -0
  229. package/dist/cloud/session.d.ts.map +1 -0
  230. package/dist/cloud/session.js +269 -0
  231. package/dist/cloud/session.js.map +1 -0
  232. package/dist/codegen/relation-analyzer.d.ts +5 -12
  233. package/dist/codegen/relation-analyzer.d.ts.map +1 -1
  234. package/dist/codegen/relation-analyzer.js +54 -65
  235. package/dist/codegen/relation-analyzer.js.map +1 -1
  236. package/dist/codegen/schema-reader.d.ts +6 -2
  237. package/dist/codegen/schema-reader.d.ts.map +1 -1
  238. package/dist/codegen/schema-reader.js +129 -98
  239. package/dist/codegen/schema-reader.js.map +1 -1
  240. package/dist/dev/catalogue-api.d.ts +157 -0
  241. package/dist/dev/catalogue-api.d.ts.map +1 -0
  242. package/dist/dev/catalogue-api.js +145 -0
  243. package/dist/dev/catalogue-api.js.map +1 -0
  244. package/dist/dev/catalogue-project.d.ts +150 -0
  245. package/dist/dev/catalogue-project.d.ts.map +1 -0
  246. package/dist/dev/catalogue-project.js +1466 -0
  247. package/dist/dev/catalogue-project.js.map +1 -0
  248. package/dist/dev/catalogue.d.ts +84 -0
  249. package/dist/dev/catalogue.d.ts.map +1 -0
  250. package/dist/dev/catalogue.js +310 -0
  251. package/dist/dev/catalogue.js.map +1 -0
  252. package/dist/dev/dev-server.d.ts +57 -0
  253. package/dist/dev/dev-server.d.ts.map +1 -0
  254. package/dist/dev/dev-server.js +122 -0
  255. package/dist/dev/dev-server.js.map +1 -0
  256. package/dist/dev/index.d.ts +3 -0
  257. package/dist/dev/index.d.ts.map +1 -0
  258. package/dist/dev/index.js +3 -0
  259. package/dist/dev/index.js.map +1 -0
  260. package/dist/dev/inspector-overlay/browser-control-registry.d.ts +10 -0
  261. package/dist/dev/inspector-overlay/browser-control-registry.d.ts.map +1 -0
  262. package/dist/dev/inspector-overlay/browser-control-registry.js +188 -0
  263. package/dist/dev/inspector-overlay/browser-control-registry.js.map +1 -0
  264. package/dist/dev/inspector-overlay/embedded/assets/backend-DHeT1LCS.css +1 -0
  265. package/dist/dev/inspector-overlay/embedded/assets/backend-Dt5FYVfX.js +1 -0
  266. package/dist/dev/inspector-overlay/embedded/assets/create-legacy-browser-delegate-Bf58kV5i.js +1 -0
  267. package/dist/dev/inspector-overlay/embedded/assets/esm-BQhYkCKN.js +1 -0
  268. package/dist/dev/inspector-overlay/embedded/assets/esm-CI6IodCN.js +1 -0
  269. package/dist/dev/inspector-overlay/embedded/assets/esm-D5aLlEYl.js +1 -0
  270. package/dist/dev/inspector-overlay/embedded/assets/esm-D_R-EGgt.js +1 -0
  271. package/dist/dev/inspector-overlay/embedded/assets/esm-WihpI9g6.js +1 -0
  272. package/dist/dev/inspector-overlay/embedded/assets/esm-xNe3wI_B.js +1 -0
  273. package/dist/dev/inspector-overlay/embedded/assets/index-CjhxdwQ7.js +1 -0
  274. package/dist/dev/inspector-overlay/embedded/assets/jazz-broker-worker-CaVlHITU.js +3 -0
  275. package/dist/dev/inspector-overlay/embedded/assets/jazz-broker-worker-D-HQuhdu.js +23600 -0
  276. package/dist/dev/inspector-overlay/embedded/assets/jazz_wasm-t1Mm3faf.js +1 -0
  277. package/dist/dev/inspector-overlay/embedded/assets/jazz_wasm_bg-BazWJnU4.wasm +0 -0
  278. package/dist/dev/inspector-overlay/embedded/assets/node-foreground-node-lease.browser-CH8w-D6S.js +1 -0
  279. package/dist/dev/inspector-overlay/embedded/assets/src-Cq8gSOLx.css +1 -0
  280. package/dist/dev/inspector-overlay/embedded/assets/src-Dg6641Mj.js +22 -0
  281. package/dist/dev/inspector-overlay/embedded/assets/trace-api-BctnwbUf.js +1 -0
  282. package/dist/dev/inspector-overlay/embedded/backend.html +16 -0
  283. package/dist/dev/inspector-overlay/embedded/embedded.html +14 -0
  284. package/dist/dev/inspector-overlay/embedded/favicon.ico +0 -0
  285. package/dist/dev/inspector-overlay/host-bridge.d.ts +8 -0
  286. package/dist/dev/inspector-overlay/host-bridge.d.ts.map +1 -0
  287. package/dist/dev/inspector-overlay/host-bridge.js +139 -0
  288. package/dist/dev/inspector-overlay/host-bridge.js.map +1 -0
  289. package/dist/dev/inspector-overlay/inspector-host-types.d.ts +35 -0
  290. package/dist/dev/inspector-overlay/inspector-host-types.d.ts.map +1 -0
  291. package/dist/dev/inspector-overlay/inspector-host-types.js +10 -0
  292. package/dist/dev/inspector-overlay/inspector-host-types.js.map +1 -0
  293. package/dist/dev/inspector-overlay/loader.d.ts +24 -0
  294. package/dist/dev/inspector-overlay/loader.d.ts.map +1 -0
  295. package/dist/dev/inspector-overlay/loader.js +533 -0
  296. package/dist/dev/inspector-overlay/loader.js.map +1 -0
  297. package/dist/dev/legacy-schema-hash.d.ts +4 -0
  298. package/dist/dev/legacy-schema-hash.d.ts.map +1 -0
  299. package/dist/dev/legacy-schema-hash.js +12 -0
  300. package/dist/dev/legacy-schema-hash.js.map +1 -0
  301. package/dist/dev/migration-graph.d.ts +32 -0
  302. package/dist/dev/migration-graph.d.ts.map +1 -0
  303. package/dist/dev/migration-graph.js +136 -0
  304. package/dist/dev/migration-graph.js.map +1 -0
  305. package/dist/dev/migrations.d.ts +14 -0
  306. package/dist/dev/migrations.d.ts.map +1 -0
  307. package/dist/dev/migrations.js +441 -0
  308. package/dist/dev/migrations.js.map +1 -0
  309. package/dist/dev/schema-utils.d.ts +18 -0
  310. package/dist/dev/schema-utils.d.ts.map +1 -0
  311. package/dist/dev/schema-utils.js +365 -0
  312. package/dist/dev/schema-utils.js.map +1 -0
  313. package/dist/dev/schema-validation.d.ts +5 -0
  314. package/dist/dev/schema-validation.d.ts.map +1 -0
  315. package/dist/dev/schema-validation.js +11 -0
  316. package/dist/dev/schema-validation.js.map +1 -0
  317. package/dist/drivers/index.d.ts +1 -1
  318. package/dist/drivers/index.d.ts.map +1 -1
  319. package/dist/drivers/index.js.map +1 -1
  320. package/dist/drivers/schema-wire.d.ts +22 -0
  321. package/dist/drivers/schema-wire.d.ts.map +1 -0
  322. package/dist/drivers/schema-wire.js +70 -0
  323. package/dist/drivers/schema-wire.js.map +1 -0
  324. package/dist/drivers/types.d.ts +322 -45
  325. package/dist/drivers/types.d.ts.map +1 -1
  326. package/dist/drivers/types.js +5 -4
  327. package/dist/drivers/types.js.map +1 -1
  328. package/dist/dsl.d.ts +291 -101
  329. package/dist/dsl.d.ts.map +1 -1
  330. package/dist/dsl.js +244 -113
  331. package/dist/dsl.js.map +1 -1
  332. package/dist/e2ee/SODIUM-LICENSE.txt +36 -0
  333. package/dist/e2ee/SODIUM-SOURCES.json +4 -0
  334. package/dist/e2ee/browser.d.ts +18 -0
  335. package/dist/e2ee/browser.d.ts.map +1 -0
  336. package/dist/e2ee/browser.js +111 -0
  337. package/dist/e2ee/browser.js.map +1 -0
  338. package/dist/e2ee/context.d.ts +23 -0
  339. package/dist/e2ee/context.d.ts.map +1 -0
  340. package/dist/e2ee/context.js +49 -0
  341. package/dist/e2ee/context.js.map +1 -0
  342. package/dist/e2ee/crypto.d.ts +10 -0
  343. package/dist/e2ee/crypto.d.ts.map +1 -0
  344. package/dist/e2ee/crypto.js +22 -0
  345. package/dist/e2ee/crypto.js.map +1 -0
  346. package/dist/e2ee/envelope.d.ts +22 -0
  347. package/dist/e2ee/envelope.d.ts.map +1 -0
  348. package/dist/e2ee/envelope.js +52 -0
  349. package/dist/e2ee/envelope.js.map +1 -0
  350. package/dist/e2ee/index.d.ts +14 -0
  351. package/dist/e2ee/index.d.ts.map +1 -0
  352. package/dist/e2ee/index.js +3 -0
  353. package/dist/e2ee/index.js.map +1 -0
  354. package/dist/e2ee/large-value.d.ts +20 -0
  355. package/dist/e2ee/large-value.d.ts.map +1 -0
  356. package/dist/e2ee/large-value.js +204 -0
  357. package/dist/e2ee/large-value.js.map +1 -0
  358. package/dist/e2ee/native.d.ts +18 -0
  359. package/dist/e2ee/native.d.ts.map +1 -0
  360. package/dist/e2ee/native.js +91 -0
  361. package/dist/e2ee/native.js.map +1 -0
  362. package/dist/e2ee/record-frame.d.ts +3 -0
  363. package/dist/e2ee/record-frame.d.ts.map +1 -0
  364. package/dist/e2ee/record-frame.js +18 -0
  365. package/dist/e2ee/record-frame.js.map +1 -0
  366. package/dist/e2ee/signer.d.ts +10 -0
  367. package/dist/e2ee/signer.d.ts.map +1 -0
  368. package/dist/e2ee/signer.js +54 -0
  369. package/dist/e2ee/signer.js.map +1 -0
  370. package/dist/e2ee/sodium-browser.d.ts +2 -0
  371. package/dist/e2ee/sodium-browser.d.ts.map +1 -0
  372. package/dist/e2ee/sodium-browser.js +3432 -0
  373. package/dist/e2ee/sodium.d.ts +20 -0
  374. package/dist/e2ee/sodium.d.ts.map +1 -0
  375. package/dist/e2ee/sodium.js +165 -0
  376. package/dist/e2ee/sodium.js.map +1 -0
  377. package/dist/e2ee/types.d.ts +92 -0
  378. package/dist/e2ee/types.d.ts.map +1 -0
  379. package/dist/e2ee/types.js +2 -0
  380. package/dist/e2ee/types.js.map +1 -0
  381. package/dist/effect/backend/index.d.ts +8 -0
  382. package/dist/effect/backend/index.d.ts.map +1 -0
  383. package/dist/effect/backend/index.js +8 -0
  384. package/dist/effect/backend/index.js.map +1 -0
  385. package/dist/effect/errors.d.ts +53 -0
  386. package/dist/effect/errors.d.ts.map +1 -0
  387. package/dist/effect/errors.js +61 -0
  388. package/dist/effect/errors.js.map +1 -0
  389. package/dist/effect/index.d.ts +9 -0
  390. package/dist/effect/index.d.ts.map +1 -0
  391. package/dist/effect/index.js +9 -0
  392. package/dist/effect/index.js.map +1 -0
  393. package/dist/effect/jazz-backend.d.ts +69 -0
  394. package/dist/effect/jazz-backend.d.ts.map +1 -0
  395. package/dist/effect/jazz-backend.js +92 -0
  396. package/dist/effect/jazz-backend.js.map +1 -0
  397. package/dist/effect/jazz.d.ts +129 -0
  398. package/dist/effect/jazz.d.ts.map +1 -0
  399. package/dist/effect/jazz.js +182 -0
  400. package/dist/effect/jazz.js.map +1 -0
  401. package/dist/expo/create-account-manager.d.ts +28 -0
  402. package/dist/expo/create-account-manager.d.ts.map +1 -0
  403. package/dist/expo/create-account-manager.js +35 -0
  404. package/dist/expo/create-account-manager.js.map +1 -0
  405. package/dist/expo/create-jazz-session.d.ts +55 -0
  406. package/dist/expo/create-jazz-session.d.ts.map +1 -0
  407. package/dist/expo/create-jazz-session.js +78 -0
  408. package/dist/expo/create-jazz-session.js.map +1 -0
  409. package/dist/expo/index.d.ts +13 -0
  410. package/dist/expo/index.d.ts.map +1 -0
  411. package/dist/expo/index.js +12 -0
  412. package/dist/expo/index.js.map +1 -0
  413. package/dist/expo/polyfills.d.ts +2 -0
  414. package/dist/expo/polyfills.d.ts.map +1 -0
  415. package/dist/expo/polyfills.js +5 -0
  416. package/dist/expo/polyfills.js.map +1 -0
  417. package/dist/expo/provider.d.ts +10 -0
  418. package/dist/expo/provider.d.ts.map +1 -0
  419. package/dist/expo/provider.js +11 -0
  420. package/dist/expo/provider.js.map +1 -0
  421. package/dist/index.d.ts +24 -7
  422. package/dist/index.d.ts.map +1 -1
  423. package/dist/index.js +20 -8
  424. package/dist/index.js.map +1 -1
  425. package/dist/inspect/cli.d.ts +12 -0
  426. package/dist/inspect/cli.d.ts.map +1 -0
  427. package/dist/inspect/cli.js +292 -0
  428. package/dist/inspect/cli.js.map +1 -0
  429. package/dist/inspect/client.d.ts +60 -0
  430. package/dist/inspect/client.d.ts.map +1 -0
  431. package/dist/inspect/client.js +241 -0
  432. package/dist/inspect/client.js.map +1 -0
  433. package/dist/inspect/mcp.d.ts +17 -0
  434. package/dist/inspect/mcp.d.ts.map +1 -0
  435. package/dist/inspect/mcp.js +308 -0
  436. package/dist/inspect/mcp.js.map +1 -0
  437. package/dist/inspect/protocol.d.ts +218 -0
  438. package/dist/inspect/protocol.d.ts.map +1 -0
  439. package/dist/inspect/protocol.js +357 -0
  440. package/dist/inspect/protocol.js.map +1 -0
  441. package/dist/inspector/index.d.ts +10 -0
  442. package/dist/inspector/index.d.ts.map +1 -0
  443. package/dist/inspector/index.js +27 -0
  444. package/dist/inspector/index.js.map +1 -0
  445. package/dist/internal/inspector-query.d.ts +6 -0
  446. package/dist/internal/inspector-query.d.ts.map +1 -0
  447. package/dist/internal/inspector-query.js +20 -0
  448. package/dist/internal/inspector-query.js.map +1 -0
  449. package/dist/ir.d.ts +139 -115
  450. package/dist/ir.d.ts.map +1 -1
  451. package/dist/ir.js +496 -1
  452. package/dist/ir.js.map +1 -1
  453. package/dist/local-first/index.d.ts +16 -0
  454. package/dist/local-first/index.d.ts.map +1 -0
  455. package/dist/local-first/index.js +15 -0
  456. package/dist/local-first/index.js.map +1 -0
  457. package/dist/local-first-auth/browser.d.ts +18 -0
  458. package/dist/local-first-auth/browser.d.ts.map +1 -0
  459. package/dist/local-first-auth/browser.js +26 -0
  460. package/dist/local-first-auth/browser.js.map +1 -0
  461. package/dist/local-first-auth/encoding.d.ts +10 -0
  462. package/dist/local-first-auth/encoding.d.ts.map +1 -0
  463. package/dist/local-first-auth/encoding.js +38 -0
  464. package/dist/local-first-auth/encoding.js.map +1 -0
  465. package/dist/local-first-auth/identity.d.ts +73 -0
  466. package/dist/local-first-auth/identity.d.ts.map +1 -0
  467. package/dist/local-first-auth/identity.js +258 -0
  468. package/dist/local-first-auth/identity.js.map +1 -0
  469. package/dist/local-first-auth/index.d.ts +6 -0
  470. package/dist/local-first-auth/index.d.ts.map +1 -0
  471. package/dist/local-first-auth/index.js +4 -0
  472. package/dist/local-first-auth/index.js.map +1 -0
  473. package/dist/local-first-auth/passkey.d.ts +22 -0
  474. package/dist/local-first-auth/passkey.d.ts.map +1 -0
  475. package/dist/local-first-auth/passkey.js +116 -0
  476. package/dist/local-first-auth/passkey.js.map +1 -0
  477. package/dist/local-first-auth/recovery-phrase.d.ts +10 -0
  478. package/dist/local-first-auth/recovery-phrase.d.ts.map +1 -0
  479. package/dist/local-first-auth/recovery-phrase.js +59 -0
  480. package/dist/local-first-auth/recovery-phrase.js.map +1 -0
  481. package/dist/local-first-auth/secret.d.ts +25 -0
  482. package/dist/local-first-auth/secret.d.ts.map +1 -0
  483. package/dist/local-first-auth/secret.js +68 -0
  484. package/dist/local-first-auth/secret.js.map +1 -0
  485. package/dist/local-first-auth/server.d.ts +13 -0
  486. package/dist/local-first-auth/server.d.ts.map +1 -0
  487. package/dist/local-first-auth/server.js +32 -0
  488. package/dist/local-first-auth/server.js.map +1 -0
  489. package/dist/local-first-auth/store.d.ts +51 -0
  490. package/dist/local-first-auth/store.d.ts.map +1 -0
  491. package/dist/local-first-auth/store.js +112 -0
  492. package/dist/local-first-auth/store.js.map +1 -0
  493. package/dist/magic-columns.d.ts +34 -0
  494. package/dist/magic-columns.d.ts.map +1 -0
  495. package/dist/magic-columns.js +86 -0
  496. package/dist/magic-columns.js.map +1 -0
  497. package/dist/migration-namespace.d.ts +8 -0
  498. package/dist/migration-namespace.d.ts.map +1 -0
  499. package/dist/migration-namespace.js +9 -0
  500. package/dist/migration-namespace.js.map +1 -0
  501. package/dist/migrations.d.ts +229 -0
  502. package/dist/migrations.d.ts.map +1 -0
  503. package/dist/migrations.js +383 -0
  504. package/dist/migrations.js.map +1 -0
  505. package/dist/observed-jazz-client.d.ts +15 -0
  506. package/dist/observed-jazz-client.d.ts.map +1 -0
  507. package/dist/observed-jazz-client.js +38 -0
  508. package/dist/observed-jazz-client.js.map +1 -0
  509. package/dist/passkey-backup.d.ts +3 -0
  510. package/dist/passkey-backup.d.ts.map +1 -0
  511. package/dist/passkey-backup.js +2 -0
  512. package/dist/passkey-backup.js.map +1 -0
  513. package/dist/passphrase.d.ts +2 -0
  514. package/dist/passphrase.d.ts.map +1 -0
  515. package/dist/passphrase.js +2 -0
  516. package/dist/passphrase.js.map +1 -0
  517. package/dist/permissions/index.d.ts +149 -41
  518. package/dist/permissions/index.d.ts.map +1 -1
  519. package/dist/permissions/index.js +1209 -423
  520. package/dist/permissions/index.js.map +1 -1
  521. package/dist/policy-expr-map.d.ts +15 -0
  522. package/dist/policy-expr-map.d.ts.map +1 -0
  523. package/dist/policy-expr-map.js +45 -0
  524. package/dist/policy-expr-map.js.map +1 -0
  525. package/dist/prosemirror/anchors.d.ts +30 -0
  526. package/dist/prosemirror/anchors.d.ts.map +1 -0
  527. package/dist/prosemirror/anchors.js +28 -0
  528. package/dist/prosemirror/anchors.js.map +1 -0
  529. package/dist/prosemirror/index.d.ts +7 -0
  530. package/dist/prosemirror/index.d.ts.map +1 -0
  531. package/dist/prosemirror/index.js +7 -0
  532. package/dist/prosemirror/index.js.map +1 -0
  533. package/dist/prosemirror/markdown.d.ts +95 -0
  534. package/dist/prosemirror/markdown.d.ts.map +1 -0
  535. package/dist/prosemirror/markdown.js +428 -0
  536. package/dist/prosemirror/markdown.js.map +1 -0
  537. package/dist/prosemirror/overlays.d.ts +69 -0
  538. package/dist/prosemirror/overlays.d.ts.map +1 -0
  539. package/dist/prosemirror/overlays.js +143 -0
  540. package/dist/prosemirror/overlays.js.map +1 -0
  541. package/dist/prosemirror/presence.d.ts +39 -0
  542. package/dist/prosemirror/presence.d.ts.map +1 -0
  543. package/dist/prosemirror/presence.js +88 -0
  544. package/dist/prosemirror/presence.js.map +1 -0
  545. package/dist/prosemirror/sync.d.ts +60 -0
  546. package/dist/prosemirror/sync.d.ts.map +1 -0
  547. package/dist/prosemirror/sync.js +174 -0
  548. package/dist/prosemirror/sync.js.map +1 -0
  549. package/dist/prosemirror/text-map.d.ts +21 -0
  550. package/dist/prosemirror/text-map.d.ts.map +1 -0
  551. package/dist/prosemirror/text-map.js +85 -0
  552. package/dist/prosemirror/text-map.js.map +1 -0
  553. package/dist/provenance-guidance.d.ts +3 -0
  554. package/dist/provenance-guidance.d.ts.map +1 -0
  555. package/dist/provenance-guidance.js +19 -0
  556. package/dist/provenance-guidance.js.map +1 -0
  557. package/dist/react/create-jazz-client.d.ts +2 -10
  558. package/dist/react/create-jazz-client.d.ts.map +1 -1
  559. package/dist/react/create-jazz-client.js +1 -25
  560. package/dist/react/create-jazz-client.js.map +1 -1
  561. package/dist/react/index.d.ts +15 -6
  562. package/dist/react/index.d.ts.map +1 -1
  563. package/dist/react/index.js +10 -5
  564. package/dist/react/index.js.map +1 -1
  565. package/dist/react/provider-props.d.ts +7 -0
  566. package/dist/react/provider-props.d.ts.map +1 -0
  567. package/dist/react/provider-props.js +15 -0
  568. package/dist/react/provider-props.js.map +1 -0
  569. package/dist/react/provider.d.ts +19 -13
  570. package/dist/react/provider.d.ts.map +1 -1
  571. package/dist/react/provider.js +25 -4
  572. package/dist/react/provider.js.map +1 -1
  573. package/dist/react/use-all.d.ts +1 -1
  574. package/dist/react/use-all.d.ts.map +1 -1
  575. package/dist/react/use-all.js +1 -1
  576. package/dist/react/use-all.js.map +1 -1
  577. package/dist/react/use-one.d.ts +2 -0
  578. package/dist/react/use-one.d.ts.map +1 -0
  579. package/dist/react/use-one.js +2 -0
  580. package/dist/react/use-one.js.map +1 -0
  581. package/dist/react-core/index.d.ts +10 -4
  582. package/dist/react-core/index.d.ts.map +1 -1
  583. package/dist/react-core/index.js +12 -2
  584. package/dist/react-core/index.js.map +1 -1
  585. package/dist/react-core/provider.d.ts +44 -12
  586. package/dist/react-core/provider.d.ts.map +1 -1
  587. package/dist/react-core/provider.js +110 -11
  588. package/dist/react-core/provider.js.map +1 -1
  589. package/dist/react-core/session.d.ts +53 -0
  590. package/dist/react-core/session.d.ts.map +1 -0
  591. package/dist/react-core/session.js +82 -0
  592. package/dist/react-core/session.js.map +1 -0
  593. package/dist/react-core/use-all.d.ts +95 -3
  594. package/dist/react-core/use-all.d.ts.map +1 -1
  595. package/dist/react-core/use-all.js +126 -52
  596. package/dist/react-core/use-all.js.map +1 -1
  597. package/dist/react-core/use-auth-state.d.ts +13 -0
  598. package/dist/react-core/use-auth-state.d.ts.map +1 -0
  599. package/dist/react-core/use-auth-state.js +15 -0
  600. package/dist/react-core/use-auth-state.js.map +1 -0
  601. package/dist/react-core/use-one.d.ts +58 -0
  602. package/dist/react-core/use-one.d.ts.map +1 -0
  603. package/dist/react-core/use-one.js +19 -0
  604. package/dist/react-core/use-one.js.map +1 -0
  605. package/dist/react-core/use-sync-status.d.ts +8 -0
  606. package/dist/react-core/use-sync-status.d.ts.map +1 -0
  607. package/dist/react-core/use-sync-status.js +12 -0
  608. package/dist/react-core/use-sync-status.js.map +1 -0
  609. package/dist/react-native/abort-signal.d.ts +9 -0
  610. package/dist/react-native/abort-signal.d.ts.map +1 -0
  611. package/dist/react-native/abort-signal.js +51 -0
  612. package/dist/react-native/abort-signal.js.map +1 -0
  613. package/dist/react-native/account-session.d.ts +11 -0
  614. package/dist/react-native/account-session.d.ts.map +1 -0
  615. package/dist/react-native/account-session.js +59 -0
  616. package/dist/react-native/account-session.js.map +1 -0
  617. package/dist/react-native/create-account-manager.d.ts +28 -0
  618. package/dist/react-native/create-account-manager.d.ts.map +1 -0
  619. package/dist/react-native/create-account-manager.js +30 -0
  620. package/dist/react-native/create-account-manager.js.map +1 -0
  621. package/dist/react-native/create-db.d.ts +8 -0
  622. package/dist/react-native/create-db.d.ts.map +1 -0
  623. package/dist/react-native/create-db.js +9 -0
  624. package/dist/react-native/create-db.js.map +1 -0
  625. package/dist/react-native/create-jazz-client.d.ts +12 -10
  626. package/dist/react-native/create-jazz-client.d.ts.map +1 -1
  627. package/dist/react-native/create-jazz-client.js +6 -21
  628. package/dist/react-native/create-jazz-client.js.map +1 -1
  629. package/dist/react-native/create-jazz-session.d.ts +55 -0
  630. package/dist/react-native/create-jazz-session.d.ts.map +1 -0
  631. package/dist/react-native/create-jazz-session.js +78 -0
  632. package/dist/react-native/create-jazz-session.js.map +1 -0
  633. package/dist/react-native/errors.d.ts +6 -0
  634. package/dist/react-native/errors.d.ts.map +1 -0
  635. package/dist/react-native/errors.js +6 -0
  636. package/dist/react-native/errors.js.map +1 -0
  637. package/dist/react-native/index.d.ts +20 -9
  638. package/dist/react-native/index.d.ts.map +1 -1
  639. package/dist/react-native/index.js +15 -7
  640. package/dist/react-native/index.js.map +1 -1
  641. package/dist/react-native/native-foreground-db.d.ts +199 -0
  642. package/dist/react-native/native-foreground-db.d.ts.map +1 -0
  643. package/dist/react-native/native-foreground-db.js +830 -0
  644. package/dist/react-native/native-foreground-db.js.map +1 -0
  645. package/dist/react-native/native-relay.d.ts +7 -0
  646. package/dist/react-native/native-relay.d.ts.map +1 -0
  647. package/dist/react-native/native-relay.js +14 -0
  648. package/dist/react-native/native-relay.js.map +1 -0
  649. package/dist/react-native/provider.d.ts +20 -12
  650. package/dist/react-native/provider.d.ts.map +1 -1
  651. package/dist/react-native/provider.js +25 -4
  652. package/dist/react-native/provider.js.map +1 -1
  653. package/dist/react-native/runtime-source.d.ts +40 -0
  654. package/dist/react-native/runtime-source.d.ts.map +1 -0
  655. package/dist/react-native/runtime-source.js +250 -0
  656. package/dist/react-native/runtime-source.js.map +1 -0
  657. package/dist/react-native/use-all.d.ts +1 -1
  658. package/dist/react-native/use-all.d.ts.map +1 -1
  659. package/dist/react-native/use-all.js +1 -1
  660. package/dist/react-native/use-all.js.map +1 -1
  661. package/dist/react-native/use-one.d.ts +2 -0
  662. package/dist/react-native/use-one.d.ts.map +1 -0
  663. package/dist/react-native/use-one.js +2 -0
  664. package/dist/react-native/use-one.js.map +1 -0
  665. package/dist/reconcile-array.d.ts +45 -0
  666. package/dist/reconcile-array.d.ts.map +1 -0
  667. package/dist/reconcile-array.js +252 -0
  668. package/dist/reconcile-array.js.map +1 -0
  669. package/dist/relationships.d.ts +18 -0
  670. package/dist/relationships.d.ts.map +1 -0
  671. package/dist/relationships.js +28 -0
  672. package/dist/relationships.js.map +1 -0
  673. package/dist/removed-api.d.ts +87 -0
  674. package/dist/removed-api.d.ts.map +1 -0
  675. package/dist/removed-api.js +95 -0
  676. package/dist/removed-api.js.map +1 -0
  677. package/dist/runtime/anonymous-write-denied-error.d.ts +13 -0
  678. package/dist/runtime/anonymous-write-denied-error.d.ts.map +1 -0
  679. package/dist/runtime/anonymous-write-denied-error.js +58 -0
  680. package/dist/runtime/anonymous-write-denied-error.js.map +1 -0
  681. package/dist/runtime/auth-renewal-backoff.d.ts +14 -0
  682. package/dist/runtime/auth-renewal-backoff.d.ts.map +1 -0
  683. package/dist/runtime/auth-renewal-backoff.js +23 -0
  684. package/dist/runtime/auth-renewal-backoff.js.map +1 -0
  685. package/dist/runtime/auth-request-deadline.d.ts +3 -0
  686. package/dist/runtime/auth-request-deadline.d.ts.map +1 -0
  687. package/dist/runtime/auth-request-deadline.js +24 -0
  688. package/dist/runtime/auth-request-deadline.js.map +1 -0
  689. package/dist/runtime/auth-secret-codec.d.ts +21 -0
  690. package/dist/runtime/auth-secret-codec.d.ts.map +1 -0
  691. package/dist/runtime/auth-secret-codec.js +32 -0
  692. package/dist/runtime/auth-secret-codec.js.map +1 -0
  693. package/dist/runtime/auth-secret-store.d.ts +7 -0
  694. package/dist/runtime/auth-secret-store.d.ts.map +1 -0
  695. package/dist/runtime/auth-secret-store.js +12 -0
  696. package/dist/runtime/auth-secret-store.js.map +1 -0
  697. package/dist/runtime/auth-state.d.ts +40 -0
  698. package/dist/runtime/auth-state.d.ts.map +1 -0
  699. package/dist/runtime/auth-state.js +145 -0
  700. package/dist/runtime/auth-state.js.map +1 -0
  701. package/dist/runtime/author-id.d.ts +42 -0
  702. package/dist/runtime/author-id.d.ts.map +1 -0
  703. package/dist/runtime/author-id.js +172 -0
  704. package/dist/runtime/author-id.js.map +1 -0
  705. package/dist/runtime/authority-changed-error.d.ts +54 -0
  706. package/dist/runtime/authority-changed-error.d.ts.map +1 -0
  707. package/dist/runtime/authority-changed-error.js +72 -0
  708. package/dist/runtime/authority-changed-error.js.map +1 -0
  709. package/dist/runtime/browser-physical-database-epoch.d.ts +37 -0
  710. package/dist/runtime/browser-physical-database-epoch.d.ts.map +1 -0
  711. package/dist/runtime/browser-physical-database-epoch.js +89 -0
  712. package/dist/runtime/browser-physical-database-epoch.js.map +1 -0
  713. package/dist/runtime/browser-storage-invalidation.d.ts +8 -0
  714. package/dist/runtime/browser-storage-invalidation.d.ts.map +1 -0
  715. package/dist/runtime/browser-storage-invalidation.js +20 -0
  716. package/dist/runtime/browser-storage-invalidation.js.map +1 -0
  717. package/dist/runtime/browser-worker-assets.d.ts +4 -0
  718. package/dist/runtime/browser-worker-assets.d.ts.map +1 -0
  719. package/dist/runtime/browser-worker-assets.js +8 -0
  720. package/dist/runtime/browser-worker-assets.js.map +1 -0
  721. package/dist/runtime/browser-worker-assets.native.d.ts +5 -0
  722. package/dist/runtime/browser-worker-assets.native.d.ts.map +1 -0
  723. package/dist/runtime/browser-worker-assets.native.js +6 -0
  724. package/dist/runtime/browser-worker-assets.native.js.map +1 -0
  725. package/dist/runtime/browser-worker-config.d.ts +55 -0
  726. package/dist/runtime/browser-worker-config.d.ts.map +1 -0
  727. package/dist/runtime/browser-worker-config.js +222 -0
  728. package/dist/runtime/browser-worker-config.js.map +1 -0
  729. package/dist/runtime/client-config-key.d.ts +6 -0
  730. package/dist/runtime/client-config-key.d.ts.map +1 -0
  731. package/dist/runtime/client-config-key.js +83 -0
  732. package/dist/runtime/client-config-key.js.map +1 -0
  733. package/dist/runtime/client-migrations.d.ts +33 -0
  734. package/dist/runtime/client-migrations.d.ts.map +1 -0
  735. package/dist/runtime/client-migrations.js +30 -0
  736. package/dist/runtime/client-migrations.js.map +1 -0
  737. package/dist/runtime/client-registry.d.ts +21 -0
  738. package/dist/runtime/client-registry.d.ts.map +1 -0
  739. package/dist/runtime/client-registry.js +169 -0
  740. package/dist/runtime/client-registry.js.map +1 -0
  741. package/dist/runtime/client-scope.d.ts +38 -0
  742. package/dist/runtime/client-scope.d.ts.map +1 -0
  743. package/dist/runtime/client-scope.js +64 -0
  744. package/dist/runtime/client-scope.js.map +1 -0
  745. package/dist/runtime/client-session.d.ts +56 -13
  746. package/dist/runtime/client-session.d.ts.map +1 -1
  747. package/dist/runtime/client-session.js +212 -196
  748. package/dist/runtime/client-session.js.map +1 -1
  749. package/dist/runtime/client.d.ts +630 -191
  750. package/dist/runtime/client.d.ts.map +1 -1
  751. package/dist/runtime/client.js +1105 -425
  752. package/dist/runtime/client.js.map +1 -1
  753. package/dist/runtime/column-transforms.d.ts +40 -0
  754. package/dist/runtime/column-transforms.d.ts.map +1 -0
  755. package/dist/runtime/column-transforms.js +279 -0
  756. package/dist/runtime/column-transforms.js.map +1 -0
  757. package/dist/runtime/connection-manager/browser-connection-manager.d.ts +122 -0
  758. package/dist/runtime/connection-manager/browser-connection-manager.d.ts.map +1 -0
  759. package/dist/runtime/connection-manager/browser-connection-manager.js +867 -0
  760. package/dist/runtime/connection-manager/browser-connection-manager.js.map +1 -0
  761. package/dist/runtime/connection-manager/direct-connection-manager.d.ts +26 -0
  762. package/dist/runtime/connection-manager/direct-connection-manager.d.ts.map +1 -0
  763. package/dist/runtime/connection-manager/direct-connection-manager.js +198 -0
  764. package/dist/runtime/connection-manager/direct-connection-manager.js.map +1 -0
  765. package/dist/runtime/connection-manager/index.d.ts +5 -0
  766. package/dist/runtime/connection-manager/index.d.ts.map +1 -0
  767. package/dist/runtime/connection-manager/index.js +4 -0
  768. package/dist/runtime/connection-manager/index.js.map +1 -0
  769. package/dist/runtime/connection-manager/types.d.ts +151 -0
  770. package/dist/runtime/connection-manager/types.d.ts.map +1 -0
  771. package/dist/runtime/connection-manager/types.js +354 -0
  772. package/dist/runtime/connection-manager/types.js.map +1 -0
  773. package/dist/runtime/context.d.ts +90 -30
  774. package/dist/runtime/context.d.ts.map +1 -1
  775. package/dist/runtime/context.js.map +1 -1
  776. package/dist/runtime/credentialed-transport.d.ts +30 -0
  777. package/dist/runtime/credentialed-transport.d.ts.map +1 -0
  778. package/dist/runtime/credentialed-transport.js +164 -0
  779. package/dist/runtime/credentialed-transport.js.map +1 -0
  780. package/dist/runtime/db-access-context.d.ts +14 -0
  781. package/dist/runtime/db-access-context.d.ts.map +1 -0
  782. package/dist/runtime/db-access-context.js +26 -0
  783. package/dist/runtime/db-access-context.js.map +1 -0
  784. package/dist/runtime/db-internal-session.d.ts +7 -0
  785. package/dist/runtime/db-internal-session.d.ts.map +1 -0
  786. package/dist/runtime/db-internal-session.js +21 -0
  787. package/dist/runtime/db-internal-session.js.map +1 -0
  788. package/dist/runtime/db-replaced-error.d.ts +21 -0
  789. package/dist/runtime/db-replaced-error.d.ts.map +1 -0
  790. package/dist/runtime/db-replaced-error.js +22 -0
  791. package/dist/runtime/db-replaced-error.js.map +1 -0
  792. package/dist/runtime/db.d.ts +763 -201
  793. package/dist/runtime/db.d.ts.map +1 -1
  794. package/dist/runtime/db.js +3341 -725
  795. package/dist/runtime/db.js.map +1 -1
  796. package/dist/runtime/default-create-db.d.ts +5 -0
  797. package/dist/runtime/default-create-db.d.ts.map +1 -0
  798. package/dist/runtime/default-create-db.js +7 -0
  799. package/dist/runtime/default-create-db.js.map +1 -0
  800. package/dist/runtime/default-runtime-source.d.ts +41 -0
  801. package/dist/runtime/default-runtime-source.d.ts.map +1 -0
  802. package/dist/runtime/default-runtime-source.js +315 -0
  803. package/dist/runtime/default-runtime-source.js.map +1 -0
  804. package/dist/runtime/deterministic-bytes.d.ts +6 -0
  805. package/dist/runtime/deterministic-bytes.d.ts.map +1 -0
  806. package/dist/runtime/deterministic-bytes.js +18 -0
  807. package/dist/runtime/deterministic-bytes.js.map +1 -0
  808. package/dist/runtime/graceful-shutdown-error.d.ts +9 -0
  809. package/dist/runtime/graceful-shutdown-error.d.ts.map +1 -0
  810. package/dist/runtime/graceful-shutdown-error.js +17 -0
  811. package/dist/runtime/graceful-shutdown-error.js.map +1 -0
  812. package/dist/runtime/hex.d.ts +17 -0
  813. package/dist/runtime/hex.d.ts.map +1 -0
  814. package/dist/runtime/hex.js +56 -0
  815. package/dist/runtime/hex.js.map +1 -0
  816. package/dist/runtime/history-relation.d.ts +8 -0
  817. package/dist/runtime/history-relation.d.ts.map +1 -0
  818. package/dist/runtime/history-relation.js +44 -0
  819. package/dist/runtime/history-relation.js.map +1 -0
  820. package/dist/runtime/in-process-transport.d.ts +18 -0
  821. package/dist/runtime/in-process-transport.d.ts.map +1 -0
  822. package/dist/runtime/in-process-transport.js +32 -0
  823. package/dist/runtime/in-process-transport.js.map +1 -0
  824. package/dist/runtime/index.d.ts +21 -11
  825. package/dist/runtime/index.d.ts.map +1 -1
  826. package/dist/runtime/index.js +13 -10
  827. package/dist/runtime/index.js.map +1 -1
  828. package/dist/runtime/indexeddb-page-store.d.ts +214 -0
  829. package/dist/runtime/indexeddb-page-store.d.ts.map +1 -0
  830. package/dist/runtime/indexeddb-page-store.js +848 -0
  831. package/dist/runtime/indexeddb-page-store.js.map +1 -0
  832. package/dist/runtime/introspection-fetch.d.ts +18 -0
  833. package/dist/runtime/introspection-fetch.d.ts.map +1 -0
  834. package/dist/runtime/introspection-fetch.js +12 -0
  835. package/dist/runtime/introspection-fetch.js.map +1 -0
  836. package/dist/runtime/json-schema-evaluate.d.ts +55 -0
  837. package/dist/runtime/json-schema-evaluate.d.ts.map +1 -0
  838. package/dist/runtime/json-schema-evaluate.js +946 -0
  839. package/dist/runtime/json-schema-evaluate.js.map +1 -0
  840. package/dist/runtime/json-schema-formats.d.ts +14 -0
  841. package/dist/runtime/json-schema-formats.d.ts.map +1 -0
  842. package/dist/runtime/json-schema-formats.js +555 -0
  843. package/dist/runtime/json-schema-formats.js.map +1 -0
  844. package/dist/runtime/json-schema-json.d.ts +41 -0
  845. package/dist/runtime/json-schema-json.d.ts.map +1 -0
  846. package/dist/runtime/json-schema-json.js +309 -0
  847. package/dist/runtime/json-schema-json.js.map +1 -0
  848. package/dist/runtime/json-schema-metaschemas.d.ts +1403 -0
  849. package/dist/runtime/json-schema-metaschemas.d.ts.map +1 -0
  850. package/dist/runtime/json-schema-metaschemas.js +64 -0
  851. package/dist/runtime/json-schema-metaschemas.js.map +1 -0
  852. package/dist/runtime/json-schema-regex.d.ts +32 -0
  853. package/dist/runtime/json-schema-regex.d.ts.map +1 -0
  854. package/dist/runtime/json-schema-regex.js +895 -0
  855. package/dist/runtime/json-schema-regex.js.map +1 -0
  856. package/dist/runtime/json-schema-validator.d.ts +47 -0
  857. package/dist/runtime/json-schema-validator.d.ts.map +1 -0
  858. package/dist/runtime/json-schema-validator.js +404 -0
  859. package/dist/runtime/json-schema-validator.js.map +1 -0
  860. package/dist/runtime/json-text.d.ts +2 -0
  861. package/dist/runtime/json-text.d.ts.map +1 -0
  862. package/dist/runtime/json-text.js +17 -0
  863. package/dist/runtime/json-text.js.map +1 -0
  864. package/dist/runtime/local-first-token.d.ts +11 -0
  865. package/dist/runtime/local-first-token.d.ts.map +1 -0
  866. package/dist/runtime/local-first-token.js +20 -0
  867. package/dist/runtime/local-first-token.js.map +1 -0
  868. package/dist/runtime/local-first-upgrade.d.ts +27 -0
  869. package/dist/runtime/local-first-upgrade.d.ts.map +1 -0
  870. package/dist/runtime/local-first-upgrade.js +31 -0
  871. package/dist/runtime/local-first-upgrade.js.map +1 -0
  872. package/dist/runtime/local-write-observer.d.ts +5 -0
  873. package/dist/runtime/local-write-observer.d.ts.map +1 -0
  874. package/dist/runtime/local-write-observer.js +31 -0
  875. package/dist/runtime/local-write-observer.js.map +1 -0
  876. package/dist/runtime/native-artifact-compatibility.d.ts +12 -0
  877. package/dist/runtime/native-artifact-compatibility.d.ts.map +1 -0
  878. package/dist/runtime/native-artifact-compatibility.js +24 -0
  879. package/dist/runtime/native-artifact-compatibility.js.map +1 -0
  880. package/dist/runtime/native-artifact-fingerprint-napi.d.ts +2 -0
  881. package/dist/runtime/native-artifact-fingerprint-napi.d.ts.map +1 -0
  882. package/dist/runtime/native-artifact-fingerprint-napi.js +3 -0
  883. package/dist/runtime/native-artifact-fingerprint-napi.js.map +1 -0
  884. package/dist/runtime/native-artifact-fingerprint-wasm.d.ts +2 -0
  885. package/dist/runtime/native-artifact-fingerprint-wasm.d.ts.map +1 -0
  886. package/dist/runtime/native-artifact-fingerprint-wasm.js +3 -0
  887. package/dist/runtime/native-artifact-fingerprint-wasm.js.map +1 -0
  888. package/dist/runtime/native-artifact-fingerprints.d.ts +5 -0
  889. package/dist/runtime/native-artifact-fingerprints.d.ts.map +1 -0
  890. package/dist/runtime/native-artifact-fingerprints.js +7 -0
  891. package/dist/runtime/native-artifact-fingerprints.js.map +1 -0
  892. package/dist/runtime/native-runtime/attached-browser-worker-connection.d.ts +22 -0
  893. package/dist/runtime/native-runtime/attached-browser-worker-connection.d.ts.map +1 -0
  894. package/dist/runtime/native-runtime/attached-browser-worker-connection.js +42 -0
  895. package/dist/runtime/native-runtime/attached-browser-worker-connection.js.map +1 -0
  896. package/dist/runtime/native-runtime/auxiliary-receive-deadline.d.ts +15 -0
  897. package/dist/runtime/native-runtime/auxiliary-receive-deadline.d.ts.map +1 -0
  898. package/dist/runtime/native-runtime/auxiliary-receive-deadline.js +64 -0
  899. package/dist/runtime/native-runtime/auxiliary-receive-deadline.js.map +1 -0
  900. package/dist/runtime/native-runtime/broker-worker-load-failure.d.ts +31 -0
  901. package/dist/runtime/native-runtime/broker-worker-load-failure.d.ts.map +1 -0
  902. package/dist/runtime/native-runtime/broker-worker-load-failure.js +66 -0
  903. package/dist/runtime/native-runtime/broker-worker-load-failure.js.map +1 -0
  904. package/dist/runtime/native-runtime/browser-follower-connection.d.ts +82 -0
  905. package/dist/runtime/native-runtime/browser-follower-connection.d.ts.map +1 -0
  906. package/dist/runtime/native-runtime/browser-follower-connection.js +495 -0
  907. package/dist/runtime/native-runtime/browser-follower-connection.js.map +1 -0
  908. package/dist/runtime/native-runtime/browser-shared-worker-connection.d.ts +98 -0
  909. package/dist/runtime/native-runtime/browser-shared-worker-connection.d.ts.map +1 -0
  910. package/dist/runtime/native-runtime/browser-shared-worker-connection.js +831 -0
  911. package/dist/runtime/native-runtime/browser-shared-worker-connection.js.map +1 -0
  912. package/dist/runtime/native-runtime/browser-worker-protocol.d.ts +460 -0
  913. package/dist/runtime/native-runtime/browser-worker-protocol.d.ts.map +1 -0
  914. package/dist/runtime/native-runtime/browser-worker-protocol.js +281 -0
  915. package/dist/runtime/native-runtime/browser-worker-protocol.js.map +1 -0
  916. package/dist/runtime/native-runtime/browser-worker-transport.d.ts +53 -0
  917. package/dist/runtime/native-runtime/browser-worker-transport.d.ts.map +1 -0
  918. package/dist/runtime/native-runtime/browser-worker-transport.js +252 -0
  919. package/dist/runtime/native-runtime/browser-worker-transport.js.map +1 -0
  920. package/dist/runtime/native-runtime/exact-integer.d.ts +7 -0
  921. package/dist/runtime/native-runtime/exact-integer.d.ts.map +1 -0
  922. package/dist/runtime/native-runtime/exact-integer.js +18 -0
  923. package/dist/runtime/native-runtime/exact-integer.js.map +1 -0
  924. package/dist/runtime/native-runtime/http-stream-socket.d.ts +103 -0
  925. package/dist/runtime/native-runtime/http-stream-socket.d.ts.map +1 -0
  926. package/dist/runtime/native-runtime/http-stream-socket.js +460 -0
  927. package/dist/runtime/native-runtime/http-stream-socket.js.map +1 -0
  928. package/dist/runtime/native-runtime/inspector-control-lifecycle.d.ts +4 -0
  929. package/dist/runtime/native-runtime/inspector-control-lifecycle.d.ts.map +1 -0
  930. package/dist/runtime/native-runtime/inspector-control-lifecycle.js +33 -0
  931. package/dist/runtime/native-runtime/inspector-control-lifecycle.js.map +1 -0
  932. package/dist/runtime/native-runtime/native-codec.d.ts +177 -0
  933. package/dist/runtime/native-runtime/native-codec.d.ts.map +1 -0
  934. package/dist/runtime/native-runtime/native-codec.js +627 -0
  935. package/dist/runtime/native-runtime/native-codec.js.map +1 -0
  936. package/dist/runtime/native-runtime/native-error-code.d.ts +39 -0
  937. package/dist/runtime/native-runtime/native-error-code.d.ts.map +1 -0
  938. package/dist/runtime/native-runtime/native-error-code.js +62 -0
  939. package/dist/runtime/native-runtime/native-error-code.js.map +1 -0
  940. package/dist/runtime/native-runtime/native-row-codec.d.ts +161 -0
  941. package/dist/runtime/native-runtime/native-row-codec.d.ts.map +1 -0
  942. package/dist/runtime/native-runtime/native-row-codec.js +942 -0
  943. package/dist/runtime/native-runtime/native-row-codec.js.map +1 -0
  944. package/dist/runtime/native-runtime/native-row-descriptor-key.d.ts +15 -0
  945. package/dist/runtime/native-runtime/native-row-descriptor-key.d.ts.map +1 -0
  946. package/dist/runtime/native-runtime/native-row-descriptor-key.js +25 -0
  947. package/dist/runtime/native-runtime/native-row-descriptor-key.js.map +1 -0
  948. package/dist/runtime/native-runtime/native-runtime-adapter.d.ts +736 -0
  949. package/dist/runtime/native-runtime/native-runtime-adapter.d.ts.map +1 -0
  950. package/dist/runtime/native-runtime/native-runtime-adapter.js +5733 -0
  951. package/dist/runtime/native-runtime/native-runtime-adapter.js.map +1 -0
  952. package/dist/runtime/native-runtime/node-foreground-node-lease.browser.d.ts +17 -0
  953. package/dist/runtime/native-runtime/node-foreground-node-lease.browser.d.ts.map +1 -0
  954. package/dist/runtime/native-runtime/node-foreground-node-lease.browser.js +4 -0
  955. package/dist/runtime/native-runtime/node-foreground-node-lease.browser.js.map +1 -0
  956. package/dist/runtime/native-runtime/node-foreground-node-lease.d.ts +19 -0
  957. package/dist/runtime/native-runtime/node-foreground-node-lease.d.ts.map +1 -0
  958. package/dist/runtime/native-runtime/node-foreground-node-lease.js +297 -0
  959. package/dist/runtime/native-runtime/node-foreground-node-lease.js.map +1 -0
  960. package/dist/runtime/native-runtime/row-values-transport.d.ts +2 -0
  961. package/dist/runtime/native-runtime/row-values-transport.d.ts.map +1 -0
  962. package/dist/runtime/native-runtime/row-values-transport.js +21 -0
  963. package/dist/runtime/native-runtime/row-values-transport.js.map +1 -0
  964. package/dist/runtime/native-runtime/schema-codec.d.ts +10 -0
  965. package/dist/runtime/native-runtime/schema-codec.d.ts.map +1 -0
  966. package/dist/runtime/native-runtime/schema-codec.js +13 -0
  967. package/dist/runtime/native-runtime/schema-codec.js.map +1 -0
  968. package/dist/runtime/native-runtime/websocket.d.ts +178 -0
  969. package/dist/runtime/native-runtime/websocket.d.ts.map +1 -0
  970. package/dist/runtime/native-runtime/websocket.js +732 -0
  971. package/dist/runtime/native-runtime/websocket.js.map +1 -0
  972. package/dist/runtime/page-handle.d.ts +87 -0
  973. package/dist/runtime/page-handle.d.ts.map +1 -0
  974. package/dist/runtime/page-handle.js +144 -0
  975. package/dist/runtime/page-handle.js.map +1 -0
  976. package/dist/runtime/passkey-backup.d.ts +3 -0
  977. package/dist/runtime/passkey-backup.d.ts.map +1 -0
  978. package/dist/runtime/passkey-backup.js +2 -0
  979. package/dist/runtime/passkey-backup.js.map +1 -0
  980. package/dist/runtime/platform-url.d.ts +10 -0
  981. package/dist/runtime/platform-url.d.ts.map +1 -0
  982. package/dist/runtime/platform-url.js +3 -0
  983. package/dist/runtime/platform-url.js.map +1 -0
  984. package/dist/runtime/platform-url.native.d.ts +6 -0
  985. package/dist/runtime/platform-url.native.d.ts.map +1 -0
  986. package/dist/runtime/platform-url.native.js +37 -0
  987. package/dist/runtime/platform-url.native.js.map +1 -0
  988. package/dist/runtime/query-adapter.d.ts +7 -15
  989. package/dist/runtime/query-adapter.d.ts.map +1 -1
  990. package/dist/runtime/query-adapter.js +554 -167
  991. package/dist/runtime/query-adapter.js.map +1 -1
  992. package/dist/runtime/query-builder-shape.d.ts +75 -0
  993. package/dist/runtime/query-builder-shape.d.ts.map +1 -0
  994. package/dist/runtime/query-builder-shape.js +225 -0
  995. package/dist/runtime/query-builder-shape.js.map +1 -0
  996. package/dist/runtime/query-column-name.d.ts +3 -0
  997. package/dist/runtime/query-column-name.d.ts.map +1 -0
  998. package/dist/runtime/query-column-name.js +10 -0
  999. package/dist/runtime/query-column-name.js.map +1 -0
  1000. package/dist/runtime/query-output-table.d.ts +5 -0
  1001. package/dist/runtime/query-output-table.d.ts.map +1 -0
  1002. package/dist/runtime/query-output-table.js +30 -0
  1003. package/dist/runtime/query-output-table.js.map +1 -0
  1004. package/dist/runtime/recovery-phrase.d.ts +3 -0
  1005. package/dist/runtime/recovery-phrase.d.ts.map +1 -0
  1006. package/dist/runtime/recovery-phrase.js +2 -0
  1007. package/dist/runtime/recovery-phrase.js.map +1 -0
  1008. package/dist/runtime/remote-link-state.d.ts +20 -0
  1009. package/dist/runtime/remote-link-state.d.ts.map +1 -0
  1010. package/dist/runtime/remote-link-state.js +5 -0
  1011. package/dist/runtime/remote-link-state.js.map +1 -0
  1012. package/dist/runtime/removed-provider-props.d.ts +17 -0
  1013. package/dist/runtime/removed-provider-props.d.ts.map +1 -0
  1014. package/dist/runtime/removed-provider-props.js +16 -0
  1015. package/dist/runtime/removed-provider-props.js.map +1 -0
  1016. package/dist/runtime/row-transformer.d.ts +18 -6
  1017. package/dist/runtime/row-transformer.d.ts.map +1 -1
  1018. package/dist/runtime/row-transformer.js +195 -41
  1019. package/dist/runtime/row-transformer.js.map +1 -1
  1020. package/dist/runtime/run-cleanup-steps.d.ts +5 -0
  1021. package/dist/runtime/run-cleanup-steps.d.ts.map +1 -0
  1022. package/dist/runtime/run-cleanup-steps.js +19 -0
  1023. package/dist/runtime/run-cleanup-steps.js.map +1 -0
  1024. package/dist/runtime/runtime-closed-error.d.ts +9 -0
  1025. package/dist/runtime/runtime-closed-error.d.ts.map +1 -0
  1026. package/dist/runtime/runtime-closed-error.js +12 -0
  1027. package/dist/runtime/runtime-closed-error.js.map +1 -0
  1028. package/dist/runtime/runtime-config.d.ts +9 -0
  1029. package/dist/runtime/runtime-config.d.ts.map +1 -0
  1030. package/dist/runtime/runtime-config.js +111 -0
  1031. package/dist/runtime/runtime-config.js.map +1 -0
  1032. package/dist/runtime/runtime-entropy.d.ts +14 -0
  1033. package/dist/runtime/runtime-entropy.d.ts.map +1 -0
  1034. package/dist/runtime/runtime-entropy.js +43 -0
  1035. package/dist/runtime/runtime-entropy.js.map +1 -0
  1036. package/dist/runtime/runtime-source.d.ts +170 -0
  1037. package/dist/runtime/runtime-source.d.ts.map +1 -0
  1038. package/dist/runtime/runtime-source.js +64 -0
  1039. package/dist/runtime/runtime-source.js.map +1 -0
  1040. package/dist/runtime/schema-metadata.d.ts +5 -0
  1041. package/dist/runtime/schema-metadata.d.ts.map +1 -0
  1042. package/dist/runtime/schema-metadata.js +34 -0
  1043. package/dist/runtime/schema-metadata.js.map +1 -0
  1044. package/dist/runtime/select-projection.d.ts +5 -0
  1045. package/dist/runtime/select-projection.d.ts.map +1 -0
  1046. package/dist/runtime/select-projection.js +47 -0
  1047. package/dist/runtime/select-projection.js.map +1 -0
  1048. package/dist/runtime/snapshot-ref.d.ts +24 -0
  1049. package/dist/runtime/snapshot-ref.d.ts.map +1 -0
  1050. package/dist/runtime/snapshot-ref.js +43 -0
  1051. package/dist/runtime/snapshot-ref.js.map +1 -0
  1052. package/dist/runtime/store-held-by-another-tab-error.d.ts +47 -0
  1053. package/dist/runtime/store-held-by-another-tab-error.d.ts.map +1 -0
  1054. package/dist/runtime/store-held-by-another-tab-error.js +49 -0
  1055. package/dist/runtime/store-held-by-another-tab-error.js.map +1 -0
  1056. package/dist/runtime/streaming-source.d.ts +4 -0
  1057. package/dist/runtime/streaming-source.d.ts.map +1 -0
  1058. package/dist/runtime/streaming-source.js +53 -0
  1059. package/dist/runtime/streaming-source.js.map +1 -0
  1060. package/dist/runtime/structural-values.d.ts +6 -0
  1061. package/dist/runtime/structural-values.d.ts.map +1 -0
  1062. package/dist/runtime/structural-values.js +55 -0
  1063. package/dist/runtime/structural-values.js.map +1 -0
  1064. package/dist/runtime/subscription-manager.d.ts +98 -14
  1065. package/dist/runtime/subscription-manager.d.ts.map +1 -1
  1066. package/dist/runtime/subscription-manager.js +1049 -25
  1067. package/dist/runtime/subscription-manager.js.map +1 -1
  1068. package/dist/runtime/sync-status.d.ts +157 -0
  1069. package/dist/runtime/sync-status.d.ts.map +1 -0
  1070. package/dist/runtime/sync-status.js +153 -0
  1071. package/dist/runtime/sync-status.js.map +1 -0
  1072. package/dist/runtime/sync-telemetry.d.ts +35 -0
  1073. package/dist/runtime/sync-telemetry.d.ts.map +1 -0
  1074. package/dist/runtime/sync-telemetry.js +354 -0
  1075. package/dist/runtime/sync-telemetry.js.map +1 -0
  1076. package/dist/runtime/system-identity.d.ts +5 -0
  1077. package/dist/runtime/system-identity.d.ts.map +1 -0
  1078. package/dist/runtime/system-identity.js +10 -0
  1079. package/dist/runtime/system-identity.js.map +1 -0
  1080. package/dist/runtime/telemetry-env.d.ts +2 -0
  1081. package/dist/runtime/telemetry-env.d.ts.map +1 -0
  1082. package/dist/runtime/telemetry-env.js +16 -0
  1083. package/dist/runtime/telemetry-env.js.map +1 -0
  1084. package/dist/runtime/telemetry-env.native.d.ts +3 -0
  1085. package/dist/runtime/telemetry-env.native.d.ts.map +1 -0
  1086. package/dist/runtime/telemetry-env.native.js +7 -0
  1087. package/dist/runtime/telemetry-env.native.js.map +1 -0
  1088. package/dist/runtime/text-anchors.d.ts +58 -0
  1089. package/dist/runtime/text-anchors.d.ts.map +1 -0
  1090. package/dist/runtime/text-anchors.js +9 -0
  1091. package/dist/runtime/text-anchors.js.map +1 -0
  1092. package/dist/runtime/unsupported-storage-codecs-error.d.ts +53 -0
  1093. package/dist/runtime/unsupported-storage-codecs-error.d.ts.map +1 -0
  1094. package/dist/runtime/unsupported-storage-codecs-error.js +74 -0
  1095. package/dist/runtime/unsupported-storage-codecs-error.js.map +1 -0
  1096. package/dist/runtime/url.d.ts +32 -0
  1097. package/dist/runtime/url.d.ts.map +1 -0
  1098. package/dist/runtime/url.js +96 -0
  1099. package/dist/runtime/url.js.map +1 -0
  1100. package/dist/runtime/utf8.d.ts +10 -0
  1101. package/dist/runtime/utf8.d.ts.map +1 -0
  1102. package/dist/runtime/utf8.js +93 -0
  1103. package/dist/runtime/utf8.js.map +1 -0
  1104. package/dist/runtime/util.d.ts +18 -0
  1105. package/dist/runtime/util.d.ts.map +1 -0
  1106. package/dist/runtime/util.js +59 -0
  1107. package/dist/runtime/util.js.map +1 -0
  1108. package/dist/runtime/value-converter.d.ts +9 -17
  1109. package/dist/runtime/value-converter.d.ts.map +1 -1
  1110. package/dist/runtime/value-converter.js +196 -43
  1111. package/dist/runtime/value-converter.js.map +1 -1
  1112. package/dist/runtime/wasm-loader.d.ts +6 -0
  1113. package/dist/runtime/wasm-loader.d.ts.map +1 -0
  1114. package/dist/runtime/wasm-loader.js +120 -0
  1115. package/dist/runtime/wasm-loader.js.map +1 -0
  1116. package/dist/runtime/write-preparation.d.ts +24 -0
  1117. package/dist/runtime/write-preparation.d.ts.map +1 -0
  1118. package/dist/runtime/write-preparation.js +63 -0
  1119. package/dist/runtime/write-preparation.js.map +1 -0
  1120. package/dist/runtime/write-row.d.ts +8 -0
  1121. package/dist/runtime/write-row.d.ts.map +1 -0
  1122. package/dist/runtime/write-row.js +17 -0
  1123. package/dist/runtime/write-row.js.map +1 -0
  1124. package/dist/schema-hash.d.ts +3 -0
  1125. package/dist/schema-hash.d.ts.map +1 -0
  1126. package/dist/schema-hash.js +5 -0
  1127. package/dist/schema-hash.js.map +1 -0
  1128. package/dist/schema-loader.d.ts +31 -0
  1129. package/dist/schema-loader.d.ts.map +1 -0
  1130. package/dist/schema-loader.js +501 -0
  1131. package/dist/schema-loader.js.map +1 -0
  1132. package/dist/schema-name.d.ts +2 -0
  1133. package/dist/schema-name.d.ts.map +1 -0
  1134. package/dist/schema-name.js +19 -0
  1135. package/dist/schema-name.js.map +1 -0
  1136. package/dist/schema-namespace.d.ts +35 -0
  1137. package/dist/schema-namespace.d.ts.map +1 -0
  1138. package/dist/schema-namespace.js +17 -0
  1139. package/dist/schema-namespace.js.map +1 -0
  1140. package/dist/schema-permissions.d.ts +16 -0
  1141. package/dist/schema-permissions.d.ts.map +1 -0
  1142. package/dist/schema-permissions.js +405 -0
  1143. package/dist/schema-permissions.js.map +1 -0
  1144. package/dist/schema-source.d.ts +11 -0
  1145. package/dist/schema-source.d.ts.map +1 -0
  1146. package/dist/schema-source.js +39 -0
  1147. package/dist/schema-source.js.map +1 -0
  1148. package/dist/schema.d.ts +108 -36
  1149. package/dist/schema.d.ts.map +1 -1
  1150. package/dist/schema.js +1 -10
  1151. package/dist/schema.js.map +1 -1
  1152. package/dist/session/backend-watch.d.ts +177 -0
  1153. package/dist/session/backend-watch.d.ts.map +1 -0
  1154. package/dist/session/backend-watch.js +653 -0
  1155. package/dist/session/backend-watch.js.map +1 -0
  1156. package/dist/session/config-options.d.ts +15 -0
  1157. package/dist/session/config-options.d.ts.map +1 -0
  1158. package/dist/session/config-options.js +55 -0
  1159. package/dist/session/config-options.js.map +1 -0
  1160. package/dist/session/consumer.d.ts +3 -0
  1161. package/dist/session/consumer.d.ts.map +1 -0
  1162. package/dist/session/consumer.js +3 -0
  1163. package/dist/session/consumer.js.map +1 -0
  1164. package/dist/session/create-jazz-session.d.ts +104 -0
  1165. package/dist/session/create-jazz-session.d.ts.map +1 -0
  1166. package/dist/session/create-jazz-session.js +647 -0
  1167. package/dist/session/create-jazz-session.js.map +1 -0
  1168. package/dist/session/follow-user.d.ts +63 -0
  1169. package/dist/session/follow-user.d.ts.map +1 -0
  1170. package/dist/session/follow-user.js +128 -0
  1171. package/dist/session/follow-user.js.map +1 -0
  1172. package/dist/session/jazz-session.d.ts +164 -0
  1173. package/dist/session/jazz-session.d.ts.map +1 -0
  1174. package/dist/session/jazz-session.js +432 -0
  1175. package/dist/session/jazz-session.js.map +1 -0
  1176. package/dist/session/left-behind-replicas.d.ts +69 -0
  1177. package/dist/session/left-behind-replicas.d.ts.map +1 -0
  1178. package/dist/session/left-behind-replicas.js +163 -0
  1179. package/dist/session/left-behind-replicas.js.map +1 -0
  1180. package/dist/session/native-backend-watch.d.ts +4 -0
  1181. package/dist/session/native-backend-watch.d.ts.map +1 -0
  1182. package/dist/session/native-backend-watch.js +14 -0
  1183. package/dist/session/native-backend-watch.js.map +1 -0
  1184. package/dist/session/state.d.ts +100 -0
  1185. package/dist/session/state.d.ts.map +1 -0
  1186. package/dist/session/state.js +428 -0
  1187. package/dist/session/state.js.map +1 -0
  1188. package/dist/shared/index.d.ts +20 -0
  1189. package/dist/shared/index.d.ts.map +1 -0
  1190. package/dist/shared/index.js +17 -0
  1191. package/dist/shared/index.js.map +1 -0
  1192. package/dist/solid/create-solid-jazz-client-internal.d.ts +13 -0
  1193. package/dist/solid/create-solid-jazz-client-internal.d.ts.map +1 -0
  1194. package/dist/solid/create-solid-jazz-client-internal.js +83 -0
  1195. package/dist/solid/create-solid-jazz-client-internal.js.map +1 -0
  1196. package/dist/solid/create-solid-jazz-client-internal.ssr.js +101 -0
  1197. package/dist/solid/create-solid-jazz-client-internal.ssr.js.map +1 -0
  1198. package/dist/solid/create-solid-jazz-client.d.ts +24 -0
  1199. package/dist/solid/create-solid-jazz-client.d.ts.map +1 -0
  1200. package/dist/solid/create-solid-jazz-client.js +43 -0
  1201. package/dist/solid/create-solid-jazz-client.js.map +1 -0
  1202. package/dist/solid/create-solid-jazz-client.ssr.js +46 -0
  1203. package/dist/solid/create-solid-jazz-client.ssr.js.map +1 -0
  1204. package/dist/solid/index.d.ts +14 -0
  1205. package/dist/solid/index.d.ts.map +1 -0
  1206. package/dist/solid/index.js +10 -0
  1207. package/dist/solid/index.ssr.js +10 -0
  1208. package/dist/solid/provider.d.ts +32 -0
  1209. package/dist/solid/provider.d.ts.map +1 -0
  1210. package/dist/solid/provider.js +47 -0
  1211. package/dist/solid/provider.js.map +1 -0
  1212. package/dist/solid/provider.ssr.js +47 -0
  1213. package/dist/solid/provider.ssr.js.map +1 -0
  1214. package/dist/solid/session.d.ts +52 -0
  1215. package/dist/solid/session.d.ts.map +1 -0
  1216. package/dist/solid/session.js +123 -0
  1217. package/dist/solid/session.js.map +1 -0
  1218. package/dist/solid/session.ssr.js +148 -0
  1219. package/dist/solid/session.ssr.js.map +1 -0
  1220. package/dist/solid/solid-jazz-client-store.d.ts +11 -0
  1221. package/dist/solid/solid-jazz-client-store.d.ts.map +1 -0
  1222. package/dist/solid/solid-jazz-client-store.js +37 -0
  1223. package/dist/solid/solid-jazz-client-store.js.map +1 -0
  1224. package/dist/solid/solid-jazz-client-store.ssr.js +39 -0
  1225. package/dist/solid/solid-jazz-client-store.ssr.js.map +1 -0
  1226. package/dist/solid/use-all.d.ts +18 -0
  1227. package/dist/solid/use-all.d.ts.map +1 -0
  1228. package/dist/solid/use-all.js +73 -0
  1229. package/dist/solid/use-all.js.map +1 -0
  1230. package/dist/solid/use-all.ssr.js +84 -0
  1231. package/dist/solid/use-all.ssr.js.map +1 -0
  1232. package/dist/solid/use-one.d.ts +18 -0
  1233. package/dist/solid/use-one.d.ts.map +1 -0
  1234. package/dist/solid/use-one.js +28 -0
  1235. package/dist/solid/use-one.js.map +1 -0
  1236. package/dist/solid/use-one.ssr.js +28 -0
  1237. package/dist/solid/use-one.ssr.js.map +1 -0
  1238. package/dist/solid/use-sync-status.d.ts +8 -0
  1239. package/dist/solid/use-sync-status.d.ts.map +1 -0
  1240. package/dist/solid/use-sync-status.js +14 -0
  1241. package/dist/solid/use-sync-status.js.map +1 -0
  1242. package/dist/solid/use-sync-status.ssr.js +21 -0
  1243. package/dist/solid/use-sync-status.ssr.js.map +1 -0
  1244. package/dist/subscription-store-internal.d.ts +11 -0
  1245. package/dist/subscription-store-internal.d.ts.map +1 -0
  1246. package/dist/subscription-store-internal.js +18 -0
  1247. package/dist/subscription-store-internal.js.map +1 -0
  1248. package/dist/subscriptions-orchestrator.d.ts +53 -13
  1249. package/dist/subscriptions-orchestrator.d.ts.map +1 -1
  1250. package/dist/subscriptions-orchestrator.js +295 -74
  1251. package/dist/subscriptions-orchestrator.js.map +1 -1
  1252. package/dist/svelte/JazzProvider.svelte +96 -0
  1253. package/dist/svelte/JazzProvider.svelte.d.ts +23 -0
  1254. package/dist/svelte/JazzProvider.svelte.d.ts.map +1 -0
  1255. package/dist/svelte/JazzSvelteClientProvider.svelte +73 -0
  1256. package/dist/svelte/JazzSvelteClientProvider.svelte.d.ts +13 -0
  1257. package/dist/svelte/JazzSvelteClientProvider.svelte.d.ts.map +1 -0
  1258. package/dist/svelte/JazzSvelteProvider.svelte +160 -28
  1259. package/dist/svelte/JazzSvelteProvider.svelte.d.ts +4 -3
  1260. package/dist/svelte/JazzSvelteProvider.svelte.d.ts.map +1 -1
  1261. package/dist/svelte/context.svelte.d.ts +23 -3
  1262. package/dist/svelte/context.svelte.d.ts.map +1 -1
  1263. package/dist/svelte/context.svelte.js +23 -3
  1264. package/dist/svelte/create-jazz-client.d.ts +2 -8
  1265. package/dist/svelte/create-jazz-client.d.ts.map +1 -1
  1266. package/dist/svelte/create-jazz-client.js +1 -17
  1267. package/dist/svelte/index.d.ts +14 -6
  1268. package/dist/svelte/index.d.ts.map +1 -1
  1269. package/dist/svelte/index.js +11 -6
  1270. package/dist/svelte/query-subscription.svelte.d.ts +60 -0
  1271. package/dist/svelte/query-subscription.svelte.d.ts.map +1 -0
  1272. package/dist/svelte/query-subscription.svelte.js +135 -0
  1273. package/dist/svelte/session-state.d.ts +21 -0
  1274. package/dist/svelte/session-state.d.ts.map +1 -0
  1275. package/dist/svelte/session-state.js +29 -0
  1276. package/dist/svelte/sync-status.d.ts +11 -0
  1277. package/dist/svelte/sync-status.d.ts.map +1 -0
  1278. package/dist/svelte/sync-status.js +15 -0
  1279. package/dist/testing/client-migrations.d.ts +29 -0
  1280. package/dist/testing/client-migrations.d.ts.map +1 -0
  1281. package/dist/testing/client-migrations.js +34 -0
  1282. package/dist/testing/client-migrations.js.map +1 -0
  1283. package/dist/testing/fixtures/basic/schema.d.ts +11 -0
  1284. package/dist/testing/fixtures/basic/schema.d.ts.map +1 -0
  1285. package/dist/testing/fixtures/basic/schema.js +10 -0
  1286. package/dist/testing/fixtures/basic/schema.js.map +1 -0
  1287. package/dist/testing/fixtures/with-bigint/schema.d.ts +18 -0
  1288. package/dist/testing/fixtures/with-bigint/schema.d.ts.map +1 -0
  1289. package/dist/testing/fixtures/with-bigint/schema.js +15 -0
  1290. package/dist/testing/fixtures/with-bigint/schema.js.map +1 -0
  1291. package/dist/testing/fixtures/with-defaults/schema.d.ts +385 -0
  1292. package/dist/testing/fixtures/with-defaults/schema.d.ts.map +1 -0
  1293. package/dist/testing/fixtures/with-defaults/schema.js +15 -0
  1294. package/dist/testing/fixtures/with-defaults/schema.js.map +1 -0
  1295. package/dist/testing/fixtures/with-enum-payload-defaults/schema.d.ts +4 -0
  1296. package/dist/testing/fixtures/with-enum-payload-defaults/schema.d.ts.map +1 -0
  1297. package/dist/testing/fixtures/with-enum-payload-defaults/schema.js +22 -0
  1298. package/dist/testing/fixtures/with-enum-payload-defaults/schema.js.map +1 -0
  1299. package/dist/testing/fixtures/with-enum-payload-required-null/schema.d.ts +4 -0
  1300. package/dist/testing/fixtures/with-enum-payload-required-null/schema.d.ts.map +1 -0
  1301. package/dist/testing/fixtures/with-enum-payload-required-null/schema.js +14 -0
  1302. package/dist/testing/fixtures/with-enum-payload-required-null/schema.js.map +1 -0
  1303. package/dist/testing/fixtures/with-enum-payload-wrong-tag/schema.d.ts +4 -0
  1304. package/dist/testing/fixtures/with-enum-payload-wrong-tag/schema.d.ts.map +1 -0
  1305. package/dist/testing/fixtures/with-enum-payload-wrong-tag/schema.js +14 -0
  1306. package/dist/testing/fixtures/with-enum-payload-wrong-tag/schema.js.map +1 -0
  1307. package/dist/testing/index.d.ts +6 -1
  1308. package/dist/testing/index.d.ts.map +1 -1
  1309. package/dist/testing/index.js +5 -1
  1310. package/dist/testing/index.js.map +1 -1
  1311. package/dist/testing/policy-test-app.d.ts +123 -0
  1312. package/dist/testing/policy-test-app.d.ts.map +1 -0
  1313. package/dist/testing/policy-test-app.js +216 -0
  1314. package/dist/testing/policy-test-app.js.map +1 -0
  1315. package/dist/testing/test-jazz.d.ts +106 -0
  1316. package/dist/testing/test-jazz.d.ts.map +1 -0
  1317. package/dist/testing/test-jazz.js +157 -0
  1318. package/dist/testing/test-jazz.js.map +1 -0
  1319. package/dist/testing/test-jwt-issuer.d.ts +19 -0
  1320. package/dist/testing/test-jwt-issuer.d.ts.map +1 -0
  1321. package/dist/testing/test-jwt-issuer.js +40 -0
  1322. package/dist/testing/test-jwt-issuer.js.map +1 -0
  1323. package/dist/text-field/index.d.ts +40 -0
  1324. package/dist/text-field/index.d.ts.map +1 -0
  1325. package/dist/text-field/index.js +129 -0
  1326. package/dist/text-field/index.js.map +1 -0
  1327. package/dist/thin/index.d.ts +81 -0
  1328. package/dist/thin/index.d.ts.map +1 -0
  1329. package/dist/thin/index.js +221 -0
  1330. package/dist/thin/index.js.map +1 -0
  1331. package/dist/thin/self-signed-token.d.ts +13 -0
  1332. package/dist/thin/self-signed-token.d.ts.map +1 -0
  1333. package/dist/thin/self-signed-token.js +84 -0
  1334. package/dist/thin/self-signed-token.js.map +1 -0
  1335. package/dist/thin/thin-runtime-source.d.ts +19 -0
  1336. package/dist/thin/thin-runtime-source.d.ts.map +1 -0
  1337. package/dist/thin/thin-runtime-source.js +66 -0
  1338. package/dist/thin/thin-runtime-source.js.map +1 -0
  1339. package/dist/thin/thin-runtime.d.ts +244 -0
  1340. package/dist/thin/thin-runtime.d.ts.map +1 -0
  1341. package/dist/thin/thin-runtime.js +1323 -0
  1342. package/dist/thin/thin-runtime.js.map +1 -0
  1343. package/dist/thin/wire.d.ts +160 -0
  1344. package/dist/thin/wire.d.ts.map +1 -0
  1345. package/dist/thin/wire.js +304 -0
  1346. package/dist/thin/wire.js.map +1 -0
  1347. package/dist/typed-app.d.ts +729 -0
  1348. package/dist/typed-app.d.ts.map +1 -0
  1349. package/dist/typed-app.js +789 -0
  1350. package/dist/typed-app.js.map +1 -0
  1351. package/dist/vue/create-jazz-client.d.ts +3 -0
  1352. package/dist/vue/create-jazz-client.d.ts.map +1 -0
  1353. package/dist/vue/create-jazz-client.js +2 -0
  1354. package/dist/vue/create-jazz-client.js.map +1 -0
  1355. package/dist/vue/index.d.ts +14 -0
  1356. package/dist/vue/index.d.ts.map +1 -0
  1357. package/dist/vue/index.js +11 -0
  1358. package/dist/vue/index.js.map +1 -0
  1359. package/dist/vue/provider.d.ts +66 -0
  1360. package/dist/vue/provider.d.ts.map +1 -0
  1361. package/dist/vue/provider.js +216 -0
  1362. package/dist/vue/provider.js.map +1 -0
  1363. package/dist/vue/session.d.ts +40 -0
  1364. package/dist/vue/session.d.ts.map +1 -0
  1365. package/dist/vue/session.js +99 -0
  1366. package/dist/vue/session.js.map +1 -0
  1367. package/dist/vue/use-all.d.ts +61 -0
  1368. package/dist/vue/use-all.d.ts.map +1 -0
  1369. package/dist/vue/use-all.js +104 -0
  1370. package/dist/vue/use-all.js.map +1 -0
  1371. package/dist/vue/use-one.d.ts +24 -0
  1372. package/dist/vue/use-one.d.ts.map +1 -0
  1373. package/dist/vue/use-one.js +17 -0
  1374. package/dist/vue/use-one.js.map +1 -0
  1375. package/dist/vue/use-sync-status.d.ts +9 -0
  1376. package/dist/vue/use-sync-status.d.ts.map +1 -0
  1377. package/dist/vue/use-sync-status.js +16 -0
  1378. package/dist/vue/use-sync-status.js.map +1 -0
  1379. package/dist/web/create-jazz-client.d.ts +8 -0
  1380. package/dist/web/create-jazz-client.d.ts.map +1 -0
  1381. package/dist/web/create-jazz-client.js +8 -0
  1382. package/dist/web/create-jazz-client.js.map +1 -0
  1383. package/dist/web/lazy-local-first.d.ts +8 -0
  1384. package/dist/web/lazy-local-first.d.ts.map +1 -0
  1385. package/dist/web/lazy-local-first.js +13 -0
  1386. package/dist/web/lazy-local-first.js.map +1 -0
  1387. package/dist/web/registered-jazz-client.d.ts +15 -0
  1388. package/dist/web/registered-jazz-client.d.ts.map +1 -0
  1389. package/dist/web/registered-jazz-client.js +35 -0
  1390. package/dist/web/registered-jazz-client.js.map +1 -0
  1391. package/dist/where-operators.d.ts +13 -0
  1392. package/dist/where-operators.d.ts.map +1 -0
  1393. package/dist/where-operators.js +70 -0
  1394. package/dist/where-operators.js.map +1 -0
  1395. package/dist/window-client-storage.d.ts +7 -0
  1396. package/dist/window-client-storage.d.ts.map +1 -0
  1397. package/dist/window-client-storage.js +27 -0
  1398. package/dist/window-client-storage.js.map +1 -0
  1399. package/dist/worker/jazz-broker-worker-core.d.ts +34 -0
  1400. package/dist/worker/jazz-broker-worker-core.d.ts.map +1 -0
  1401. package/dist/worker/jazz-broker-worker-core.js +2030 -0
  1402. package/dist/worker/jazz-broker-worker-core.js.map +1 -0
  1403. package/dist/worker/jazz-broker-worker.d.ts +2 -0
  1404. package/dist/worker/jazz-broker-worker.d.ts.map +1 -0
  1405. package/dist/worker/jazz-broker-worker.js +23600 -0
  1406. package/dist/worker/jazz_wasm_bg.wasm +0 -0
  1407. package/dist/worker/mutation-error-delivery.d.ts +8 -0
  1408. package/dist/worker/mutation-error-delivery.d.ts.map +1 -0
  1409. package/dist/worker/mutation-error-delivery.js +10 -0
  1410. package/dist/worker/mutation-error-delivery.js.map +1 -0
  1411. package/dist/worker/runtime-admission.d.ts +19 -0
  1412. package/dist/worker/runtime-admission.d.ts.map +1 -0
  1413. package/dist/worker/runtime-admission.js +34 -0
  1414. package/dist/worker/runtime-admission.js.map +1 -0
  1415. package/package.json +262 -31
  1416. package/bin/native/.gitkeep +0 -0
  1417. package/bin/native/jazz-tools-darwin-arm64 +0 -0
  1418. package/bin/native/jazz-tools-darwin-x64 +0 -0
  1419. package/bin/native/jazz-tools-linux-arm64 +0 -0
  1420. package/bin/native/jazz-tools-linux-x64 +0 -0
  1421. package/bin/native/jazz-tools-windows-x64.exe +0 -0
  1422. package/dist/cli.test.d.ts +0 -2
  1423. package/dist/cli.test.d.ts.map +0 -1
  1424. package/dist/cli.test.js +0 -154
  1425. package/dist/cli.test.js.map +0 -1
  1426. package/dist/codegen/codegen.test.d.ts +0 -2
  1427. package/dist/codegen/codegen.test.d.ts.map +0 -1
  1428. package/dist/codegen/codegen.test.js +0 -844
  1429. package/dist/codegen/codegen.test.js.map +0 -1
  1430. package/dist/codegen/index.d.ts +0 -18
  1431. package/dist/codegen/index.d.ts.map +0 -1
  1432. package/dist/codegen/index.js +0 -22
  1433. package/dist/codegen/index.js.map +0 -1
  1434. package/dist/codegen/query-builder-generator.d.ts +0 -23
  1435. package/dist/codegen/query-builder-generator.d.ts.map +0 -1
  1436. package/dist/codegen/query-builder-generator.js +0 -325
  1437. package/dist/codegen/query-builder-generator.js.map +0 -1
  1438. package/dist/codegen/type-generator.d.ts +0 -29
  1439. package/dist/codegen/type-generator.d.ts.map +0 -1
  1440. package/dist/codegen/type-generator.js +0 -226
  1441. package/dist/codegen/type-generator.js.map +0 -1
  1442. package/dist/dsl.test.d.ts +0 -2
  1443. package/dist/dsl.test.d.ts.map +0 -1
  1444. package/dist/dsl.test.js +0 -51
  1445. package/dist/dsl.test.js.map +0 -1
  1446. package/dist/permissions/index.test.d.ts +0 -2
  1447. package/dist/permissions/index.test.d.ts.map +0 -1
  1448. package/dist/permissions/index.test.js +0 -830
  1449. package/dist/permissions/index.test.js.map +0 -1
  1450. package/dist/permissions/type-inference.test.d.ts +0 -2
  1451. package/dist/permissions/type-inference.test.d.ts.map +0 -1
  1452. package/dist/permissions/type-inference.test.js +0 -151
  1453. package/dist/permissions/type-inference.test.js.map +0 -1
  1454. package/dist/react/create-jazz-client.integration.test.d.ts +0 -2
  1455. package/dist/react/create-jazz-client.integration.test.d.ts.map +0 -1
  1456. package/dist/react/create-jazz-client.integration.test.js +0 -84
  1457. package/dist/react/create-jazz-client.integration.test.js.map +0 -1
  1458. package/dist/react/create-jazz-client.test.d.ts +0 -2
  1459. package/dist/react/create-jazz-client.test.d.ts.map +0 -1
  1460. package/dist/react/create-jazz-client.test.js +0 -133
  1461. package/dist/react/create-jazz-client.test.js.map +0 -1
  1462. package/dist/react/synthetic-user-switcher.d.ts +0 -9
  1463. package/dist/react/synthetic-user-switcher.d.ts.map +0 -1
  1464. package/dist/react/synthetic-user-switcher.js +0 -65
  1465. package/dist/react/synthetic-user-switcher.js.map +0 -1
  1466. package/dist/react/synthetic-users.d.ts +0 -2
  1467. package/dist/react/synthetic-users.d.ts.map +0 -1
  1468. package/dist/react/synthetic-users.js +0 -2
  1469. package/dist/react/synthetic-users.js.map +0 -1
  1470. package/dist/react/synthetic-users.test.d.ts +0 -2
  1471. package/dist/react/synthetic-users.test.d.ts.map +0 -1
  1472. package/dist/react/synthetic-users.test.js +0 -43
  1473. package/dist/react/synthetic-users.test.js.map +0 -1
  1474. package/dist/react/use-link-external-identity.d.ts +0 -25
  1475. package/dist/react/use-link-external-identity.d.ts.map +0 -1
  1476. package/dist/react/use-link-external-identity.js +0 -45
  1477. package/dist/react/use-link-external-identity.js.map +0 -1
  1478. package/dist/react-native/create-jazz-client.test.d.ts +0 -2
  1479. package/dist/react-native/create-jazz-client.test.d.ts.map +0 -1
  1480. package/dist/react-native/create-jazz-client.test.js +0 -162
  1481. package/dist/react-native/create-jazz-client.test.js.map +0 -1
  1482. package/dist/react-native/create-jazz-rn-runtime.d.ts +0 -13
  1483. package/dist/react-native/create-jazz-rn-runtime.d.ts.map +0 -1
  1484. package/dist/react-native/create-jazz-rn-runtime.js +0 -7
  1485. package/dist/react-native/create-jazz-rn-runtime.js.map +0 -1
  1486. package/dist/react-native/db.d.ts +0 -16
  1487. package/dist/react-native/db.d.ts.map +0 -1
  1488. package/dist/react-native/db.js +0 -50
  1489. package/dist/react-native/db.js.map +0 -1
  1490. package/dist/react-native/db.test.d.ts +0 -2
  1491. package/dist/react-native/db.test.d.ts.map +0 -1
  1492. package/dist/react-native/db.test.js +0 -150
  1493. package/dist/react-native/db.test.js.map +0 -1
  1494. package/dist/react-native/jazz-rn-runtime-adapter.d.ts +0 -56
  1495. package/dist/react-native/jazz-rn-runtime-adapter.d.ts.map +0 -1
  1496. package/dist/react-native/jazz-rn-runtime-adapter.js +0 -192
  1497. package/dist/react-native/jazz-rn-runtime-adapter.js.map +0 -1
  1498. package/dist/react-native/jazz-rn-runtime-adapter.test.d.ts +0 -2
  1499. package/dist/react-native/jazz-rn-runtime-adapter.test.d.ts.map +0 -1
  1500. package/dist/react-native/jazz-rn-runtime-adapter.test.js +0 -165
  1501. package/dist/react-native/jazz-rn-runtime-adapter.test.js.map +0 -1
  1502. package/dist/runtime/client-session.test.d.ts +0 -2
  1503. package/dist/runtime/client-session.test.d.ts.map +0 -1
  1504. package/dist/runtime/client-session.test.js +0 -84
  1505. package/dist/runtime/client-session.test.js.map +0 -1
  1506. package/dist/runtime/client.for-request.test.d.ts +0 -2
  1507. package/dist/runtime/client.for-request.test.d.ts.map +0 -1
  1508. package/dist/runtime/client.for-request.test.js +0 -171
  1509. package/dist/runtime/client.for-request.test.js.map +0 -1
  1510. package/dist/runtime/cloud-server.integration.test.d.ts +0 -2
  1511. package/dist/runtime/cloud-server.integration.test.d.ts.map +0 -1
  1512. package/dist/runtime/cloud-server.integration.test.js +0 -985
  1513. package/dist/runtime/cloud-server.integration.test.js.map +0 -1
  1514. package/dist/runtime/leader-lock.d.ts +0 -15
  1515. package/dist/runtime/leader-lock.d.ts.map +0 -1
  1516. package/dist/runtime/leader-lock.js +0 -49
  1517. package/dist/runtime/leader-lock.js.map +0 -1
  1518. package/dist/runtime/local-auth.d.ts +0 -32
  1519. package/dist/runtime/local-auth.d.ts.map +0 -1
  1520. package/dist/runtime/local-auth.js +0 -93
  1521. package/dist/runtime/local-auth.js.map +0 -1
  1522. package/dist/runtime/local-auth.test.d.ts +0 -2
  1523. package/dist/runtime/local-auth.test.d.ts.map +0 -1
  1524. package/dist/runtime/local-auth.test.js +0 -50
  1525. package/dist/runtime/local-auth.test.js.map +0 -1
  1526. package/dist/runtime/query-adapter.test.d.ts +0 -5
  1527. package/dist/runtime/query-adapter.test.d.ts.map +0 -1
  1528. package/dist/runtime/query-adapter.test.js +0 -1209
  1529. package/dist/runtime/query-adapter.test.js.map +0 -1
  1530. package/dist/runtime/row-transformer.test.d.ts +0 -5
  1531. package/dist/runtime/row-transformer.test.d.ts.map +0 -1
  1532. package/dist/runtime/row-transformer.test.js +0 -364
  1533. package/dist/runtime/row-transformer.test.js.map +0 -1
  1534. package/dist/runtime/subscription-manager.test.d.ts +0 -5
  1535. package/dist/runtime/subscription-manager.test.d.ts.map +0 -1
  1536. package/dist/runtime/subscription-manager.test.js +0 -120
  1537. package/dist/runtime/subscription-manager.test.js.map +0 -1
  1538. package/dist/runtime/sync-transport.d.ts +0 -163
  1539. package/dist/runtime/sync-transport.d.ts.map +0 -1
  1540. package/dist/runtime/sync-transport.js +0 -477
  1541. package/dist/runtime/sync-transport.js.map +0 -1
  1542. package/dist/runtime/sync-transport.test.d.ts +0 -2
  1543. package/dist/runtime/sync-transport.test.d.ts.map +0 -1
  1544. package/dist/runtime/sync-transport.test.js +0 -310
  1545. package/dist/runtime/sync-transport.test.js.map +0 -1
  1546. package/dist/runtime/tab-leader-election.d.ts +0 -97
  1547. package/dist/runtime/tab-leader-election.d.ts.map +0 -1
  1548. package/dist/runtime/tab-leader-election.js +0 -339
  1549. package/dist/runtime/tab-leader-election.js.map +0 -1
  1550. package/dist/runtime/tab-leader-election.test.d.ts +0 -2
  1551. package/dist/runtime/tab-leader-election.test.d.ts.map +0 -1
  1552. package/dist/runtime/tab-leader-election.test.js +0 -278
  1553. package/dist/runtime/tab-leader-election.test.js.map +0 -1
  1554. package/dist/runtime/testing/wasm-runtime-test-utils.d.ts +0 -13
  1555. package/dist/runtime/testing/wasm-runtime-test-utils.d.ts.map +0 -1
  1556. package/dist/runtime/testing/wasm-runtime-test-utils.js +0 -75
  1557. package/dist/runtime/testing/wasm-runtime-test-utils.js.map +0 -1
  1558. package/dist/runtime/utils.d.ts +0 -2
  1559. package/dist/runtime/utils.d.ts.map +0 -1
  1560. package/dist/runtime/utils.js +0 -16
  1561. package/dist/runtime/utils.js.map +0 -1
  1562. package/dist/runtime/value-converter.test.d.ts +0 -5
  1563. package/dist/runtime/value-converter.test.d.ts.map +0 -1
  1564. package/dist/runtime/value-converter.test.js +0 -212
  1565. package/dist/runtime/value-converter.test.js.map +0 -1
  1566. package/dist/runtime/worker-bridge.d.ts +0 -86
  1567. package/dist/runtime/worker-bridge.d.ts.map +0 -1
  1568. package/dist/runtime/worker-bridge.js +0 -250
  1569. package/dist/runtime/worker-bridge.js.map +0 -1
  1570. package/dist/runtime/worker-bridge.race-harness.test.d.ts +0 -2
  1571. package/dist/runtime/worker-bridge.race-harness.test.d.ts.map +0 -1
  1572. package/dist/runtime/worker-bridge.race-harness.test.js +0 -265
  1573. package/dist/runtime/worker-bridge.race-harness.test.js.map +0 -1
  1574. package/dist/runtime/worker-bridge.test.d.ts +0 -2
  1575. package/dist/runtime/worker-bridge.test.d.ts.map +0 -1
  1576. package/dist/runtime/worker-bridge.test.js +0 -233
  1577. package/dist/runtime/worker-bridge.test.js.map +0 -1
  1578. package/dist/sql-gen.d.ts +0 -4
  1579. package/dist/sql-gen.d.ts.map +0 -1
  1580. package/dist/sql-gen.js +0 -163
  1581. package/dist/sql-gen.js.map +0 -1
  1582. package/dist/sql-gen.test.d.ts +0 -2
  1583. package/dist/sql-gen.test.d.ts.map +0 -1
  1584. package/dist/sql-gen.test.js +0 -412
  1585. package/dist/sql-gen.test.js.map +0 -1
  1586. package/dist/subscriptions-orchestrator.integration.test.d.ts +0 -2
  1587. package/dist/subscriptions-orchestrator.integration.test.d.ts.map +0 -1
  1588. package/dist/subscriptions-orchestrator.integration.test.js +0 -194
  1589. package/dist/subscriptions-orchestrator.integration.test.js.map +0 -1
  1590. package/dist/subscriptions-orchestrator.test.d.ts +0 -2
  1591. package/dist/subscriptions-orchestrator.test.d.ts.map +0 -1
  1592. package/dist/subscriptions-orchestrator.test.js +0 -367
  1593. package/dist/subscriptions-orchestrator.test.js.map +0 -1
  1594. package/dist/svelte/SyntheticUserSwitcher.svelte +0 -121
  1595. package/dist/svelte/SyntheticUserSwitcher.svelte.d.ts +0 -11
  1596. package/dist/svelte/SyntheticUserSwitcher.svelte.d.ts.map +0 -1
  1597. package/dist/svelte/context.test.d.ts +0 -2
  1598. package/dist/svelte/context.test.d.ts.map +0 -1
  1599. package/dist/svelte/context.test.js +0 -51
  1600. package/dist/svelte/create-jazz-client.test.d.ts +0 -2
  1601. package/dist/svelte/create-jazz-client.test.d.ts.map +0 -1
  1602. package/dist/svelte/create-jazz-client.test.js +0 -50
  1603. package/dist/svelte/use-all.svelte.d.ts +0 -32
  1604. package/dist/svelte/use-all.svelte.d.ts.map +0 -1
  1605. package/dist/svelte/use-all.svelte.js +0 -61
  1606. package/dist/svelte/use-all.test.d.ts +0 -2
  1607. package/dist/svelte/use-all.test.d.ts.map +0 -1
  1608. package/dist/svelte/use-all.test.js +0 -154
  1609. package/dist/svelte/use-link-external-identity.d.ts +0 -25
  1610. package/dist/svelte/use-link-external-identity.d.ts.map +0 -1
  1611. package/dist/svelte/use-link-external-identity.js +0 -33
  1612. package/dist/svelte/use-link-external-identity.test.d.ts +0 -2
  1613. package/dist/svelte/use-link-external-identity.test.d.ts.map +0 -1
  1614. package/dist/svelte/use-link-external-identity.test.js +0 -97
  1615. package/dist/synthetic-user-switcher.d.ts +0 -16
  1616. package/dist/synthetic-user-switcher.d.ts.map +0 -1
  1617. package/dist/synthetic-user-switcher.js +0 -134
  1618. package/dist/synthetic-user-switcher.js.map +0 -1
  1619. package/dist/synthetic-users.d.ts +0 -32
  1620. package/dist/synthetic-users.d.ts.map +0 -1
  1621. package/dist/synthetic-users.js +0 -124
  1622. package/dist/synthetic-users.js.map +0 -1
  1623. package/dist/testing/fixtures/basic/app.d.ts +0 -55
  1624. package/dist/testing/fixtures/basic/app.d.ts.map +0 -1
  1625. package/dist/testing/fixtures/basic/app.js +0 -176
  1626. package/dist/testing/fixtures/basic/app.js.map +0 -1
  1627. package/dist/testing/fixtures/basic/current.d.ts +0 -2
  1628. package/dist/testing/fixtures/basic/current.d.ts.map +0 -1
  1629. package/dist/testing/fixtures/basic/current.js +0 -6
  1630. package/dist/testing/fixtures/basic/current.js.map +0 -1
  1631. package/dist/testing/index.test.d.ts +0 -2
  1632. package/dist/testing/index.test.d.ts.map +0 -1
  1633. package/dist/testing/index.test.js +0 -234
  1634. package/dist/testing/index.test.js.map +0 -1
  1635. package/dist/testing/local-jazz-server.d.ts +0 -34
  1636. package/dist/testing/local-jazz-server.d.ts.map +0 -1
  1637. package/dist/testing/local-jazz-server.js +0 -313
  1638. package/dist/testing/local-jazz-server.js.map +0 -1
  1639. package/dist/worker/jazz-worker.d.ts +0 -9
  1640. package/dist/worker/jazz-worker.d.ts.map +0 -1
  1641. package/dist/worker/jazz-worker.js +0 -516
  1642. package/dist/worker/jazz-worker.js.map +0 -1
  1643. package/dist/worker/jazz-worker.ts +0 -581
  1644. package/dist/worker/worker-protocol.d.ts +0 -136
  1645. package/dist/worker/worker-protocol.d.ts.map +0 -1
  1646. package/dist/worker/worker-protocol.js +0 -7
  1647. package/dist/worker/worker-protocol.js.map +0 -1
@@ -0,0 +1,3026 @@
1
+ import { createHmac, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
2
+ import { verifyChallenge } from "../local-first-auth/server.js";
3
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
4
+ import { join, resolve } from "node:path";
5
+ import { JazzCore } from "jazz-napi";
6
+ import { registerInProcessTransport } from "../runtime/in-process-transport.js";
7
+ import { accountAppId, localFirstAccountId } from "../accounts/local-first.js";
8
+ import { AUTHENTICATE_EXPIRES_AT_MISSING } from "../accounts/registry-client.js";
9
+ import { LOCAL_FIRST_JWT_ISSUER, parseJwtPayload } from "../runtime/client-session.js";
10
+ import { verifyLocalFirstToken } from "../runtime/local-first-token.js";
11
+ import { endpointScope } from "../runtime/client-scope.js";
12
+ import { PostcardWriter } from "../runtime/native-runtime/native-codec.js";
13
+ import { encodeWebSocketFrameBatch, REAUTHENTICATE_WIRE_MESSAGE_PREFIX, } from "../runtime/native-runtime/websocket.js";
14
+ import { STREAM_RECORD_MESSAGE, STREAM_RECORD_SESSION, StreamRecordReader, encodeStreamClose, encodeStreamRecord, } from "../runtime/native-runtime/http-stream-socket.js";
15
+ import { resolveSchemaSource } from "../schema-source.js";
16
+ import { deployApp } from "../dev/catalogue.js";
17
+ import { DeploymentError } from "../dev/catalogue-api.js";
18
+ import { backendDbAttributedTo, backendDbForSession, openJazzSession, } from "./create-jazz-session.js";
19
+ import { BackendClientsUnavailable, backendClientVerifier, } from "./backend-clients.js";
20
+ import { BACKEND_USER_ISSUER } from "./backend-issuer.js";
21
+ import { earlyDb } from "./early-db.js";
22
+ import { defaultCoreName, onVercelDeployment, onVercelHost, openVercelCore, refuseVercelAppId, } from "./vercel-store.js";
23
+ import { files } from "./blobs.js";
24
+ import { createInspector, inspectorSettings, newTokenSecret, } from "./inspect.js";
25
+ import { createInspectorUi } from "./inspect-ui.js";
26
+ export { files, s3, vercelBlob, } from "./blobs.js";
27
+ import { AuthenticateExpiresAtError, reauthenticateAt, sessionDeadline, startTimer, withCheckedExpiry, } from "./session-expiry.js";
28
+ import { NoJazzAccountError } from "./no-account-error.js";
29
+ import { RequestAuthenticationError } from "./request-auth.js";
30
+ import { optionalPeerImportError } from "./optional-peer.js";
31
+ import { closingBeforeDeadline } from "./socket-deadline.js";
32
+ import { vercelUpgradesSockets } from "./vercel-sockets.js";
33
+ /**
34
+ * A SQLite core in this process, kept in the directory `path`. It generates
35
+ * its app id on first start and keeps it beside its data, in `<path>/app-id`
36
+ * (`jazz-alpha59-alpha60-import` writes an alpha.59 app's id there). Large
37
+ * values' bytes go to `blobs`, by default `files()` in `<path>/blobs`.
38
+ *
39
+ * Only one process can open `path` at a time (it holds `<path>/jazz.lock`
40
+ * while the core is open); a second one fails with "already open". It
41
+ * refuses to start on serverless hosts with no lasting disk (Vercel, AWS
42
+ * Lambda, Netlify): use `vercel()` or `remote()` there.
43
+ */
44
+ export function sqlite(options) {
45
+ refuseStoreAppId("sqlite", options);
46
+ const blobs = options.blobs ?? files();
47
+ if (blobs !== "sqlite" &&
48
+ (typeof blobs !== "object" || (blobs.kind !== "files" && blobs.kind !== "s3"))) {
49
+ throw new Error('sqlite(): blobs must be files(), s3() or "sqlite"');
50
+ }
51
+ return { kind: "sqlite", path: options.path, blobs };
52
+ }
53
+ /**
54
+ * An in-memory core in this process: for tests and throwaway previews. Each
55
+ * one is its own store, with a new app id.
56
+ */
57
+ export function memory(options) {
58
+ refuseStoreAppId("memory", options);
59
+ return { kind: "memory" };
60
+ }
61
+ /** Stores keep their own app id; one passed from JavaScript is refused, not ignored. */
62
+ function refuseStoreAppId(store, options) {
63
+ if (typeof options === "object" && options !== null && "appId" in options) {
64
+ throw new Error(`${store}(): appId is not an option: the store keeps its own app id. To keep an alpha.59 app's id, import its data with \`jazz-alpha59-alpha60-import import --app-id\`.`);
65
+ }
66
+ }
67
+ /**
68
+ * A core running elsewhere (Jazz Cloud, or a sync server you run), serving
69
+ * the app `appId`, reached from this backend with the app's one secret (its
70
+ * admin secret), or with a `backendCredential` of your own. Browsers still
71
+ * talk only to your backend: it decides who each user is, and the core
72
+ * trusts it to say so. The secret never leaves your server.
73
+ */
74
+ export function remote(options) {
75
+ const appId = options.appId;
76
+ if (typeof appId !== "string" || !appId.trim()) {
77
+ throw new Error("remote(): appId must name the app the core serves (it is empty)");
78
+ }
79
+ let backendCredential;
80
+ let secret;
81
+ if ("backendCredential" in options) {
82
+ backendCredential = options.backendCredential;
83
+ }
84
+ else {
85
+ secret = options.secret;
86
+ if (secret === undefined && "adminSecret" in options) {
87
+ throw new Error("remote(): `adminSecret` and `backendSecret` were replaced by one `secret`, the app's admin secret");
88
+ }
89
+ if (typeof secret !== "string" || !secret.trim()) {
90
+ throw new Error("remote(): secret must be the app's admin secret (it is empty)");
91
+ }
92
+ const given = secret;
93
+ backendCredential = () => given;
94
+ }
95
+ return {
96
+ kind: "remote",
97
+ url: options.url.replace(/\/+$/, ""),
98
+ appId,
99
+ backendCredential,
100
+ ...(secret === undefined ? {} : { secret }),
101
+ };
102
+ }
103
+ /**
104
+ * The store for apps deployed on Vercel. Use it in dev too: outside a
105
+ * production or preview deployment (`next dev`, `vercel dev`, tests) it runs
106
+ * `local`, by default `sqlite({ path: ".jazz/local" })`.
107
+ *
108
+ * Deployed, it runs a core in a persistent Vercel Sandbox in your own Vercel
109
+ * project, with its data on a Drive: one for production and one per Git
110
+ * branch for previews.
111
+ * It is created on first use, wakes when a request needs it (about a second)
112
+ * and stops after `idleMs` without requests or sockets. The function's Vercel
113
+ * OIDC token is its only credential, so there are no secrets and no env vars:
114
+ * the core admits only tokens naming the workload its first start pinned
115
+ * (team, project and environment by name), and a deployment of another
116
+ * environment refuses to start or retarget it. All previews share one
117
+ * workload, so preview branches' cores are kept apart, not secured from each
118
+ * other. Anyone with Sandbox access to the project controls its cores. The
119
+ * token comes with each request (it can't be read at module scope), so the
120
+ * core opens on the first request, not when `createJazz` is called; work
121
+ * between requests uses the freshest one seen, and open sockets outlive its
122
+ * expiry. A team or project rename (or
123
+ * a change of OIDC issuer mode) changes the workload: delete `/data/trust` in
124
+ * the Sandbox to re-pin the core. Install `@vercel/sandbox` and
125
+ * `@vercel/functions` next to `jazz-tools`. A deployment of a newer jazz-tools
126
+ * restarts the core on its version, and an older deployment never moves it
127
+ * back. Branch cores are not deleted when a branch merges yet: each keeps its
128
+ * Sandbox and a Drive of up to `maxDriveBytes` until you remove them.
129
+ */
130
+ export function vercel(options = {}) {
131
+ // Refused here, not on the first deployed request: in dev the local
132
+ // store runs and would never read it.
133
+ refuseVercelAppId(options);
134
+ const { local, ...rest } = options;
135
+ return { kind: "vercel", options: rest, local: local ?? sqlite({ path: ".jazz/local" }) };
136
+ }
137
+ function blobOptions(blobs) {
138
+ if (blobs === "sqlite")
139
+ return { blobs: "sqlite" };
140
+ if (blobs.kind === "s3") {
141
+ return {
142
+ blobs: "s3",
143
+ ...(blobs.bucket === undefined ? {} : { s3Bucket: blobs.bucket }),
144
+ ...(blobs.region === undefined ? {} : { s3Region: blobs.region }),
145
+ ...(blobs.endpoint === undefined ? {} : { s3Endpoint: blobs.endpoint }),
146
+ ...(blobs.prefix === undefined ? {} : { s3Prefix: blobs.prefix }),
147
+ };
148
+ }
149
+ return { blobs: "files", ...(blobs.dir === undefined ? {} : { blobsDir: blobs.dir }) };
150
+ }
151
+ /**
152
+ * The marker's brand, registered globally like `createJazz`'s store registry:
153
+ * a bundler may load this module more than once (Next dev evaluates it per
154
+ * route), and a shared Jazz must still recognise a marker made by another copy.
155
+ */
156
+ const LOCAL_FIRST_GUEST_BRAND = Symbol.for("jazz-tools.acceptDeviceAccounts.guest");
157
+ const LOCAL_FIRST_GUEST = Object.freeze({
158
+ [LOCAL_FIRST_GUEST_BRAND]: true,
159
+ kind: "jazz:local-first-guest",
160
+ });
161
+ /** Whether `answer` is {@link acceptDeviceAccounts}'s marker, from any copy of this module. */
162
+ function isLocalFirstGuest(answer) {
163
+ return (typeof answer === "object" &&
164
+ answer !== null &&
165
+ answer[LOCAL_FIRST_GUEST_BRAND] === true);
166
+ }
167
+ /**
168
+ * `authenticate`'s answer, checked: a user must have a string `userId`. Any
169
+ * other answer is a bug in the app's `authenticate`, said so here rather than
170
+ * as a failure from the core about a missing identity.
171
+ */
172
+ function checkedUser(answer) {
173
+ const userId = answer?.userId;
174
+ if (typeof answer === "object" && answer !== null && typeof userId === "string" && userId !== "")
175
+ return answer;
176
+ throw new TypeError(`createJazz: authenticate must return { userId: string, expiresAt: number }, acceptDeviceAccounts(request) or null; it returned ${describeAnswer(answer)}`);
177
+ }
178
+ function describeAnswer(answer) {
179
+ if (typeof answer !== "object" || answer === null)
180
+ return String(answer);
181
+ const keys = Reflect.ownKeys(answer).map(String);
182
+ const userId = answer.userId;
183
+ const detail = "userId" in answer ? `, userId: ${JSON.stringify(userId) ?? String(userId)}` : "";
184
+ return `an object with keys [${keys.join(", ")}]${detail}`;
185
+ }
186
+ /** `request` without the credentials a browser sends with it (its cookies, an `Authorization` header). */
187
+ function withoutCredentials(request) {
188
+ const headers = new Headers(request.headers);
189
+ headers.delete("cookie");
190
+ headers.delete("authorization");
191
+ return new Request(request.url, { method: request.method, headers });
192
+ }
193
+ /**
194
+ * Let this request through as a device account, when it comes from one: an
195
+ * account whose key lives on the user's device, with no user in your auth.
196
+ * It's how your app lets people in as guests, and a local-first friendly way
197
+ * to sign in at all. Device accounts are refused unless `authenticate`
198
+ * returns this, since only your permissions stand between them and your
199
+ * data.
200
+ *
201
+ * ```ts
202
+ * authenticate: async (request) => {
203
+ * const session = await auth.api.getSession({ headers: request.headers });
204
+ * if (!session) return acceptDeviceAccounts(request);
205
+ * return {
206
+ * userId: session.user.id,
207
+ * expiresAt: Math.floor(session.session.expiresAt.getTime() / 1000),
208
+ * };
209
+ * },
210
+ * ```
211
+ *
212
+ * An app with no sign-in of its own, where every browser has a device
213
+ * account, passes it as is: `authenticate: acceptDeviceAccounts`.
214
+ *
215
+ * For a request that is not a device account's, it means the same as `null`:
216
+ * no one is signed in.
217
+ *
218
+ * A device account's request may also carry a user's cookie: someone signed
219
+ * in (or up) on that browser, and the device account still uploads its
220
+ * writes before it links to them. Jazz then asks `authenticate` about the
221
+ * request without its cookies and `Authorization` header, so the device
222
+ * account is let in as it would be on its own.
223
+ */
224
+ export function acceptDeviceAccounts(_request) {
225
+ return LOCAL_FIRST_GUEST;
226
+ }
227
+ const DEFAULT_BASE_PATH = "/jazz";
228
+ // Routes a browser may reach. Everything else (admin, backend admission,
229
+ // shutdown) stays behind this backend.
230
+ /** How long a sync session may take to send its sign-in (its first message). */
231
+ const PRELUDE_DEADLINE_MS = 30_000;
232
+ /** On createJazz's 426 for a socket path: this endpoint serves the HTTP stream. */
233
+ const STREAM_AVAILABLE_HEADER = "x-jazz-stream";
234
+ /** The answer for a socket path where this host can't upgrade sockets. */
235
+ const useHttpStream = () => new Response("WebSocket upgrade not available here; use the HTTP stream", {
236
+ status: 426,
237
+ headers: { [STREAM_AVAILABLE_HEADER]: "1" },
238
+ });
239
+ /** The stream session's key, on each send and close (see `openStream`). */
240
+ const STREAM_KEY_HEADER = "x-jazz-stream-key";
241
+ const PUBLIC_APP_ROUTES = /^\/apps\/[^/]+\/(schemas|schema\/[^/]+)$/;
242
+ // What a browser can't hand the core: secrets, a backend credential or the
243
+ // access it states, or the core's own mark for sockets a credential vouched for.
244
+ // Nor a bearer token: this backend decides who a request is (`authenticate`,
245
+ // backend clients), never the core.
246
+ const STRIPPED_HEADERS = [
247
+ "authorization",
248
+ "x-jazz-backend-secret",
249
+ "x-jazz-admin-secret",
250
+ "x-jazz-session",
251
+ "x-jazz-backend-credential",
252
+ "x-jazz-backend-access",
253
+ "x-jazz-internal-workload-vouched",
254
+ ];
255
+ const CREDENTIAL_HEADER = "x-jazz-backend-credential";
256
+ const ACCESS_HEADER = "x-jazz-backend-access";
257
+ // What the secret slots carry to a remote core: the access stated next to
258
+ // the backend credential decides what a request gets, not these.
259
+ const STAND_IN_SECRET = "stated-by-backend-credential";
260
+ /** The core's refusal of every local-first identity: it admits none. */
261
+ const LOCAL_FIRST_AUTH_DISABLED = "local_first_auth_disabled";
262
+ /**
263
+ * What a core that admits no local-first identity tells a guest's session
264
+ * (`LOCAL_FIRST_AUTH_DISABLED_MESSAGE` in jazz-server's middleware/auth.rs;
265
+ * vercel-guest.integration.test.ts pins it against a real core).
266
+ */
267
+ const CORE_REFUSES_GUESTS = "Local-first auth is not enabled";
268
+ // What a browser's request to a public route carries on to a remote core:
269
+ // never its cookies or its app session.
270
+ const REMOTE_FORWARDED_HEADERS = ["accept", "content-type", "if-none-match"];
271
+ const MAX_STREAM_MESSAGE_BYTES = 2 * 1024 * 1024;
272
+ /**
273
+ * Bytes a session's client may have sent that the core has not taken yet.
274
+ * A transport that waits for the core stays well under it; past it, the
275
+ * client ignored flow control and its session ends.
276
+ */
277
+ const MAX_WAITING_SESSION_BYTES = 32 * 1024 * 1024;
278
+ /** What `inspector` is when createJazz isn't given one: one object, so the Inspector reads it once. */
279
+ const NO_INSPECTOR_OPTIONS = Object.freeze({});
280
+ /** The peer address of requests that came through a Node handler, where Jazz can know it. */
281
+ const remoteAddresses = new WeakMap();
282
+ function headerPairs(headers) {
283
+ const pairs = [];
284
+ headers.forEach((value, name) => {
285
+ if (!STRIPPED_HEADERS.includes(name.toLowerCase()))
286
+ pairs.push([name, value]);
287
+ });
288
+ return pairs;
289
+ }
290
+ function coreResponse(response) {
291
+ const headers = new Headers();
292
+ for (const [name, value] of response.headers)
293
+ headers.append(name, value);
294
+ const nullBody = response.status === 204 || response.status === 304;
295
+ return new Response(nullBody ? null : response.body, {
296
+ status: response.status,
297
+ headers,
298
+ });
299
+ }
300
+ function toBytes(data) {
301
+ if (data instanceof Uint8Array)
302
+ return data;
303
+ if (data instanceof ArrayBuffer)
304
+ return new Uint8Array(data);
305
+ if (Array.isArray(data))
306
+ return Buffer.concat(data);
307
+ if (typeof data === "string")
308
+ return new TextEncoder().encode(data);
309
+ throw new Error("unsupported socket message");
310
+ }
311
+ function arrayBufferOf(bytes) {
312
+ return bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
313
+ }
314
+ /** A WebSocket-shaped session on the core, for clients in this process. */
315
+ function inProcessWebSocket(open) {
316
+ return class InProcessSocket {
317
+ binaryType = "arraybuffer";
318
+ readyState = 0;
319
+ listeners = new Map();
320
+ session;
321
+ constructor(url) {
322
+ queueMicrotask(() => {
323
+ if (this.readyState !== 0)
324
+ return;
325
+ try {
326
+ this.session = open(url, (error, event) => this.onCoreEvent(error, event));
327
+ }
328
+ catch (error) {
329
+ this.emit("error", error);
330
+ this.finish(1011, error instanceof Error ? error.message : String(error));
331
+ return;
332
+ }
333
+ this.readyState = 1;
334
+ this.emit("open");
335
+ });
336
+ }
337
+ addEventListener(type, listener) {
338
+ const list = this.listeners.get(type) ?? [];
339
+ list.push(listener);
340
+ this.listeners.set(type, list);
341
+ }
342
+ send(data) {
343
+ if (this.readyState !== 1 || !this.session)
344
+ throw new Error("socket is not open");
345
+ // Like a socket's own buffer: messages wait here, in order, until the
346
+ // core has room, so this client's pace is the core's.
347
+ this.outbox.push(toBytes(data));
348
+ void this.drain();
349
+ }
350
+ outbox = [];
351
+ draining = false;
352
+ async drain() {
353
+ if (this.draining)
354
+ return;
355
+ this.draining = true;
356
+ try {
357
+ while (this.outbox.length > 0 && this.readyState === 1 && this.session) {
358
+ const data = this.outbox.shift();
359
+ const sent = this.session.sendWithRoom
360
+ ? await this.session.sendWithRoom(data)
361
+ : this.session.send(data);
362
+ if (!sent)
363
+ break;
364
+ }
365
+ }
366
+ catch (error) {
367
+ this.emit("error", error);
368
+ this.close();
369
+ }
370
+ finally {
371
+ this.draining = false;
372
+ }
373
+ }
374
+ close() {
375
+ if (this.readyState >= 2)
376
+ return;
377
+ this.session?.close();
378
+ this.finish(1000, "client closed");
379
+ }
380
+ onCoreEvent(error, event) {
381
+ if (error) {
382
+ this.emit("error", error);
383
+ this.finish(1011, error.message);
384
+ }
385
+ else if (event.kind === "message" && event.data) {
386
+ this.emit("message", { data: arrayBufferOf(event.data) });
387
+ }
388
+ else if (event.kind === "close") {
389
+ this.finish(event.code ?? 1000, event.reason ?? "");
390
+ }
391
+ }
392
+ emit(type, event) {
393
+ for (const listener of this.listeners.get(type) ?? [])
394
+ listener(event);
395
+ }
396
+ finish(code, reason) {
397
+ if (this.readyState >= 2)
398
+ return;
399
+ this.readyState = 3;
400
+ this.emit("close", { code, reason });
401
+ }
402
+ };
403
+ }
404
+ /** The app's schema versions, migrations and permissions, as its code declares them. */
405
+ async function applyBundle(origin, options) {
406
+ // Published, never activated: this backend's sessions are pinned to its
407
+ // bundle, so deployments of the app serve side by side and a rollback is
408
+ // publishing the older bundle again.
409
+ const deployed = await deployApp({
410
+ appId: options.appId,
411
+ serverUrl: origin,
412
+ adminSecret: options.adminSecret,
413
+ app: options.app,
414
+ permissions: options.permissions,
415
+ allowDroppingHistory: options.allowDroppingHistory,
416
+ }).catch((error) => {
417
+ // A core without `/bundles` predates per-deployment permissions; it
418
+ // must not be handed a deployment it would activate for every backend.
419
+ if (error instanceof DeploymentError && (error.status === 404 || error.status === 405)) {
420
+ throw new Error("createJazz: the sync server predates per-deployment permissions bundles; upgrade it before this backend", { cause: error });
421
+ }
422
+ throw error;
423
+ });
424
+ // An older core answers a publish without the bundle it made.
425
+ if (!deployed.bundle) {
426
+ throw new Error("createJazz: the core did not publish a permissions bundle; upgrade it");
427
+ }
428
+ return deployed.bundle;
429
+ }
430
+ /**
431
+ * `socket`, its first frame (the prelude) pinned to the published bundle
432
+ * this backend serves with. The core honours the pin only on this backend's
433
+ * word, so whatever bundle a browser stated is replaced.
434
+ */
435
+ export function pinnedSocket(socket, bundle) {
436
+ let first = true;
437
+ /** `data`, with the pin stamped into the prelude; null if it can't be. */
438
+ const pin = (data) => {
439
+ if (!first)
440
+ return data;
441
+ first = false;
442
+ const pinned = withBundle(data, bundle());
443
+ // A prelude the pin cannot be stamped into would open unpinned.
444
+ if (pinned === null)
445
+ socket.close();
446
+ return pinned;
447
+ };
448
+ return {
449
+ send(data) {
450
+ const pinned = pin(data);
451
+ return pinned !== null && socket.send(pinned);
452
+ },
453
+ async sendWithRoom(data) {
454
+ const pinned = pin(data);
455
+ if (pinned === null)
456
+ return false;
457
+ return socket.sendWithRoom ? socket.sendWithRoom(pinned) : socket.send(pinned);
458
+ },
459
+ close: () => socket.close(),
460
+ };
461
+ }
462
+ /**
463
+ * `prelude` pinned to `bundle`, or with no pin while none is published yet
464
+ * (the backend's own sockets while it boots): a bundle a browser stated
465
+ * never reaches the core. `null` when the prelude is not a JSON object.
466
+ */
467
+ function withBundle(prelude, bundle) {
468
+ let parsed;
469
+ try {
470
+ parsed = JSON.parse(new TextDecoder().decode(prelude));
471
+ }
472
+ catch {
473
+ return null;
474
+ }
475
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
476
+ return null;
477
+ const { bundle: _stated, ...rest } = parsed;
478
+ return new TextEncoder().encode(JSON.stringify(bundle === undefined ? rest : { ...rest, bundle }));
479
+ }
480
+ /** `bundle` is the published bundle every socket the core opens is pinned to. */
481
+ async function openInProcessCore(store, bundle) {
482
+ const backendSecret = randomBytes(32).toString("base64url");
483
+ const adminSecret = randomBytes(32).toString("base64url");
484
+ // The core holds `<path>/jazz.lock` with an OS lock while it's open.
485
+ if (store.kind === "sqlite")
486
+ refuseServerlessDisk(store.path);
487
+ const appId = store.kind === "sqlite" ? await keptAppId(store.path) : randomUUID();
488
+ const core = await JazzCore.open({
489
+ appId,
490
+ backendSecret,
491
+ adminSecret,
492
+ ...(store.kind === "sqlite"
493
+ ? { dataDir: store.path, ...blobOptions(store.blobs) }
494
+ : { inMemory: true }),
495
+ });
496
+ const handle = async (method, path, headers, body) => core.handle(method, path, headers, Buffer.from(body));
497
+ const serverUrl = `http://jazz-${randomUUID()}.invalid`;
498
+ const unregister = registerInProcessTransport(serverUrl, {
499
+ fetch: async (input, init) => {
500
+ const request = new Request(input, init);
501
+ const url = new URL(request.url);
502
+ return coreResponse(await handle(request.method, url.pathname + url.search, [...request.headers].map(([name, value]) => [name, value]), new Uint8Array(await request.arrayBuffer())));
503
+ },
504
+ // This process's own clients: no handshake deadline, as a burst of
505
+ // synchronous writes right after one opens holds its Hello back.
506
+ WebSocket: inProcessWebSocket((_url, onEvent) => pinnedSocket(core.openInProcessSocket(onEvent), bundle)),
507
+ });
508
+ const opened = {
509
+ appId,
510
+ serverUrl,
511
+ adminSecret,
512
+ backendSecret,
513
+ handle,
514
+ openSocket: (headers, onEvent) => pinnedSocket(core.openSocket(headers, onEvent), bundle),
515
+ async close() {
516
+ unregister();
517
+ await core.close();
518
+ },
519
+ };
520
+ return opened;
521
+ }
522
+ /**
523
+ * The app id an in-process SQLite core keeps beside its data, in
524
+ * `<path>/app-id`: a new one on first start, so the app's identities stay
525
+ * the same across restarts without the app naming an id.
526
+ */
527
+ async function keptAppId(dir) {
528
+ const file = join(dir, "app-id");
529
+ const kept = async () => {
530
+ try {
531
+ return (await readFile(file, "utf8")).trim() || undefined;
532
+ }
533
+ catch (error) {
534
+ if (error.code !== "ENOENT")
535
+ throw error;
536
+ return undefined;
537
+ }
538
+ };
539
+ let appId = await kept();
540
+ if (appId === undefined) {
541
+ await mkdir(dir, { recursive: true });
542
+ // `wx`: two processes starting the same store at once agree on one id.
543
+ try {
544
+ appId = randomUUID();
545
+ await writeFile(file, `${appId}\n`, { flag: "wx" });
546
+ }
547
+ catch (error) {
548
+ if (error.code !== "EEXIST")
549
+ throw error;
550
+ appId = (await kept());
551
+ }
552
+ }
553
+ return appId;
554
+ }
555
+ /**
556
+ * The secret an in-process SQLite core's agent tokens are signed with, kept
557
+ * beside its data in `<path>/inspect-token-secret` (mode 0600) so tokens
558
+ * survive restarts. Deleting the file revokes every token.
559
+ */
560
+ async function keptTokenSecret(dir) {
561
+ const file = join(dir, "inspect-token-secret");
562
+ try {
563
+ const kept = (await readFile(file, "utf8")).trim();
564
+ if (kept)
565
+ return kept;
566
+ }
567
+ catch (error) {
568
+ if (error.code !== "ENOENT")
569
+ throw error;
570
+ }
571
+ const secret = newTokenSecret();
572
+ try {
573
+ await writeFile(file, `${secret}\n`, { flag: "wx", mode: 0o600 });
574
+ return secret;
575
+ }
576
+ catch (error) {
577
+ if (error.code !== "EEXIST")
578
+ throw error;
579
+ return (await readFile(file, "utf8")).trim();
580
+ }
581
+ }
582
+ /**
583
+ * Serverless functions have no disk that outlives an instance (or none
584
+ * writable at all), so a sqlite store there loses data silently.
585
+ */
586
+ function refuseServerlessDisk(dir) {
587
+ const host = onVercelHost()
588
+ ? "Vercel"
589
+ : process.env.AWS_LAMBDA_FUNCTION_NAME
590
+ ? "AWS Lambda"
591
+ : process.env.NETLIFY
592
+ ? "Netlify"
593
+ : undefined;
594
+ if (!host)
595
+ return;
596
+ throw new Error(`sqlite({ path: ${JSON.stringify(dir)} }) can't keep data on ${host}: its functions have no lasting disk. ` +
597
+ (host === "Vercel" ? "Use vercel(), whose local store runs sqlite() in dev, or " : "Use ") +
598
+ "remote({ url, appId, secret }) to a sync server or Jazz Cloud.");
599
+ }
600
+ /** The access a request from this process's own clients asks for, by the secret slot it fills. */
601
+ function accessOffered(headers) {
602
+ if (headers.has("x-jazz-admin-secret"))
603
+ return "admin";
604
+ if (headers.has("x-jazz-backend-secret"))
605
+ return "backend";
606
+ return "session";
607
+ }
608
+ /**
609
+ * A core reached over the network. Every request and socket carries the
610
+ * backend credential and the access it states; a core that trusts a workload
611
+ * admits nothing else, and either way the secrets a request offers itself
612
+ * never count next to it. `secrets` fill the secret slots (stand-ins unless
613
+ * the caller holds the real ones).
614
+ */
615
+ function openRemoteCore(appId, target, bundle) {
616
+ const socketUrl = `${target.url.replace(/^http/, "ws")}/apps/${encodeURIComponent(appId)}/ws`;
617
+ if (!globalThis.WebSocket) {
618
+ throw new Error("remote() needs a global WebSocket (Node 22 or newer)");
619
+ }
620
+ // Node's WebSocket (undici) takes upgrade headers as a second argument.
621
+ const NativeWebSocket = globalThis.WebSocket;
622
+ const credentialHeaders = async (access) => {
623
+ const credential = await target.backendCredential();
624
+ if (typeof credential !== "string" || !credential) {
625
+ throw new Error("backendCredential() returned no credential");
626
+ }
627
+ return access === "session"
628
+ ? [[CREDENTIAL_HEADER, credential]]
629
+ : [
630
+ [CREDENTIAL_HEADER, credential],
631
+ [ACCESS_HEADER, access],
632
+ ];
633
+ };
634
+ const withoutStated = (headers) => headers.filter(([name]) => {
635
+ const lower = name.toLowerCase();
636
+ return lower !== CREDENTIAL_HEADER && lower !== ACCESS_HEADER;
637
+ });
638
+ const core = {
639
+ appId,
640
+ serverUrl: `http://jazz-remote-${randomUUID()}.invalid`,
641
+ adminSecret: target.secrets?.adminSecret ?? STAND_IN_SECRET,
642
+ backendSecret: target.secrets?.backendSecret ?? STAND_IN_SECRET,
643
+ async handle(method, path, headers, body, access = "session") {
644
+ const response = await fetch(`${target.url}${path}`, {
645
+ method,
646
+ headers: [...withoutStated(headers), ...(await credentialHeaders(access))].map(([name, value]) => [name, value]),
647
+ ...(method === "GET" || method === "HEAD" ? {} : { body: body }),
648
+ });
649
+ const replyHeaders = [];
650
+ response.headers.forEach((value, name) => {
651
+ // fetch already decoded the body.
652
+ if (name !== "content-encoding" && name !== "content-length") {
653
+ replyHeaders.push([name, value]);
654
+ }
655
+ });
656
+ return {
657
+ status: response.status,
658
+ headers: replyHeaders,
659
+ body: new Uint8Array(await response.arrayBuffer()),
660
+ };
661
+ },
662
+ openSocket: (_headers, onEvent, access = "session") => pinnedSocket(connect(socketUrl, onEvent, access), bundle),
663
+ async close() {
664
+ unregister();
665
+ },
666
+ };
667
+ // Browsers' own headers stay here: the core sees only this backend.
668
+ function connect(url, onEvent, access) {
669
+ let ws;
670
+ const queued = [];
671
+ let ended = false;
672
+ const finish = (code, reason) => {
673
+ if (ended)
674
+ return;
675
+ ended = true;
676
+ onEvent(null, { kind: "close", code, reason });
677
+ };
678
+ credentialHeaders(access)
679
+ .then((headers) => {
680
+ if (ended)
681
+ return;
682
+ ws = new NativeWebSocket(url, { headers: Object.fromEntries(headers) });
683
+ ws.binaryType = "arraybuffer";
684
+ ws.addEventListener("open", () => {
685
+ for (const data of queued.splice(0))
686
+ ws.send(data);
687
+ });
688
+ ws.addEventListener("message", (event) => {
689
+ const data = typeof event.data === "string"
690
+ ? new TextEncoder().encode(event.data)
691
+ : new Uint8Array(event.data);
692
+ onEvent(null, { kind: "message", data });
693
+ });
694
+ ws.addEventListener("close", (event) => finish(event.code, event.reason));
695
+ // A socket that never connects (the core is down or restarting) can
696
+ // report only the error, and stay CONNECTING: without this, the link
697
+ // waits on it forever instead of retrying.
698
+ ws.addEventListener("error", () => {
699
+ finish(1006, "connection to the core failed");
700
+ try {
701
+ ws?.close();
702
+ }
703
+ catch {
704
+ // Already closing.
705
+ }
706
+ });
707
+ })
708
+ // A failing credential hook, or a socket that can't even be created.
709
+ .catch((error) => finish(1011, error instanceof Error ? error.message : "no backend credential"));
710
+ return {
711
+ send(data) {
712
+ if (ended)
713
+ return false;
714
+ if (ws?.readyState === 1)
715
+ ws.send(data);
716
+ else
717
+ queued.push(data);
718
+ return true;
719
+ },
720
+ close() {
721
+ ended = true;
722
+ ws?.close();
723
+ },
724
+ };
725
+ }
726
+ // This process's own clients (the backend's session) reach the core
727
+ // through an in-process origin, so they present the credential too.
728
+ const unregister = registerInProcessTransport(core.serverUrl, {
729
+ fetch: async (input, init) => {
730
+ const request = new Request(input, init);
731
+ const url = new URL(request.url);
732
+ const headers = [];
733
+ request.headers.forEach((value, name) => headers.push([name, value]));
734
+ return coreResponse(await core.handle(request.method, url.pathname + url.search, headers, new Uint8Array(await request.arrayBuffer()), accessOffered(request.headers)));
735
+ },
736
+ WebSocket: inProcessWebSocket((url, onEvent) => {
737
+ const { pathname, search } = new URL(url);
738
+ return pinnedSocket(connect(`${target.url.replace(/^http/, "ws")}${pathname}${search}`, onEvent, "backend"), bundle);
739
+ }),
740
+ });
741
+ return core;
742
+ }
743
+ /**
744
+ * A request `authenticate` names no user for: what an app answers with 401.
745
+ * (A throwing `authenticate` passes its own error through instead.)
746
+ */
747
+ function signedOut(operation) {
748
+ return new RequestAuthenticationError(`${operation}: the request has no signed-in user`, {
749
+ code: "signed_out",
750
+ });
751
+ }
752
+ /** How long `close()` waits for pending writes to reach the core. */
753
+ const CLOSE_SYNC_TIMEOUT_MS = 10_000;
754
+ function jazzSettings(options) {
755
+ if (options.recheckSeconds !== undefined)
756
+ throw new Error("createJazz: recheckSeconds was removed. A sync session now lasts until the expiresAt your authenticate returns, and then authenticates again on its client's new connection; to end a user's sessions at once, call jazz.revokeUser(userId).");
757
+ const basePath = (options.basePath ?? DEFAULT_BASE_PATH).replace(/\/+$/, "");
758
+ const publicUrls = [options.publicUrl ?? []].flat().map((value) => {
759
+ try {
760
+ // The same form a browser client scopes itself by (`clientScope`).
761
+ if (!/^(https?|wss?):\/\//.test(value))
762
+ throw new Error("relative");
763
+ return endpointScope(value);
764
+ }
765
+ catch {
766
+ throw new Error(`createJazz: publicUrl ${JSON.stringify(value)} is not an absolute URL like "https://app.example.com/jazz"`);
767
+ }
768
+ });
769
+ const allowedOrigins = new Set((options.allowedOrigins ?? []).map((origin) => {
770
+ let parsed;
771
+ try {
772
+ parsed = new URL(origin).origin;
773
+ }
774
+ catch {
775
+ // Not a URL: refused below.
776
+ }
777
+ // "localhost:3000" parses with an opaque "null" origin, which would let
778
+ // sandboxed iframes and file:// pages through.
779
+ if (!parsed || parsed === "null") {
780
+ throw new Error(`createJazz: allowedOrigins entry ${JSON.stringify(origin)} is not an origin like "https://app.example.com"`);
781
+ }
782
+ return parsed;
783
+ }));
784
+ if ("appId" in options) {
785
+ throw new Error("createJazz(): appId moved to the store: remote({ url, appId, secret }) names the app it serves, and sqlite(), memory() and vercel() keep their own id.");
786
+ }
787
+ return { basePath, publicUrls, allowedOrigins };
788
+ }
789
+ /** The store this process runs: `vercel()` outside a Vercel deployment runs its `local` store. */
790
+ function runningStore(store) {
791
+ return store.kind === "vercel" && !onVercelDeployment() ? store.local : store;
792
+ }
793
+ /**
794
+ * Open `store` and apply the schema, migrations and permissions `options`
795
+ * declare to its core.
796
+ */
797
+ async function openJazz(initial, store) {
798
+ let options = initial;
799
+ let { basePath, publicUrls, allowedOrigins } = jazzSettings(options);
800
+ // The bundle this backend published: every socket to the core carries it,
801
+ // and the core governs this backend's sessions by its permissions alone.
802
+ let pin;
803
+ const bundle = () => pin;
804
+ const core = store.kind === "remote"
805
+ ? openRemoteCore(store.appId, store, bundle)
806
+ : store.kind === "vercel"
807
+ ? await openVercelCore({
808
+ options: store.options,
809
+ // The function's OIDC token is the core's only credential.
810
+ openRemote: ({ appId, url, backendCredential }) => openRemoteCore(appId, { url, backendCredential }, bundle),
811
+ })
812
+ : await openInProcessCore(store, bundle);
813
+ const appId = core.appId;
814
+ const issuer = BACKEND_USER_ISSUER;
815
+ // An in-memory store's agent tokens last as long as its data: this process.
816
+ const memoryTokenSecret = newTokenSecret();
817
+ /** Publish `next`'s bundle: what it is pinned by. Publishing one already published changes nothing. */
818
+ const publish = (next) => applyBundle(core.serverUrl, { ...next, appId, adminSecret: core.adminSecret });
819
+ /** Publish `next`'s bundle and open the backend's own session on it. */
820
+ async function backendSession(next, published) {
821
+ pin = published ?? (await publish(next));
822
+ const session = await openJazzSession({
823
+ appId,
824
+ app: next.app,
825
+ permissions: next.permissions,
826
+ serverUrl: core.serverUrl,
827
+ driver: { type: "memory" },
828
+ initial: { backendSecret: core.backendSecret },
829
+ });
830
+ const opened = session.getSnapshot();
831
+ if (opened.status !== "ready" || !opened.client) {
832
+ await session.close();
833
+ throw opened.error ?? new Error(`Jazz backend session did not open (${opened.status})`);
834
+ }
835
+ return { session, client: opened.client };
836
+ }
837
+ let session;
838
+ let backend;
839
+ try {
840
+ ({ session, client: backend } = await backendSession(options));
841
+ }
842
+ catch (error) {
843
+ await core.close();
844
+ throw store.kind === "remote" ? unreachableCore(store.url, error) : error;
845
+ }
846
+ let backendClients = backendClientVerifier(options.backendClients ?? []);
847
+ /**
848
+ * A later `createJazz` for this store (a dev server's hot reload): publish
849
+ * its bundle, move the backend's own database to it, and read its options
850
+ * from now on. Open sync sessions stay; the core reconnects those pinned
851
+ * to the old bundle.
852
+ */
853
+ async function reload(next) {
854
+ const settings = jazzSettings(next);
855
+ inspectorSettings(next.inspector ?? NO_INSPECTOR_OPTIONS);
856
+ // The same app and permissions (a reload of a module that imports them
857
+ // unchanged, or a hot reload that rebuilt equal ones): the bundle, and
858
+ // the backend's session with its writes and `forReqUser` dbs, stay.
859
+ if (next.app !== options.app || next.permissions !== options.permissions) {
860
+ const published = await publish(next);
861
+ if (published !== pin) {
862
+ const previousPin = pin;
863
+ let fresh;
864
+ try {
865
+ fresh = await backendSession(next, published);
866
+ }
867
+ catch (error) {
868
+ pin = previousPin;
869
+ throw error;
870
+ }
871
+ retire(session);
872
+ ({ session, client: backend } = fresh);
873
+ }
874
+ }
875
+ options = next;
876
+ ({ basePath, publicUrls, allowedOrigins } = settings);
877
+ backendClients = backendClientVerifier(next.backendClients ?? []);
878
+ upgradesSockets = attached || (next.upgradesSockets ?? false);
879
+ }
880
+ /**
881
+ * Sessions a reload replaced. Each stays open for
882
+ * `RETIRED_SESSION_GRACE_MS`, so the writes it has in flight and the
883
+ * `forReqUser` dbs requests still hold finish, then closes (draining its
884
+ * writes); a close of this Jazz closes those left.
885
+ */
886
+ const retiring = new Set();
887
+ function retire(old) {
888
+ let closed;
889
+ const closeOld = () => {
890
+ clearTimeout(timer);
891
+ return (closed ??= old
892
+ .close()
893
+ .catch((error) => console.error("jazz: a retired session did not close", error))
894
+ .finally(() => retiring.delete(closeOld)));
895
+ };
896
+ const timer = setTimeout(closeOld, RETIRED_SESSION_GRACE_MS);
897
+ timer.unref?.();
898
+ retiring.add(closeOld);
899
+ }
900
+ // An `authenticate` that returns expired answers, or none at all, is a
901
+ // bug in the app: said once per process.
902
+ let warnedExpiredAnswer = false;
903
+ function warnExpiredAnswer() {
904
+ if (warnedExpiredAnswer)
905
+ return;
906
+ warnedExpiredAnswer = true;
907
+ console.error("createJazz: authenticate named a user with an expiresAt in the past, so Jazz treats them as signed out. Return the expiry of the session the user is signed in with (the one a sign-out ends), in Unix seconds, not of a short-lived access token.");
908
+ }
909
+ let warnedMissingExpiry = false;
910
+ function warnMissingExpiry(error) {
911
+ if (warnedMissingExpiry)
912
+ return;
913
+ warnedMissingExpiry = true;
914
+ console.error(error.message);
915
+ }
916
+ /**
917
+ * Who sent `request`: a scoped backend client's user, or the user the
918
+ * app's own `authenticate` names. A trusted backend client has no user.
919
+ */
920
+ async function authenticate(request) {
921
+ const client = await backendClients.resolve(request);
922
+ if (client !== null)
923
+ return client !== "refused" && client.kind === "user"
924
+ ? { ...client.user, expiresAt: client.expiresAt }
925
+ : null;
926
+ const answer = await askAuthenticate(request);
927
+ if (answer === null || isLocalFirstGuest(answer))
928
+ return null;
929
+ const user = withCheckedExpiry(checkedUser(answer));
930
+ // An answer that has already expired names no one, here and in every
931
+ // other place that asks (who is signed in, sign-in, forReqUser), so a
932
+ // client can't be told it is signed in while its sync is refused.
933
+ if (user.expiresAt * 1000 <= Date.now()) {
934
+ warnExpiredAnswer();
935
+ return null;
936
+ }
937
+ return user;
938
+ }
939
+ async function askAuthenticate(request) {
940
+ if (!options.authenticate)
941
+ return null;
942
+ return (await options.authenticate(request)) ?? null;
943
+ }
944
+ /** Whether the app lets `request` in as a device account (`acceptDeviceAccounts`). */
945
+ let warnedGuestsOff = false;
946
+ async function acceptsGuest(request) {
947
+ const answer = await askAuthenticate(request);
948
+ if (isLocalFirstGuest(answer))
949
+ return true;
950
+ // A user is signed in on this browser too: one who just signed up, whose
951
+ // guest still uploads its writes before it links to them. A guest is
952
+ // bound to its own key, never to that user, and whether the app lets
953
+ // guests in doesn't depend on who else is signed in: ask as the request
954
+ // would be without the user's credentials.
955
+ if (answer && isLocalFirstGuest(await askAuthenticate(withoutCredentials(request))))
956
+ return true;
957
+ if (!warnedGuestsOff) {
958
+ warnedGuestsOff = true;
959
+ console.warn("createJazz: refused a local-first guest. To let guests sync, return acceptDeviceAccounts(request) from authenticate for them.");
960
+ }
961
+ return false;
962
+ }
963
+ /** Say once that the core turns every local-first guest away, whatever `authenticate` says. */
964
+ let warnedGuestsOffOnCore = false;
965
+ function warnGuestsOffOnCore() {
966
+ if (warnedGuestsOffOnCore)
967
+ return;
968
+ warnedGuestsOffOnCore = true;
969
+ console.error("createJazz: the core refuses local-first guests (local_first_auth_disabled), so device accounts can't sync or link. Start the core with allowLocalFirstAuth: true. A vercel() core started by an older jazz-tools keeps refusing them until a deployment of a newer one restarts it.");
970
+ }
971
+ /** One admin account request to the core: this backend vouches for the identities. */
972
+ async function adminAccounts(operation, body) {
973
+ const response = await core.handle("POST", `/apps/${encodeURIComponent(accountAppId(appId))}/admin/accounts/${operation}`, [
974
+ ["x-jazz-admin-secret", core.adminSecret],
975
+ ["content-type", "application/json"],
976
+ ], new TextEncoder().encode(JSON.stringify(body)), "admin");
977
+ const text = new TextDecoder().decode(response.body);
978
+ if (response.status !== 200) {
979
+ throw Object.assign(new Error(`Jazz account ${operation} failed (${response.status}): ${text}`), {
980
+ status: response.status,
981
+ code: text.trim(),
982
+ });
983
+ }
984
+ const parsed = JSON.parse(text);
985
+ return { ...parsed, account: String(parsed.account) };
986
+ }
987
+ const identity = (userId) => ({ issuer, subject: userId });
988
+ // A user's account never changes once assigned (linking only adds
989
+ // identities to an account), so the core is asked once per user for a
990
+ // while, not on every sign-in, socket and request. Only assignments are
991
+ // cached: a user without an account may get one at any moment.
992
+ const accounts = new Map();
993
+ const ACCOUNT_CACHE_LIMIT = 10_000;
994
+ function remember(userId, account) {
995
+ if (accounts.size >= ACCOUNT_CACHE_LIMIT) {
996
+ accounts.delete(accounts.keys().next().value);
997
+ }
998
+ accounts.set(userId, {
999
+ account,
1000
+ until: Date.now() + (options.sessionTtlSeconds ?? 3600) * 1000,
1001
+ });
1002
+ return account;
1003
+ }
1004
+ /**
1005
+ * The user's account, or null while they have none. Never creates one:
1006
+ * only a client's sign-in (`backend-sign-in`), a guest's link
1007
+ * (`backend-link`) and `createAccountFor` do, so a local-first guest can
1008
+ * still link to a user the backend has only looked up or acted for (V9).
1009
+ */
1010
+ async function existingAccountOf(userId) {
1011
+ const cached = accounts.get(userId);
1012
+ if (cached && cached.until > Date.now())
1013
+ return cached.account;
1014
+ try {
1015
+ const { account } = await adminAccounts("resolve", { identity: identity(userId) });
1016
+ return remember(userId, account);
1017
+ }
1018
+ catch (error) {
1019
+ // Only the core's own "no account for this identity" answer: any other
1020
+ // 404 (an unknown app, a missing route) is a server error, not a user
1021
+ // without an account.
1022
+ const { status, code } = error;
1023
+ if (status === 404 && code === "identity_not_assigned")
1024
+ return null;
1025
+ throw error;
1026
+ }
1027
+ }
1028
+ /** The user's account, created if they have none (a sign-in, or `createAccountFor`). */
1029
+ async function accountOf(userId) {
1030
+ const cached = accounts.get(userId);
1031
+ if (cached && cached.until > Date.now())
1032
+ return cached.account;
1033
+ const { account } = await adminAccounts("login-or-register", { identity: identity(userId) });
1034
+ return remember(userId, account);
1035
+ }
1036
+ /** The user's session, on the account they already have. */
1037
+ async function sessionFor(user, caller) {
1038
+ const account = await existingAccountOf(user.userId);
1039
+ if (account === null)
1040
+ throw new NoJazzAccountError(user.userId, caller);
1041
+ return {
1042
+ account_id: account,
1043
+ issuer,
1044
+ user_id: user.userId,
1045
+ claims: user.claims ?? {},
1046
+ authMode: "external",
1047
+ };
1048
+ }
1049
+ async function linkIdentity(link) {
1050
+ if (link.from === link.to)
1051
+ throw new Error("linkIdentity: from and to are the same identity");
1052
+ const { account } = await adminAccounts("link", {
1053
+ from: identity(link.from),
1054
+ to: identity(link.to),
1055
+ });
1056
+ return { account };
1057
+ }
1058
+ /**
1059
+ * The account sign-in a browser makes with only the app's own session: the
1060
+ * backend's `authenticate` names the user, and the core resolves (or
1061
+ * creates) their account.
1062
+ */
1063
+ async function backendSignIn(request) {
1064
+ if (request.method !== "POST")
1065
+ return new Response(null, { status: 405 });
1066
+ const user = await authenticate(request);
1067
+ if (!user)
1068
+ return new Response("signed_out", { status: 401 });
1069
+ const account = await accountOf(user.userId);
1070
+ const expiresAt = Math.floor(Date.now() / 1000) + (options.sessionTtlSeconds ?? 3600);
1071
+ return Response.json({ account, identity: identity(user.userId), claims: user.claims ?? {}, expiresAt }, { headers: { "Cache-Control": "no-store" } });
1072
+ }
1073
+ /**
1074
+ * Who `request`'s user is, without changing anything: the user
1075
+ * `authenticate` names, and whether the core already holds an account for
1076
+ * them. A browser's session asks this to follow the backend; only a sign-in
1077
+ * (`backend-sign-in`) or a link (`backend-link`) assigns an account, so a
1078
+ * local-first guest whose user has none yet can still link to them.
1079
+ */
1080
+ async function backendUser(request) {
1081
+ if (request.method !== "POST")
1082
+ return new Response(null, { status: 405 });
1083
+ const user = await authenticate(request);
1084
+ if (!user)
1085
+ return new Response("signed_out", { status: 401 });
1086
+ let account;
1087
+ try {
1088
+ account = await existingAccountOf(user.userId);
1089
+ }
1090
+ catch (error) {
1091
+ // The core refuses this identity (it was revoked): say so, as the
1092
+ // core does, rather than fail as a server error.
1093
+ if (error.status === 403)
1094
+ return new Response("identity_not_authorized", { status: 403 });
1095
+ throw error;
1096
+ }
1097
+ return Response.json({ account, identity: identity(user.userId), claims: user.claims ?? {} }, { headers: { "Cache-Control": "no-store" } });
1098
+ }
1099
+ /**
1100
+ * Link challenges: a guest links only on a proof made for one challenge,
1101
+ * never on its sync token, so a leaked token can't link it to someone
1102
+ * else. A challenge names the user it links to and expires quickly; it is
1103
+ * signed with a key only this app's backend instances share (derived from
1104
+ * the core's admin secret), and its nonce becomes the link's single-use
1105
+ * intent id at the core, so a proof works once.
1106
+ */
1107
+ const challengeKey = createHmac("sha256", core.adminSecret)
1108
+ .update(`jazz-link-challenge-v1\0${accountAppId(appId)}`)
1109
+ .digest();
1110
+ const LINK_CHALLENGE_TTL_SECONDS = 120;
1111
+ const challengeMac = (payload) => createHmac("sha256", challengeKey).update(payload).digest("base64url");
1112
+ function issueLinkChallenge(userId) {
1113
+ const expiresAt = Math.floor(Date.now() / 1000) + LINK_CHALLENGE_TTL_SECONDS;
1114
+ const payload = Buffer.from(JSON.stringify({ v: 1, sub: userId, nonce: randomUUID(), exp: expiresAt })).toString("base64url");
1115
+ return { challenge: `${payload}.${challengeMac(payload)}`, expiresAt };
1116
+ }
1117
+ /** The nonce of a challenge this backend issued for `userId`, still fresh; else null. */
1118
+ function readLinkChallenge(challenge, userId) {
1119
+ if (typeof challenge !== "string" || challenge.length > 1024)
1120
+ return null;
1121
+ const [payload, mac, extra] = challenge.split(".");
1122
+ if (!payload || !mac || extra !== undefined)
1123
+ return null;
1124
+ const expected = Buffer.from(challengeMac(payload));
1125
+ const given = Buffer.from(mac);
1126
+ if (expected.length !== given.length || !timingSafeEqual(expected, given))
1127
+ return null;
1128
+ let claims;
1129
+ try {
1130
+ claims = JSON.parse(Buffer.from(payload, "base64url").toString("utf8"));
1131
+ }
1132
+ catch {
1133
+ return null;
1134
+ }
1135
+ if (claims.v !== 1 ||
1136
+ claims.sub !== userId ||
1137
+ typeof claims.nonce !== "string" ||
1138
+ typeof claims.exp !== "number" ||
1139
+ claims.exp <= Date.now() / 1000) {
1140
+ return null;
1141
+ }
1142
+ return claims.nonce;
1143
+ }
1144
+ /** A challenge for the guest to sign before it links to the signed-in user. */
1145
+ async function backendLinkChallenge(request) {
1146
+ if (request.method !== "POST")
1147
+ return new Response(null, { status: 405 });
1148
+ const user = await authenticate(request);
1149
+ if (!user)
1150
+ return new Response("signed_out", { status: 401 });
1151
+ return Response.json(issueLinkChallenge(user.userId), {
1152
+ headers: { "Cache-Control": "no-store" },
1153
+ });
1154
+ }
1155
+ /**
1156
+ * A local-first guest who just signed up: link the guest's identity to the
1157
+ * user `authenticate` now names, so the account and its data carry over.
1158
+ * The guest proves itself by signing a challenge issued for this user
1159
+ * (see {@link issueLinkChallenge}).
1160
+ */
1161
+ async function backendLink(request) {
1162
+ if (request.method !== "POST")
1163
+ return new Response(null, { status: 405 });
1164
+ const user = await authenticate(request);
1165
+ if (!user)
1166
+ return new Response("signed_out", { status: 401 });
1167
+ let body;
1168
+ try {
1169
+ body = (await request.json());
1170
+ }
1171
+ catch {
1172
+ return new Response("local_first_proof_required", { status: 400 });
1173
+ }
1174
+ const nonce = readLinkChallenge(body?.challenge, user.userId);
1175
+ if (!nonce)
1176
+ return new Response("invalid_link_challenge", { status: 400 });
1177
+ let guest;
1178
+ try {
1179
+ const proven = verifyChallenge(String(body.proof ?? ""), body.challenge);
1180
+ guest = { issuer: proven.issuer, subject: proven.subject };
1181
+ }
1182
+ catch {
1183
+ return new Response("invalid_local_first_proof", { status: 401 });
1184
+ }
1185
+ // The guest's account follows from its key and the namespace it was
1186
+ // founded in: this app's id, or one of this endpoint's URLs for an
1187
+ // app-less client. Any other namespace is another app's guest.
1188
+ const founding = linkAudience(request, body.audience);
1189
+ if (!founding)
1190
+ return new Response("invalid_local_first_proof", { status: 401 });
1191
+ const account = localFirstAccountId(founding.endpoint ?? appId, guest.subject);
1192
+ const userIs = async (expected) => (await adminAccounts("resolve", { identity: identity(user.userId) })).account === expected;
1193
+ let guestRevoked = false;
1194
+ try {
1195
+ try {
1196
+ await adminAccounts("found-local-first", {
1197
+ identity: guest,
1198
+ ...(founding.endpoint !== undefined ? { audience: founding.endpoint } : {}),
1199
+ });
1200
+ }
1201
+ catch (error) {
1202
+ // A guest key an earlier link retired: only that link's own user
1203
+ // gets an answer (the retry of a link whose response was lost).
1204
+ if (error.status !== 403 ||
1205
+ error.code === LOCAL_FIRST_AUTH_DISABLED ||
1206
+ !(await userIs(account)))
1207
+ throw error;
1208
+ guestRevoked = true;
1209
+ }
1210
+ if (!guestRevoked) {
1211
+ try {
1212
+ await adminAccounts("link", { from: guest, to: identity(user.userId), nonce });
1213
+ }
1214
+ catch (error) {
1215
+ // Linking is idempotent for this guest and this user: when the user
1216
+ // already belongs to the guest's account (an earlier link went
1217
+ // through, then perhaps its revoke failed, or another tab's link
1218
+ // won the race and revoked the key since), this link is done. A
1219
+ // used challenge (the core refuses its nonce first) and a user of
1220
+ // another account are still refused.
1221
+ const status = error.status;
1222
+ if ((status !== 409 && status !== 403) || !(await userIs(account)))
1223
+ throw error;
1224
+ // Refused for a retired key: the link that won already retired it.
1225
+ if (status === 403)
1226
+ guestRevoked = true;
1227
+ }
1228
+ }
1229
+ }
1230
+ catch (error) {
1231
+ const status = error.status;
1232
+ // A core that admits no local-first accounts refuses every guest, not
1233
+ // this user's link: say that, not that the user has another account.
1234
+ if (error.code === LOCAL_FIRST_AUTH_DISABLED) {
1235
+ warnGuestsOffOnCore();
1236
+ // A setup problem on the backend's side, not a refusal of this link:
1237
+ // 503, so the client tries again later.
1238
+ return new Response(LOCAL_FIRST_AUTH_DISABLED, { status: 503 });
1239
+ }
1240
+ // Only the core's own refusals refuse the link for good: an invalid
1241
+ // link intent (400), a retired or foreign identity (403), a user with
1242
+ // no account to check (404), an identity of another account (409).
1243
+ // Its reason stays on the backend.
1244
+ if (status === 400 || status === 403 || status === 404 || status === 409)
1245
+ return new Response("link_refused", { status: 409 });
1246
+ // Anything else (the core down or failing, its credential check
1247
+ // refusing this backend mid-rotation, a proxy's 408 or 429) may pass on
1248
+ // a retry, so say so rather than strand the guest.
1249
+ console.error("Jazz: linking a guest failed on the core", error);
1250
+ return new Response("account_registry_unavailable", { status: 503 });
1251
+ }
1252
+ if (options.guestKeyAfterLink === "revoke" && !guestRevoked) {
1253
+ // The link already stands. If the revoke fails, the guest key stays
1254
+ // usable until the browser retries the link, which is idempotent and
1255
+ // revokes then: a server error, logged here, not a silent success.
1256
+ const revoked = await core.handle("POST", `/apps/${encodeURIComponent(accountAppId(appId))}/admin/accounts/revoke`, [
1257
+ ["x-jazz-admin-secret", core.adminSecret],
1258
+ ["content-type", "application/json"],
1259
+ ], new TextEncoder().encode(JSON.stringify({ approver: identity(user.userId), target: guest })), "admin");
1260
+ if (revoked.status !== 204) {
1261
+ console.error(`Jazz: revoking the guest key after a link failed (${revoked.status}): ${new TextDecoder().decode(revoked.body)}`);
1262
+ return new Response("guest_key_revoke_failed", { status: 500 });
1263
+ }
1264
+ }
1265
+ const expiresAt = Math.floor(Date.now() / 1000) + (options.sessionTtlSeconds ?? 3600);
1266
+ return Response.json({ account, identity: identity(user.userId), claims: user.claims ?? {}, expiresAt }, { headers: { "Cache-Control": "no-store" } });
1267
+ }
1268
+ /** The sessions this instance serves, for the Inspector's `sessions`. */
1269
+ const liveSessions = new Set();
1270
+ function openClientSession(request, onEvent, transport) {
1271
+ // The core socket opens once the prelude is admitted, with the access
1272
+ // that admission needs: a vouched user's session is the backend's, and
1273
+ // so is the endpoint it vouches for on a guest's behalf; a guest signed
1274
+ // for the app itself rides on its own token alone.
1275
+ let socket;
1276
+ let ended = false;
1277
+ let userId;
1278
+ let trusted = false;
1279
+ // A session that never sends its prelude ends too.
1280
+ let stopExpiry = startTimer(() => {
1281
+ onEvent(null, { kind: "close", code: 1008, reason: "no sign-in in time" });
1282
+ end();
1283
+ }, PRELUDE_DEADLINE_MS);
1284
+ const end = () => {
1285
+ if (ended)
1286
+ return;
1287
+ ended = true;
1288
+ liveSessions.delete(live);
1289
+ stopExpiry?.();
1290
+ socket?.close();
1291
+ };
1292
+ // Ask the client to connect again, so the app's auth decides on a new
1293
+ // request: a planned reconnect the client doesn't show as an outage.
1294
+ const reauthenticate = () => {
1295
+ if (ended)
1296
+ return;
1297
+ onEvent(null, { kind: "message", data: reauthenticateBatch() });
1298
+ onEvent(null, { kind: "close", code: 1008, reason: "reauthenticate" });
1299
+ end();
1300
+ };
1301
+ const admit = async (prelude) => {
1302
+ const admitted = await admitPrelude(request, prelude);
1303
+ if (!admitted || ended) {
1304
+ // An auth failure, not a dropped link: the client stops retrying and
1305
+ // reports `offline: auth`, and its session asks the backend whether
1306
+ // anyone is still signed in.
1307
+ if (!ended)
1308
+ onEvent(null, {
1309
+ kind: "message",
1310
+ data: authFailedBatch("session missing: not signed in"),
1311
+ });
1312
+ onEvent(null, { kind: "close", code: 1008, reason: "not signed in" });
1313
+ end();
1314
+ return false;
1315
+ }
1316
+ userId = admitted.userId;
1317
+ trusted = admitted.trusted;
1318
+ stopExpiry?.();
1319
+ const admittedAt = Date.now();
1320
+ if (admitted.user) {
1321
+ // A signed-in user's session holds until the expiry `authenticate`
1322
+ // gave it, and at most `sessionTtlSeconds`. Shortly before, the
1323
+ // client is asked to connect again, so `authenticate` decides on its
1324
+ // new request with current cookies.
1325
+ const at = reauthenticateAt(admittedAt, sessionDeadline(admittedAt, admitted.user.expiresAt, options.sessionTtlSeconds));
1326
+ if (at === null) {
1327
+ // `authenticate` named the user with an answer already expired.
1328
+ warnExpiredAnswer();
1329
+ onEvent(null, {
1330
+ kind: "message",
1331
+ data: authFailedBatch("session expired: authenticate returned an expiresAt in the past"),
1332
+ });
1333
+ onEvent(null, { kind: "close", code: 1008, reason: "session expired" });
1334
+ end();
1335
+ return false;
1336
+ }
1337
+ stopExpiry = startTimer(reauthenticate, at - admittedAt);
1338
+ }
1339
+ else if (admitted.guest) {
1340
+ // A guest's key is its credential; the app lets it in anew each
1341
+ // `sessionTtlSeconds`, the same way.
1342
+ const ttl = (options.sessionTtlSeconds ?? 3600) * 1000;
1343
+ stopExpiry = startTimer(reauthenticate, ttl);
1344
+ }
1345
+ else {
1346
+ // A backend client's session ends with its token, so it reconnects
1347
+ // with a fresh one.
1348
+ const ttl = Math.min((options.sessionTtlSeconds ?? 3600) * 1000, admitted.expiresAt === undefined ? Infinity : admitted.expiresAt * 1000 - admittedAt);
1349
+ stopExpiry = startTimer(end, ttl);
1350
+ }
1351
+ // A guest's session the core refuses because it admits no device
1352
+ // accounts at all: the client only goes offline, so say why here.
1353
+ // The core refuses in its first message, so only that one is looked at.
1354
+ let firstFromCore = admitted.guest === true;
1355
+ const relay = (error, event) => {
1356
+ if (firstFromCore && event.kind === "message" && event.data) {
1357
+ firstFromCore = false;
1358
+ const { buffer, byteOffset, byteLength } = event.data;
1359
+ if (Buffer.from(buffer, byteOffset, byteLength).includes(CORE_REFUSES_GUESTS))
1360
+ warnGuestsOffOnCore();
1361
+ }
1362
+ onEvent(error, event);
1363
+ };
1364
+ socket = core.openSocket(headerPairs(request.headers), relay, admitted.access);
1365
+ return socket.send(admitted.prelude);
1366
+ };
1367
+ // Messages after the prelude wait for its admission, in order.
1368
+ let chain;
1369
+ // Bytes handed to `deliver` the core has not taken yet: a host that
1370
+ // doesn't wait for it (a socket that can't pause) is cut off past the
1371
+ // limit, as the core cuts off a peer that ignores flow control.
1372
+ let waitingBytes = 0;
1373
+ const deliver = (data) => {
1374
+ if (ended)
1375
+ return Promise.resolve(false);
1376
+ if (waitingBytes + data.byteLength > MAX_WAITING_SESSION_BYTES) {
1377
+ // 1013 (try again later): the client may come back and send at the
1378
+ // pace this host takes.
1379
+ onEvent(null, {
1380
+ kind: "close",
1381
+ code: 1013,
1382
+ reason: "client sent faster than the server takes",
1383
+ });
1384
+ end();
1385
+ return Promise.resolve(false);
1386
+ }
1387
+ waitingBytes += data.byteLength;
1388
+ const taken = (ok) => {
1389
+ waitingBytes -= data.byteLength;
1390
+ return ok;
1391
+ };
1392
+ chain = chain
1393
+ ? chain
1394
+ .then(async (ok) => {
1395
+ if (!ok || ended || !socket)
1396
+ return false;
1397
+ return socket.sendWithRoom ? socket.sendWithRoom(data) : socket.send(data);
1398
+ })
1399
+ .catch(() => {
1400
+ // A core that failed to take a message ends the session.
1401
+ onEvent(null, { kind: "close", code: 1011, reason: "session failed" });
1402
+ end();
1403
+ return false;
1404
+ })
1405
+ .then(taken)
1406
+ : admit(data)
1407
+ .catch((error) => {
1408
+ if (!ended && isRefusal(error)) {
1409
+ // The core refused this identity (revoked, local-first auth
1410
+ // disabled, invalid): an auth failure the client must not
1411
+ // retry, reported as a sign-in refusal is.
1412
+ onEvent(null, {
1413
+ kind: "message",
1414
+ data: authFailedBatch(`session refused: ${refusalCode(error)}`),
1415
+ });
1416
+ onEvent(null, { kind: "close", code: 1008, reason: "sign-in refused" });
1417
+ }
1418
+ else {
1419
+ // The core is unreachable or failed (5xx), or the app's own
1420
+ // `authenticate` threw: the client tries again later. An
1421
+ // `authenticate` without `expiresAt` fails the same way every
1422
+ // time: say why, once.
1423
+ if (error instanceof AuthenticateExpiresAtError)
1424
+ warnMissingExpiry(error);
1425
+ onEvent(null, { kind: "close", code: 1011, reason: "admission failed" });
1426
+ }
1427
+ end();
1428
+ return false;
1429
+ })
1430
+ .then(taken);
1431
+ return chain;
1432
+ };
1433
+ const clientSession = {
1434
+ send(data) {
1435
+ if (ended)
1436
+ return false;
1437
+ void deliver(data);
1438
+ return true;
1439
+ },
1440
+ deliver,
1441
+ close: end,
1442
+ revoke(reason) {
1443
+ if (ended)
1444
+ return;
1445
+ // A refusal the client doesn't retry: its session asks the backend
1446
+ // who is signed in, and signs out if no one is.
1447
+ onEvent(null, { kind: "message", data: authFailedBatch(`session revoked: ${reason}`) });
1448
+ onEvent(null, { kind: "close", code: 1008, reason: "session revoked" });
1449
+ end();
1450
+ },
1451
+ get userId() {
1452
+ return userId;
1453
+ },
1454
+ get trusted() {
1455
+ return trusted;
1456
+ },
1457
+ };
1458
+ const live = { session: clientSession, transport, openedAt: Date.now() };
1459
+ liveSessions.add(live);
1460
+ return clientSession;
1461
+ }
1462
+ /**
1463
+ * Turn a browser prelude into one the core admits on this backend's word:
1464
+ * the user `authenticate` finds on this request, with their account and
1465
+ * claims, vouched for with the backend secret. A local-first guest's
1466
+ * prelude passes through: the core verifies its self-signed token. Any
1467
+ * other credential, or a prelude naming another user, is refused.
1468
+ */
1469
+ async function admitPrelude(request, prelude) {
1470
+ let parsed;
1471
+ try {
1472
+ parsed = JSON.parse(new TextDecoder().decode(prelude));
1473
+ }
1474
+ catch {
1475
+ return null;
1476
+ }
1477
+ const auth = (parsed.auth && typeof parsed.auth === "object" ? parsed.auth : parsed);
1478
+ const client = await backendClients.resolve(request);
1479
+ if (client === "refused")
1480
+ return null;
1481
+ if (client?.kind === "backend") {
1482
+ // A trusted backend client syncs with this backend's authority: it
1483
+ // states a backend secret (any stand-in) and, to act for a user, that
1484
+ // user's session, as the main backend's own client does (the user's
1485
+ // policies then apply to those writes at the core). Never an admin
1486
+ // secret or a token of its own.
1487
+ for (const key of ["admin_secret", "jwt_token"]) {
1488
+ if (parsed[key] != null || auth[key] != null)
1489
+ return null;
1490
+ }
1491
+ if (parsed.backend_secret == null && auth.backend_secret == null)
1492
+ return null;
1493
+ const vouched = { backend_secret: core.backendSecret };
1494
+ const rewritten = { ...parsed, ...vouched, auth: { ...auth, ...vouched } };
1495
+ return {
1496
+ prelude: new TextEncoder().encode(JSON.stringify(rewritten)),
1497
+ userId: undefined,
1498
+ access: "backend",
1499
+ trusted: true,
1500
+ expiresAt: client.expiresAt,
1501
+ };
1502
+ }
1503
+ const others = ["backend_secret", "admin_secret", "backend_session"];
1504
+ // Browser worker transports send `jwt_token: null` alongside a backend
1505
+ // session; only a real token counts as one.
1506
+ const token = auth.jwt_token ?? parsed.jwt_token;
1507
+ if (token !== undefined && token !== null) {
1508
+ const localFirst = typeof token === "string" && parseJwtPayload(token)?.iss === LOCAL_FIRST_JWT_ISSUER;
1509
+ const alone = others.every((key) => parsed[key] == null && auth[key] == null);
1510
+ if (!localFirst || !alone || parsed.local_first_audience != null)
1511
+ return null;
1512
+ // A guest has no user here: its session is bound to its own key.
1513
+ if (client)
1514
+ return null;
1515
+ const audience = guestAudience(request, token);
1516
+ if (!audience)
1517
+ return null;
1518
+ // Guests are off unless the app's `authenticate` lets this one in.
1519
+ if (!(await acceptsGuest(request)))
1520
+ return null;
1521
+ if (audience.endpoint === undefined) {
1522
+ // Its own token decides who it is; the backend's secret only vouches
1523
+ // for the bundle this socket is pinned to (see `pinnedSocket`).
1524
+ const pinned = { ...parsed, auth: { ...auth, backend_secret: core.backendSecret } };
1525
+ return {
1526
+ prelude: new TextEncoder().encode(JSON.stringify(pinned)),
1527
+ userId: undefined,
1528
+ access: "session",
1529
+ trusted: false,
1530
+ guest: true,
1531
+ };
1532
+ }
1533
+ // Signed for this endpoint, which the core can't know: vouch for it.
1534
+ const vouched = {
1535
+ ...parsed,
1536
+ local_first_audience: audience.endpoint,
1537
+ auth: { ...auth, backend_secret: core.backendSecret },
1538
+ };
1539
+ // The backend's word on the endpoint needs backend access; the
1540
+ // guest's own token still decides who it is.
1541
+ return {
1542
+ prelude: new TextEncoder().encode(JSON.stringify(vouched)),
1543
+ userId: undefined,
1544
+ access: "backend",
1545
+ trusted: false,
1546
+ guest: true,
1547
+ };
1548
+ }
1549
+ const stated = auth.backend_session;
1550
+ if (!stated || typeof stated !== "object")
1551
+ return null;
1552
+ for (const credential of ["backend_secret", "admin_secret"]) {
1553
+ if (parsed[credential] != null || auth[credential] != null)
1554
+ return null;
1555
+ }
1556
+ const user = await authenticate(request);
1557
+ if (!user || user.userId !== stated.user_id)
1558
+ return null;
1559
+ // A browser states a user's session only once its sign-in (or link)
1560
+ // gave them an account; this never makes one.
1561
+ let session;
1562
+ try {
1563
+ session = await sessionFor(user, "a sync session");
1564
+ }
1565
+ catch (error) {
1566
+ if (error instanceof NoJazzAccountError)
1567
+ return null;
1568
+ throw error;
1569
+ }
1570
+ const vouched = { backend_secret: core.backendSecret, backend_session: session };
1571
+ const rewritten = { ...parsed, ...vouched, auth: { ...auth, ...vouched } };
1572
+ return {
1573
+ prelude: new TextEncoder().encode(JSON.stringify(rewritten)),
1574
+ userId: user.userId,
1575
+ user,
1576
+ access: "backend",
1577
+ trusted: false,
1578
+ expiresAt: client?.expiresAt,
1579
+ };
1580
+ }
1581
+ // HTTP stream sessions, by id, with the key that proves a request comes
1582
+ // from the client that opened them.
1583
+ const streams = new Map();
1584
+ // Sockets accepted for clients, so close() can end them.
1585
+ const clientSockets = new Set();
1586
+ // Why stream sessions this process served lately ended, by id: a send that
1587
+ // arrives after its session ended (refused at sign-in, say) is told that,
1588
+ // not that it reached the wrong instance.
1589
+ const endedStreams = new Map();
1590
+ const ENDED_STREAMS_KEPT = 1000;
1591
+ function openStream(request) {
1592
+ const id = randomUUID();
1593
+ // The id goes in URLs (and so in logs); the key only in a header.
1594
+ const key = randomBytes(32);
1595
+ let controller;
1596
+ let closed = false;
1597
+ const end = (code, reason) => {
1598
+ if (closed)
1599
+ return;
1600
+ closed = true;
1601
+ streams.delete(id);
1602
+ endedStreams.set(id, { key, reason: reason || `closed (${code})` });
1603
+ if (endedStreams.size > ENDED_STREAMS_KEPT) {
1604
+ endedStreams.delete(endedStreams.keys().next().value);
1605
+ }
1606
+ try {
1607
+ controller.enqueue(encodeStreamClose(code, reason));
1608
+ controller.close();
1609
+ }
1610
+ catch {
1611
+ // The client already went away.
1612
+ }
1613
+ };
1614
+ const body = new ReadableStream({
1615
+ start(c) {
1616
+ controller = c;
1617
+ },
1618
+ cancel() {
1619
+ streams.get(id)?.session.close();
1620
+ end(1001, "client went away");
1621
+ },
1622
+ });
1623
+ let socket;
1624
+ try {
1625
+ socket = openClientSession(request, (error, event) => {
1626
+ if (error)
1627
+ return end(1011, error.message);
1628
+ if (event.kind === "message" && event.data) {
1629
+ if (!closed)
1630
+ controller.enqueue(encodeStreamRecord(STREAM_RECORD_MESSAGE, event.data));
1631
+ }
1632
+ else if (event.kind === "close") {
1633
+ end(event.code ?? 1000, event.reason ?? "");
1634
+ }
1635
+ }, "stream");
1636
+ }
1637
+ catch (error) {
1638
+ return new Response(error instanceof Error ? error.message : String(error), { status: 503 });
1639
+ }
1640
+ streams.set(id, { session: socket, key, end });
1641
+ controller.enqueue(encodeStreamRecord(STREAM_RECORD_SESSION, new TextEncoder().encode(JSON.stringify({ id, key: key.toString("base64url") }))));
1642
+ return new Response(body, {
1643
+ headers: {
1644
+ "Content-Type": "application/octet-stream",
1645
+ "Cache-Control": "no-store",
1646
+ "X-Accel-Buffering": "no",
1647
+ },
1648
+ });
1649
+ }
1650
+ function holdsKey(request, key) {
1651
+ const given = Buffer.from(request.headers.get(STREAM_KEY_HEADER) ?? "", "base64url");
1652
+ return given.length === key.length && timingSafeEqual(given, key);
1653
+ }
1654
+ /**
1655
+ * The stream session `id`, when `request` comes from the client that
1656
+ * opened it (it carries the session's key) and, once the session is
1657
+ * admitted as a user, from that user still: a session id alone (which
1658
+ * can end up in logs) doesn't let anyone act in it, before admission or
1659
+ * for a guest either.
1660
+ */
1661
+ async function ownStream(id, request) {
1662
+ const entry = streams.get(id);
1663
+ if (!entry) {
1664
+ const ended = endedStreams.get(id);
1665
+ if (ended !== undefined) {
1666
+ if (!holdsKey(request, ended.key))
1667
+ return new Response("not this stream's client", { status: 403 });
1668
+ return new Response(`stream session ended: ${ended.reason}`, { status: 410 });
1669
+ }
1670
+ // Sessions live in the process that opened them.
1671
+ return new Response("unknown stream session: HTTP stream sessions need a single backend instance or sticky routing", { status: 404 });
1672
+ }
1673
+ if (!holdsKey(request, entry.key)) {
1674
+ return new Response("not this stream's client", { status: 403 });
1675
+ }
1676
+ const socket = entry.session;
1677
+ if (socket.trusted) {
1678
+ const client = await backendClients.resolve(request);
1679
+ if (client === null || client === "refused" || client.kind !== "backend") {
1680
+ return new Response("not this backend client", { status: 403 });
1681
+ }
1682
+ }
1683
+ else if (socket.userId !== undefined) {
1684
+ const user = await authenticate(request);
1685
+ if (user?.userId !== socket.userId)
1686
+ return new Response("not signed in", { status: 403 });
1687
+ }
1688
+ return socket;
1689
+ }
1690
+ /**
1691
+ * Pass a send's records to the session as they arrive, each once the core
1692
+ * has room for it: the body is not read ahead of the core, so a client
1693
+ * sending faster than the core takes is held back by the request itself.
1694
+ */
1695
+ async function streamSend(id, request) {
1696
+ const socket = await ownStream(id, request);
1697
+ if (socket instanceof Response)
1698
+ return socket;
1699
+ // A send's records go in whole and in order: one send at a time.
1700
+ if (sendingStreams.has(id)) {
1701
+ return new Response("a send to this stream is in progress", { status: 409 });
1702
+ }
1703
+ sendingStreams.add(id);
1704
+ try {
1705
+ return await passStreamRecords(socket, request);
1706
+ }
1707
+ finally {
1708
+ sendingStreams.delete(id);
1709
+ }
1710
+ }
1711
+ /** Stream sessions with a send in progress. */
1712
+ const sendingStreams = new Set();
1713
+ async function passStreamRecords(socket, request) {
1714
+ const refuse = (reason) => {
1715
+ socket.close();
1716
+ return new Response(reason, { status: 400 });
1717
+ };
1718
+ const records = new StreamRecordReader();
1719
+ const body = request.body?.getReader();
1720
+ for (;;) {
1721
+ const chunk = body ? await body.read() : { done: true, value: undefined };
1722
+ if (chunk.done)
1723
+ break;
1724
+ for (const record of records.push(chunk.value)) {
1725
+ if (record.kind !== STREAM_RECORD_MESSAGE ||
1726
+ record.payload.byteLength > MAX_STREAM_MESSAGE_BYTES) {
1727
+ void body?.cancel().catch(() => undefined);
1728
+ return refuse("invalid record");
1729
+ }
1730
+ if (!(await socket.deliver(record.payload))) {
1731
+ void body?.cancel().catch(() => undefined);
1732
+ return new Response("session ended", { status: 410 });
1733
+ }
1734
+ }
1735
+ // A record no message may be: refused before it is buffered.
1736
+ if (records.pending > 5 + MAX_STREAM_MESSAGE_BYTES) {
1737
+ void body?.cancel().catch(() => undefined);
1738
+ return refuse("invalid record");
1739
+ }
1740
+ }
1741
+ if (records.pending > 0)
1742
+ return refuse("truncated record");
1743
+ return new Response(null, { status: 204 });
1744
+ }
1745
+ /** Close codes a socket may send: 1005/1006/1015 only describe a close. */
1746
+ function sendableCloseCode(code) {
1747
+ if (code === undefined || code === 1005)
1748
+ return 1000;
1749
+ if (code === 1006 || code === 1015)
1750
+ return 1011;
1751
+ return code;
1752
+ }
1753
+ function acceptSocket(request, ws) {
1754
+ if (!originAllowed(request)) {
1755
+ ws.close(1008, "origin not allowed");
1756
+ return;
1757
+ }
1758
+ // A paused socket reads no close handshake: resume it to close.
1759
+ const close = (code, reason) => {
1760
+ ws.resume?.();
1761
+ ws.close(code, reason);
1762
+ };
1763
+ let socket;
1764
+ try {
1765
+ socket = openClientSession(request, (error, event) => {
1766
+ if (error)
1767
+ return close(1011, error.message);
1768
+ if (event.kind === "message" && event.data)
1769
+ ws.send(event.data);
1770
+ else if (event.kind === "close") {
1771
+ close(sendableCloseCode(event.code), event.reason ?? "");
1772
+ }
1773
+ }, "socket");
1774
+ }
1775
+ catch (error) {
1776
+ close(1013, error instanceof Error ? error.message : String(error));
1777
+ return;
1778
+ }
1779
+ clientSockets.add(ws);
1780
+ // Messages go to the core in order, each once it has room; the socket
1781
+ // is not read while one waits, so a fast client is held back.
1782
+ let waiting = 0;
1783
+ ws.on("message", (data) => {
1784
+ waiting += 1;
1785
+ ws.pause?.();
1786
+ // `deliver` resolves false, never rejects, when the session fails.
1787
+ void socket.deliver(toBytes(data)).then((ok) => {
1788
+ waiting -= 1;
1789
+ if (!ok)
1790
+ close(1000, "session ended");
1791
+ else if (waiting === 0)
1792
+ ws.resume?.();
1793
+ });
1794
+ });
1795
+ ws.on("close", () => {
1796
+ clientSockets.delete(ws);
1797
+ socket.close();
1798
+ });
1799
+ ws.on("error", () => socket.close());
1800
+ }
1801
+ /**
1802
+ * Whether a browser on the request's origin may act as its user here.
1803
+ * Sign-in and sync ride the app's own session (usually a cookie), which a
1804
+ * browser also attaches to requests that other pages start, so a request
1805
+ * from another origin is refused: one with no Origin (a non-browser
1806
+ * client, which holds no ambient cookie) passes. The backend's own origin
1807
+ * is the host the request was sent to, as a proxy forwards it.
1808
+ */
1809
+ /** This process upgrades sockets for handle() and nodeHandler (set by attach()). */
1810
+ let upgradesSockets = options.upgradesSockets ?? false;
1811
+ let attached = false;
1812
+ function originAllowed(request) {
1813
+ const origin = request.headers.get("origin");
1814
+ if (origin === null) {
1815
+ const site = request.headers.get("sec-fetch-site");
1816
+ return site === null || site === "same-origin" || site === "none";
1817
+ }
1818
+ if (allowedOrigins.has(origin))
1819
+ return true;
1820
+ let parsed;
1821
+ try {
1822
+ parsed = new URL(origin);
1823
+ }
1824
+ catch {
1825
+ return false; // "null" (a sandboxed or opaque origin) or garbage
1826
+ }
1827
+ const requestHost = request.headers.get("x-forwarded-host")?.split(",")[0]?.trim() ||
1828
+ request.headers.get("host") ||
1829
+ new URL(request.url).host;
1830
+ if (parsed.host !== requestHost)
1831
+ return false;
1832
+ // A page over plain http may not act on a backend reached over https. The
1833
+ // other way round is allowed: a proxy that ends TLS may hand us plain http.
1834
+ const requestScheme = request.headers.get("x-forwarded-proto")?.split(",")[0]?.trim().toLowerCase() ||
1835
+ new URL(request.url).protocol.replace(/:$/, "");
1836
+ return !(requestScheme === "https" && parsed.protocol === "http:");
1837
+ }
1838
+ /**
1839
+ * A trusted backend client asks to sync as a backend (what a backend's
1840
+ * own client asks its core first). Only its token admits it: the core is
1841
+ * asked with this backend's secret. Anyone else gets the 404 this route
1842
+ * has without backend clients.
1843
+ */
1844
+ async function admitBackendClient(request) {
1845
+ const client = await backendClients.resolve(request);
1846
+ if (client === null)
1847
+ return new Response("Not found", { status: 404 });
1848
+ if (client === "refused" || client.kind !== "backend") {
1849
+ return new Response("not a trusted backend client", { status: 401 });
1850
+ }
1851
+ if (request.method !== "POST")
1852
+ return new Response(null, { status: 405 });
1853
+ const response = await core.handle("POST", `/apps/${encodeURIComponent(accountAppId(appId))}/backend/admit`, [["x-jazz-backend-secret", core.backendSecret]], new Uint8Array(0), "backend");
1854
+ return new Response(null, { status: response.status === 204 ? 204 : 502 });
1855
+ }
1856
+ /**
1857
+ * A trusted backend client asks for a user's session, to act for them
1858
+ * (`client.forUser`): the account `forReqUser` would act as for a request
1859
+ * of theirs. Never creates an account (see `createAccountFor`). Anyone but
1860
+ * a trusted machine gets what `admitBackendClient` gives them.
1861
+ */
1862
+ async function backendClientUserSession(request) {
1863
+ const client = await backendClients.resolve(request);
1864
+ if (client === null)
1865
+ return new Response("Not found", { status: 404 });
1866
+ if (client === "refused" || client.kind !== "backend") {
1867
+ return new Response("not a trusted backend client", { status: 401 });
1868
+ }
1869
+ if (request.method !== "POST")
1870
+ return new Response(null, { status: 405 });
1871
+ let userId;
1872
+ try {
1873
+ ({ userId } = (await request.json()));
1874
+ }
1875
+ catch {
1876
+ return new Response("expected a JSON body", { status: 400 });
1877
+ }
1878
+ if (typeof userId !== "string" || userId === "") {
1879
+ return new Response("userId must be a non-empty string", { status: 400 });
1880
+ }
1881
+ let account;
1882
+ try {
1883
+ account = await existingAccountOf(userId);
1884
+ }
1885
+ catch (error) {
1886
+ // The core refuses this identity (it was revoked): say so, as
1887
+ // `backendUser` does, rather than fail as a server error.
1888
+ if (error.status === 403)
1889
+ return Response.json({ code: "identity_not_authorized" }, { status: 403 });
1890
+ throw error;
1891
+ }
1892
+ const noStore = { "Cache-Control": "no-store" };
1893
+ if (account === null)
1894
+ return Response.json({ code: "no_account" }, { status: 404, headers: noStore });
1895
+ return Response.json({ account, issuer }, { headers: noStore });
1896
+ }
1897
+ /**
1898
+ * The endpoint URLs a browser may have named this backend by, as its client
1899
+ * scope (see `clientScope`): the page's origin when it is one this backend
1900
+ * serves, and this request's own host, each with `basePath`.
1901
+ */
1902
+ function endpointAudiences(request) {
1903
+ if (publicUrls.length)
1904
+ return publicUrls;
1905
+ const audiences = new Set();
1906
+ // The page origin when it is this Host or an allowed origin, and this
1907
+ // Host. A browser can't forge Host, but a caller reaching this backend
1908
+ // directly can, so production backends should set `publicUrl`.
1909
+ // X-Forwarded-Host is never read here.
1910
+ const url = new URL(request.url);
1911
+ const host = request.headers.get("host") || url.host;
1912
+ const forwardedProto = request.headers
1913
+ .get("x-forwarded-proto")
1914
+ ?.split(",")[0]
1915
+ ?.trim()
1916
+ .toLowerCase();
1917
+ const scheme = forwardedProto === "https" || url.protocol === "https:" ? "https" : "http";
1918
+ const origin = request.headers.get("origin");
1919
+ if (origin) {
1920
+ try {
1921
+ const parsed = new URL(origin);
1922
+ if (allowedOrigins.has(parsed.origin) || parsed.host === host)
1923
+ audiences.add(`${parsed.origin}${basePath}`);
1924
+ }
1925
+ catch {
1926
+ // Not an origin a page has.
1927
+ }
1928
+ }
1929
+ try {
1930
+ audiences.add(`${new URL(`${scheme}://${host}`).origin}${basePath}`);
1931
+ }
1932
+ catch {
1933
+ // A host header no URL takes.
1934
+ }
1935
+ return [...audiences];
1936
+ }
1937
+ const warnedAudiences = new Set();
1938
+ let warnedHeaderAudience = false;
1939
+ /** Say once per audience why a guest's proof was refused, so a proxy mismatch is visible. */
1940
+ function warnUnknownAudience(token, accepted, isAudience = false) {
1941
+ const audience = isAudience ? token : parseJwtPayload(token)?.aud;
1942
+ const named = typeof audience === "string" ? audience : JSON.stringify(audience);
1943
+ if (warnedAudiences.has(named) || warnedAudiences.size > 100)
1944
+ return;
1945
+ warnedAudiences.add(named);
1946
+ console.warn(`createJazz: refused a local-first guest whose proof is for ${named}; this endpoint accepts ${JSON.stringify([appId, ...accepted])}. If browsers reach Jazz through a proxy that changes the host or path, set publicUrl to the URL they use.`);
1947
+ }
1948
+ /**
1949
+ * What a guest's local-first proof is for: this app (an app whose browser
1950
+ * clients still name its id, or carry it as their `scope`), one of this
1951
+ * endpoint's URLs, or neither (null).
1952
+ */
1953
+ function guestAudience(request, token) {
1954
+ try {
1955
+ verifyLocalFirstToken(token, appId);
1956
+ return {};
1957
+ }
1958
+ catch {
1959
+ // Not this app's id; try the endpoint.
1960
+ }
1961
+ const endpoints = endpointAudiences(request);
1962
+ for (const endpoint of endpoints) {
1963
+ try {
1964
+ verifyLocalFirstToken(token, endpoint);
1965
+ if (!publicUrls.length && !warnedHeaderAudience && !isLocalEndpoint(endpoint)) {
1966
+ warnedHeaderAudience = true;
1967
+ console.warn(`createJazz: vouched for a local-first guest of ${endpoint}, taken from the request's headers. Set publicUrl to the URL browsers use so a caller can't name another host.`);
1968
+ }
1969
+ return { endpoint };
1970
+ }
1971
+ catch {
1972
+ // Not this one.
1973
+ }
1974
+ }
1975
+ warnUnknownAudience(token, endpoints);
1976
+ return null;
1977
+ }
1978
+ /**
1979
+ * The namespace a linking guest names for its account: this app (no
1980
+ * audience, or the app's id), one of this endpoint's URLs, or neither (null).
1981
+ */
1982
+ function linkAudience(request, audience) {
1983
+ // Tokens name their audience as given or as its app id (a UUID).
1984
+ const names = (value) => audience === value || audience === accountAppId(value);
1985
+ if (audience === undefined || (typeof audience === "string" && names(appId)))
1986
+ return {};
1987
+ if (typeof audience !== "string")
1988
+ return null;
1989
+ const endpoints = endpointAudiences(request);
1990
+ const endpoint = endpoints.find(names);
1991
+ if (endpoint !== undefined)
1992
+ return { endpoint };
1993
+ warnUnknownAudience(audience, endpoints, true);
1994
+ return null;
1995
+ }
1996
+ /** The path below `basePath`, or null for a request Jazz doesn't serve. */
1997
+ function innerPath(request) {
1998
+ const { pathname } = new URL(request.url);
1999
+ if (pathname === basePath)
2000
+ return "/";
2001
+ if (!pathname.startsWith(`${basePath}/`))
2002
+ return null;
2003
+ return pathname.slice(basePath.length);
2004
+ }
2005
+ /**
2006
+ * Answer `request`. `upgrades`: whether the handler it came through
2007
+ * upgrades sockets on this host, which decides what a plain request for
2008
+ * the socket path is told.
2009
+ */
2010
+ async function handle(request, upgrades = upgradesSockets) {
2011
+ try {
2012
+ return await route(request, upgrades);
2013
+ }
2014
+ catch (error) {
2015
+ if (error instanceof AuthenticateExpiresAtError) {
2016
+ // The app's own setup is wrong, the same way on every request: tell
2017
+ // the client by a stable code it explains (naming the fix), and log
2018
+ // the detail (what `authenticate` returned) here once. The response
2019
+ // carries nothing of the app's answer.
2020
+ warnMissingExpiry(error);
2021
+ return new Response(AUTHENTICATE_EXPIRES_AT_MISSING, {
2022
+ status: 500,
2023
+ headers: { "Cache-Control": "no-store" },
2024
+ });
2025
+ }
2026
+ if (!(error instanceof BackendClientsUnavailable))
2027
+ throw error;
2028
+ // The reason stays in the backend's logs.
2029
+ console.error(error);
2030
+ return new Response("backend client keys unavailable", {
2031
+ status: 503,
2032
+ headers: { "Retry-After": "5" },
2033
+ });
2034
+ }
2035
+ }
2036
+ async function route(request, upgrades) {
2037
+ const path = innerPath(request);
2038
+ if (path === null)
2039
+ return new Response("Not found", { status: 404 });
2040
+ if (request.method !== "GET" && request.method !== "HEAD" && !originAllowed(request)) {
2041
+ return new Response("origin not allowed", { status: 403 });
2042
+ }
2043
+ if (path === "/inspect" || path.startsWith("/inspect/")) {
2044
+ return inspector.handle(request, path);
2045
+ }
2046
+ if (/^\/apps\/[^/]+\/accounts\/backend-sign-in$/.test(path)) {
2047
+ return backendSignIn(request);
2048
+ }
2049
+ if (/^\/apps\/[^/]+\/accounts\/backend-user$/.test(path)) {
2050
+ return backendUser(request);
2051
+ }
2052
+ if (/^\/apps\/[^/]+\/backend\/admit$/.test(path)) {
2053
+ return admitBackendClient(request);
2054
+ }
2055
+ if (/^\/apps\/[^/]+\/backend\/user-session$/.test(path)) {
2056
+ return backendClientUserSession(request);
2057
+ }
2058
+ if (/^\/apps\/[^/]+\/accounts\/backend-link$/.test(path)) {
2059
+ return backendLink(request);
2060
+ }
2061
+ if (/^\/apps\/[^/]+\/accounts\/backend-link\/challenge$/.test(path)) {
2062
+ return backendLinkChallenge(request);
2063
+ }
2064
+ const stream = /^\/apps\/[^/]+\/stream(?:\/([^/]+))?$/.exec(path);
2065
+ if (stream) {
2066
+ const id = stream[1] && decodeURIComponent(stream[1]);
2067
+ if (!id && request.method === "POST")
2068
+ return openStream(request);
2069
+ if (id && request.method === "POST")
2070
+ return streamSend(id, request);
2071
+ if (id && request.method === "DELETE") {
2072
+ const socket = await ownStream(id, request);
2073
+ if (socket instanceof Response)
2074
+ return socket;
2075
+ socket.close();
2076
+ return new Response(null, { status: 204 });
2077
+ }
2078
+ return new Response(null, { status: 405 });
2079
+ }
2080
+ if (path.endsWith("/ws")) {
2081
+ // A plain request for the socket path: the browser client asks this
2082
+ // after a socket failed before it opened. Where this host upgrades
2083
+ // sockets (attach(), or Vercel), that failure was transient (a
2084
+ // restart, a draining instance) and the client should retry the
2085
+ // socket. Only where it can't does the marker send it to the stream
2086
+ // at once; the client also switches after several failed sockets in
2087
+ // a row, when something in between doesn't pass upgrades on. It asks
2088
+ // with a POST, so a page origin the socket was refused for is refused
2089
+ // here too (403, above), and not taken for a proxy's doing.
2090
+ if (upgrades) {
2091
+ return new Response("Upgrade to a WebSocket", { status: 426 });
2092
+ }
2093
+ return useHttpStream();
2094
+ }
2095
+ if (!PUBLIC_APP_ROUTES.test(path))
2096
+ return new Response("Not found", { status: 404 });
2097
+ const url = new URL(request.url);
2098
+ const body = request.method === "GET" || request.method === "HEAD"
2099
+ ? Buffer.alloc(0)
2100
+ : Buffer.from(await request.arrayBuffer());
2101
+ const headers = headerPairs(request.headers);
2102
+ // A browser names the app however its scope does; the core knows it by id.
2103
+ const corePath = path.replace(/^\/apps\/[^/]+/, `/apps/${encodeURIComponent(appId)}`);
2104
+ return coreResponse(await core.handle(request.method, corePath + url.search, store.kind === "remote" || store.kind === "vercel"
2105
+ ? headers.filter(([name]) => REMOTE_FORWARDED_HEADERS.includes(name.toLowerCase()))
2106
+ : headers, body));
2107
+ }
2108
+ async function nextHandler(request) {
2109
+ const path = innerPath(request);
2110
+ // On Vercel this handler upgrades sockets (below), once `ws` is
2111
+ // installed; elsewhere (next dev) only if attach() runs on the same
2112
+ // server. Where it can't, a socket gets the HTTP stream marker, as a
2113
+ // plain request for the socket path does.
2114
+ const onVercel = onVercelHost();
2115
+ const vercelUpgrades = onVercel && (await vercelUpgradesSockets());
2116
+ if (request.method === "GET" &&
2117
+ path?.endsWith("/ws") &&
2118
+ request.headers.get("upgrade")?.toLowerCase() === "websocket" &&
2119
+ onVercel) {
2120
+ if (!originAllowed(request))
2121
+ return new Response("origin not allowed", { status: 403 });
2122
+ if (!vercelUpgrades)
2123
+ return useHttpStream();
2124
+ // An optional peer: a literal import inside `try`, so bundlers report
2125
+ // a missing one at runtime, not on every route (see importSandboxSdk).
2126
+ let vercelFunctions;
2127
+ try {
2128
+ vercelFunctions = (await import(
2129
+ /* @vite-ignore */ "@vercel/functions"));
2130
+ }
2131
+ catch (error) {
2132
+ throw optionalPeerImportError("Jazz on Vercel", "@vercel/functions", error);
2133
+ }
2134
+ const { upgradeWebSocket } = vercelFunctions;
2135
+ // The socket ends with this invocation, at the route's maxDuration:
2136
+ // close it just before, so the client reconnects without a stall.
2137
+ const deadline = vercelFunctions.getDeadline?.()?.getTime();
2138
+ return upgradeWebSocket((ws) => acceptSocket(request, deadline === undefined ? ws : closingBeforeDeadline(ws, deadline)), { maxPayload: MAX_STREAM_MESSAGE_BYTES });
2139
+ }
2140
+ return handle(request, upgradesSockets || vercelUpgrades);
2141
+ }
2142
+ function nodeRequest(req) {
2143
+ const host = req.headers.host ?? "localhost";
2144
+ const headers = new Headers();
2145
+ for (const [name, value] of Object.entries(req.headers)) {
2146
+ if (value === undefined)
2147
+ continue;
2148
+ for (const item of Array.isArray(value) ? value : [value])
2149
+ headers.append(name, item);
2150
+ }
2151
+ const hasBody = req.method !== "GET" && req.method !== "HEAD";
2152
+ // A body parser mounted before nodeHandler (express.json(), express.raw())
2153
+ // has read the stream already: its buffer is the body, or nothing is.
2154
+ const parsed = req.body;
2155
+ // No bytes to read: what a parser made of nothing (`{}`) doesn't matter.
2156
+ const empty = req.headers["content-length"] === "0" ||
2157
+ (req.headers["content-length"] === undefined &&
2158
+ req.headers["transfer-encoding"] === undefined);
2159
+ const json = /^application\/json\b/i.test(req.headers["content-type"] ?? "");
2160
+ let body;
2161
+ if (hasBody && req.readableEnded) {
2162
+ if (parsed instanceof Uint8Array) {
2163
+ body = parsed;
2164
+ }
2165
+ else if (empty) {
2166
+ body = undefined;
2167
+ }
2168
+ else if (json && parsed !== null && typeof parsed === "object") {
2169
+ // express.json()'s result: Jazz's JSON routes read it as JSON again
2170
+ // (none signs its bytes), so it serves as the body.
2171
+ body = JSON.stringify(parsed);
2172
+ headers.delete("content-length");
2173
+ }
2174
+ else {
2175
+ throw new Error("jazz: the request body was already read by another handler; mount jazz.nodeHandler before body parsers such as express.json()");
2176
+ }
2177
+ }
2178
+ else if (hasBody) {
2179
+ body = req;
2180
+ }
2181
+ const request = new Request(`http://${host}${req.url ?? "/"}`, {
2182
+ method: req.method,
2183
+ headers,
2184
+ ...(body === undefined ? {} : { body, duplex: "half" }),
2185
+ });
2186
+ const address = req.socket?.remoteAddress;
2187
+ if (address)
2188
+ remoteAddresses.set(request, address);
2189
+ return request;
2190
+ }
2191
+ function nodeHandler(req, res, next) {
2192
+ // Only Jazz's own paths: a request for the app passes on untouched, its
2193
+ // body unread, whatever read it before.
2194
+ const pathname = requestPathname(req.url);
2195
+ if (pathname === null || (pathname !== basePath && !pathname.startsWith(`${basePath}/`))) {
2196
+ if (next)
2197
+ return next();
2198
+ res.statusCode = 404;
2199
+ res.end();
2200
+ return;
2201
+ }
2202
+ let request;
2203
+ try {
2204
+ request = nodeRequest(req);
2205
+ }
2206
+ catch (error) {
2207
+ console.error(error instanceof Error ? error.message : error);
2208
+ // A code the client reports, so the browser doesn't fail silently.
2209
+ res.statusCode = 500;
2210
+ res.end("request_body_already_read");
2211
+ return;
2212
+ }
2213
+ void handle(request).then(async (response) => {
2214
+ res.statusCode = response.status;
2215
+ response.headers.forEach((value, name) => res.setHeader(name, value));
2216
+ if (!response.body)
2217
+ return void res.end();
2218
+ res.flushHeaders();
2219
+ const reader = response.body.getReader();
2220
+ res.on("close", () => void reader.cancel().catch(() => undefined));
2221
+ for (;;) {
2222
+ const { done, value } = await reader.read();
2223
+ if (done)
2224
+ break;
2225
+ res.write(value);
2226
+ }
2227
+ res.end();
2228
+ }, (error) => {
2229
+ // The reason stays in the backend's logs, not in the response.
2230
+ console.error("jazz: request failed", error);
2231
+ res.statusCode = 500;
2232
+ res.end("Internal error");
2233
+ });
2234
+ }
2235
+ function upgrade(wss, req, socket, head) {
2236
+ let request;
2237
+ try {
2238
+ request = nodeRequest(req);
2239
+ }
2240
+ catch {
2241
+ // A request no URL can be made of (a bad Host header).
2242
+ socket.end(BAD_UPGRADE);
2243
+ return;
2244
+ }
2245
+ const path = innerPath(request);
2246
+ if (path === null || !SOCKET_PATH.test(path))
2247
+ return void socket.end(BAD_UPGRADE);
2248
+ if (!originAllowed(request)) {
2249
+ socket.end("HTTP/1.1 403 Forbidden\r\nConnection: close\r\n\r\n");
2250
+ return;
2251
+ }
2252
+ wss.handleUpgrade(req, socket, head, (ws) => acceptSocket(request, ws));
2253
+ }
2254
+ function markAttached() {
2255
+ upgradesSockets = true;
2256
+ attached = true;
2257
+ }
2258
+ // The Inspector follows `reload`: it reads the current options each time.
2259
+ let keptSecret;
2260
+ let schemaOf = null;
2261
+ const inspector = createInspector({
2262
+ appId,
2263
+ get basePath() {
2264
+ return basePath;
2265
+ },
2266
+ get publicUrls() {
2267
+ return publicUrls;
2268
+ },
2269
+ schema: () => {
2270
+ if (schemaOf?.app !== options.app) {
2271
+ schemaOf = { app: options.app, schema: resolveSchemaSource(options.app) };
2272
+ }
2273
+ return schemaOf.schema;
2274
+ },
2275
+ get permissions() {
2276
+ return options.permissions;
2277
+ },
2278
+ db: () => backend.db,
2279
+ dbAs: async (user) => backendDbForSession(backend, await sessionFor(user, "inspect `as`")),
2280
+ sessions: () => [...liveSessions].map(({ session: live, transport, openedAt }) => ({
2281
+ userId: live.userId ?? null,
2282
+ kind: live.trusted ? "backend-client" : live.userId === undefined ? "guest" : "user",
2283
+ transport,
2284
+ openedAt,
2285
+ })),
2286
+ get hook() {
2287
+ return options.inspect;
2288
+ },
2289
+ get options() {
2290
+ return options.inspector ?? NO_INSPECTOR_OPTIONS;
2291
+ },
2292
+ tokenSecret: async () => {
2293
+ const configured = options.inspector?.tokenSecret;
2294
+ if (configured !== undefined)
2295
+ return configured;
2296
+ if (store.kind === "remote")
2297
+ return store.secret ?? null;
2298
+ if (store.kind === "sqlite") {
2299
+ // Read once; a failed read is tried again on the next call.
2300
+ keptSecret ??= keptTokenSecret(store.path).catch((error) => {
2301
+ keptSecret = undefined;
2302
+ throw error;
2303
+ });
2304
+ return keptSecret;
2305
+ }
2306
+ if (store.kind === "memory")
2307
+ return memoryTokenSecret;
2308
+ // A Vercel core's only credential is the function's OIDC token: there
2309
+ // is no shared secret to sign with.
2310
+ return null;
2311
+ },
2312
+ remoteAddress: (request) => remoteAddresses.get(request),
2313
+ serveUi: createInspectorUi(),
2314
+ });
2315
+ let closing;
2316
+ return {
2317
+ appId,
2318
+ get basePath() {
2319
+ return basePath;
2320
+ },
2321
+ reload,
2322
+ handle: (request) => handle(request),
2323
+ next: () => ({ GET: nextHandler, POST: nextHandler, DELETE: nextHandler }),
2324
+ upgrade,
2325
+ markAttached,
2326
+ nodeHandler,
2327
+ acceptSocket,
2328
+ get db() {
2329
+ return backend.db;
2330
+ },
2331
+ linkIdentity,
2332
+ async forReqUser(request) {
2333
+ const user = await authenticate(request);
2334
+ if (!user)
2335
+ throw signedOut("forReqUser");
2336
+ return backendDbForSession(backend, await sessionFor(user, "forReqUser"));
2337
+ },
2338
+ async withAttribution(request) {
2339
+ const user = await authenticate(request);
2340
+ if (!user)
2341
+ throw signedOut("withAttribution");
2342
+ return backendDbAttributedTo(backend, await sessionFor(user, "withAttribution"));
2343
+ },
2344
+ async accountFor(request) {
2345
+ const user = await authenticate(request);
2346
+ return user ? await existingAccountOf(user.userId) : null;
2347
+ },
2348
+ async createAccountFor(userId) {
2349
+ if (typeof userId !== "string" || userId === "")
2350
+ throw new Error("createAccountFor: pass the user's id, as your authenticate names it");
2351
+ return accountOf(userId);
2352
+ },
2353
+ async revokeUser(userId) {
2354
+ if (typeof userId !== "string" || userId === "")
2355
+ throw new Error("revokeUser: pass the user's id, as your authenticate names it");
2356
+ let ended = 0;
2357
+ for (const { session } of [...liveSessions]) {
2358
+ if (session.trusted || session.userId !== userId)
2359
+ continue;
2360
+ session.revoke("revokeUser");
2361
+ ended += 1;
2362
+ }
2363
+ return ended;
2364
+ },
2365
+ close() {
2366
+ closing ??= (async () => {
2367
+ // Every client connection ends, so the host's own shutdown (which
2368
+ // waits for the connections it serves) can finish, and the clients
2369
+ // reconnect to whichever instance serves next.
2370
+ for (const stream of [...streams.values()]) {
2371
+ stream.session.close();
2372
+ stream.end(1012, "server shutting down");
2373
+ }
2374
+ streams.clear();
2375
+ for (const ws of [...clientSockets]) {
2376
+ ws.resume?.();
2377
+ ws.close(1012, "server shutting down");
2378
+ }
2379
+ clientSockets.clear();
2380
+ await Promise.all([...retiring].map((close) => close()));
2381
+ // Writes that resolved at the "local" tier may still be on their way
2382
+ // to the core. Hand them over before closing it, so a close right
2383
+ // after a write never loses it.
2384
+ const timer = setTimeout(() => backend.db.abortGracefulShutdown(), CLOSE_SYNC_TIMEOUT_MS);
2385
+ await backend
2386
+ .shutdown({ waitForSync: true })
2387
+ .catch((error) => {
2388
+ console.warn("Jazz backend closed before every write reached the core.", error);
2389
+ })
2390
+ .finally(() => clearTimeout(timer));
2391
+ await session.close();
2392
+ await core.close();
2393
+ })();
2394
+ return closing;
2395
+ },
2396
+ };
2397
+ }
2398
+ /**
2399
+ * Run Jazz inside your backend. It applies the schema, migrations and
2400
+ * permissions your code declares to its core (in this process, or a remote
2401
+ * one), and serves sync on your own origin under `basePath`. There is no
2402
+ * separate deploy step: a rollback of your backend rolls Jazz back with it.
2403
+ *
2404
+ * It opens nothing when called, so a module can export it at its top level:
2405
+ * the store opens on first use (a request, a `db` call, `ready()`). A process
2406
+ * runs one Jazz per store (a `sqlite()` directory, a `vercel()` core): a
2407
+ * later `createJazz` for it (a dev server's hot reload, another module
2408
+ * graph) returns that same Jazz with the later
2409
+ * call's app, permissions and options. Each `remote()` and `memory()` store
2410
+ * is its own: a module that hot reloads keeps that Jazz across reloads
2411
+ * itself, or closes it.
2412
+ */
2413
+ export function createJazz(options) {
2414
+ jazzSettings(options);
2415
+ // Checked at startup, so a missing `ws` is in the logs before the first socket.
2416
+ if (onVercelHost())
2417
+ void vercelUpgradesSockets();
2418
+ const store = runningStore(options.store);
2419
+ const key = storeKey(store);
2420
+ const entries = registry();
2421
+ const shared = key === undefined ? undefined : entries.get(key);
2422
+ if (shared && !shared.closing) {
2423
+ adoptStore(shared, store);
2424
+ shared.options = options;
2425
+ return shared.jazz;
2426
+ }
2427
+ // A Jazz for this store still closing: the new one opens once it let go.
2428
+ const entry = newEntry(options, store, key, shared?.released);
2429
+ if (key !== undefined)
2430
+ entries.set(key, entry);
2431
+ return entry.jazz;
2432
+ }
2433
+ /** How long a session a reload replaced stays open for the requests still using it. */
2434
+ const RETIRED_SESSION_GRACE_MS = 60_000;
2435
+ /** How long `close()` waits for a store still opening before it gives up on it. */
2436
+ export const CLOSE_WAITS_FOR_OPEN_MS = 30_000;
2437
+ /** A failed open is tried again after this, doubling up to `MAX_OPEN_RETRY_MS`. */
2438
+ const FIRST_OPEN_RETRY_MS = 1_000;
2439
+ const MAX_OPEN_RETRY_MS = 30_000;
2440
+ /** At most this many sockets wait for the store to open, each holding at most this much. */
2441
+ export const MAX_HELD_SOCKETS = 1_000;
2442
+ export const MAX_HELD_SOCKET_BYTES = 4 * 1024 * 1024;
2443
+ const REGISTRY = Symbol.for("jazz-tools.createJazz.stores");
2444
+ /**
2445
+ * Open stores by key, on `globalThis` so that two copies of this module
2446
+ * (a bundler's server and route chunks, a hot reload) share them.
2447
+ */
2448
+ function registry() {
2449
+ const scope = globalThis;
2450
+ return (scope[REGISTRY] ??= new Map());
2451
+ }
2452
+ /**
2453
+ * The store's identity in this process: one Jazz runs per store, so a hot
2454
+ * reload finds the one it opened. A `remote()` store has none: two
2455
+ * backends (deployments, tests) may each run their own Jazz on one remote
2456
+ * app, with their own permissions. Nor has a `memory()` store, a new,
2457
+ * empty database each time. A module that hot reloads keeps such a Jazz
2458
+ * across reloads itself (on `globalThis`), or closes it.
2459
+ */
2460
+ function storeKey(store) {
2461
+ if (store.kind === "sqlite")
2462
+ return `sqlite:${resolve(store.path)}`;
2463
+ if (store.kind === "vercel") {
2464
+ const project = store.options.credentials?.projectId ?? process.env.VERCEL_PROJECT_ID;
2465
+ let name = store.options.name;
2466
+ try {
2467
+ name ??= project ? defaultCoreName(project, process.env) : undefined;
2468
+ }
2469
+ catch {
2470
+ // A preview without a branch: its open reports that, not createJazz.
2471
+ }
2472
+ // Without a name the core is unknown: its open reports that.
2473
+ return name ? `vercel:${name}` : undefined;
2474
+ }
2475
+ return undefined;
2476
+ }
2477
+ /**
2478
+ * What a store's settings are. The functions it holds (a credential hook)
2479
+ * are not settings: the open store calls the latest call's. A Sandbox SDK
2480
+ * is: another one is another setting.
2481
+ */
2482
+ function storeSettings(store) {
2483
+ return JSON.stringify(store, (name, value) => {
2484
+ if (name === "sdk" && value !== undefined)
2485
+ return `sdk#${identity(value)}`;
2486
+ return typeof value === "function" ? "function" : value;
2487
+ });
2488
+ }
2489
+ const identities = new WeakMap();
2490
+ let lastIdentity = 0;
2491
+ function identity(value) {
2492
+ let id = identities.get(value);
2493
+ if (id === undefined)
2494
+ identities.set(value, (id = ++lastIdentity));
2495
+ return id;
2496
+ }
2497
+ /**
2498
+ * The entry's store, its function settings (a credential hook) calling
2499
+ * through to the latest `createJazz` call's, so a reload applies them.
2500
+ */
2501
+ function liveStore(entry) {
2502
+ const through = (value, current) => {
2503
+ const out = { ...value };
2504
+ for (const [name, field] of Object.entries(value)) {
2505
+ if (typeof field !== "function")
2506
+ continue;
2507
+ out[name] = (...args) => {
2508
+ const latest = current()?.[name];
2509
+ return (typeof latest === "function" ? latest : field)(...args);
2510
+ };
2511
+ }
2512
+ return out;
2513
+ };
2514
+ const store = entry.store;
2515
+ if (store.kind === "vercel") {
2516
+ return {
2517
+ ...store,
2518
+ options: through(store.options, () => entry.store.kind === "vercel" ? entry.store.options : undefined),
2519
+ };
2520
+ }
2521
+ return through(store, () => entry.store);
2522
+ }
2523
+ /**
2524
+ * A later `createJazz` for an entry's store. Before the store opens it takes
2525
+ * the new settings; once open, settings that would need another core are
2526
+ * refused, so a change never silently goes unapplied.
2527
+ */
2528
+ function adoptStore(entry, store) {
2529
+ if (!entry.opening && !entry.opened) {
2530
+ entry.store = store;
2531
+ // A later call (a hot reload after a fix) tries the open again at once.
2532
+ entry.failure = undefined;
2533
+ return;
2534
+ }
2535
+ if (storeSettings(store) !== storeSettings(entry.store)) {
2536
+ throw new Error(`createJazz(): ${entry.key} is already open in this process with other store settings; restart the process to change them`);
2537
+ }
2538
+ // The same settings: its function settings are the latest call's now.
2539
+ entry.store = store;
2540
+ }
2541
+ function newEntry(options, store, key, after) {
2542
+ const entry = { key, store, options, after };
2543
+ entry.jazz = facade(entry);
2544
+ return entry;
2545
+ }
2546
+ /**
2547
+ * The entry's open Jazz, with the latest call's options applied. Once it is
2548
+ * closing, only `draining` (the writes made before the close) still gets it.
2549
+ */
2550
+ async function settled(entry, draining = false) {
2551
+ for (;;) {
2552
+ if (entry.closing && !draining)
2553
+ throw new Error("createJazz: this Jazz was closed");
2554
+ const opened = await (entry.opening ?? openEntry(entry));
2555
+ if (entry.closing && !draining)
2556
+ throw new Error("createJazz: this Jazz was closed");
2557
+ if (entry.applied === entry.options)
2558
+ return opened;
2559
+ await (entry.reloading ??= reloadEntry(entry, opened));
2560
+ }
2561
+ }
2562
+ /**
2563
+ * Open the entry's store. A failed open is not tried again at once: until
2564
+ * its backoff has passed, every use fails with the same error, so a store
2565
+ * that is down is not asked again on every request.
2566
+ */
2567
+ function openEntry(entry) {
2568
+ const failed = entry.failure;
2569
+ if (failed && Date.now() < failed.retryAt)
2570
+ return Promise.reject(failed.error);
2571
+ const options = entry.options;
2572
+ const opening = (async () => {
2573
+ await entry.after;
2574
+ return openJazz(options, liveStore(entry));
2575
+ })().then((opened) => {
2576
+ entry.failure = undefined;
2577
+ if (entry.attached)
2578
+ opened.markAttached();
2579
+ entry.opened = opened;
2580
+ entry.applied = options;
2581
+ drainOnSignal(entry);
2582
+ return opened;
2583
+ }, (error) => {
2584
+ const delayMs = failed
2585
+ ? Math.min(failed.delayMs * 2, MAX_OPEN_RETRY_MS)
2586
+ : FIRST_OPEN_RETRY_MS;
2587
+ entry.failure = { error, retryAt: Date.now() + delayMs, delayMs };
2588
+ if (entry.opening === opening)
2589
+ entry.opening = undefined;
2590
+ throw error;
2591
+ });
2592
+ entry.opening = opening;
2593
+ return opening;
2594
+ }
2595
+ /** The signals a host stops a server with (a deploy, a rolling restart, Ctrl-C). */
2596
+ const SHUTDOWN_SIGNALS = ["SIGTERM", "SIGINT"];
2597
+ /** Every open Jazz in this process, closed when the process is asked to stop. */
2598
+ const drained = new Set();
2599
+ const onShutdownSignal = (signal) => void shutDownOnSignal(signal);
2600
+ /**
2601
+ * Close every open Jazz when the process is asked to stop. A host's own
2602
+ * shutdown (`next start`, an Effect runtime, `server.close()`) waits for the
2603
+ * connections it serves, and Jazz's sync sockets and streams last until Jazz
2604
+ * ends them: without this, the process lingers and keeps its store locked
2605
+ * for as long as a browser stays connected. The clients reconnect to
2606
+ * whichever instance serves next. With no other handler for the signal the
2607
+ * process then stops as it would have; otherwise that handler decides.
2608
+ */
2609
+ function drainOnSignal(entry) {
2610
+ if (typeof process === "undefined" || typeof process.on !== "function")
2611
+ return;
2612
+ if (drained.size === 0) {
2613
+ for (const signal of SHUTDOWN_SIGNALS)
2614
+ process.on(signal, onShutdownSignal);
2615
+ }
2616
+ drained.add(entry);
2617
+ }
2618
+ function undrain(entry) {
2619
+ if (!drained.delete(entry) || drained.size > 0)
2620
+ return;
2621
+ for (const signal of SHUTDOWN_SIGNALS)
2622
+ process.off(signal, onShutdownSignal);
2623
+ }
2624
+ async function shutDownOnSignal(signal) {
2625
+ for (const each of SHUTDOWN_SIGNALS)
2626
+ process.off(each, onShutdownSignal);
2627
+ const open = [...drained];
2628
+ drained.clear();
2629
+ await Promise.allSettled(open.map((entry) => entry.jazz.close()));
2630
+ // Nobody else asked to handle it: stop the way the signal would have.
2631
+ if (process.listenerCount(signal) === 0)
2632
+ process.kill(process.pid, signal);
2633
+ }
2634
+ /**
2635
+ * Close the entry: apply the writes made before the close, then close its
2636
+ * store. A store still opening is waited for at most
2637
+ * `CLOSE_WAITS_FOR_OPEN_MS`; past that the writes still waiting fail and
2638
+ * the store closes once it has opened. Until it has, a new `createJazz` for
2639
+ * the store waits for it rather than finding the store held.
2640
+ */
2641
+ async function closeEntry(entry, early) {
2642
+ let release;
2643
+ entry.released = new Promise((resolve) => (release = resolve));
2644
+ const stopped = (async () => {
2645
+ await early.drain();
2646
+ const opened = await entry.opening?.catch(() => undefined);
2647
+ await entry.reloading?.catch(() => undefined);
2648
+ await opened?.close();
2649
+ })();
2650
+ void stopped
2651
+ .catch(() => undefined)
2652
+ .finally(() => {
2653
+ if (entry.key !== undefined && registry().get(entry.key) === entry) {
2654
+ registry().delete(entry.key);
2655
+ }
2656
+ undrain(entry);
2657
+ release();
2658
+ });
2659
+ let timer;
2660
+ const gaveUp = new Promise((resolve) => {
2661
+ timer = setTimeout(() => resolve(true), CLOSE_WAITS_FOR_OPEN_MS);
2662
+ });
2663
+ const late = await Promise.race([stopped.then(() => false), gaveUp]);
2664
+ clearTimeout(timer);
2665
+ if (!late)
2666
+ return;
2667
+ early.abandon(new Error("createJazz: closed before its store opened"));
2668
+ console.warn(`jazz: close() gave up after ${CLOSE_WAITS_FOR_OPEN_MS / 1000}s waiting for ${entry.key ?? "its store"} to open; it closes once it has`);
2669
+ }
2670
+ async function reloadEntry(entry, opened) {
2671
+ const options = entry.options;
2672
+ try {
2673
+ await opened.reload(options);
2674
+ entry.applied = options;
2675
+ }
2676
+ finally {
2677
+ entry.reloading = undefined;
2678
+ }
2679
+ }
2680
+ /** The entry's open Jazz when nothing is left to apply, without waiting. */
2681
+ function settledNow(entry) {
2682
+ return !entry.closing && entry.applied === entry.options ? entry.opened : undefined;
2683
+ }
2684
+ /**
2685
+ * A socket handed over before the store opened: it keeps what arrives until
2686
+ * the session takes it over, so no message is lost while it waits. Past
2687
+ * `MAX_HELD_SOCKET_BYTES` held, it is closed (1013, try again later).
2688
+ */
2689
+ function heldSocket(ws) {
2690
+ const held = [];
2691
+ let heldBytes = 0;
2692
+ let listeners = null;
2693
+ const deliver = (event) => {
2694
+ if (!listeners) {
2695
+ if (event[0] === "message") {
2696
+ heldBytes += byteLength(event[1]);
2697
+ if (heldBytes > MAX_HELD_SOCKET_BYTES) {
2698
+ held.length = 0;
2699
+ ws.close(1013, "store still opening");
2700
+ return;
2701
+ }
2702
+ }
2703
+ return void held.push(event);
2704
+ }
2705
+ if (event[0] === "message")
2706
+ listeners.message?.(event[1], event[2]);
2707
+ else if (event[0] === "close")
2708
+ listeners.close?.();
2709
+ else
2710
+ listeners.error?.(event[1]);
2711
+ };
2712
+ ws.on("message", (data, isBinary) => deliver(["message", data, isBinary]));
2713
+ ws.on("close", () => deliver(["close"]));
2714
+ ws.on("error", (error) => deliver(["error", error]));
2715
+ const socket = {
2716
+ send: (data) => ws.send(data),
2717
+ close: (code, reason) => ws.close(code, reason),
2718
+ pause: () => ws.pause?.(),
2719
+ resume: () => ws.resume?.(),
2720
+ on(event, listener) {
2721
+ const first = listeners === null;
2722
+ listeners ??= {};
2723
+ listeners[event] = listener;
2724
+ // The session adds its listeners in one go: replay once it has.
2725
+ if (first) {
2726
+ queueMicrotask(() => {
2727
+ for (const event of held.splice(0))
2728
+ deliver(event);
2729
+ });
2730
+ }
2731
+ return socket;
2732
+ },
2733
+ };
2734
+ return { socket, refuse: (reason) => ws.close(1011, reason) };
2735
+ }
2736
+ function byteLength(data) {
2737
+ if (typeof data === "string")
2738
+ return data.length * 3;
2739
+ if (Array.isArray(data))
2740
+ return data.reduce((sum, part) => sum + byteLength(part), 0);
2741
+ const sized = data;
2742
+ return typeof sized?.byteLength === "number" ? sized.byteLength : 0;
2743
+ }
2744
+ /**
2745
+ * A remote core that could not be reached, named, instead of the bare
2746
+ * `fetch failed` the request saw. The next use of this Jazz tries again.
2747
+ */
2748
+ function unreachableCore(url, error) {
2749
+ const cause = error?.cause;
2750
+ if (!(error instanceof TypeError) || !cause)
2751
+ return error;
2752
+ const why = typeof cause.code === "string" ? cause.code : String(cause.message ?? error.message);
2753
+ return new Error(`createJazz: could not reach the Jazz core at ${url} (${why}); this Jazz tries again on its next use`, { cause: error });
2754
+ }
2755
+ async function socketUpgrader() {
2756
+ const { WebSocketServer } = (await import("ws"));
2757
+ return new WebSocketServer({ noServer: true, maxPayload: MAX_STREAM_MESSAGE_BYTES });
2758
+ }
2759
+ /** A sync socket's path below `basePath`. */
2760
+ const SOCKET_PATH = /^\/apps\/[^/]+\/ws$/;
2761
+ /** Whether an upgrade's URL is a sync socket of this Jazz (`<basePath>/apps/<app>/ws`). */
2762
+ function isSocketUpgrade(url, basePath) {
2763
+ const pathname = requestPathname(url);
2764
+ return (pathname !== null &&
2765
+ pathname.startsWith(`${basePath}/`) &&
2766
+ SOCKET_PATH.test(pathname.slice(basePath.length)));
2767
+ }
2768
+ /** A Node request's path, or null for one no URL can be made of: not Jazz's. */
2769
+ function requestPathname(url) {
2770
+ try {
2771
+ return new URL(url ?? "/", "http://localhost").pathname;
2772
+ }
2773
+ catch {
2774
+ return null;
2775
+ }
2776
+ }
2777
+ /**
2778
+ * Whether `server` is an HTTP/2 server that can't serve HTTP/1: one without
2779
+ * upgrades (h2c, or TLS without `allowHTTP1`). Node keeps the options under
2780
+ * a symbol; a server that hides them is taken as able.
2781
+ */
2782
+ function http2Only(server) {
2783
+ const name = server.constructor?.name;
2784
+ if (name === "Http2Server")
2785
+ return true;
2786
+ if (name !== "Http2SecureServer")
2787
+ return false;
2788
+ const key = Object.getOwnPropertySymbols(server).find((symbol) => symbol.description === "options");
2789
+ const options = key
2790
+ ? server[key]
2791
+ : undefined;
2792
+ return options !== undefined && options.allowHTTP1 !== true;
2793
+ }
2794
+ /**
2795
+ * What a 503 tells the client to wait: until the store is tried again. The
2796
+ * reason stays in the backend's logs; it can name internal hosts.
2797
+ */
2798
+ function retryAfterSeconds(entry) {
2799
+ const at = entry.failure?.retryAt;
2800
+ return at === undefined ? 1 : Math.max(1, Math.ceil((at - Date.now()) / 1000));
2801
+ }
2802
+ const UNAVAILABLE_BODY = "Jazz is unavailable; try again shortly";
2803
+ /**
2804
+ * The 503 a Jazz route answers while its store can't open, or after it
2805
+ * closed. After a close it also closes the connection: a host shutting down
2806
+ * (`next start` on SIGTERM) waits for its keep-alive connections, and a
2807
+ * client re-opening its sync stream over one would keep it, and the
2808
+ * process, alive. (A Fetch response can't tell an HTTP/2 host, which drops
2809
+ * the header with a warning; nodeHandler leaves it off there.)
2810
+ */
2811
+ function storeUnavailable(retryAfter, closed) {
2812
+ return new Response(UNAVAILABLE_BODY, {
2813
+ status: 503,
2814
+ headers: {
2815
+ "content-type": "text/plain",
2816
+ "retry-after": String(retryAfter),
2817
+ ...(closed ? { connection: "close" } : {}),
2818
+ },
2819
+ });
2820
+ }
2821
+ const storeUnavailableUpgrade = (retryAfter) => `HTTP/1.1 503 Service Unavailable\r\nRetry-After: ${retryAfter}\r\nConnection: close\r\n\r\n`;
2822
+ const BAD_UPGRADE = "HTTP/1.1 400 Bad Request\r\nConnection: close\r\n\r\n";
2823
+ /** The `Jazz` every `createJazz` for one store returns. */
2824
+ function facade(entry) {
2825
+ const use = () => settled(entry);
2826
+ const basePath = () => jazzSettings(entry.options).basePath;
2827
+ // After close() its routes answer 503 as the host shuts down: no news.
2828
+ const logUnavailable = (error) => {
2829
+ if (!entry.closing)
2830
+ console.error("jazz: the store did not open", error);
2831
+ };
2832
+ /** The open Jazz, or the 503 a Jazz route answers while its store can't open. */
2833
+ const useOr503 = async () => {
2834
+ try {
2835
+ return await use();
2836
+ }
2837
+ catch (error) {
2838
+ logUnavailable(error);
2839
+ return storeUnavailable(retryAfterSeconds(entry), entry.closing !== undefined);
2840
+ }
2841
+ };
2842
+ const handle = async (request) => {
2843
+ const opened = await useOr503();
2844
+ return opened instanceof Response ? opened : opened.handle(request);
2845
+ };
2846
+ const nextHandler = async (request) => {
2847
+ const opened = await useOr503();
2848
+ return opened instanceof Response ? opened : opened.next().GET(request);
2849
+ };
2850
+ // The writes made before a close still apply as it drains them.
2851
+ const early = earlyDb(async () => (await settled(entry, true)).db, () => settledNow(entry)?.db);
2852
+ const db = early.db;
2853
+ let heldSockets = 0;
2854
+ /** The servers `attach()` took the upgrades of: a second call changes nothing. */
2855
+ const attachedTo = new WeakSet();
2856
+ const jazz = {
2857
+ get basePath() {
2858
+ return basePath();
2859
+ },
2860
+ handle,
2861
+ next: () => ({ GET: nextHandler, POST: nextHandler, DELETE: nextHandler }),
2862
+ async attach(server) {
2863
+ // An HTTP/2 server without HTTP/1 never sees a WebSocket upgrade.
2864
+ if (http2Only(server)) {
2865
+ throw new Error("attach(): an HTTP/2 server has no WebSocket upgrades; pass an HTTP/1 server (or an HTTPS one with allowHTTP1), or serve Jazz with handle() alone, over its HTTP stream");
2866
+ }
2867
+ if (attachedTo.has(server))
2868
+ return;
2869
+ attachedTo.add(server);
2870
+ const wss = await socketUpgrader();
2871
+ // Upgrades work from now on, opened or not: the store opens on the
2872
+ // first socket (or request), and one that can't open is refused with
2873
+ // a 503 the client retries, instead of failing the host's startup.
2874
+ entry.attached = true;
2875
+ entry.opened?.markAttached();
2876
+ const take = (opened, req, socket, head) => {
2877
+ try {
2878
+ opened.upgrade(wss, req, socket, head);
2879
+ }
2880
+ catch (error) {
2881
+ console.error("jazz: a socket upgrade failed", error);
2882
+ socket.destroy();
2883
+ }
2884
+ };
2885
+ const upgradeJazz = (req, socket, head) => {
2886
+ const now = settledNow(entry);
2887
+ if (now)
2888
+ return take(now, req, socket, head);
2889
+ use().then((opened) => take(opened, req, socket, head), (error) => {
2890
+ logUnavailable(error);
2891
+ socket.end(storeUnavailableUpgrade(retryAfterSeconds(entry)));
2892
+ });
2893
+ };
2894
+ const events = server;
2895
+ // Jazz's own sync sockets go to Jazz alone: another upgrade listener
2896
+ // on the server (a custom Next.js server adds one on its first
2897
+ // request) would take the same socket too, and close it. The listener
2898
+ // is there because Node only emits upgrades to a server that has one.
2899
+ events.on("upgrade", () => undefined);
2900
+ const emit = events.emit;
2901
+ events.emit = function (event, ...args) {
2902
+ if (event === "upgrade" && isSocketUpgrade(args[0].url, basePath())) {
2903
+ upgradeJazz(...args);
2904
+ return true;
2905
+ }
2906
+ return emit.call(this, event, ...args);
2907
+ };
2908
+ events.on("close", () => wss.close());
2909
+ },
2910
+ nodeHandler(req, res, next) {
2911
+ const now = settledNow(entry);
2912
+ if (now)
2913
+ return now.nodeHandler(req, res, next);
2914
+ const prefix = basePath();
2915
+ const pathname = requestPathname(req.url);
2916
+ // Requests Jazz doesn't serve pass on without opening the store.
2917
+ if (pathname === null || (pathname !== prefix && !pathname.startsWith(`${prefix}/`))) {
2918
+ if (next)
2919
+ return next();
2920
+ res.statusCode = 404;
2921
+ res.end();
2922
+ return;
2923
+ }
2924
+ use().then((opened) => opened.nodeHandler(req, res, next), (error) => {
2925
+ logUnavailable(error);
2926
+ res.statusCode = 503;
2927
+ res.setHeader("retry-after", String(retryAfterSeconds(entry)));
2928
+ // HTTP/2 has no Connection header (Node warns and drops it).
2929
+ if (entry.closing && req.httpVersionMajor < 2)
2930
+ res.setHeader("connection", "close");
2931
+ res.setHeader("content-type", "text/plain");
2932
+ res.end(UNAVAILABLE_BODY);
2933
+ });
2934
+ },
2935
+ acceptSocket(request, ws) {
2936
+ const now = settledNow(entry);
2937
+ if (now)
2938
+ return now.acceptSocket(request, ws);
2939
+ if (heldSockets >= MAX_HELD_SOCKETS)
2940
+ return ws.close(1013, "store still opening");
2941
+ heldSockets++;
2942
+ const { socket, refuse } = heldSocket(ws);
2943
+ use()
2944
+ .then((opened) => opened.acceptSocket(request, socket), (error) => {
2945
+ logUnavailable(error);
2946
+ refuse("store unavailable");
2947
+ })
2948
+ .finally(() => heldSockets--);
2949
+ },
2950
+ db,
2951
+ forReqUser: async (request) => (await use()).forReqUser(request),
2952
+ withAttribution: async (request) => (await use()).withAttribution(request),
2953
+ accountFor: async (request) => (await use()).accountFor(request),
2954
+ createAccountFor: async (userId) => (await use()).createAccountFor(userId),
2955
+ revokeUser: async (userId) => (await use()).revokeUser(userId),
2956
+ linkIdentity: async (link) => (await use()).linkIdentity(link),
2957
+ async ready() {
2958
+ await use();
2959
+ return jazz;
2960
+ },
2961
+ close() {
2962
+ return (entry.closing ??= closeEntry(entry, early));
2963
+ },
2964
+ };
2965
+ // Not enumerable, so printing or comparing a Jazz before it opens reads it not.
2966
+ Object.defineProperty(jazz, "appId", {
2967
+ get() {
2968
+ const opened = entry.opened;
2969
+ if (!opened) {
2970
+ throw new Error("jazz.appId is known once the store has opened: `await jazz.ready()` first");
2971
+ }
2972
+ return opened.appId;
2973
+ },
2974
+ });
2975
+ return jazz;
2976
+ }
2977
+ /** An account request the core answered with a 4xx: a refusal, not an outage. */
2978
+ function isRefusal(error) {
2979
+ const status = error?.status;
2980
+ // Timeouts and throttling are 4xx too, but pass.
2981
+ if (status === 408 || status === 425 || status === 429)
2982
+ return false;
2983
+ return typeof status === "number" && status >= 400 && status < 500;
2984
+ }
2985
+ function refusalCode(error) {
2986
+ const message = error instanceof Error ? error.message : "";
2987
+ const code = /: ([a-z_]{1,80})$/.exec(message)?.[1];
2988
+ return code ?? "refused";
2989
+ }
2990
+ /** A WireFrame::Error batch with code AuthFailed and retry Never. */
2991
+ /**
2992
+ * The error a session sends its client when the expiry its app's auth gave
2993
+ * it is near: `auth_failed` with `after_resume` retry, which a client takes
2994
+ * as "connect again now" (`isReauthenticateWireError`). A client that
2995
+ * doesn't know it takes it as a refused credential and asks its backend.
2996
+ */
2997
+ function reauthenticateBatch() {
2998
+ const frame = new PostcardWriter();
2999
+ frame.u64(1); // WireFrame::Error
3000
+ frame.u64(3); // WireErrorCode::AuthFailed
3001
+ frame.u64(2); // WireRetry::AfterResume
3002
+ frame.string(`${REAUTHENTICATE_WIRE_MESSAGE_PREFIX} the session reached the expiry authenticate gave it`);
3003
+ return Buffer.from(encodeWebSocketFrameBatch([frame.finish()]));
3004
+ }
3005
+ function authFailedBatch(message) {
3006
+ const frame = new PostcardWriter();
3007
+ frame.u64(1); // WireFrame::Error
3008
+ frame.u64(3); // WireErrorCode::AuthFailed
3009
+ frame.u64(0); // WireRetry::Never
3010
+ frame.string(message);
3011
+ return Buffer.from(encodeWebSocketFrameBatch([frame.finish()]));
3012
+ }
3013
+ /** A development endpoint on this machine, where header-derived audiences are fine. */
3014
+ function isLocalEndpoint(endpoint) {
3015
+ try {
3016
+ const host = new URL(endpoint).hostname;
3017
+ return (host === "localhost" ||
3018
+ host.endsWith(".localhost") ||
3019
+ host === "127.0.0.1" ||
3020
+ host === "[::1]");
3021
+ }
3022
+ catch {
3023
+ return false;
3024
+ }
3025
+ }
3026
+ //# sourceMappingURL=create-jazz.js.map