@dim24/servin 0.2.2 → 1.1.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.
package/README.md CHANGED
@@ -28,6 +28,7 @@
28
28
  - [5.1 Static File & Folder Routing (`serveStatic` & `static`)](#51-static-file--folder-routing-servestatic--static)
29
29
  - [5.2 HTTP Redirects (`wire.redirect` & `redirect`)](#52-http-redirects-wireredirect--redirect)
30
30
  - [5.3 Custom Error Pages (`404`, `401`, `403`, `500`, etc.)](#53-custom-error-pages-404-401-403-500-etc)
31
+ - [5.4 Alias Routing (`alias`)](#54-alias-routing-alias)
31
32
  6. [Server Configuration (`serve`)](#6-server-configuration-serve)
32
33
  - [6.1 All `serve()` Options](#61-all-serve-options)
33
34
  - [6.2 Server Instance Control (`port`, `url`, `fetch`, `close`)](#62-server-instance-control-port-url-fetch-close)
@@ -505,7 +506,7 @@ const updated = await api.tasks.$id.patch(1, { done: true });
505
506
  await api.tasks.$id.delete(1);
506
507
  ```
507
508
 
508
- ### 4.3 Step 3: Consuming SSE Streams & WebSockets on the Client
509
+ ### 4.3 Step 3: Consuming SSE Streams
509
510
 
510
511
  `/@client.js` also translates Server-Sent Events and WebSockets into standard JavaScript `for await...of` async iterators:
511
512
 
@@ -516,14 +517,764 @@ import { api } from "/@client.js";
516
517
  for await (const tick of api.clock.get()) {
517
518
  console.log("Server tick:", tick);
518
519
  }
520
+ ```
521
+
522
+ ---
523
+
524
+ # Servin WebSocket Guide
525
+
526
+ `servin` provides a declarative, integrated directly into your domain routing tree (`api.<route>.ws`) and virtual ESM client (`/@client.js`). It is designed to work cleanly alongside standard HTTP routes, sessions, and route guards while supporting per-socket state, rooms, targeted socket filtering, payload/rate/backpressure guards, action validation, optional room state with sequence tracking (`seq`), ring-buffer replay on reconnect, and explicit client sync/refresh/resync controls.
527
+
528
+ ## Feature Overview & Scope
529
+
530
+ ### Included in the Final WebSocket API
531
+
532
+ - **Declarative `open`, `actions`, and `close` blocks:** Separates connection lifecycle hooks from named client-callable actions.
533
+
534
+ - **Per-socket context (`socket.state`):** Mutable state attached to a single socket instance across `open`, `actions`, and `close`.
535
+
536
+ - **Direct connection data (`api.<route>.ws({ ... })`):** Passes initial connection data directly as an object without wrapping it in `{ query: { ... } }`, mapped automatically to the WebSocket upgrade URL.
537
+
538
+ - **Built-in rooms & broadcasting (`join`, `leave`, `to(room).broadcast(...)`):** Groups sockets into channels and broadcasts events with optional exclusions (such as `except: socket`).
539
+
540
+ - **Targeted socket filtering (`sockets.where(predicate).send(...)`):** Filters active sockets dynamically by predicate and sends targeted messages without manual loops or room-wide broadcasts.
541
+
542
+ - **Guards & action validation:** Enforces payload size limits (`maxPayloadBytes`), inbound message rate limits (`maxEventsPerSec`), outbound backpressure limits (`maxBufferedBytes`), and per-action `validate` hooks.
543
+
544
+ - **Optional room state & `commit`:** Maintains shared state per room when `state(socket, req)` is defined, incrementing a monotonic `seq` counter on every `commit` and storing entries in a bounded ring buffer.
545
+
546
+ - **Automatic sequence sync, ring-buffer replay & snapshot fallback:** Tracks mutation sequence numbers, replays missed patches upon reconnect via `__lastSeq`, and falls back to a full snapshot when `__lastSeq` falls outside the ring buffer window.
547
+
548
+ - **Standalone client `.sync(callback)`:** Delivers synchronized state and metadata to user-managed client code without coupling the framework to DOM elements or rendering libraries.
549
+
550
+ - **Connection & sync controls (`ws.refresh(...)` and `ws.resync(...)`):** `ws.refresh(nextData)` closes and reopens the connection (optionally updating connection data), while `ws.resync(room)` requests a fresh full snapshot without closing the active socket.
551
+
552
+ ## Guide
553
+
554
+ ### Step 1: Basic Connection (`open`, `actions`, `close`, `.on()`, and `.emit()`)
555
+
556
+ Start with a minimal WebSocket endpoint on a route node (for example, `api.chat.ws`) and connect from the browser using `api.chat.ws()`.
557
+
558
+ #### Server
559
+
560
+ ```
561
+ import { serve } from './server.js';
562
+
563
+ await serve({
564
+ port: 3000,
565
+ api: {
566
+ chat: {
567
+ ws: {
568
+ //handle when client connect
569
+ open(socket) {
570
+ socket.send({ event: 'welcome', message: 'Connected to chat' });
571
+ },
572
+ //list all events
573
+ actions: {
574
+ //each event
575
+ ping(payload, socket) {
576
+ //send back to the client
577
+ socket.send({
578
+ event: 'pong',
579
+ payload: data,
580
+ sentAt: payload?.sentAt ?? null,
581
+ serverTime: Date.now()
582
+ });
583
+ }
584
+ },
585
+ close() {
586
+ // Clean up any non-room resources tied to this connection
587
+ }
588
+ }
589
+ }
590
+ }
591
+ });
592
+
593
+ ```
594
+
595
+ #### Client (`/@client.js`)
596
+
597
+ ```
598
+ import { api } from '/@client.js';
599
+
600
+ const ws = api.chat.ws();
601
+
602
+ ws
603
+ .on('open', ({ reconnected }) => {
604
+ console.log(reconnected ? 'Reconnected to chat' : 'Connected to chat');
605
+ //emit an event
606
+ ws.emit('ping', { data:"hello" });
607
+ })
608
+ .on('event', (data) => {
609
+ console.log('Received from server:', data);
610
+ })
611
+ .on('close', ({ code, reason, manual }) => {
612
+ console.log('Socket closed:', { code, reason, manual });
613
+ });
614
+
615
+ ```
616
+
617
+ #### How It Works
618
+
619
+ - Defining `ws` as an object inside an API node compiles a route with verb `WS` at that node's path (`/chat`).
620
+
621
+ - On the client, `ws.emit(actionName, payload)` serializes `{ type: 'action', name, payload }` and dispatches the matching handler in `actions`.
622
+
623
+ - Server-sent targeted events (`socket.send(...)`) arrive on the client under the `'event'` listener.
624
+
625
+ ### Step 2: Direct Connection Data & Per-Socket State (`socket.state`)
626
+
627
+ Pass initial connection data directly to `api.<route>.ws({ ... })` without a `{ query: { ... } }` wrapper. On the server, read those values from `req.data` and store connection-specific properties on `socket.state`.
628
+
629
+ #### Server
630
+
631
+ ```
632
+ api: {
633
+ presence: {
634
+ ws: {
635
+ open(socket, req) {
636
+ socket.state = {
637
+ userId: req.data.userId || 'anonymous',
638
+ role: req.data.role || 'member',
639
+ room: req.data.room || 'lobby'
640
+ };
641
+
642
+ socket.join(socket.state.room);
643
+ socket.send({
644
+ event: 'session_ready',
645
+ state: socket.state
646
+ });
647
+ },
648
+
649
+ actions: {
650
+ updateRole(payload, socket) {
651
+ if (!payload?.role) return;
652
+ socket.state.role = String(payload.role);
653
+ socket.send({
654
+ event: 'role_updated',
655
+ role: socket.state.role
656
+ });
657
+ }
658
+ },
659
+
660
+ close(socket) {
661
+ if (socket.state?.room) {
662
+ socket.leave(socket.state.room);
663
+ }
664
+ }
665
+ }
666
+ }
667
+ }
668
+
669
+ ```
670
+
671
+ #### Client
672
+
673
+ ```
674
+ import { api } from '/@client.js';
675
+
676
+ const ws = api.presence.ws({
677
+ userId: 'usr_42',
678
+ role: 'member',
679
+ room: 'lobby'
680
+ });
681
+
682
+ ws
683
+ .on('open', () => {
684
+ ws.emit('updateRole', { role: 'editor' });
685
+ })
686
+ .on('event', (msg) => {
687
+ console.log('Presence event:', msg);
688
+ });
689
+
690
+ ```
691
+
692
+ #### How It Works
693
+
694
+ - `api.presence.ws({ userId: 'usr_42', room: 'lobby' })` encodes top-level keys directly onto the WebSocket handshake URL query string.
695
+
696
+ - `req.data` exposes those connection parameters (excluding internal `__lastSeq`) cleanly in `open` and `state`.
697
+
698
+ - `socket.state` is a plain object scoped to a single socket connection, making it safe for per-user attributes like `userId`, `role`, or active `room`.
699
+
700
+ ### Step 3: Rooms & Broadcasting (`join`, `leave`, `to(room).broadcast`)
701
+
702
+ Group sockets into rooms using `socket.join(room)` and `socket.leave(room)`, and publish updates to room members via `socket.to(room).broadcast(data, options)`.
703
+
704
+ #### Server
519
705
 
520
- // 2. Consuming a WebSocket endpoint (async ws(room, socket))
521
- const room = api.chat.$room.ws("general");
522
- room.send({ text: "Hello everyone!" });
706
+ ```
707
+ api: {
708
+ rooms: {
709
+ ws: {
710
+ open(socket, req) {
711
+ const room = req.data.room || 'general';
712
+ const user = req.data.user || 'guest';
713
+
714
+ socket.state = { room, user };
715
+ socket.join(room);
716
+
717
+ socket.to(room).broadcast(
718
+ { data:here },
719
+ { except: socket } //if you need to excluded
720
+ );
721
+ },
722
+
723
+ actions: {
724
+ switchRoom(payload, socket) {
725
+ const nextRoom = String(payload?.room || '').trim();
726
+ if (!nextRoom) return;
727
+
728
+ const prevRoom = socket.state.room;
729
+ if (prevRoom) {
730
+ socket.leave(prevRoom);
731
+ socket.to(prevRoom).broadcast(
732
+ { type: 'member_left', user: socket.state.user, to: nextRoom },
733
+ { except: socket }
734
+ );
735
+ }
736
+
737
+ socket.state.room = nextRoom;
738
+ socket.join(nextRoom);
739
+ socket.to(nextRoom).broadcast(
740
+ { type: 'member_joined', user: socket.state.user, from: prevRoom },
741
+ { except: socket }
742
+ );
743
+ },
744
+
745
+ say(payload, socket) {
746
+ const { room, user } = socket.state;
747
+ if (!room) return;
523
748
 
524
- for await (const message of room) {
525
- console.log("Chat message:", message);
749
+ socket.to(room).broadcast(
750
+ { type: 'message', from: user, text: String(payload?.text ?? '') },
751
+ { except: socket }
752
+ );
753
+ }
754
+ },
755
+
756
+ close(socket) {
757
+ const { room, user } = socket.state || {};
758
+ if (room) {
759
+ socket.leave(room);
760
+ socket.to(room).broadcast(
761
+ { type: 'member_left', user },
762
+ { except: socket }
763
+ );
764
+ }
765
+ }
766
+ }
767
+ }
526
768
  }
769
+
770
+ ```
771
+
772
+ #### Client
773
+
774
+ ```
775
+ import { api } from '/@client.js';
776
+
777
+ const ws = api.rooms.ws({ room: 'general', user: 'maya' });
778
+
779
+ ws
780
+ .on('broadcast', ({ room, payload }) => {
781
+ console.log(`[${room}]`, payload);
782
+ })
783
+ .on('open', () => {
784
+ ws.emit('say', { text: 'Hello room!' });
785
+ ws.emit('switchRoom', { room: 'engineering' });
786
+ });
787
+
788
+ ```
789
+
790
+ #### How It Works
791
+
792
+ - `socket.to(room).broadcast(data, { except })` sends a `'broadcast'` envelope `{ type: 'broadcast', room, payload }` to open sockets subscribed to `room`.
793
+
794
+ - Passing `{ except: socket }` prevents echoing a peer's own action back to the sender. By default, `except` excludes the acting `socket`.
795
+
796
+ - Always call `socket.leave(room)` when switching rooms or in `close` so room memberships stay accurate.
797
+
798
+ ### Step 4: Targeted Socket Filtering (`sockets.where(...)`)
799
+
800
+ When you need to reach a subset of active connections based on dynamic attributes (such as role, workspace, or tenant) rather than an entire room, use `sockets.where(predicate).send(data)` from the action helpers object.
801
+
802
+ #### Server
803
+
804
+ ```
805
+ api: {
806
+ support: {
807
+ ws: {
808
+ open(socket, req) {
809
+ socket.state = {
810
+ userId: req.data.userId || 'guest',
811
+ role: req.data.role || 'customer',
812
+ tier: req.data.tier || 'standard'
813
+ };
814
+ },
815
+
816
+ actions: {
817
+ escalate(payload, socket, { sockets }) {
818
+ const target = sockets.where(
819
+ (peer) =>
820
+ peer !== socket &&
821
+ peer.state?.role === 'agent' &&
822
+ peer.state?.tier === 'enterprise'
823
+ );
824
+
825
+ target.send({
826
+ type: 'escalation',
827
+ from: socket.state.userId,
828
+ issue: String(payload?.issue ?? '')
829
+ });
830
+
831
+ socket.send({
832
+ type: 'escalation_ack',
833
+ notifiedAgents: target.count
834
+ });
835
+ }
836
+ }
837
+ }
838
+ }
839
+ }
840
+
841
+ ```
842
+
843
+ #### Client
844
+
845
+ ```
846
+ import { api } from '/@client.js';
847
+
848
+ const ws = api.support.ws({
849
+ userId: 'cust_99',
850
+ role: 'customer',
851
+ tier: 'enterprise'
852
+ });
853
+
854
+ ws
855
+ .on('event', (msg) => {
856
+ if (msg.type === 'escalation_ack') {
857
+ console.log(`Notified ${msg.notifiedAgents} enterprise agents`);
858
+ }
859
+ if (msg.type === 'escalation') {
860
+ console.log('Incoming escalation:', msg);
861
+ }
862
+ })
863
+ .on('open', () => {
864
+ ws.emit('escalate', { issue: 'Production webhook timeout' });
865
+ });
866
+
867
+ ```
868
+
869
+ #### How It Works
870
+
871
+ - `sockets.where(predicate)` evaluates `predicate(peerSocket)` across active sockets and returns `{ sockets, count, send(data) }`.
872
+
873
+ - Calling `.send(data)` delivers `{ type: 'event', payload: data }` to every matched socket.
874
+
875
+ - Because `socket.state` is checked inside the predicate, filtering reflects live state changes made during the session.
876
+
877
+ ### Step 5: Guards, Backpressure & Action Validation
878
+
879
+ Protect your endpoint against oversized frames, message floods, slow consumers, and malformed action payloads using route-level guard options and action `{ validate, run }` definitions.
880
+
881
+ #### Server
882
+
883
+ ```
884
+ api: {
885
+ tasks: {
886
+ ws: {
887
+ maxPayloadBytes: 16384, // Reject incoming frames larger than 16 KB
888
+ maxEventsPerSec: 20, // Cap inbound messages per socket per second
889
+ maxBufferedBytes: 131072, // Close slow sockets exceeding 128 KB outbound buffer
890
+
891
+ open(socket, req) {
892
+ socket.state = {
893
+ room: req.data.room || 'sprint-1',
894
+ actor: req.data.actor || 'member'
895
+ };
896
+ socket.join(socket.state.room);
897
+ },
898
+
899
+ actions: {
900
+ addTask: {
901
+ validate(payload) {
902
+ const title = String(payload?.title ?? '').trim();
903
+ if (!title) {
904
+ throw new Error('VALIDATION_TITLE_REQUIRED');
905
+ }
906
+ if (title.length > 120) {
907
+ throw new Error('VALIDATION_TITLE_TOO_LONG');
908
+ }
909
+ return { title };
910
+ },
911
+
912
+ run(cleanPayload, socket, { commit }) {
913
+ const { room, actor } = socket.state;
914
+ commit(room, { op: 'add_task', actor }, (draft) => {
915
+ draft.tasks = draft.tasks || [];
916
+ draft.tasks.push({
917
+ id: `${Date.now()}-${Math.random().toString(36).slice(2, 7)}`,
918
+ title: cleanPayload.title,
919
+ completed: false
920
+ });
921
+ });
922
+ }
923
+ }
924
+ }
925
+ }
926
+ }
927
+ }
928
+
929
+ ```
930
+
931
+ #### Client
932
+
933
+ ```
934
+ import { api } from '/@client.js';
935
+
936
+ const ws = api.tasks.ws({ room: 'sprint-1', actor: 'alex' });
937
+
938
+ ws
939
+ .on('error', (err) => {
940
+ console.error('Server rejected request:', err);
941
+ })
942
+ .on('open', () => {
943
+ // Triggers validation error -> sent back via 'error' event
944
+ ws.emit('addTask', { title: ' ' });
945
+
946
+ // Passes validation -> mutates room state via commit
947
+ ws.emit('addTask', { title: 'Ship WebSocket guide' });
948
+ });
949
+
950
+ ```
951
+
952
+ #### How It Works
953
+
954
+ - `maxPayloadBytes` checks incoming WebSocket frame payload length before parsing.
955
+
956
+ - `maxEventsPerSec` tracks a 1-second window per socket and emits `{ type: 'error', message: 'RATE_LIMIT_EXCEEDED' }` when exceeded.
957
+
958
+ - `maxBufferedBytes` monitors `socket.bufferedAmount` (`tcpSocket.writableLength`) before writing outbound frames, closing sockets that fall too far behind.
959
+
960
+ - When an action is defined as `{ validate, run }`, `validate` runs first; if it throws, `run` is skipped and `{ type: 'error', action, message }` is sent back to the caller socket.
961
+
962
+ ### Step 6: Room State, `commit`, `seq`, Ring Buffer Replay & `.sync(...)`
963
+
964
+ Add a `state(socket, req)` hook to enable room-level synchronized state. Every `commit(room, meta, mutator)` mutates the room state in place, increments `seq`, records the update in a bounded ring buffer (`sync.bufferSize`), and pushes state updates to room subscribers.
965
+
966
+ #### Server
967
+
968
+ ```
969
+ api: {
970
+ board: {
971
+ ws: {
972
+ sync: {
973
+ bufferSize: 100
974
+ },
975
+
976
+ state(socket, req) {
977
+ const room = req.data.room || 'default-board';
978
+ return {
979
+ room,
980
+ items: []
981
+ };
982
+ },
983
+
984
+ open(socket, req) {
985
+ const room = req.data.room || 'default-board';
986
+ socket.state = {
987
+ room,
988
+ user: req.data.user || 'guest'
989
+ };
990
+ if (!socket.rooms.has(room)) {
991
+ socket.join(room);
992
+ }
993
+ },
994
+
995
+ actions: {
996
+ toggleItem: {
997
+ validate(payload) {
998
+ const id = String(payload?.id ?? '').trim();
999
+ if (!id) throw new Error('ITEM_ID_REQUIRED');
1000
+ return { id };
1001
+ },
1002
+ run({ id }, socket, { commit }) {
1003
+ const { room, user } = socket.state;
1004
+ commit(room, { op: 'toggle_item', by: user, id }, (draft) => {
1005
+ const item = draft.items.find((entry) => entry.id === id);
1006
+ if (item) {
1007
+ item.done = !item.done;
1008
+ }
1009
+ });
1010
+ }
1011
+ },
1012
+
1013
+ createItem: {
1014
+ validate(payload) {
1015
+ const label = String(payload?.label ?? '').trim();
1016
+ if (!label) throw new Error('LABEL_REQUIRED');
1017
+ return { label };
1018
+ },
1019
+ run({ label }, socket, { commit }) {
1020
+ const { room, user } = socket.state;
1021
+ commit(room, { op: 'create_item', by: user }, (draft) => {
1022
+ draft.items.push({
1023
+ id: `item_${Date.now()}_${Math.random().toString(36).slice(2, 6)}`,
1024
+ label,
1025
+ done: false
1026
+ });
1027
+ });
1028
+ }
1029
+ }
1030
+ }
1031
+ }
1032
+ }
1033
+ }
1034
+
1035
+ ```
1036
+
1037
+ #### Client
1038
+
1039
+ ```
1040
+ import { api } from '/@client.js';
1041
+
1042
+ let latestBoardState = null;
1043
+
1044
+ const ws = api.board.ws({
1045
+ room: 'default-board',
1046
+ user: 'maya'
1047
+ });
1048
+
1049
+ ws.sync((state, meta) => {
1050
+ // Store and render state in your own application layer
1051
+ latestBoardState = state;
1052
+ console.log('State synced:', {
1053
+ seq: meta.seq,
1054
+ room: meta.room,
1055
+ fullSnapshot: meta.fullSnapshot,
1056
+ replayed: meta.replayed,
1057
+ meta: meta.meta ?? null
1058
+ });
1059
+ renderBoardView(latestBoardState);
1060
+ });
1061
+
1062
+ ```
1063
+
1064
+ #### How It Works
1065
+
1066
+ - On initial connection (when `__lastSeq` is `0`), the server sends a `sync_snapshot` (`fullSnapshot: true, replayed: false`) with the current `seq` and `state`.
1067
+
1068
+ - On `commit`, the server increments `seq`, pushes `{ seq, meta, state }` into the room's ring buffer, and sends `sync_patch` (`fullSnapshot: false, replayed: false`) to members of that room.
1069
+
1070
+ - On automatic reconnect, the client appends `__lastSeq=<lastSeq>` to the WebSocket URL:
1071
+ - If `lastSeq` is within the ring buffer range, missed entries are replayed in order with `replayed: true`.
1072
+
1073
+ - If `lastSeq` is too old or outside the ring buffer range, the server falls back to sending a `sync_snapshot` (`fullSnapshot: true`).
1074
+
1075
+ - `.sync(callback)` is standalone: if a snapshot has already arrived when `.sync` is attached, `callback` is immediately invoked with the current state so late subscribers stay up to date.
1076
+
1077
+ ### Step 7: Refreshing Connections & Manual Resync (`ws.refresh(...)` & `ws.resync(...)`)
1078
+
1079
+ Use `ws.refresh(nextData)` when you want to close and reopen the socket—such as moving to another room or changing connection parameters—and `ws.resync(room)` when you want a fresh snapshot without closing the active connection.
1080
+
1081
+ #### Client
1082
+
1083
+ ```
1084
+ import { api } from '/@client.js';
1085
+
1086
+ const ws = api.board.ws({
1087
+ room: 'sprint-1',
1088
+ user: 'maya'
1089
+ });
1090
+
1091
+ ws.sync((state, meta) => {
1092
+ console.log(`Room ${meta.room} @ seq ${meta.seq}`, state);
1093
+ });
1094
+
1095
+ // Close and reopen the connection with updated connection data (no { query: ... } wrapper)
1096
+ function moveToSprint(nextRoom) {
1097
+ ws.refresh({ room: nextRoom });
1098
+ }
1099
+
1100
+ // Request a full state snapshot while keeping the current WebSocket open
1101
+ function requestFreshSnapshot() {
1102
+ ws.resync('sprint-2');
1103
+ }
1104
+
1105
+ ```
1106
+
1107
+ #### How It Works
1108
+
1109
+ - `ws.refresh(nextData)` merges any provided `nextData` object into the connection data, resets `lastSeq` to `0`, closes the existing socket cleanly, and opens a new connection with the updated URL.
1110
+
1111
+ - `ws.resync(room)` sends `{ type: 'resync', room }` over the open socket, prompting the server to send a `sync_snapshot` for the target room.
1112
+
1113
+ ### Step 8: Complete End-to-End Example
1114
+
1115
+ Below is a complete, self-contained example combining direct connection data, `socket.state`, rooms & `broadcast`, `sockets.where(...)`, guards & `validate`, room state + `commit` + `seq` replay, `.sync(...)`, `.refresh(...)`, and `.resync(...)`.
1116
+
1117
+ #### Server (`server.js` entry)
1118
+
1119
+ ```
1120
+ import { serve } from './server.js';
1121
+
1122
+ await serve({
1123
+ port: 3000,
1124
+ api: {
1125
+ workspace: {
1126
+ ws: {
1127
+ maxPayloadBytes: 32768,
1128
+ maxEventsPerSec: 25,
1129
+ maxBufferedBytes: 262144,
1130
+ sync: {
1131
+ bufferSize: 100
1132
+ },
1133
+
1134
+ state(socket, req) {
1135
+ const room = req.data.room || 'general';
1136
+ return {
1137
+ room,
1138
+ notes: []
1139
+ };
1140
+ },
1141
+
1142
+ open(socket, req) {
1143
+ const room = req.data.room || 'general';
1144
+ const user = req.data.user || 'guest';
1145
+ const role = req.data.role || 'member';
1146
+
1147
+ socket.state = { room, user, role };
1148
+ if (!socket.rooms.has(room)) {
1149
+ socket.join(room);
1150
+ }
1151
+
1152
+ socket.to(room).broadcast(
1153
+ { event: 'presence', status: 'online', user },
1154
+ { except: socket }
1155
+ );
1156
+ },
1157
+
1158
+ actions: {
1159
+ addNote: {
1160
+ validate(payload) {
1161
+ const text = String(payload?.text ?? '').trim();
1162
+ if (!text) throw new Error('NOTE_TEXT_REQUIRED');
1163
+ return { text };
1164
+ },
1165
+ run({ text }, socket, { commit }) {
1166
+ const { room, user } = socket.state;
1167
+ commit(room, { op: 'add_note', author: user }, (draft) => {
1168
+ draft.notes.push({
1169
+ id: `${Date.now()}-${Math.random().toString(36).slice(2, 6)}`,
1170
+ author: user,
1171
+ text
1172
+ });
1173
+ });
1174
+ }
1175
+ },
1176
+
1177
+ removeNote: {
1178
+ validate(payload) {
1179
+ const id = String(payload?.id ?? '').trim();
1180
+ if (!id) throw new Error('NOTE_ID_REQUIRED');
1181
+ return { id };
1182
+ },
1183
+ run({ id }, socket, { commit }) {
1184
+ const { room, user } = socket.state;
1185
+ commit(room, { op: 'remove_note', actor: user, id }, (draft) => {
1186
+ draft.notes = draft.notes.filter((note) => note.id !== id);
1187
+ });
1188
+ }
1189
+ },
1190
+
1191
+ pingRole: {
1192
+ validate(payload) {
1193
+ const role = String(payload?.role ?? '').trim();
1194
+ if (!role) throw new Error('TARGET_ROLE_REQUIRED');
1195
+ return {
1196
+ role,
1197
+ message: String(payload?.message ?? '')
1198
+ };
1199
+ },
1200
+ run({ role, message }, socket, { sockets }) {
1201
+ sockets
1202
+ .where((peer) => peer !== socket && peer.state?.role === role)
1203
+ .send({
1204
+ event: 'role_ping',
1205
+ from: socket.state.user,
1206
+ message
1207
+ });
1208
+ }
1209
+ }
1210
+ },
1211
+
1212
+ close(socket) {
1213
+ const { room, user } = socket.state || {};
1214
+ if (room) {
1215
+ socket.leave(room);
1216
+ socket.to(room).broadcast(
1217
+ { event: 'presence', status: 'offline', user },
1218
+ { except: socket }
1219
+ );
1220
+ }
1221
+ }
1222
+ }
1223
+ }
1224
+ }
1225
+ });
1226
+
1227
+ ```
1228
+
1229
+ #### Client (`client.js`)
1230
+
1231
+ ```
1232
+ import { api } from '/@client.js';
1233
+
1234
+ let workspaceState = null;
1235
+
1236
+ const ws = api.workspace.ws({
1237
+ room: 'general',
1238
+ user: 'maya',
1239
+ role: 'lead'
1240
+ });
1241
+
1242
+ ws
1243
+ .on('open', ({ reconnected }) => {
1244
+ console.log(reconnected ? 'Reconnected to workspace' : 'Connected to workspace');
1245
+ })
1246
+ .on('broadcast', ({ room, payload }) => {
1247
+ console.log(`Broadcast in ${room}:`, payload);
1248
+ })
1249
+ .on('event', (payload) => {
1250
+ console.log('Targeted event:', payload);
1251
+ })
1252
+ .on('error', (err) => {
1253
+ console.error('WS error:', err);
1254
+ })
1255
+ .sync((state, meta) => {
1256
+ workspaceState = state;
1257
+ console.log('Synced state:', {
1258
+ seq: meta.seq,
1259
+ room: meta.room,
1260
+ fullSnapshot: meta.fullSnapshot,
1261
+ replayed: meta.replayed,
1262
+ notesCount: workspaceState?.notes?.length ?? 0
1263
+ });
1264
+ });
1265
+
1266
+ // Add a note to the current room state
1267
+ ws.emit('addNote', { text: 'Kickoff sync notes' });
1268
+
1269
+ // Send a targeted message only to other connected sockets with role 'lead'
1270
+ ws.emit('pingRole', { role: 'lead', message: 'Check latest notes' });
1271
+
1272
+ // Switch room with a fresh connection and updated connection data
1273
+ ws.refresh({ room: 'planning' });
1274
+
1275
+ // Request a full snapshot without closing the connection
1276
+ ws.resync('planning');
1277
+
527
1278
  ```
528
1279
 
529
1280
  ---
@@ -711,6 +1462,53 @@ await serve({
711
1462
  | `error` | `Error \| null` | Original thrown error instance if available. |
712
1463
  | `wire` | `object` | Active `wire` ambient context handle. |
713
1464
 
1465
+ ### 5.4 Alias Routing (`alias`)
1466
+
1467
+ Unlike `redirect()` (which responds with a `301`/`302` redirect and changes the browser URL), **alias routing** maps a URL path internally to another static file or API route without changing the URL in the client's browser.
1468
+
1469
+ **1. Config-level aliases via `serve({ alias })`:**
1470
+
1471
+ ```javascript
1472
+ import { serve } from "servin";
1473
+
1474
+ await serve({
1475
+ port: 3000,
1476
+ static: {
1477
+ "/": "./public", // contains home.html, pages/intro.html
1478
+ },
1479
+ alias: {
1480
+ "/": "/home.html",
1481
+ "/home": "/home.html",
1482
+ "/docs/$slug": "/pages/$slug.html",
1483
+ },
1484
+ });
1485
+ ```
1486
+
1487
+ **2. Tree-level `alias(target)` helper inside `api` (composable with `guard()` and `param()`):**
1488
+
1489
+ ```javascript
1490
+ import { serve, alias, guard, param } from "servin";
1491
+
1492
+ await serve({
1493
+ port: 3000,
1494
+ static: { "/": "./public" },
1495
+ api: {
1496
+ home: alias("/home.html"),
1497
+ secret: guard(requireAuth, alias("/secret.html")),
1498
+ user: {
1499
+ $id: param("int", alias((id) => `/v2/users/${id}`)),
1500
+ },
1501
+ v2: {
1502
+ users: {
1503
+ $id: param("int", {
1504
+ get: (id) => ({ userId: id }),
1505
+ }),
1506
+ },
1507
+ },
1508
+ },
1509
+ });
1510
+ ```
1511
+
714
1512
  ---
715
1513
 
716
1514
  ## 6. Server Configuration (`serve`)
@@ -723,6 +1521,7 @@ await serve({
723
1521
  | `host` | `string` | `'127.0.0.1'` | Host interface to bind (use `'0.0.0.0'` inside Docker/containers). |
724
1522
  | `api` | `object` | `{}` | Root domain object defining all routes. |
725
1523
  | `static` | `string \| StaticDescriptor \| object` | `null` | Root or prefix-mapped static files/directories (e.g., `{ '/assets': './public' }`). |
1524
+ | `alias` | `object \| null` | `null` | Internal route aliases mapping paths to target paths/resolvers (e.g., `{ '/home': '/home.html' }`). |
726
1525
  | `errors` | `object` | `undefined` | Custom status handlers (`404`, `401`, `403`, `500`, `'4xx'`, `'5xx'`, `default`). |
727
1526
  | `types` | `object` | `{}` | Named custom parameter types usable via `param('typeName', branch)`. |
728
1527
  | `session` | `object \| null` | `null` | Session config `{ secret, ttl, cookieName, rolling, secure, sameSite, store }`. |
@@ -1390,76 +2189,6 @@ const exportsApi = {
1390
2189
 
1391
2190
  ---
1392
2191
 
1393
- ## 11. Linear WebSockets & Pub/Sub
1394
-
1395
- ### 11.1 Step 1: Minimal Echo WebSocket (`ws` & `for await`)
1396
-
1397
- Add a `ws(socket)` method anywhere in your tree and iterate over incoming messages linearly with `for await`:
1398
-
1399
- ```javascript
1400
- const echo = {
1401
- // WS /echo
1402
- async ws(socket) {
1403
- socket.send({ status: "connected" });
1404
-
1405
- for await (const msg of socket) {
1406
- socket.send({ echoed: msg });
1407
- }
1408
- },
1409
- };
1410
- ```
1411
-
1412
- ### 11.2 Step 2: Rooms & Pub/Sub Broadcasting (`socket.join`, `wire.publish`)
1413
-
1414
- Subscribe sockets to named topics and broadcast messages from either WebSocket handlers or HTTP routes:
1415
-
1416
- ```javascript
1417
- const chat = {
1418
- $room: {
1419
- // WS /chat/:room
1420
- async ws(room, socket) {
1421
- socket.join(`room:${room}`);
1422
- socket.broadcast(`room:${room}`, { event: "joined" });
1423
-
1424
- for await (const msg of socket) {
1425
- wire.publish(`room:${room}`, { text: msg.text });
1426
- }
1427
- },
1428
- },
1429
-
1430
- // Any HTTP route can also publish to WebSocket subscribers!
1431
- announce: {
1432
- post({ room, text }) {
1433
- wire.publish(`room:${room}`, { announcement: text });
1434
- return { sent: true };
1435
- },
1436
- },
1437
- };
1438
- ```
1439
-
1440
- ### 11.3 Step 3: Guarded WebSockets & `wsConfig`
1441
-
1442
- Combine `guard()`, `param()`, and `wsConfig` (`heartbeat`, `maxPayload`, `binary`) on the same branch:
1443
-
1444
- ```javascript
1445
- const liveStream = guard(requireAuth, {
1446
- wsConfig: {
1447
- maxPayload: "256kb",
1448
- heartbeat: "30s",
1449
- },
1450
- $channelId: param("int", {
1451
- async ws(channelId, socket) {
1452
- socket.join(`ch:${channelId}`);
1453
- for await (const msg of socket) {
1454
- socket.broadcast(`ch:${channelId}`, msg);
1455
- }
1456
- },
1457
- }),
1458
- });
1459
- ```
1460
-
1461
- ---
1462
-
1463
2192
  ## 12. Streaming File Uploads (`wire.multipart` & `rawBody`)
1464
2193
 
1465
2194
  **1. Streaming `multipart/form-data` without buffering in RAM:**
@@ -1613,7 +2342,6 @@ await replay(
1613
2342
  | `wire.multipart(opts)` | `(opts?) => AsyncGenerator` | Iterates streaming `multipart/form-data` fields and files sequentially. |
1614
2343
  | `wire.session` | `Proxy \| null` | Lazy encrypted session object (`.rotate()`, `.bind(userId)`, or `wire.session = null`). |
1615
2344
  | `wire.sessions` | `{ list, revokeOthers }` | Multi-device session listing and remote session revocation helpers. |
1616
- | `wire.publish(topic, data)` | `(string, any) => void` | Broadcasts a message to all WebSocket clients subscribed to `topic`. |
1617
2345
  | `wire.cost(points)` | `(number) => void` | Adjusts rate-limit quota consumption for the current request. |
1618
2346
  | `wire.log.debug(msg, meta)` | `(string, any?) => void` | Buffers a debug log entry emitted only on unhandled errors. |
1619
2347
  | `wire.mark(label)` | `(string) => () => number` | Starts a performance timer; calling the returned function records `Server-Timing`. |