on-zero 0.7.1 → 0.7.2-1784530701923

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 (297) hide show
  1. package/dist/cjs/helpers/createMutators.cjs +4 -3
  2. package/dist/cjs/helpers/createMutators.native.js +6 -3
  3. package/dist/cjs/helpers/createMutators.native.js.map +1 -1
  4. package/dist/cjs/httpPull/transport.test.cjs +109 -0
  5. package/dist/cjs/httpPull/transport.test.native.js +148 -0
  6. package/dist/cjs/httpPull/transport.test.native.js.map +1 -1
  7. package/dist/cjs/httpPullTransport.cjs +41 -24
  8. package/dist/cjs/httpPullTransport.native.js +47 -26
  9. package/dist/cjs/httpPullTransport.native.js.map +1 -1
  10. package/dist/cjs/index.cjs +0 -1
  11. package/dist/cjs/index.native.js +0 -1
  12. package/dist/cjs/index.native.js.map +1 -1
  13. package/dist/cjs/mutations.cjs +5 -1
  14. package/dist/cjs/mutations.native.js +5 -1
  15. package/dist/cjs/mutations.native.js.map +1 -1
  16. package/dist/cjs/mutations.test.cjs +28 -0
  17. package/dist/cjs/mutations.test.native.js +40 -0
  18. package/dist/cjs/mutations.test.native.js.map +1 -0
  19. package/dist/cjs/orez.cjs +227 -0
  20. package/dist/cjs/orez.native.js +314 -0
  21. package/dist/cjs/orez.native.js.map +1 -0
  22. package/dist/cjs/orez.test.cjs +211 -0
  23. package/dist/cjs/orez.test.native.js +226 -0
  24. package/dist/cjs/orez.test.native.js.map +1 -0
  25. package/dist/cjs/run.cjs +1 -1
  26. package/dist/cjs/run.native.js +1 -1
  27. package/dist/cjs/state.cjs +1 -1
  28. package/dist/cjs/state.native.js +1 -1
  29. package/dist/cjs/zeroRunner.cjs +1 -1
  30. package/dist/cjs/zeroRunner.native.js +1 -1
  31. package/dist/esm/helpers/createMutators.mjs +4 -3
  32. package/dist/esm/helpers/createMutators.mjs.map +1 -1
  33. package/dist/esm/helpers/createMutators.native.js +6 -3
  34. package/dist/esm/helpers/createMutators.native.js.map +1 -1
  35. package/dist/esm/httpPull/transport.test.mjs +109 -0
  36. package/dist/esm/httpPull/transport.test.mjs.map +1 -1
  37. package/dist/esm/httpPull/transport.test.native.js +148 -0
  38. package/dist/esm/httpPull/transport.test.native.js.map +1 -1
  39. package/dist/esm/httpPullTransport.mjs +41 -24
  40. package/dist/esm/httpPullTransport.mjs.map +1 -1
  41. package/dist/esm/httpPullTransport.native.js +47 -26
  42. package/dist/esm/httpPullTransport.native.js.map +1 -1
  43. package/dist/esm/index.js +0 -1
  44. package/dist/esm/index.js.map +1 -1
  45. package/dist/esm/index.mjs +0 -1
  46. package/dist/esm/index.mjs.map +1 -1
  47. package/dist/esm/index.native.js +0 -1
  48. package/dist/esm/index.native.js.map +1 -1
  49. package/dist/esm/mutations.mjs +5 -1
  50. package/dist/esm/mutations.mjs.map +1 -1
  51. package/dist/esm/mutations.native.js +5 -1
  52. package/dist/esm/mutations.native.js.map +1 -1
  53. package/dist/esm/mutations.test.mjs +29 -0
  54. package/dist/esm/mutations.test.mjs.map +1 -0
  55. package/dist/esm/mutations.test.native.js +38 -0
  56. package/dist/esm/mutations.test.native.js.map +1 -0
  57. package/dist/esm/orez.mjs +202 -0
  58. package/dist/esm/orez.mjs.map +1 -0
  59. package/dist/esm/orez.native.js +286 -0
  60. package/dist/esm/orez.native.js.map +1 -0
  61. package/dist/esm/orez.test.mjs +188 -0
  62. package/dist/esm/orez.test.mjs.map +1 -0
  63. package/dist/esm/orez.test.native.js +200 -0
  64. package/dist/esm/orez.test.native.js.map +1 -0
  65. package/dist/esm/run.mjs +1 -1
  66. package/dist/esm/run.mjs.map +1 -1
  67. package/dist/esm/run.native.js +1 -1
  68. package/dist/esm/state.mjs +1 -1
  69. package/dist/esm/state.native.js +1 -1
  70. package/dist/esm/zeroRunner.mjs +1 -1
  71. package/dist/esm/zeroRunner.mjs.map +1 -1
  72. package/dist/esm/zeroRunner.native.js +1 -1
  73. package/package.json +8 -23
  74. package/readme.md +42 -67
  75. package/src/createZeroClient.tsx +1 -1
  76. package/src/helpers/createMutators.ts +6 -2
  77. package/src/httpPull/transport.test.ts +132 -0
  78. package/src/httpPullTransport.ts +74 -42
  79. package/src/index.ts +0 -1
  80. package/src/mutations.test.ts +38 -0
  81. package/src/mutations.ts +10 -2
  82. package/src/orez.test.ts +195 -0
  83. package/src/orez.ts +331 -0
  84. package/src/run.ts +1 -1
  85. package/src/state.ts +1 -1
  86. package/src/types.ts +0 -5
  87. package/src/zeroRunner.ts +1 -1
  88. package/test-fixtures/server-return-types.ts +21 -58
  89. package/types/helpers/createMutators.d.ts +2 -1
  90. package/types/helpers/createMutators.d.ts.map +1 -1
  91. package/types/httpPull/fixtureSchema.d.ts +1 -1
  92. package/types/httpPullTransport.d.ts +14 -1
  93. package/types/httpPullTransport.d.ts.map +1 -1
  94. package/types/index.d.ts +0 -1
  95. package/types/index.d.ts.map +1 -1
  96. package/types/mutations.d.ts.map +1 -1
  97. package/types/mutations.test.d.ts +2 -0
  98. package/types/mutations.test.d.ts.map +1 -0
  99. package/types/orez.d.ts +53 -0
  100. package/types/orez.d.ts.map +1 -0
  101. package/types/orez.test.d.ts +2 -0
  102. package/types/orez.test.d.ts.map +1 -0
  103. package/types/types.d.ts +0 -4
  104. package/types/types.d.ts.map +1 -1
  105. package/dist/cjs/asyncTasks.cjs +0 -51
  106. package/dist/cjs/asyncTasks.native.js +0 -84
  107. package/dist/cjs/asyncTasks.native.js.map +0 -1
  108. package/dist/cjs/createZeroDirectServer.cjs +0 -269
  109. package/dist/cjs/createZeroDirectServer.native.js +0 -287
  110. package/dist/cjs/createZeroDirectServer.native.js.map +0 -1
  111. package/dist/cjs/createZeroSQLiteServer.cjs +0 -50
  112. package/dist/cjs/createZeroSQLiteServer.native.js +0 -58
  113. package/dist/cjs/createZeroSQLiteServer.native.js.map +0 -1
  114. package/dist/cjs/createZeroSQLiteServer.test.cjs +0 -553
  115. package/dist/cjs/createZeroSQLiteServer.test.native.js +0 -602
  116. package/dist/cjs/createZeroSQLiteServer.test.native.js.map +0 -1
  117. package/dist/cjs/createZeroServer.cjs +0 -82
  118. package/dist/cjs/createZeroServer.native.js +0 -93
  119. package/dist/cjs/createZeroServer.native.js.map +0 -1
  120. package/dist/cjs/createZeroServer.test.cjs +0 -378
  121. package/dist/cjs/createZeroServer.test.native.js +0 -448
  122. package/dist/cjs/createZeroServer.test.native.js.map +0 -1
  123. package/dist/cjs/createZeroServerCore.cjs +0 -211
  124. package/dist/cjs/createZeroServerCore.native.js +0 -355
  125. package/dist/cjs/createZeroServerCore.native.js.map +0 -1
  126. package/dist/cjs/httpPull/auth.test.cjs +0 -197
  127. package/dist/cjs/httpPull/auth.test.native.js +0 -279
  128. package/dist/cjs/httpPull/auth.test.native.js.map +0 -1
  129. package/dist/cjs/httpPull/churn.test.cjs +0 -132
  130. package/dist/cjs/httpPull/churn.test.native.js +0 -155
  131. package/dist/cjs/httpPull/churn.test.native.js.map +0 -1
  132. package/dist/cjs/httpPull/completeAck.test.cjs +0 -69
  133. package/dist/cjs/httpPull/completeAck.test.native.js +0 -76
  134. package/dist/cjs/httpPull/completeAck.test.native.js.map +0 -1
  135. package/dist/cjs/httpPull/fixtureServer.cjs +0 -340
  136. package/dist/cjs/httpPull/fixtureServer.native.js +0 -534
  137. package/dist/cjs/httpPull/fixtureServer.native.js.map +0 -1
  138. package/dist/cjs/httpPull/integration.test.cjs +0 -53
  139. package/dist/cjs/httpPull/integration.test.native.js +0 -60
  140. package/dist/cjs/httpPull/integration.test.native.js.map +0 -1
  141. package/dist/cjs/httpPull/rebase.test.cjs +0 -360
  142. package/dist/cjs/httpPull/rebase.test.native.js +0 -420
  143. package/dist/cjs/httpPull/rebase.test.native.js.map +0 -1
  144. package/dist/cjs/httpPull/relations.test.cjs +0 -107
  145. package/dist/cjs/httpPull/relations.test.native.js +0 -119
  146. package/dist/cjs/httpPull/relations.test.native.js.map +0 -1
  147. package/dist/cjs/httpPull/testHarness.cjs +0 -100
  148. package/dist/cjs/httpPull/testHarness.native.js +0 -112
  149. package/dist/cjs/httpPull/testHarness.native.js.map +0 -1
  150. package/dist/cjs/server.cjs +0 -22
  151. package/dist/cjs/server.native.js +0 -4
  152. package/dist/cjs/server.native.js.map +0 -1
  153. package/dist/cjs/sqliteRuntime.cjs +0 -318
  154. package/dist/cjs/sqliteRuntime.native.js +0 -438
  155. package/dist/cjs/sqliteRuntime.native.js.map +0 -1
  156. package/dist/cjs/syncHost.cjs +0 -179
  157. package/dist/cjs/syncHost.native.js +0 -388
  158. package/dist/cjs/syncHost.native.js.map +0 -1
  159. package/dist/cjs/syncHost.test.cjs +0 -240
  160. package/dist/cjs/syncHost.test.native.js +0 -290
  161. package/dist/cjs/syncHost.test.native.js.map +0 -1
  162. package/dist/esm/asyncTasks.mjs +0 -26
  163. package/dist/esm/asyncTasks.mjs.map +0 -1
  164. package/dist/esm/asyncTasks.native.js +0 -56
  165. package/dist/esm/asyncTasks.native.js.map +0 -1
  166. package/dist/esm/createZeroDirectServer.mjs +0 -241
  167. package/dist/esm/createZeroDirectServer.mjs.map +0 -1
  168. package/dist/esm/createZeroDirectServer.native.js +0 -256
  169. package/dist/esm/createZeroDirectServer.native.js.map +0 -1
  170. package/dist/esm/createZeroSQLiteServer.mjs +0 -24
  171. package/dist/esm/createZeroSQLiteServer.mjs.map +0 -1
  172. package/dist/esm/createZeroSQLiteServer.native.js +0 -29
  173. package/dist/esm/createZeroSQLiteServer.native.js.map +0 -1
  174. package/dist/esm/createZeroSQLiteServer.test.mjs +0 -554
  175. package/dist/esm/createZeroSQLiteServer.test.mjs.map +0 -1
  176. package/dist/esm/createZeroSQLiteServer.test.native.js +0 -600
  177. package/dist/esm/createZeroSQLiteServer.test.native.js.map +0 -1
  178. package/dist/esm/createZeroServer.mjs +0 -57
  179. package/dist/esm/createZeroServer.mjs.map +0 -1
  180. package/dist/esm/createZeroServer.native.js +0 -65
  181. package/dist/esm/createZeroServer.native.js.map +0 -1
  182. package/dist/esm/createZeroServer.test.mjs +0 -379
  183. package/dist/esm/createZeroServer.test.mjs.map +0 -1
  184. package/dist/esm/createZeroServer.test.native.js +0 -446
  185. package/dist/esm/createZeroServer.test.native.js.map +0 -1
  186. package/dist/esm/createZeroServerCore.mjs +0 -186
  187. package/dist/esm/createZeroServerCore.mjs.map +0 -1
  188. package/dist/esm/createZeroServerCore.native.js +0 -327
  189. package/dist/esm/createZeroServerCore.native.js.map +0 -1
  190. package/dist/esm/httpPull/auth.test.mjs +0 -198
  191. package/dist/esm/httpPull/auth.test.mjs.map +0 -1
  192. package/dist/esm/httpPull/auth.test.native.js +0 -277
  193. package/dist/esm/httpPull/auth.test.native.js.map +0 -1
  194. package/dist/esm/httpPull/churn.test.mjs +0 -133
  195. package/dist/esm/httpPull/churn.test.mjs.map +0 -1
  196. package/dist/esm/httpPull/churn.test.native.js +0 -153
  197. package/dist/esm/httpPull/churn.test.native.js.map +0 -1
  198. package/dist/esm/httpPull/completeAck.test.mjs +0 -70
  199. package/dist/esm/httpPull/completeAck.test.mjs.map +0 -1
  200. package/dist/esm/httpPull/completeAck.test.native.js +0 -74
  201. package/dist/esm/httpPull/completeAck.test.native.js.map +0 -1
  202. package/dist/esm/httpPull/fixtureServer.mjs +0 -315
  203. package/dist/esm/httpPull/fixtureServer.mjs.map +0 -1
  204. package/dist/esm/httpPull/fixtureServer.native.js +0 -506
  205. package/dist/esm/httpPull/fixtureServer.native.js.map +0 -1
  206. package/dist/esm/httpPull/integration.test.mjs +0 -54
  207. package/dist/esm/httpPull/integration.test.mjs.map +0 -1
  208. package/dist/esm/httpPull/integration.test.native.js +0 -58
  209. package/dist/esm/httpPull/integration.test.native.js.map +0 -1
  210. package/dist/esm/httpPull/rebase.test.mjs +0 -361
  211. package/dist/esm/httpPull/rebase.test.mjs.map +0 -1
  212. package/dist/esm/httpPull/rebase.test.native.js +0 -418
  213. package/dist/esm/httpPull/rebase.test.native.js.map +0 -1
  214. package/dist/esm/httpPull/relations.test.mjs +0 -108
  215. package/dist/esm/httpPull/relations.test.mjs.map +0 -1
  216. package/dist/esm/httpPull/relations.test.native.js +0 -117
  217. package/dist/esm/httpPull/relations.test.native.js.map +0 -1
  218. package/dist/esm/httpPull/testHarness.mjs +0 -72
  219. package/dist/esm/httpPull/testHarness.mjs.map +0 -1
  220. package/dist/esm/httpPull/testHarness.native.js +0 -81
  221. package/dist/esm/httpPull/testHarness.native.js.map +0 -1
  222. package/dist/esm/server.mjs +0 -4
  223. package/dist/esm/server.mjs.map +0 -1
  224. package/dist/esm/server.native.js +0 -2
  225. package/dist/esm/server.native.js.map +0 -1
  226. package/dist/esm/sqliteRuntime.mjs +0 -289
  227. package/dist/esm/sqliteRuntime.mjs.map +0 -1
  228. package/dist/esm/sqliteRuntime.native.js +0 -406
  229. package/dist/esm/sqliteRuntime.native.js.map +0 -1
  230. package/dist/esm/syncHost.mjs +0 -153
  231. package/dist/esm/syncHost.mjs.map +0 -1
  232. package/dist/esm/syncHost.native.js +0 -359
  233. package/dist/esm/syncHost.native.js.map +0 -1
  234. package/dist/esm/syncHost.test.mjs +0 -217
  235. package/dist/esm/syncHost.test.mjs.map +0 -1
  236. package/dist/esm/syncHost.test.native.js +0 -264
  237. package/dist/esm/syncHost.test.native.js.map +0 -1
  238. package/src/asyncTasks.ts +0 -36
  239. package/src/createZeroDirectServer.ts +0 -411
  240. package/src/createZeroSQLiteServer.test.ts +0 -571
  241. package/src/createZeroSQLiteServer.ts +0 -56
  242. package/src/createZeroServer.test.ts +0 -421
  243. package/src/createZeroServer.ts +0 -105
  244. package/src/createZeroServerCore.ts +0 -296
  245. package/src/httpPull/auth.test.ts +0 -208
  246. package/src/httpPull/churn.test.ts +0 -147
  247. package/src/httpPull/completeAck.test.ts +0 -80
  248. package/src/httpPull/fixtureServer.ts +0 -391
  249. package/src/httpPull/integration.test.ts +0 -57
  250. package/src/httpPull/rebase.test.ts +0 -368
  251. package/src/httpPull/relations.test.ts +0 -135
  252. package/src/httpPull/testHarness.ts +0 -95
  253. package/src/server.native.ts +0 -3
  254. package/src/server.ts +0 -4
  255. package/src/sqliteRuntime.ts +0 -512
  256. package/src/syncHost.test.ts +0 -223
  257. package/src/syncHost.ts +0 -294
  258. package/types/asyncTasks.d.ts +0 -11
  259. package/types/asyncTasks.d.ts.map +0 -1
  260. package/types/createZeroDirectServer.d.ts +0 -80
  261. package/types/createZeroDirectServer.d.ts.map +0 -1
  262. package/types/createZeroSQLiteServer.d.ts +0 -12
  263. package/types/createZeroSQLiteServer.d.ts.map +0 -1
  264. package/types/createZeroSQLiteServer.test.d.ts +0 -2
  265. package/types/createZeroSQLiteServer.test.d.ts.map +0 -1
  266. package/types/createZeroServer.d.ts +0 -18
  267. package/types/createZeroServer.d.ts.map +0 -1
  268. package/types/createZeroServer.test.d.ts +0 -2
  269. package/types/createZeroServer.test.d.ts.map +0 -1
  270. package/types/createZeroServerCore.d.ts +0 -256
  271. package/types/createZeroServerCore.d.ts.map +0 -1
  272. package/types/httpPull/auth.test.d.ts +0 -2
  273. package/types/httpPull/auth.test.d.ts.map +0 -1
  274. package/types/httpPull/churn.test.d.ts +0 -2
  275. package/types/httpPull/churn.test.d.ts.map +0 -1
  276. package/types/httpPull/completeAck.test.d.ts +0 -2
  277. package/types/httpPull/completeAck.test.d.ts.map +0 -1
  278. package/types/httpPull/fixtureServer.d.ts +0 -14
  279. package/types/httpPull/fixtureServer.d.ts.map +0 -1
  280. package/types/httpPull/integration.test.d.ts +0 -2
  281. package/types/httpPull/integration.test.d.ts.map +0 -1
  282. package/types/httpPull/rebase.test.d.ts +0 -2
  283. package/types/httpPull/rebase.test.d.ts.map +0 -1
  284. package/types/httpPull/relations.test.d.ts +0 -2
  285. package/types/httpPull/relations.test.d.ts.map +0 -1
  286. package/types/httpPull/testHarness.d.ts +0 -32
  287. package/types/httpPull/testHarness.d.ts.map +0 -1
  288. package/types/server.d.ts +0 -5
  289. package/types/server.d.ts.map +0 -1
  290. package/types/server.native.d.ts +0 -1
  291. package/types/server.native.d.ts.map +0 -1
  292. package/types/sqliteRuntime.d.ts +0 -71
  293. package/types/sqliteRuntime.d.ts.map +0 -1
  294. package/types/syncHost.d.ts +0 -42
  295. package/types/syncHost.d.ts.map +0 -1
  296. package/types/syncHost.test.d.ts +0 -2
  297. package/types/syncHost.test.d.ts.map +0 -1
package/readme.md CHANGED
@@ -501,77 +501,57 @@ export const { ProvideZero, useQuery, zero, usePermission } = createZeroClient({
501
501
  </ProvideZero>
502
502
  ```
503
503
 
504
- server:
504
+ server bindings:
505
505
 
506
506
  ```ts
507
- import { createZeroServer } from 'on-zero/server'
507
+ import { createOrezBindings } from 'on-zero/orez'
508
+ import {
509
+ createPostgreSQLApplicationDatabase,
510
+ createSyncExecutor,
511
+ handleSyncExecutorPushRequest,
512
+ } from 'orez/sync-executor'
508
513
  import { syncedQueries } from '~/data/generated/syncedQueries'
509
514
  import { mutationValidators } from '~/data/generated/syncedMutations'
510
515
 
511
- export const zeroServer = createZeroServer({
516
+ export const zeroBindings = createOrezBindings({
512
517
  schema,
513
518
  models,
514
- database: process.env.DATABASE_URL,
515
- queries: syncedQueries, // required for synced queries / pull endpoint
516
- mutations: mutationValidators, // auto-validates mutation args with valibot
519
+ queries: syncedQueries,
520
+ mutations: mutationValidators,
517
521
  createServerActions: () => ({
518
522
  sendEmail: async (to, subject, body) => { ... }
519
523
  })
520
524
  })
521
525
 
522
- // push endpoint for mutations
523
- app.post('/api/zero/push', async (req) => {
524
- const authData = await getAuthFromRequest(req)
525
- const { response } = await zeroServer.handleMutationRequest({
526
- authData,
527
- request: req,
528
- scheduleBackgroundTask: (promise) => host.waitUntil(promise)
529
- })
530
- return response
531
- })
532
-
533
- // pull endpoint for synced queries
534
- app.post('/api/zero/pull', async (req) => {
535
- const authData = await getAuthFromRequest(req)
536
- const { response } = await zeroServer.handleQueryRequest({
537
- authData,
538
- request: req
539
- })
540
- return response
526
+ export const zeroExecutor = createSyncExecutor({
527
+ schema,
528
+ mutators: zeroBindings.mutators,
529
+ database: createPostgreSQLApplicationDatabase(pool, {
530
+ schema,
531
+ internalSchema: 'zero_0',
532
+ }),
533
+ effects: {
534
+ runBackground: (promise) => host.waitUntil(promise),
535
+ report: (error) => console.error(error),
536
+ },
541
537
  })
542
- ```
543
538
 
544
- `scheduleBackgroundTask` is the request host's lifetime hook, such as
545
- Cloudflare Workers' `ctx.waitUntil`. on-zero passes it one promise that settles
546
- after every non-barrier mutator task settles, including when a sibling rejects.
547
- Without a scheduler, `handleMutationRequest` waits for those tasks before it
548
- returns.
539
+ export const zeroServer = zeroBindings.server(zeroExecutor)
549
540
 
550
- SQLite uses the same handler surface through a separate entrypoint that does
551
- not import the PostgreSQL adapter:
552
-
553
- ```ts
554
- import { createZeroSQLiteServer } from 'on-zero/sqlite'
541
+ app.post('/api/zero/push', async (request) => {
542
+ const claims = await getClaimsFromRequest(request)
543
+ return handleSyncExecutorPushRequest({ executor: zeroExecutor, request, claims })
544
+ })
555
545
 
556
- export const zeroServer = createZeroSQLiteServer({
557
- schema,
558
- models,
559
- queries: syncedQueries,
560
- mutations: mutationValidators,
561
- createServerActions: () => ({ ... }),
562
- transactionProvider: (callback) =>
563
- storage.transaction(() => callback(sqliteExecutor)),
546
+ app.post('/api/zero/pull', async (request) => {
547
+ const authData = await getAuthFromRequest(request)
548
+ return Response.json(await zeroBindings.transformQueryRequest({ authData, request }))
564
549
  })
565
550
  ```
566
551
 
567
- `sqliteExecutor` implements `exec`, `query`, and `queryAst`. `queryAst` receives
568
- the query format and returns the fully materialized logical result, including
569
- nested relationships and singular shaping. The provider must run the callback
570
- inside the authoritative SQLite transaction. If the storage engine retries the
571
- callback, on-zero discards tasks from the abandoned attempt and returns only
572
- tasks from the committed attempt. The first push creates the `<schema>_clients`
573
- and `<schema>_mutations` ledger tables in that transaction; for example,
574
- `schema=zero_0` creates `zero_0_clients` and `zero_0_mutations`.
552
+ Orez owns the transaction, CRUD SQL, client ledger, replay, and effect
553
+ scheduling. on-zero supplies the mutator registry, auth/query helpers, and typed
554
+ direct-call facade.
575
555
 
576
556
  ### multiple client instances
577
557
 
@@ -631,7 +611,7 @@ constraints:
631
611
  - a mutator may only read/write tables owned by its own instance. its
632
612
  transaction runs on that instance alone; cross-instance writes are not
633
613
  detectable at registration and will silently miss the other store.
634
- - the server stays single: one `createZeroServer` per backend process.
614
+ - the server stays single: one Orez executor and binding registry per database.
635
615
  - omitting `instanceName` keeps the exact single-instance behavior.
636
616
 
637
617
  **guarding the partition against drift.** a generated namespace that ends up in
@@ -659,10 +639,9 @@ assertZeroInstancePartition('model namespace', models, {
659
639
  add custom validation for all queries and mutations:
660
640
 
661
641
  ```ts
662
- export const zeroServer = createZeroServer({
642
+ export const zeroBindings = createOrezBindings({
663
643
  schema,
664
644
  models,
665
- database: process.env.DATABASE_URL,
666
645
  queries: syncedQueries,
667
646
  createServerActions: () => ({ ... }),
668
647
 
@@ -687,9 +666,6 @@ export const zeroServer = createZeroServer({
687
666
  // - 'off': no admin bypass, normal permission checks apply
688
667
  defaultAllowAdminRole: 'all',
689
668
 
690
- // default authData for zeroServer.mutate when none is provided or in scope
691
- // defaults to {}
692
- defaultMutateAuthData: { id: 'system', email: 'system@example.com' },
693
669
  })
694
670
  ```
695
671
 
@@ -700,12 +676,12 @@ generator uses the TypeScript type checker to deeply resolve param types -
700
676
  including imported types, aliases, and cross-file references - then converts them
701
677
  to valibot schemas.
702
678
 
703
- pass the generated `mutationValidators` to `createZeroServer`:
679
+ pass the generated `mutationValidators` to `createOrezBindings`:
704
680
 
705
681
  ```ts
706
682
  import { mutationValidators } from '~/data/generated/syncedMutations'
707
683
 
708
- export const zeroServer = createZeroServer({
684
+ export const zeroBindings = createOrezBindings({
709
685
  // ...
710
686
  mutations: mutationValidators,
711
687
  })
@@ -838,8 +814,8 @@ therefore reuse the same WebSocket shim instead of chaining installations.
838
814
  Every socket lifecycle event carries stable `pageID`, `transportID`,
839
815
  `zeroInstanceID`, `clientGroupID`, `connectionAttemptID`, and `socketID` fields,
840
816
  plus Zero's `clientID` / `wsid`, the socket generation, and attempt age. on-zero
841
- logs each event as one `[on-zero:http-pull]` JSON line by default. Pass
842
- `lifecycle(event)` to collect the same events yourself instead.
817
+ logs failures as `[on-zero:http-pull]` JSON lines by default. Pass
818
+ `lifecycle(event)` to collect every event yourself instead.
843
819
 
844
820
  `close`, `superseded`, and `aborted` are mutually exclusive terminal events for
845
821
  one socket generation. An attempt whose Zero `ts` is already beyond the stock
@@ -963,21 +939,17 @@ await zeroServer.mutate.user.insert(user)
963
939
  // with explicit auth (optional - authData auto-resolves from context)
964
940
  await zeroServer.mutate.user.insert(user, { authData: { id: userId, email } })
965
941
 
966
- // await async tasks (effects) before returning
967
- await zeroServer.mutate.user.insert(user, { awaitEffects: true })
968
942
  ```
969
943
 
970
944
  the second argument is an options object:
971
945
 
972
946
  - `authData` — override auth for this call (optional, auto-resolves from context)
973
- - `awaitEffects` — if `true`, awaits async tasks before returning (default: fire-and-forget)
974
947
 
975
948
  authData is automatically resolved in this order:
976
949
 
977
950
  1. explicit `authData` in options (if passed)
978
951
  2. current mutation context (inside a mutation)
979
952
  3. auth scope (inside async tasks - automatically inherited)
980
- 4. `defaultMutateAuthData` from `createZeroServer` config (defaults to `{}`)
981
953
 
982
954
  **one-off queries with `run()`:**
983
955
 
@@ -1046,7 +1018,10 @@ useful for prefetching data before navigation to avoid loading states.
1046
1018
  for ad-hoc queries that don't use query functions:
1047
1019
 
1048
1020
  ```ts
1049
- const user = await zeroServer.query((q) => q.user.where('id', userId).one())
1021
+ const user = await zeroServer.query(
1022
+ { userID: userId },
1023
+ (q) => q.user.where('id', userId).one(),
1024
+ )
1050
1025
  ```
1051
1026
 
1052
1027
  **controlling queries with `ControlQueries`:**
@@ -144,7 +144,7 @@ export function createZeroClientInternal<
144
144
  setSchema(schema, createBuilder(schema))
145
145
 
146
146
  // only set environment to 'client' if server hasn't already claimed it
147
- // (during SSR, createZeroServer runs first and sets 'server')
147
+ // server bindings may set this first during SSR
148
148
  if (getEnvironment() === null) {
149
149
  setEnvironment('client')
150
150
  }
@@ -30,6 +30,7 @@ export function createMutators<Models extends GenericModels>({
30
30
  models,
31
31
  validateMutation,
32
32
  mutationValidators,
33
+ resolveAuthData,
33
34
  }: {
34
35
  environment: 'server' | 'client'
35
36
  authData: AuthData | null
@@ -40,6 +41,7 @@ export function createMutators<Models extends GenericModels>({
40
41
  validateMutation?: ValidateMutationFn
41
42
  /** valibot schemas keyed by model.mutationName, auto-validates args before running */
42
43
  mutationValidators?: Record<string, Record<string, any>>
44
+ resolveAuthData?: () => AuthData | null
43
45
  }): GetZeroMutators<Models> {
44
46
  const serverActions = createServerActions?.()
45
47
 
@@ -54,7 +56,8 @@ export function createMutators<Models extends GenericModels>({
54
56
  tx,
55
57
  // on client, read authData dynamically to avoid stale closure during auth transitions
56
58
  // (ZeroProvider recreates Zero instance in useEffect, but mutations can run before that)
57
- authData: environment === 'client' ? getAuthData() : authData,
59
+ authData:
60
+ environment === 'client' ? getAuthData() : (resolveAuthData?.() ?? authData),
58
61
  environment,
59
62
  can,
60
63
  server:
@@ -168,7 +171,8 @@ export function createMutators<Models extends GenericModels>({
168
171
  // then run user-provided validation hook as escape hatch
169
172
  if (validateMutation) {
170
173
  await validateMutation({
171
- authData: environment === 'client' ? getAuthData() : authData,
174
+ authData:
175
+ environment === 'client' ? getAuthData() : (resolveAuthData?.() ?? authData),
172
176
  tableName,
173
177
  mutatorName,
174
178
  args: args[1],
@@ -20,10 +20,13 @@ type RequestRecord = {
20
20
  const zeros: Zero<any, any>[] = []
21
21
  const transports: Array<{ uninstall(): void }> = []
22
22
  let storageID = 0
23
+ let restoreNativeWebSocket: (() => void) | undefined
23
24
 
24
25
  afterEach(async () => {
25
26
  while (zeros.length) await zeros.pop()?.close()
26
27
  while (transports.length) transports.pop()?.uninstall()
28
+ restoreNativeWebSocket?.()
29
+ restoreNativeWebSocket = undefined
27
30
  vi.useRealTimers()
28
31
  })
29
32
 
@@ -662,6 +665,90 @@ describe('zero-http transport', () => {
662
665
  expect(errors).toEqual([])
663
666
  })
664
667
 
668
+ test('authenticated wake appends a freshly minted token when the socket opens', async () => {
669
+ const wakeSockets = useFakeNativeWebSocket()
670
+ const getToken = vi.fn(async () => 'signed token&scope=one')
671
+ const fetch = unchangedPullFetch()
672
+ const transport = installHttpPullTransport({
673
+ origin: ORIGIN,
674
+ fetch,
675
+ wake: { getToken },
676
+ })
677
+ transports.push(transport)
678
+
679
+ openRawSocketWithMessages()
680
+
681
+ await eventually(() => expect(wakeSockets).toHaveLength(1))
682
+ expect(getToken).toHaveBeenCalledTimes(1)
683
+ expect(wakeSockets[0].url).toBe(
684
+ 'wss://zero-http.local/wake?clientID=c1&wakeToken=signed%20token%26scope%3Done',
685
+ )
686
+ })
687
+
688
+ test('authenticated wake gets a fresh token for every reconnect attempt', async () => {
689
+ const wakeSockets = useFakeNativeWebSocket()
690
+ const getToken = vi
691
+ .fn<() => Promise<string>>()
692
+ .mockResolvedValueOnce('wake-token-1')
693
+ .mockResolvedValueOnce('wake-token-2')
694
+ const transport = installHttpPullTransport({
695
+ origin: ORIGIN,
696
+ fetch: unchangedPullFetch(),
697
+ wake: { getToken },
698
+ })
699
+ transports.push(transport)
700
+
701
+ openRawSocketWithMessages()
702
+ await eventually(() => expect(wakeSockets).toHaveLength(1))
703
+ wakeSockets[0].onerror?.()
704
+
705
+ await eventually(() => expect(wakeSockets).toHaveLength(2), 1_000)
706
+ expect(getToken).toHaveBeenCalledTimes(2)
707
+ expect(wakeSockets.map((socket) => socket.url)).toEqual([
708
+ 'wss://zero-http.local/wake?clientID=c1&wakeToken=wake-token-1',
709
+ 'wss://zero-http.local/wake?clientID=c1&wakeToken=wake-token-2',
710
+ ])
711
+ })
712
+
713
+ test('wake token rejection leaves pulls healthy and retries the advisory channel', async () => {
714
+ const wakeSockets = useFakeNativeWebSocket()
715
+ const getToken = vi.fn(async () => {
716
+ throw new Error('mint route unavailable')
717
+ })
718
+ const fetch = unchangedPullFetch()
719
+ const transport = installHttpPullTransport({
720
+ origin: ORIGIN,
721
+ fetch,
722
+ wake: { getToken },
723
+ })
724
+ transports.push(transport)
725
+
726
+ openRawSocketWithMessages()
727
+ await eventually(() => expect(fetch).toHaveBeenCalled())
728
+ const pullsBeforeManualPull = fetch.mock.calls.length
729
+
730
+ await expect(transport.pull()).resolves.toBeUndefined()
731
+ expect(fetch.mock.calls.length).toBeGreaterThan(pullsBeforeManualPull)
732
+ await eventually(() => expect(getToken).toHaveBeenCalledTimes(2), 1_000)
733
+ expect(wakeSockets).toHaveLength(0)
734
+ expect(transport.connections).toBe(1)
735
+ })
736
+
737
+ test('wake true preserves the bare unauthenticated socket URL', async () => {
738
+ const wakeSockets = useFakeNativeWebSocket()
739
+ const transport = installHttpPullTransport({
740
+ origin: ORIGIN,
741
+ fetch: unchangedPullFetch(),
742
+ wake: true,
743
+ })
744
+ transports.push(transport)
745
+
746
+ openRawSocketWithMessages()
747
+
748
+ await eventually(() => expect(wakeSockets).toHaveLength(1))
749
+ expect(wakeSockets[0].url).toBe('wss://zero-http.local/wake?clientID=c1')
750
+ })
751
+
665
752
  test('non-origin WebSockets pass through to the native implementation', () => {
666
753
  const previous = globalThis.WebSocket
667
754
  class NativeWebSocket {
@@ -832,6 +919,51 @@ function jsonResponse(body: unknown, init?: ResponseInit) {
832
919
  })
833
920
  }
834
921
 
922
+ function unchangedPullFetch() {
923
+ return vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
924
+ const request = recordRequest(input, init)
925
+ expect(request.path).toBe('/pull')
926
+ return jsonResponse({ cookie: request.body.cookie, unchanged: true })
927
+ })
928
+ }
929
+
930
+ function useFakeNativeWebSocket() {
931
+ const previous = globalThis.WebSocket
932
+ const sockets: Array<{
933
+ url: string
934
+ onmessage: (() => void) | null
935
+ onclose: (() => void) | null
936
+ onerror: (() => void) | null
937
+ }> = []
938
+
939
+ class FakeNativeWebSocket {
940
+ static CONNECTING = 0
941
+ static OPEN = 1
942
+ static CLOSING = 2
943
+ static CLOSED = 3
944
+
945
+ readonly url: string
946
+ onmessage: (() => void) | null = null
947
+ onclose: (() => void) | null = null
948
+ onerror: (() => void) | null = null
949
+
950
+ constructor(url: string | URL) {
951
+ this.url = String(url)
952
+ sockets.push(this)
953
+ }
954
+
955
+ close() {
956
+ this.onclose?.()
957
+ }
958
+ }
959
+
960
+ globalThis.WebSocket = FakeNativeWebSocket as unknown as typeof WebSocket
961
+ restoreNativeWebSocket = () => {
962
+ globalThis.WebSocket = previous
963
+ }
964
+ return sockets
965
+ }
966
+
835
967
  async function waitForComplete<T>(view: {
836
968
  addListener(listener: (data: any, resultType: string) => void): () => void
837
969
  }): Promise<T> {
@@ -78,7 +78,7 @@ type TransportState = {
78
78
  readonly nativeWebSocket: WebSocketConstructor | undefined
79
79
  readonly sockets: Set<ZeroHttpSocket>
80
80
  readonly pullIntervalMs: number | undefined
81
- readonly wakeEnabled: boolean
81
+ readonly wake: HttpPullTransportOptions['wake']
82
82
  readonly queryTransform: QueryTransform | undefined
83
83
  readonly queryForward: boolean
84
84
  readonly queryAware: boolean
@@ -117,12 +117,18 @@ export type HttpPullTransportOptions = {
117
117
  // when set, every open connection also pulls on this interval so
118
118
  // server-initiated changes arrive without a client-side trigger
119
119
  pullIntervalMs?: number
120
- // when true, each connection also opens a notification-only wake socket to
121
- // <origin>/wake and pulls immediately on any wake, demoting the interval
122
- // poll to a safety net. the wake channel carries no data ("pull now" only)
123
- // and zero correctness weight: a lost or duplicated wake can never cause
124
- // missed or wrong data because convergence comes from the pull protocol.
125
- wake?: boolean
120
+ /**
121
+ * opens a notification-only socket to <origin>/wake and pulls immediately on
122
+ * any wake, demoting interval polling to a safety net. true preserves the
123
+ * bare unauthenticated URL. for an authenticated host, pass getToken: each
124
+ * socket attempt calls it afresh and appends the result as wakeToken because
125
+ * browser WebSockets cannot send headers. consumers should implement
126
+ * getToken by calling an authenticated edge route that mints a short-lived,
127
+ * namespace-scoped signed token; the consumer's authorizeWake callback must
128
+ * verify that token. mint failures leave this advisory channel down and retry
129
+ * with backoff; pulls remain the source of correctness.
130
+ */
131
+ wake?: boolean | { getToken(): Promise<string> }
126
132
  // when provided, the query-aware extension is on and desired queries are
127
133
  // resolved client-side to an AST before shipping (native host / trusted
128
134
  // harness). omit for the baseline dialect (client-local got-query synthesis).
@@ -132,7 +138,8 @@ export type HttpPullTransportOptions = {
132
138
  // auth. the production path for permission-transformed queries.
133
139
  queryForward?: boolean
134
140
  // receives the structured connection lifecycle. when omitted, on-zero logs
135
- // each event as one JSON line so production failures retain their owners.
141
+ // failures so production errors retain their owners without logging routine
142
+ // connection and mutation traffic.
136
143
  lifecycle?: (event: HttpPullLifecycleEvent) => void
137
144
  }
138
145
 
@@ -200,8 +207,8 @@ function getHttpPullPageRegistry(): HttpPullPageRegistry {
200
207
  }
201
208
 
202
209
  function logHttpPullLifecycle(event: HttpPullLifecycleEvent) {
203
- if (process.env.NODE_ENV === 'test') return
204
- console.info(`[on-zero:http-pull] ${JSON.stringify(event)}`)
210
+ if (process.env.NODE_ENV === 'test' || event.type !== 'failure') return
211
+ console.error(`[on-zero:http-pull] ${JSON.stringify(event)}`)
205
212
  }
206
213
 
207
214
  export function installHttpPullTransport(
@@ -233,7 +240,7 @@ export function installHttpPullTransport(
233
240
  nativeWebSocket: previousWebSocket,
234
241
  sockets: new Set(),
235
242
  pullIntervalMs: opts.pullIntervalMs,
236
- wakeEnabled: opts.wake ?? false,
243
+ wake: opts.wake ?? false,
237
244
  queryTransform: opts.queryTransform,
238
245
  queryForward: opts.queryForward === true,
239
246
  queryAware: opts.queryTransform !== undefined || opts.queryForward === true,
@@ -338,6 +345,7 @@ class ZeroHttpSocket {
338
345
  private openTimer: ReturnType<typeof setTimeout> | undefined
339
346
  private pullTimer: ReturnType<typeof setInterval> | undefined
340
347
  private wakeSocket: { close(): void } | undefined
348
+ private wakeConnecting = false
341
349
  private wakeReconnectTimer: ReturnType<typeof setTimeout> | undefined
342
350
  private readonly generation: number
343
351
  private readonly zeroInstanceID: string
@@ -491,7 +499,7 @@ class ZeroHttpSocket {
491
499
  this.run(this.pull())
492
500
  }, this.state.pullIntervalMs)
493
501
  }
494
- if (this.state.wakeEnabled) this.openWakeChannel()
502
+ if (this.state.wake) this.openWakeChannel()
495
503
  }
496
504
 
497
505
  // notification-only wake channel: a real WebSocket to <origin>/wake that
@@ -501,38 +509,62 @@ class ZeroHttpSocket {
501
509
  // interval poll remains the safety net that guarantees convergence.
502
510
  private openWakeChannel() {
503
511
  const Native = this.state.nativeWebSocket
504
- if (!Native || this.wakeSocket || this.readyState !== this.OPEN) return
505
- const wsBase = this.state.originString.replace(/^http/, 'ws')
506
- const url = `${wsBase}/wake?clientID=${encodeURIComponent(this.clientID)}`
507
- let socket: {
508
- onmessage: (() => void) | null
509
- onclose: (() => void) | null
510
- onerror: (() => void) | null
511
- close(): void
512
- }
513
- try {
514
- socket = new Native(url) as unknown as typeof socket
515
- } catch {
512
+ if (
513
+ !Native ||
514
+ this.wakeSocket ||
515
+ this.wakeConnecting ||
516
+ this.readyState !== this.OPEN
517
+ ) {
516
518
  return
517
519
  }
518
- this.wakeSocket = socket
519
- const reconnect = () => {
520
- if (this.wakeSocket !== socket) return
521
- this.wakeSocket = undefined
522
- if (this.readyState !== this.OPEN || this.wakeReconnectTimer) return
523
- this.wakeReconnectTimer = setTimeout(() => {
524
- this.wakeReconnectTimer = undefined
525
- this.openWakeChannel()
526
- }, 500)
527
- }
528
- // route through requestPullAfterCurrent, NOT pull() directly: a wake that
529
- // lands while a pull is already in flight must set pullAfterCurrent so the
530
- // in-flight pull re-runs and picks up the woken change. calling pull()
531
- // directly would return the existing promise and silently drop the wake,
532
- // leaving convergence to the safety poll (a burst-storm latency bug).
533
- socket.onmessage = () => this.requestPullAfterCurrent()
534
- socket.onclose = reconnect
535
- socket.onerror = reconnect
520
+ this.wakeConnecting = true
521
+ const wsBase = this.state.originString.replace(/^http/, 'ws')
522
+ void (async () => {
523
+ let wakeToken: string | undefined
524
+ let socket: {
525
+ onmessage: (() => void) | null
526
+ onclose: (() => void) | null
527
+ onerror: (() => void) | null
528
+ close(): void
529
+ }
530
+ try {
531
+ if (typeof this.state.wake === 'object') {
532
+ wakeToken = await this.state.wake.getToken()
533
+ }
534
+ if (this.readyState !== this.OPEN || this.wakeSocket) return
535
+ const url =
536
+ `${wsBase}/wake?clientID=${encodeURIComponent(this.clientID)}` +
537
+ (wakeToken === undefined ? '' : `&wakeToken=${encodeURIComponent(wakeToken)}`)
538
+ socket = new Native(url) as unknown as typeof socket
539
+ } catch {
540
+ this.scheduleWakeReconnect()
541
+ return
542
+ } finally {
543
+ this.wakeConnecting = false
544
+ }
545
+ this.wakeSocket = socket
546
+ const reconnect = () => {
547
+ if (this.wakeSocket !== socket) return
548
+ this.wakeSocket = undefined
549
+ this.scheduleWakeReconnect()
550
+ }
551
+ // route through requestPullAfterCurrent, NOT pull() directly: a wake that
552
+ // lands while a pull is already in flight must set pullAfterCurrent so the
553
+ // in-flight pull re-runs and picks up the woken change. calling pull()
554
+ // directly would return the existing promise and silently drop the wake,
555
+ // leaving convergence to the safety poll (a burst-storm latency bug).
556
+ socket.onmessage = () => this.requestPullAfterCurrent()
557
+ socket.onclose = reconnect
558
+ socket.onerror = reconnect
559
+ })()
560
+ }
561
+
562
+ private scheduleWakeReconnect() {
563
+ if (this.readyState !== this.OPEN || this.wakeReconnectTimer) return
564
+ this.wakeReconnectTimer = setTimeout(() => {
565
+ this.wakeReconnectTimer = undefined
566
+ this.openWakeChannel()
567
+ }, 500)
536
568
  }
537
569
 
538
570
  private closeWakeChannel() {
package/src/index.ts CHANGED
@@ -1,5 +1,4 @@
1
1
  export * from './createPermissions'
2
- export * from './asyncTasks'
3
2
  export * from './queryRegistry'
4
3
  export * from './helpers/batchQuery'
5
4
  export * from './helpers/createMutators'
@@ -0,0 +1,38 @@
1
+ import { describe, expect, test } from 'vitest'
2
+
3
+ import { mutations } from './mutations'
4
+ import { serverWhere } from './serverWhere'
5
+
6
+ describe('mutations registry', () => {
7
+ test('two modules registering the same table keep both custom mutators', () => {
8
+ // a template commonly splits a table's mutators across files (the table's
9
+ // own mutations file plus a seed.ts firing a demo seed on that table).
10
+ // the registry is keyed by table, so a wholesale replace made whichever
11
+ // module imported LAST win: alphabetical import order silently dropped
12
+ // seed.ts's seedDemo whenever the seed file sorted before the table file.
13
+ const permissions = serverWhere('todo', () => true)
14
+
15
+ const seedModule = mutations('todo', permissions, {
16
+ seedDemo: async () => {},
17
+ })
18
+ const tableModule = mutations('todo', permissions, {})
19
+
20
+ expect(typeof seedModule.seedDemo).toBe('function')
21
+ expect(typeof tableModule.insert).toBe('function')
22
+ // both proxies read the same per-table registry: the later CRUD-only
23
+ // registration must not clobber the earlier custom mutator
24
+ expect(typeof (tableModule as Record<string, unknown>).seedDemo).toBe('function')
25
+ expect(Object.keys(tableModule)).toContain('seedDemo')
26
+ })
27
+
28
+ test('re-registering a handler replaces it per key (HMR)', () => {
29
+ const permissions = serverWhere('post', () => true)
30
+ const v1 = async () => {}
31
+ const v2 = async () => {}
32
+ mutations('post', permissions, { custom: v1 })
33
+ const proxy = mutations('post', permissions, { custom: v2 })
34
+ // per-key merge must still take the newest registration for an edited
35
+ // handler, otherwise HMR would pin the stale implementation
36
+ expect(proxy.custom).toBe(v2)
37
+ })
38
+ })
package/src/mutations.ts CHANGED
@@ -39,8 +39,16 @@ function getOrCreateMutationProxy<T extends Record<string, Function>>(
39
39
  tableName: string,
40
40
  implementations: T,
41
41
  ): T {
42
- // always update implementations (supports HMR)
43
- mutationRegistry().set(tableName, implementations)
42
+ // merge with any prior registration for this table: multiple modules may
43
+ // register mutators on the same table (a seed.ts alongside the table's own
44
+ // mutations file) and module import order is arbitrary, so replacing
45
+ // wholesale drops whichever module registered first. per-key replacement
46
+ // still supports HMR updates of edited handlers.
47
+ const prior = mutationRegistry().get(tableName)
48
+ mutationRegistry().set(
49
+ tableName,
50
+ prior ? { ...prior, ...implementations } : implementations,
51
+ )
44
52
 
45
53
  // return existing proxy if we have one (HMR case)
46
54
  const existing = proxyRegistry().get(tableName)