@mmstack/mesh 22.8.1 → 22.9.1

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mmstack/mesh",
3
- "version": "22.8.1",
3
+ "version": "22.9.1",
4
4
  "keywords": [
5
5
  "angular",
6
6
  "signals",
@@ -20,7 +20,7 @@
20
20
  "homepage": "https://github.com/mihajm/mmstack/blob/master/packages/mesh/client",
21
21
  "peerDependencies": {
22
22
  "@angular/core": ">=22 <23",
23
- "@mmstack/primitives": ">=22.14 <23",
23
+ "@mmstack/primitives": ">=22.15 <23",
24
24
  "@mmstack/mesh-protocol": ">=0.9 <1"
25
25
  },
26
26
  "sideEffects": false,
@@ -1,4 +1,4 @@
1
- import { ClientMsg, ServerMsg, Relay, PrincipalCtx, PresenceState, OpPolicy } from '@mmstack/mesh-protocol';
1
+ import { ClientMsg, ServerMsg, Relay, PrincipalCtx, PresenceState, OpPolicy, ClientSignalMsg } from '@mmstack/mesh-protocol';
2
2
  import { OpSync, MergePolicyEntry, OpEnvelope, AsyncStore, ForkStoreOptions, SyncedFork, WritableSignalStore, StoreOp, toStoreOptions } from '@mmstack/primitives/core';
3
3
  import { Injector, Signal, WritableSignal } from '@angular/core';
4
4
 
@@ -314,37 +314,154 @@ type DataChannelLike = {
314
314
  onClose(cb: () => void): () => void;
315
315
  close(): void;
316
316
  };
317
+ /** One data channel on a peer link. `ordered: false` + `maxRetransmits: 0` makes it lossy. */
318
+ type PeerChannelSpec = {
319
+ readonly label: string;
320
+ readonly ordered?: boolean;
321
+ readonly maxRetransmits?: number;
322
+ };
323
+ /** The single reliable channel every link carries when no channels are asked for. */
324
+ declare const defaultPeerChannels: readonly PeerChannelSpec[];
317
325
  /**
318
326
  * Creates one peer link. `polite` assigns the perfect-negotiation role (derived
319
327
  * deterministically from origin ordering); `sendSignal` routes offer/answer/ICE payloads
320
- * through the relay; `signal` delivers the remote side's payloads.
328
+ * through the relay; `signal` delivers the remote side's payloads. Object payloads gain a
329
+ * `link` field on the way out (the sending link's instance id) and, once the remote instance
330
+ * is known, a `to` field; both are stripped before `signal` sees the payload.
331
+ *
332
+ * `channels` lists the labelled channels the link carries; `channel` is the first of them and
333
+ * `channels` (by label) all of them. A connector that returns only `channel` supports a single
334
+ * channel. Signal payloads carry no channel field: one link per remote carries every channel,
335
+ * so nothing needs routing. The field name `ch` is kept free for a future where it does.
321
336
  */
322
337
  type PeerConnector = (opt: {
323
338
  readonly remote: string;
324
339
  readonly polite: boolean;
325
340
  readonly sendSignal: (data: unknown) => void;
341
+ readonly channels: readonly PeerChannelSpec[];
326
342
  }) => {
327
343
  readonly channel: DataChannelLike;
344
+ readonly channels?: Readonly<Record<string, DataChannelLike>>;
328
345
  signal(data: unknown): void;
329
346
  close(): void;
330
347
  };
331
348
  /** WebRTC `PeerConnector` implementing the perfect-negotiation pattern. Browser-only. */
332
349
  declare function rtcPeerConnector(config?: RTCConfiguration): PeerConnector;
350
+ /**
351
+ * A relay connection someone else owns (a live session, say). Peer links ride on it without
352
+ * saying hello, so the links share that connection's origin and room membership.
353
+ */
354
+ type SignalingPort = {
355
+ /** Current relay membership for this room, or undefined until welcomed. Read after subscribing. */
356
+ members(): readonly string[] | undefined;
357
+ send(msg: ClientSignalMsg): void;
358
+ onMessage(cb: (msg: ServerMsg) => void): () => void;
359
+ };
360
+ type PeerLinksOptions = {
361
+ readonly room: string;
362
+ /** This side's origin; also decides the perfect-negotiation role against each remote. */
363
+ readonly origin: string;
364
+ /**
365
+ * A transport factory means the links own their relay connection (hello, reconnect); a
366
+ * {@link SignalingPort} means they ride on one that is already joined.
367
+ */
368
+ readonly signaling: MeshTransportFactory | SignalingPort;
369
+ /** Peer link factory; defaults to {@link rtcPeerConnector}. Injectable for tests. */
370
+ readonly connector?: PeerConnector;
371
+ /**
372
+ * The channels every link carries, first one the default for `send` and `broadcast`.
373
+ * Defaults to {@link defaultPeerChannels}. Both sides must ask for the same labels.
374
+ */
375
+ readonly channels?: readonly PeerChannelSpec[];
376
+ /** Sent in the hello when the links own their connection. */
377
+ readonly policyVersion?: number;
378
+ /**
379
+ * `false` defers signaling until {@link PeerLinks.connect}, so a consumer can subscribe
380
+ * before the first link opens. Defaults to `true`.
381
+ */
382
+ readonly autoConnect?: boolean;
383
+ readonly injector?: Injector;
384
+ };
385
+ type PeerLinks = {
386
+ /**
387
+ * `live` once the relay has welcomed this side (or, over a port, once it has seen a
388
+ * welcome); back to `connecting` while an owned relay connection is being re-established.
389
+ * Peer links outlive that: they are torn down only by their own close or a relay `gone`.
390
+ */
391
+ readonly status: Signal<'connecting' | 'live'>;
392
+ /** Origins whose link has every channel open. */
393
+ readonly peers: Signal<readonly string[]>;
394
+ /**
395
+ * Other origins in the room as the relay reports them (welcome, then join and leave). The
396
+ * relay is the authority on who is present; a link can outlive a dead socket for a while.
397
+ */
398
+ readonly members: Signal<readonly string[]>;
399
+ /** Replays current membership synchronously, then reports every change without coalescing. */
400
+ onMembers(cb: (members: readonly string[]) => void): () => void;
401
+ /** The labels every link carries, in the order they were asked for. */
402
+ readonly channels: readonly string[];
403
+ /** Fires when one channel of a link opens; replays channels that are already open. */
404
+ onOpen(cb: (origin: string, channel: string) => void): () => void;
405
+ onMessage(cb: (origin: string, frame: string, channel: string) => void): () => void;
406
+ /** Fires when a link goes away: a channel closed or the relay reported the origin gone. */
407
+ onClose(cb: (origin: string) => void): () => void;
408
+ /** Fires once when the links shut down: `close()`, or the relay rejected the hello. */
409
+ onEnd(cb: () => void): () => void;
410
+ /** Sends on one open channel; a frame for a channel that is not open is dropped. */
411
+ send(origin: string, frame: string, channel?: string): void;
412
+ /** Sends on the channel of every link where it is open. */
413
+ broadcast(frame: string, channel?: string): void;
414
+ /** Starts signaling when created with `autoConnect: false`; a no-op otherwise. */
415
+ connect(): void;
416
+ close(): void;
417
+ };
418
+ /**
419
+ * The link layer under peer-to-peer consumers: one peer connection per remote origin in the
420
+ * room, set up from relay membership and negotiated over relay `signal` frames. Each link
421
+ * carries the same labelled channels; frames are opaque strings, what they mean is the
422
+ * consumer's business.
423
+ *
424
+ * An origin is one seat: the relay hands a second connection with the same origin the seat
425
+ * and reports it to the room as a plain join. Links tell seats apart by instance, not by
426
+ * order: every link announces a random instance id in its signals and, once it knows the
427
+ * instance across, addresses its signals to it. A signal addressed to an instance this side
428
+ * no longer has is dropped. An unaddressed signal from an instance other than the one linked
429
+ * is a new seat or a restarted link, and this side rebuilds its end, addressed; an addressed
430
+ * one from a new instance is adopted. Only unaddressed signals cause a rebuild and a rebuilt
431
+ * end never sends one, so a takeover settles in one exchange. Two tabs with the same origin
432
+ * still take the seat from each other on every reconnect; give each tab its own origin.
433
+ */
434
+ declare function peerLinks(opt: PeerLinksOptions): PeerLinks;
435
+
333
436
  type WebRtcMeshOptions = {
334
437
  readonly room: string;
335
438
  readonly writer: string;
439
+ /**
440
+ * This replica's origin, its identity in the room; defaults to a random id per instance.
441
+ * One origin is one seat, so never share one between two live instances.
442
+ */
443
+ readonly origin?: string;
336
444
  /** Signaling path to the relay (ws or direct) — data flows peer-to-peer. */
337
445
  readonly signaling: MeshTransportFactory;
338
446
  /** Peer link factory; defaults to {@link rtcPeerConnector}. Injectable for tests. */
339
447
  readonly connector?: PeerConnector;
448
+ /**
449
+ * Further channels every link carries beside the mesh's own reliable one, for consumers
450
+ * that share the links (`rtcPresence`, say). Reach them through {@link WebRtcMeshRef.links}.
451
+ */
452
+ readonly channels?: readonly PeerChannelSpec[];
340
453
  readonly policies?: readonly MergePolicyEntry[];
341
454
  readonly policyVersion?: number;
342
455
  readonly injector?: Injector;
343
456
  };
344
457
  type WebRtcMeshRef = {
458
+ /** This replica's origin: what other peers see this side as, in `peers` and on the wire. */
459
+ readonly origin: string;
345
460
  readonly status: Signal<'connecting' | 'live'>;
346
461
  /** Origins with an OPEN data channel. */
347
462
  readonly peers: Signal<readonly string[]>;
463
+ /** The links the mesh runs on; other channels asked for in `channels` are sent on these. */
464
+ readonly links: PeerLinks;
348
465
  close(): void;
349
466
  };
350
467
  /**
@@ -363,5 +480,65 @@ type WebRtcMeshRef = {
363
480
  */
364
481
  declare function webRtcMesh<T extends object>(source: WritableSignal<T>, opt: WebRtcMeshOptions): WebRtcMeshRef;
365
482
 
366
- export { agentSeat, describeOp, directTransport, meshSync, rtcPeerConnector, setAtPath, webRtcMesh, webSocketTransport };
367
- export type { AgentSeat, AgentSeatOptions, DataChannelLike, MeshPeer, MeshStatus, MeshSyncOptions, MeshSyncRef, MeshTransport, MeshTransportFactory, PeerConnector, SeatChange, SeatEvent, SeatResync, SeatSync, StableSnapshot, SyncHealth, SyncHealthStatus, WebRtcMeshOptions, WebRtcMeshRef };
483
+ /**
484
+ * The channel `rtcPresence` uses by default. Lossy and unordered on purpose: a pointer that
485
+ * waits for a retransmit is already stale, and ordering would hold newer frames behind it.
486
+ * Put it in the `channels` of the {@link PeerLinks} the presence rides on.
487
+ */
488
+ declare const presenceChannel: PeerChannelSpec;
489
+ /**
490
+ * What goes over the wire. `seq` counts frames sent on one channel of one links object, in
491
+ * send order, and is shared by every sender created on those links; it never restarts while
492
+ * the links live. It orders frames of one link only, and is never compared across links.
493
+ */
494
+ type PresenceFrame<T> = {
495
+ readonly seq: number;
496
+ readonly value: T;
497
+ };
498
+ type RtcPresenceOptions = {
499
+ /** The channel label on the links; defaults to {@link presenceChannel}'s. */
500
+ readonly channel?: string;
501
+ /** Minimum gap between two published frames. Defaults to 33 ms (about 30 per second). */
502
+ readonly throttleMs?: number;
503
+ /**
504
+ * Who is in the room, from the relay. A value is held only for an origin in it: a peer link
505
+ * can outlive the relay membership on a dead socket, so the link is not proof of presence.
506
+ * Subscribe synchronously with the current roster, then report every transition, including
507
+ * a leave followed immediately by a rejoin. Use `links.onMembers` for the links' relay roster.
508
+ * A sampled signal or an effect cannot preserve these transitions.
509
+ */
510
+ readonly roster: (cb: (members: readonly string[]) => void) => () => void;
511
+ readonly injector?: Injector;
512
+ };
513
+ type RtcPresenceRef<T> = {
514
+ /** Publishes this side's value; throttled, and the last value of a burst always goes out. */
515
+ set(value: T): void;
516
+ /** The latest value per origin, only for origins in the roster. */
517
+ readonly peers: Signal<ReadonlyMap<string, T>>;
518
+ /** Stops publishing and forgets every held value. The links stay open. */
519
+ close(): void;
520
+ };
521
+ /**
522
+ * Ephemeral per-peer values (pointers, viewports) over peer links: last value per sender, no
523
+ * ordering, no retransmits, no catch-up and no persistence. A new link sees nothing until the
524
+ * sender's next `set`.
525
+ *
526
+ * Order comes from causality the receiver observes, never from clocks or from numbers chosen
527
+ * by different senders. A value is held only for an origin in the roster, and it is removed
528
+ * as soon as the origin leaves. Within one link the highest `seq` wins and anything at or
529
+ * below it is dropped: one counter stamps every frame sent on that link in send order, so a
530
+ * lower `seq` was sent earlier. A link that opens or closes starts its origin fresh, and a
531
+ * frame of an old link cannot arrive on a new one. An origin that leaves and comes back
532
+ * starts fresh. Every roster transition is consumed synchronously, even if no frame arrives
533
+ * and nobody reads `peers` between leave and rejoin.
534
+ *
535
+ * The counter belongs to the links and the channel, not to this sender, so a sender closed
536
+ * and recreated on the same links carries on where the last one stopped and is heard at
537
+ * once. A new tab or device is a new link, which every receiver already treats as fresh.
538
+ *
539
+ * Values travel as JSON.
540
+ */
541
+ declare function rtcPresence<T>(links: PeerLinks, opt: RtcPresenceOptions): RtcPresenceRef<T>;
542
+
543
+ export { agentSeat, defaultPeerChannels, describeOp, directTransport, meshSync, peerLinks, presenceChannel, rtcPeerConnector, rtcPresence, setAtPath, webRtcMesh, webSocketTransport };
544
+ export type { AgentSeat, AgentSeatOptions, DataChannelLike, MeshPeer, MeshStatus, MeshSyncOptions, MeshSyncRef, MeshTransport, MeshTransportFactory, PeerChannelSpec, PeerConnector, PeerLinks, PeerLinksOptions, PresenceFrame, RtcPresenceOptions, RtcPresenceRef, SeatChange, SeatEvent, SeatResync, SeatSync, SignalingPort, StableSnapshot, SyncHealth, SyncHealthStatus, WebRtcMeshOptions, WebRtcMeshRef };