@cero-base/cero 2.2.0 → 2.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/README.md +24 -16
  2. package/package.json +7 -6
  3. package/src/build/index.js +38 -34
  4. package/src/build/internal.js +96 -11
  5. package/src/build/schemas.js +119 -19
  6. package/src/extensions/handle-sync.js +8 -12
  7. package/src/extensions/index.js +17 -63
  8. package/src/extensions/mirror.js +44 -0
  9. package/src/extensions/profile-sync.js +10 -12
  10. package/src/handle/index.js +499 -374
  11. package/src/handle/join.js +144 -0
  12. package/src/index.js +89 -118
  13. package/src/lib/bluetooth.js +83 -19
  14. package/src/lib/constants.js +1 -0
  15. package/src/lib/operators.js +298 -128
  16. package/src/lib/peek.js +1 -1
  17. package/src/lib/refs.js +7 -7
  18. package/src/lib/spec.js +32 -0
  19. package/src/local/index.js +27 -3
  20. package/src/rpc/client.js +240 -202
  21. package/src/rpc/server.js +186 -133
  22. package/types/build/index.d.ts +3 -8
  23. package/types/build/internal.d.ts +86 -27
  24. package/types/build/schemas.d.ts +91 -12
  25. package/types/extensions/handle-sync.d.ts +4 -12
  26. package/types/extensions/index.d.ts +59 -59
  27. package/types/extensions/mirror.d.ts +13 -0
  28. package/types/extensions/profile-sync.d.ts +4 -13
  29. package/types/handle/index.d.ts +229 -198
  30. package/types/handle/join.d.ts +63 -0
  31. package/types/index.d.ts +27 -55
  32. package/types/lib/bluetooth.d.ts +57 -19
  33. package/types/lib/constants.d.ts +1 -0
  34. package/types/lib/operators.d.ts +166 -81
  35. package/types/lib/peek.d.ts +2 -2
  36. package/types/lib/refs.d.ts +14 -15
  37. package/types/lib/spec.d.ts +87 -0
  38. package/types/local/index.d.ts +19 -9
  39. package/types/rpc/client.d.ts +55 -112
  40. package/types/rpc/server.d.ts +91 -50
  41. package/src/rpc/index.js +0 -8
  42. package/types/rpc/index.d.ts +0 -7
package/src/rpc/client.js CHANGED
@@ -1,34 +1,52 @@
1
1
  import { Readable } from 'streamx'
2
+ import b4a from 'b4a'
2
3
  import { RPCClient, bindCodec } from '@cero-base/core/rpc'
4
+ import { CeroError } from '@cero-base/core/errors'
5
+ import { checkFields, checkRequired } from '@cero-base/core/utils'
3
6
  import c from 'compact-encoding'
4
7
  import z32 from 'z32'
5
8
  import { decodeId } from '@cero-base/core/blobs/codec'
6
9
 
7
10
  import { Ref } from '../lib/refs.js'
8
- import { put, set, get, del, watch, changes, call, open, rotate } from '../lib/operators.js'
11
+ import * as verbs from '../lib/operators.js'
9
12
  import { t, schema } from '../lib/spec.js'
10
- import { operatorsOf, bind } from '../extensions/index.js'
11
13
 
12
- export { put, set, get, del, watch, changes, call, open, rotate, t, schema }
14
+ // hooks and batches take functions: they run where the data lives, never in the UI
15
+ const { before, after, tx, ...remote } = verbs
16
+
17
+ export const {
18
+ put,
19
+ set,
20
+ get,
21
+ del,
22
+ watch,
23
+ call,
24
+ open,
25
+ invite,
26
+ revoke,
27
+ rotate,
28
+ accept,
29
+ deny,
30
+ leave,
31
+ close,
32
+ cancel,
33
+ suspend,
34
+ resume,
35
+ activate,
36
+ deactivate,
37
+ phrase,
38
+ nearby
39
+ } = remote
40
+ export { t, schema }
13
41
 
14
42
  /**
15
43
  * @typedef {import('@cero-base/core/rpc').RPCClient} BaseRPCClient
16
44
  *
17
- * @typedef {object} RefInfo
18
- * @property {'single'|'collection'|'action'|'handle'} [kind]
19
- * @property {string} [schema]
20
- * @property {string} [type]
21
- * @property {boolean} [internal]
22
- *
23
- * @typedef {import('@cero-base/core/rpc').Spec & { meta: { ns?: string, refs: Record<string, RefInfo>, local?: { refs: Record<string, RefInfo> }, handles?: Record<string, Spec> }, handles: Record<string, Spec> }} Spec Built cero spec (schema + rpc + per-handle child specs).
24
- *
25
- * @typedef {{ data: any }} SingleResult
26
- * @typedef {{ data: any[], total: number, size: number }} ListResult
27
- * @typedef {{ data: any | null }} GetByIdResult
28
- *
29
- * @typedef {object} ClientIdentity
30
- * @property {string} id
31
- * @property {() => string|null} toPhrase
45
+ * @typedef {import('../lib/spec.js').RefInfo} RefInfo
46
+ * @typedef {import('../lib/spec.js').Spec} Spec
47
+ * @typedef {import('../lib/spec.js').Row} Row
48
+ * @typedef {import('../lib/operators.js').SingleResult} SingleResult
49
+ * @typedef {import('../lib/operators.js').ListResult} ListResult
32
50
  *
33
51
  * @typedef {object} HandleStub
34
52
  * @property {string} id
@@ -63,13 +81,19 @@ const blobIdEnc = {
63
81
  const operators = {
64
82
  _local: false,
65
83
 
66
- /** @param {string} name @returns {RefInfo|undefined} */
84
+ /**
85
+ * @param {string} name @returns {RefInfo|undefined}
86
+ * @private
87
+ */
67
88
  _refInfo(name) {
68
89
  const refs = this._local ? this.spec.meta.local?.refs : this.spec.meta.refs
69
90
  return refs?.[name]
70
91
  },
71
92
 
72
- /** @returns {any} */
93
+ /**
94
+ * @returns {import('@cero-base/core/rpc').Codec}
95
+ * @private
96
+ */
73
97
  _codec() {
74
98
  return this._local ? this.spec.local.codec : this.spec.codec
75
99
  },
@@ -79,13 +103,9 @@ const operators = {
79
103
  return this._refInfo(name)?.schema
80
104
  },
81
105
 
82
- /**
83
- * Build a renderable URL for a file id using the base + token learned at init.
84
- *
85
- * @param {string} id
86
- * @returns {string}
87
- */
88
- url(id) {
106
+ // the worker's file server, reached with the base and token learned at init
107
+ /** @private */
108
+ _link(id) {
89
109
  const root = this.parent || this
90
110
  const base = root._fileBase || ''
91
111
  const token = root._fileToken || ''
@@ -102,8 +122,9 @@ const operators = {
102
122
  * size, url }` objects.
103
123
  *
104
124
  * @param {string} name
105
- * @param {any} data
106
- * @returns {any}
125
+ * @param {Row | Row[] | null} data
126
+ * @returns {Row | Row[] | null}
127
+ * @private
107
128
  */
108
129
  _resolveFiles(name, data) {
109
130
  if (data == null) return data
@@ -112,13 +133,14 @@ const operators = {
112
133
  return this._resolveRow(name, info, data)
113
134
  },
114
135
 
136
+ /** @private */
115
137
  _resolveRow(name, info, row) {
116
138
  if (!row || typeof row !== 'object') return row
117
139
  if (info?.internal && info?.verb === 'file') {
118
140
  if (!row.id) return row
119
141
  try {
120
142
  const { type, blobId } = decodeId(row.id)
121
- return { ...row, type, size: blobId.byteLength, url: this.url(row.id) }
143
+ return { ...row, type, size: blobId.byteLength, url: this._link(row.id) }
122
144
  } catch {
123
145
  return row
124
146
  }
@@ -131,7 +153,7 @@ const operators = {
131
153
  if (v == null) continue
132
154
  try {
133
155
  const { type, blobId } = decodeId(v)
134
- out[f] = { id: v, type, size: blobId.byteLength, url: this.url(v) }
156
+ out[f] = { id: v, type, size: blobId.byteLength, url: this._link(v) }
135
157
  } catch {
136
158
  // leave as-is if not a valid file id
137
159
  }
@@ -143,7 +165,7 @@ const operators = {
143
165
  * Insert a row over the wire.
144
166
  *
145
167
  * @param {string} name
146
- * @param {Record<string, any>} row
168
+ * @param {Row} row
147
169
  * @returns {Promise<SingleResult>}
148
170
  */
149
171
  async put(name, row) {
@@ -159,11 +181,10 @@ const operators = {
159
181
  const decoded = codec.decodeRow(schema, res.data)
160
182
  return { data: this._resolveRow(name, this._refInfo(name), decoded) }
161
183
  }
162
- const input = row?.id ? row : { id: '', ...row }
163
184
  const res = await this.rpc.addRow({
164
185
  handle: this.id,
165
186
  ref: name,
166
- data: codec.encodeRow(schema, input),
187
+ data: this._encode(name, row, true).data,
167
188
  local: this._local
168
189
  })
169
190
  return { data: codec.decodeRow(schema, res.data) }
@@ -173,21 +194,23 @@ const operators = {
173
194
  * Upsert a row over the wire. Pass `{ upsert: false }` to update-only.
174
195
  *
175
196
  * @param {string} name
176
- * @param {Record<string, any>} row
197
+ * @param {Row} row
177
198
  * @param {{ upsert?: boolean }} [opts]
178
- * @returns {Promise<SingleResult>}
199
+ * @returns {Promise<SingleResult | null>}
179
200
  */
180
201
  async set(name, row, opts) {
181
202
  const codec = this._codec()
182
203
  const schema = this.schemaOf(name)
204
+ const { data, fields } = this._encode(name, row, false)
183
205
  const res = await this.rpc.set({
184
206
  handle: this.id,
185
207
  ref: name,
186
- data: codec.encodeRow(schema, row),
208
+ data,
209
+ fields,
187
210
  local: this._local,
188
211
  noUpsert: opts?.upsert === false || undefined
189
212
  })
190
- return { data: codec.decodeRow(schema, res.data) }
213
+ return res.data ? { data: codec.decodeRow(schema, res.data) } : null
191
214
  },
192
215
 
193
216
  /**
@@ -195,35 +218,56 @@ const operators = {
195
218
  * `Storage.get` contract.
196
219
  *
197
220
  * @param {string} name
198
- * @param {string | Record<string, any>} [query]
199
- * @returns {Promise<SingleResult | ListResult | GetByIdResult>}
221
+ * @param {string | Record<string, unknown>} [query]
222
+ * @returns {Promise<SingleResult | ListResult>}
200
223
  */
201
224
  async get(name, query) {
202
- const codec = this._codec()
203
- const schema = this.schemaOf(name)
204
- if (typeof query === 'string') {
205
- const res = await this.rpc.getOne({
206
- handle: this.id,
207
- ref: name,
208
- id: query,
209
- local: this._local
210
- })
211
- const decoded = res.data ? codec.decodeRow(schema, res.data) : null
212
- return { data: this._resolveFiles(name, decoded) }
213
- }
225
+ const one = typeof query === 'string' || this._refInfo(name)?.kind === 'single'
214
226
  const res = await this.rpc.get({
215
227
  handle: this.id,
216
228
  ref: name,
217
- query: codec.encodeQuery(query),
229
+ query: toWire(query),
218
230
  local: this._local
219
231
  })
232
+ return this._read(name, one, res)
233
+ },
234
+
235
+ /**
236
+ * The typed row and the indexes of the declared fields it carries, checked as the worker
237
+ * would: the encoder drops an undeclared field and fails on a missing required one.
238
+ *
239
+ * @param {string} name
240
+ * @param {Row} row
241
+ * @param {boolean} whole A put's row; a set's may leave fields out.
242
+ * @returns {{ data: Uint8Array, fields: number[] }}
243
+ * @private
244
+ */
245
+ _encode(name, row, whole) {
220
246
  const info = this._refInfo(name)
221
- const raw =
222
- info?.kind === 'single'
223
- ? codec.decodeRow(schema, res.data)
224
- : codec.decodeRows(schema, res.data)
247
+ checkFields(name, info, row)
248
+ if (whole) checkRequired(name, info, row)
249
+ const declared = info?.fields || []
250
+ const fields = Object.keys(row)
251
+ .map((k) => declared.indexOf(k))
252
+ .filter((i) => i !== -1)
253
+ return { data: this._codec().encodeRow(this.schemaOf(name), filled(row, info)), fields }
254
+ },
255
+
256
+ /**
257
+ * Decode a result: one row or null when `one`, the list with its counts otherwise.
258
+ *
259
+ * @param {string} name
260
+ * @param {boolean} one
261
+ * @param {{ data: Uint8Array | null, total?: number, size?: number }} res
262
+ * @returns {SingleResult | ListResult}
263
+ * @private
264
+ */
265
+ _read(name, one, res) {
266
+ const codec = this._codec()
267
+ const schema = this.schemaOf(name)
268
+ if (one) return { data: this._resolveFiles(name, codec.decodeRow(schema, res.data) ?? null) }
225
269
  return {
226
- data: this._resolveFiles(name, raw),
270
+ data: this._resolveFiles(name, codec.decodeRows(schema, res.data)),
227
271
  total: res.total === -1 ? null : res.total,
228
272
  size: res.size
229
273
  }
@@ -245,17 +289,15 @@ const operators = {
245
289
  * underlying mutation. Destroy the stream to stop watching.
246
290
  *
247
291
  * @param {string} name
248
- * @param {Record<string, any>} [query]
292
+ * @param {string | Record<string, unknown>} [query]
249
293
  * @returns {import('streamx').Readable}
250
294
  */
251
295
  watch(name, query) {
252
- const refInfo = this._refInfo(name)
253
- const codec = this._codec()
254
- const schema = refInfo?.schema
296
+ const one = typeof query === 'string' || this._refInfo(name)?.kind === 'single'
255
297
  const wire = this.rpc.watch({
256
298
  handle: this.id,
257
299
  ref: name,
258
- query: codec.encodeQuery(query),
300
+ query: toWire(query),
259
301
  local: this._local
260
302
  })
261
303
  const out = new Readable({
@@ -263,17 +305,7 @@ const operators = {
263
305
  wire.destroy()
264
306
  }
265
307
  })
266
- wire.on('data', (snap) => {
267
- const raw =
268
- refInfo.kind === 'single'
269
- ? (codec.decodeRow(schema, snap.data) ?? null)
270
- : codec.decodeRows(schema, snap.data)
271
- out.push({
272
- data: this._resolveFiles(name, raw),
273
- total: snap.total === -1 ? null : snap.total,
274
- size: snap.size
275
- })
276
- })
308
+ wire.on('data', (snap) => out.push(this._read(name, one, snap)))
277
309
  // end exactly once whether the wire ends or the server destroys it (handle close)
278
310
  let ended = false
279
311
  const end = () => {
@@ -289,52 +321,11 @@ const operators = {
289
321
  return out
290
322
  },
291
323
 
292
- /**
293
- * Delta subscription over the wire — same contract as the local operator: batches of `{
294
- * prev, next }` with file fields resolved, `reset` marks a full replay.
295
- */
296
- changes(name, query) {
297
- const refInfo = this._refInfo(name)
298
- const codec = this._codec()
299
- const schema = refInfo?.schema
300
- const wire = this.rpc.changes({
301
- handle: this.id,
302
- ref: name,
303
- query: codec.encodeQuery(query),
304
- local: this._local
305
- })
306
- const out = new Readable({
307
- predestroy() {
308
- wire.destroy()
309
- }
310
- })
311
- const pump = async () => {
312
- for await (const frame of wire) {
313
- const changes = []
314
- for (const { prev, next } of codec.decodeChanges(schema, frame.changes)) {
315
- changes.push({
316
- prev: prev && this._resolveFiles(name, prev),
317
- next: next && this._resolveFiles(name, next)
318
- })
319
- }
320
- out.push({ changes, reset: frame.reset === true })
321
- }
322
- if (!out.destroyed) out.push(null)
323
- }
324
- pump().catch((err) => {
325
- if (out.destroyed) return
326
- // both are ends, not failures
327
- if (err.code === 'PREMATURE_CLOSE' || err.code === 'CHANNEL_CLOSED') out.push(null)
328
- else out.destroy(err)
329
- })
330
- return out
331
- },
332
-
333
324
  /**
334
325
  * Invoke a named action ref over the wire.
335
326
  *
336
327
  * @param {string} op
337
- * @param {any} [data]
328
+ * @param {Row} [data]
338
329
  * @returns {Promise<void>}
339
330
  */
340
331
  async call(op, data) {
@@ -344,51 +335,72 @@ const operators = {
344
335
  await this.rpc.call({ handle: this.id, op, data: encoded })
345
336
  },
346
337
 
347
- /**
348
- * Mint a pairing invite for this handle.
349
- *
350
- * @param {{ role?: string }} [opts]
351
- * @returns {Promise<string>}
352
- */
353
- async invite({ role, expiresIn, reuse } = {}) {
338
+ // the verbs in lib/operators.js land here, and cross to the worker
339
+
340
+ /** @private */
341
+ async _invite({ role, ttl, reuse, confirm, data } = {}) {
354
342
  const { invite } = await this.rpc.invite({
355
343
  handle: this.id,
356
344
  role: role || '',
357
- expiresIn: expiresIn || 0,
358
- reuse: reuse === true
345
+ ttl: ttl ? String(ttl) : '',
346
+ reuse: reuse === true,
347
+ confirm: confirm === true,
348
+ data: data || null
359
349
  })
360
350
  return invite
361
351
  },
362
352
 
363
- /**
364
- * Revoke a previously issued invite.
365
- *
366
- * @param {string} invite
367
- * @returns {Promise<boolean>}
368
- */
369
- async revoke(invite) {
353
+ /** @private */
354
+ async _revoke(invite) {
370
355
  const { ok } = await this.rpc.revoke({ handle: this.id, invite })
371
356
  return ok
372
357
  },
373
358
 
374
- /**
375
- * Rotate this handle's encryption epoch on the server.
376
- *
377
- * @returns {Promise<{ epoch: number }>}
378
- */
379
- async rotate() {
359
+ /** @private */
360
+ async _rotate() {
380
361
  const { epoch } = await this.rpc.rotate({ handle: this.id })
381
362
  return { epoch }
382
363
  },
383
364
 
384
- /**
385
- * `true` ranks this handle as just updated on the server, `false` takes it off the swarm.
386
- *
387
- * @param {boolean} active
388
- * @returns {Promise<void>}
389
- */
390
- async setActive(active) {
391
- await this.rpc.setActive({ handle: this.id, active })
365
+ /** @private */
366
+ async _answer(id, { accept, role, reason }) {
367
+ await this.rpc.answer({ handle: this.id, id, accept, role: role || '', reason: reason || '' })
368
+ },
369
+
370
+ /** @private */
371
+ async _leave() {
372
+ await this.rpc.leave({ handle: this.id })
373
+ },
374
+
375
+ /** @private */
376
+ async _cancel(invite) {
377
+ return (await this.rpc.cancel({ invite })).ok
378
+ },
379
+
380
+ /** @private */
381
+ async _suspend() {
382
+ await this.rpc.suspend({ handle: this.id })
383
+ },
384
+
385
+ /** @private */
386
+ async _resume() {
387
+ await this.rpc.resume({ handle: this.id })
388
+ },
389
+
390
+ /** @private */
391
+ async _active(on) {
392
+ await this.rpc.setActive({ handle: this.id, active: on })
393
+ },
394
+
395
+ /** @private */
396
+ async _phrase() {
397
+ return (await this.rpc.seed({})).phrase || null
398
+ },
399
+
400
+ /** @private */
401
+ async _nearby(mode) {
402
+ const invite = typeof mode === 'string' ? mode : ''
403
+ await this.rpc.nearby({ on: mode !== false, invite })
392
404
  }
393
405
  }
394
406
 
@@ -403,8 +415,7 @@ const operators = {
403
415
  export async function restore(me, phrase) {
404
416
  const res = await me.rpc.restore({ phrase })
405
417
  me.id = res.id
406
- me.deviceId = res.deviceId || null
407
- me.identity = { id: res.id, toPhrase: async () => (await me.rpc.seed({})).phrase || null }
418
+ me.device = device(res)
408
419
  return me
409
420
  }
410
421
 
@@ -418,6 +429,7 @@ class LocalRefs {
418
429
  this.parent = client
419
430
  this.spec = client.spec
420
431
  this.store = this
432
+ /** @private */
421
433
  this._local = true
422
434
  const refs = client.spec.meta.local?.refs || {}
423
435
  const exposed = Object.fromEntries(Object.entries(refs).filter(([, info]) => !info.internal))
@@ -429,7 +441,11 @@ class LocalRefs {
429
441
  return this.parent.rpc
430
442
  }
431
443
 
432
- /** Root handle id (local ops are resolved against the root's local store). */
444
+ /**
445
+ * The root's id: local ops resolve against the root's local store.
446
+ *
447
+ * @returns {string | null}
448
+ */
433
449
  get id() {
434
450
  return this.parent.id
435
451
  }
@@ -442,28 +458,38 @@ class LocalRefs {
442
458
  */
443
459
  export class Client extends RPCClient {
444
460
  /**
445
- * @param {any} ipc Framed IPC stream (must be writable).
461
+ * @param {import('streamx').Duplex} ipc Framed IPC stream (must be writable).
446
462
  * @param {Spec} spec Compiled cero spec (schema + rpc + handles).
447
- * @param {{ operators?: Record<string, any> }} [opts] The operators to bind, instead of the ones the spec carries.
463
+ * @param {{ onerror?: (err: Error) => void }} [opts] Where the worker's background errors go; the console without one.
448
464
  */
449
- constructor(ipc, spec, opts = {}) {
465
+ constructor(ipc, spec, { onerror } = {}) {
450
466
  super(ipc, spec)
451
467
  if (spec.local?.schema && !spec.local.codec) bindCodec(spec.local)
452
468
  Object.assign(this, operators)
453
- this.operators = operatorsOf(spec, opts.operators)
469
+ /** @private */
470
+ this._onerror = onerror || ((err) => console.error(err))
471
+ /** @type {string | null} */
454
472
  this.id = null
455
- this.deviceId = null
473
+ /** @type {{ id: string, name: string | null } | null} */
474
+ this.device = null
456
475
  this.store = this
457
476
  this.local = null
458
477
  }
459
478
 
460
479
  // the worker's background errors, delivered the way a local root delivers them
480
+ /** @private */
461
481
  _pumpErrors() {
462
- const report = (err) =>
463
- this.listenerCount('error') ? this.emit('error', err) : console.error(err)
482
+ const report = this._onerror
464
483
  const pump = async () => {
465
- for await (const { message, code, stack } of this.rpc.errors({})) {
466
- report(Object.assign(new Error(message), code && { code }, stack && { stack }))
484
+ for await (const { message, code, stack, reason } of this.rpc.errors({})) {
485
+ report(
486
+ Object.assign(
487
+ new Error(message),
488
+ code && { code },
489
+ stack && { stack },
490
+ reason && { reason }
491
+ )
492
+ )
467
493
  }
468
494
  }
469
495
  pump().catch((err) => {
@@ -471,44 +497,35 @@ export class Client extends RPCClient {
471
497
  })
472
498
  }
473
499
 
500
+ /** @private */
474
501
  async _open() {
475
502
  await super._open()
476
- const { id, deviceId, fileBase, fileToken } = await this.rpc.init({})
503
+ const res = await this.rpc.init({})
504
+ const { id, fileBase, fileToken } = res
477
505
  this.id = id
478
- this.deviceId = deviceId || null
506
+ this.device = device(res)
507
+ /** @private */
479
508
  this._fileBase = fileBase || ''
509
+ /** @private */
480
510
  this._fileToken = fileToken || ''
481
- this.identity = { id, toPhrase: async () => (await this.rpc.seed({})).phrase || null }
482
511
  Ref.attach(this, /** @type {Spec} */ (this.spec).meta.refs)
483
- bind(this, null, this.operators)
484
512
  if (/** @type {Spec} */ (this.spec).meta.local?.refs) this.local = new LocalRefs(this)
485
513
  this._pumpErrors()
486
514
  }
487
515
 
488
- /** Pause networking and storage on the server. Idempotent. */
489
- async suspend() {
490
- await this.rpc.suspend({})
491
- }
492
-
493
- /** Resume a suspended server. Idempotent. */
494
- async resume() {
495
- await this.rpc.resume({})
496
- }
497
-
498
516
  /**
499
517
  * Create a new child handle of the given type.
500
518
  *
501
519
  * @param {string} type
502
- * @param {Record<string, any>} [opts]
520
+ * @param {{ name?: string | null }} [opts]
503
521
  * @returns {Promise<Handle>}
522
+ * @private
504
523
  */
505
524
  async _create(type, opts = {}) {
506
- // routes are functions and cannot cross the wire
507
- const wire = { ...opts, noAccept: opts.accept === false || undefined }
508
525
  const stub = await this.rpc.addHandle({
509
526
  ref: type,
510
527
  handle: this.id,
511
- data: this.spec.codec.encodeCreate(wire)
528
+ data: this.spec.codec.encodeCreate({ name: opts.name })
512
529
  })
513
530
  return new Handle(this, stub.id, stub.type, stub.name || null)
514
531
  }
@@ -519,6 +536,7 @@ export class Client extends RPCClient {
519
536
  * @param {string} type
520
537
  * @param {string} id
521
538
  * @returns {Promise<Handle>}
539
+ * @private
522
540
  */
523
541
  async _load(type, id) {
524
542
  const stub = await this.rpc.openHandle({ parent: this.id, row: id })
@@ -531,9 +549,11 @@ export class Client extends RPCClient {
531
549
  * @param {string} invite
532
550
  * @param {string} type
533
551
  * @returns {Promise<Handle>}
552
+ * @private
534
553
  */
535
554
  async _join(invite, type) {
536
555
  const stub = await this.rpc.join({ parent: this.id, ref: type, invite })
556
+ if (stub.denied) throw CeroError.DENIED(stub.reason || null)
537
557
  return new Handle(this, stub.id, stub.type, stub.name || null)
538
558
  }
539
559
  }
@@ -560,7 +580,6 @@ class Handle {
560
580
  if (!this.spec.codec) bindCodec(this.spec)
561
581
  this.store = this
562
582
  Ref.attach(this, this.spec.meta.refs)
563
- bind(this, this.type, parent.operators)
564
583
  }
565
584
 
566
585
  /** Underlying RPC channel borrowed from the parent. */
@@ -568,23 +587,17 @@ class Handle {
568
587
  return this.parent.rpc
569
588
  }
570
589
 
571
- /** Tear down the remote handle without leaving the room. */
572
590
  close() {
573
591
  return this.parent.rpc.closeHandle({ handle: this.id })
574
592
  }
575
-
576
- /** Tear down the remote handle and drop membership. */
577
- leave() {
578
- return this.parent.rpc.leave({ handle: this.id })
579
- }
580
593
  }
581
594
 
582
595
  /**
583
596
  * Construct a `Client`, wait for `init` to complete, and return it.
584
597
  *
585
- * @param {any} ipc
586
- * @param {object} spec
587
- * @param {{ operators?: Record<string, any> }} [opts]
598
+ * @param {import('streamx').Duplex} ipc
599
+ * @param {Spec} spec
600
+ * @param {{ onerror?: (err: Error) => void }} [opts]
588
601
  * @returns {Promise<Client>}
589
602
  */
590
603
  export async function connect(ipc, spec, opts) {
@@ -597,24 +610,49 @@ export async function connect(ipc, spec, opts) {
597
610
  * Symmetric client entry. Mirrors the main `cero`, but `cero(ipc, spec)` connects to a
598
611
  * server (via `connect`) instead of opening a local store.
599
612
  *
600
- * @param {any} ipc Framed IPC duplex stream.
601
- * @param {any} spec Built cero spec.
602
- * @param {{ operators?: Record<string, any> }} [opts]
613
+ * @param {import('streamx').Duplex} ipc Framed IPC duplex stream.
614
+ * @param {Spec} spec Built cero spec.
615
+ * @param {{ onerror?: (err: Error) => void }} [opts]
603
616
  * @returns {Promise<Client>}
604
617
  */
605
618
  export function cero(ipc, spec, opts) {
606
619
  return connect(ipc, spec, opts)
607
620
  }
608
- cero.connect = connect
609
- cero.restore = restore
610
- cero.t = t
611
- cero.put = put
612
- cero.set = set
613
- cero.get = get
614
- cero.del = del
615
- cero.watch = watch
616
- cero.changes = changes
617
- cero.call = call
618
- cero.open = open
619
- cero.rotate = rotate
620
- cero.schema = schema
621
+ Object.assign(cero, remote, { connect, restore, t, schema })
622
+
623
+ // the same shape a local root has
624
+ function device({ deviceId, deviceName }) {
625
+ return deviceId ? { id: deviceId, name: deviceName || null } : null
626
+ }
627
+
628
+ // the typed row carries an id and every required field: what a row leaves out is filled, the
629
+ // worker keeps only the fields sent
630
+ function filled(row, info) {
631
+ let out = row.id === undefined ? { id: '', ...row } : row
632
+ for (const key in info?.required) {
633
+ if (out[key] == null) out = { ...out, [key]: ZERO[info.required[key]] }
634
+ }
635
+ return out
636
+ }
637
+
638
+ const ZERO = {
639
+ string: '',
640
+ file: '',
641
+ json: null,
642
+ uint: 0,
643
+ int: 0,
644
+ bool: false,
645
+ bytes: b4a.alloc(0),
646
+ fixed32: b4a.alloc(32),
647
+ fixed64: b4a.alloc(64)
648
+ }
649
+
650
+ // c.any carries undefined as null, and in a query undefined is absent
651
+ function toWire(query) {
652
+ if (query === undefined) return null
653
+ const defined =
654
+ query && typeof query === 'object'
655
+ ? Object.fromEntries(Object.entries(query).filter(([, v]) => v !== undefined))
656
+ : query
657
+ return c.encode(c.any, defined)
658
+ }