verani 0.8.0 → 0.8.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/README.md CHANGED
@@ -35,7 +35,7 @@ import { defineRoom, createActorHandler } from "verani";
35
35
 
36
36
  // Define your room with lifecycle hooks
37
37
  export const chatRoom = defineRoom({
38
- name: "chat",
38
+ name: "chatRoom",
39
39
  websocketPath: "/chat",
40
40
 
41
41
  onConnect(ctx) {
@@ -64,13 +64,17 @@ chatRoom.on("chat.message", (ctx, data) => {
64
64
  });
65
65
  });
66
66
 
67
- // Create the Durable Object class
67
+ // Create the Durable Object class from the room definition
68
+ // Important: Each defineRoom() creates a room definition object.
69
+ // createActorHandler() converts it into a Durable Object class that must be exported.
68
70
  export const ChatRoom = createActorHandler(chatRoom);
69
71
  ```
70
72
 
71
73
  ### Wrangler Configuration
72
74
 
73
- **Critical**: Your Durable Object export names in `src/index.ts` **must match** the `class_name` in `wrangler.jsonc`:
75
+ **Critical**: Each `defineRoom()` creates a room definition, and `createActorHandler()` converts it into a Durable Object class. This class **must be exported** and **declared in Wrangler configuration**.
76
+
77
+ The export name in `src/index.ts` **must match** the `class_name` in `wrangler.jsonc`:
74
78
 
75
79
  ```jsonc
76
80
  {
@@ -91,10 +95,18 @@ export const ChatRoom = createActorHandler(chatRoom);
91
95
  }
92
96
  ```
93
97
 
94
- The three-way relationship:
95
- 1. **Export** in `src/index.ts`: `export { ChatRoom }`
96
- 2. **Class name** in `wrangler.jsonc`: `"class_name": "ChatRoom"`
97
- 3. **Env binding**: Access via `env.ChatRoom` in your fetch handler
98
+ **Three-way relationship** - these must all align:
99
+
100
+ 1. **Room definition**: `defineRoom({ name: "ChatRoom" })` - The `name` property is optional but recommended for consistency
101
+ 2. **Export** in `src/index.ts`: `export const ChatRoom = createActorHandler(chatRoom)` - The export name becomes the class name
102
+ 3. **Class name** in `wrangler.jsonc`: `"class_name": "ChatRoom"` - Must match the export name exactly
103
+
104
+ **Important Notes:**
105
+ - `defineRoom()` returns a room definition object, **not** a Durable Object class
106
+ - `createActorHandler(room)` creates the actual Durable Object class
107
+ - Each room definition must be converted to a class with `createActorHandler()` and exported
108
+ - For multiple rooms, you need multiple exports and multiple bindings in `wrangler.jsonc`
109
+ - The export name (e.g., `ChatRoom`) becomes the class name and must match `class_name` in configuration
98
110
 
99
111
  ### Client Side
100
112
 
@@ -181,6 +193,9 @@ Verani handles Cloudflare's hibernation automatically:
181
193
  - **[Concepts](./docs/concepts/)** - Architecture, hibernation, and core concepts
182
194
  - **[Security](./docs/security/)** - Authentication, authorization, and best practices
183
195
 
196
+ ## More Examples
197
+ **[Vchats](https://github.com/v0id-user/vchats)** - A simple chat application built with Verani
198
+
184
199
  ## Features
185
200
 
186
201
  ### Server (Actor) Side
@@ -1,4 +1,4 @@
1
- import { n as ConnectionMeta, r as MessageFrame } from "./types-Ds_V-GWZ.mjs";
1
+ import { n as ConnectionMeta, r as MessageFrame } from "./types-DOI6EHQJ.cjs";
2
2
  import { Actor, ActorConfiguration } from "@cloudflare/actors";
3
3
 
4
4
  //#region src/actor/persist.d.ts
@@ -1,4 +1,4 @@
1
- import { n as ConnectionMeta, r as MessageFrame } from "./types-BefWc1M_.cjs";
1
+ import { n as ConnectionMeta, r as MessageFrame } from "./types-_41fL9Dn.mjs";
2
2
  import { Actor, ActorConfiguration } from "@cloudflare/actors";
3
3
 
4
4
  //#region src/actor/persist.d.ts
@@ -17,7 +17,9 @@ interface ReconnectionConfig {
17
17
  }
18
18
  declare const DEFAULT_RECONNECTION_CONFIG: ReconnectionConfig;
19
19
  /**
20
- * Manages WebSocket connection lifecycle and reconnection logic
20
+ * Manages WebSocket connection lifecycle and reconnection logic.
21
+ * Tracks connection state transitions, schedules reconnection attempts with exponential backoff,
22
+ * and validates state transitions to ensure consistency.
21
23
  */
22
24
  declare class ConnectionManager {
23
25
  private config;
@@ -28,43 +30,69 @@ declare class ConnectionManager {
28
30
  private currentDelay;
29
31
  constructor(config?: ReconnectionConfig, onStateChange?: ((state: ConnectionState) => void) | undefined);
30
32
  /**
31
- * Gets the current connection state
33
+ * Gets the current connection state.
34
+ *
35
+ * @returns The current connection state ("connecting", "connected", "disconnected", "reconnecting", or "error")
32
36
  */
33
37
  getState(): ConnectionState;
34
38
  /**
35
- * Validates if a state transition is valid
39
+ * Validates if a state transition is valid.
40
+ * Ensures that state changes follow a logical flow and prevents invalid transitions.
41
+ *
42
+ * @param from - The current state
43
+ * @param to - The target state
44
+ * @returns True if the transition is valid, false otherwise
36
45
  */
37
46
  private isValidStateTransition;
38
47
  /**
39
- * Updates the connection state and notifies listeners
48
+ * Updates the connection state and notifies listeners.
49
+ * Validates the state transition and logs warnings for invalid transitions.
50
+ * Only triggers callbacks if the state actually changes.
51
+ *
52
+ * @param newState - The new connection state to transition to
40
53
  */
41
54
  setState(newState: ConnectionState): void;
42
55
  /**
43
- * Resets reconnection state (called on successful connection)
56
+ * Resets reconnection state (called on successful connection).
57
+ * Clears the reconnection attempt counter and resets the delay to the initial value.
58
+ * Also cancels any pending reconnection timers.
44
59
  */
45
60
  resetReconnection(): void;
46
61
  /**
47
- * Schedules a reconnection attempt
62
+ * Schedules a reconnection attempt with exponential backoff.
63
+ * Checks if reconnection is enabled and if max attempts haven't been reached.
64
+ * Updates the delay for the next attempt using exponential backoff.
65
+ *
66
+ * @param connectFn - Function to call when it's time to reconnect
67
+ * @returns True if reconnection was scheduled, false if reconnection is disabled or max attempts reached
48
68
  */
49
69
  scheduleReconnect(connectFn: () => void): boolean;
50
70
  /**
51
- * Cancels any pending reconnection
71
+ * Cancels any pending reconnection attempt.
72
+ * Clears the reconnection timer and transitions state from "reconnecting" to "disconnected" if applicable.
52
73
  */
53
74
  cancelReconnect(): void;
54
75
  /**
55
- * Clears the reconnect timer
76
+ * Clears the reconnect timer if one is set.
77
+ * Internal helper method used to clean up pending reconnection attempts.
56
78
  */
57
79
  private clearReconnectTimer;
58
80
  /**
59
- * Gets the current reconnection attempt count
81
+ * Gets the current reconnection attempt count.
82
+ *
83
+ * @returns The number of reconnection attempts made so far
60
84
  */
61
85
  getReconnectAttempts(): number;
62
86
  /**
63
- * Gets the next reconnection delay
87
+ * Gets the next reconnection delay in milliseconds.
88
+ * This value increases with each attempt due to exponential backoff.
89
+ *
90
+ * @returns The delay in milliseconds before the next reconnection attempt
64
91
  */
65
92
  getNextDelay(): number;
66
93
  /**
67
- * Cleanup method
94
+ * Cleanup method that clears all timers and resources.
95
+ * Should be called when the ConnectionManager is no longer needed.
68
96
  */
69
97
  destroy(): void;
70
98
  }
@@ -17,7 +17,9 @@ interface ReconnectionConfig {
17
17
  }
18
18
  declare const DEFAULT_RECONNECTION_CONFIG: ReconnectionConfig;
19
19
  /**
20
- * Manages WebSocket connection lifecycle and reconnection logic
20
+ * Manages WebSocket connection lifecycle and reconnection logic.
21
+ * Tracks connection state transitions, schedules reconnection attempts with exponential backoff,
22
+ * and validates state transitions to ensure consistency.
21
23
  */
22
24
  declare class ConnectionManager {
23
25
  private config;
@@ -28,43 +30,69 @@ declare class ConnectionManager {
28
30
  private currentDelay;
29
31
  constructor(config?: ReconnectionConfig, onStateChange?: ((state: ConnectionState) => void) | undefined);
30
32
  /**
31
- * Gets the current connection state
33
+ * Gets the current connection state.
34
+ *
35
+ * @returns The current connection state ("connecting", "connected", "disconnected", "reconnecting", or "error")
32
36
  */
33
37
  getState(): ConnectionState;
34
38
  /**
35
- * Validates if a state transition is valid
39
+ * Validates if a state transition is valid.
40
+ * Ensures that state changes follow a logical flow and prevents invalid transitions.
41
+ *
42
+ * @param from - The current state
43
+ * @param to - The target state
44
+ * @returns True if the transition is valid, false otherwise
36
45
  */
37
46
  private isValidStateTransition;
38
47
  /**
39
- * Updates the connection state and notifies listeners
48
+ * Updates the connection state and notifies listeners.
49
+ * Validates the state transition and logs warnings for invalid transitions.
50
+ * Only triggers callbacks if the state actually changes.
51
+ *
52
+ * @param newState - The new connection state to transition to
40
53
  */
41
54
  setState(newState: ConnectionState): void;
42
55
  /**
43
- * Resets reconnection state (called on successful connection)
56
+ * Resets reconnection state (called on successful connection).
57
+ * Clears the reconnection attempt counter and resets the delay to the initial value.
58
+ * Also cancels any pending reconnection timers.
44
59
  */
45
60
  resetReconnection(): void;
46
61
  /**
47
- * Schedules a reconnection attempt
62
+ * Schedules a reconnection attempt with exponential backoff.
63
+ * Checks if reconnection is enabled and if max attempts haven't been reached.
64
+ * Updates the delay for the next attempt using exponential backoff.
65
+ *
66
+ * @param connectFn - Function to call when it's time to reconnect
67
+ * @returns True if reconnection was scheduled, false if reconnection is disabled or max attempts reached
48
68
  */
49
69
  scheduleReconnect(connectFn: () => void): boolean;
50
70
  /**
51
- * Cancels any pending reconnection
71
+ * Cancels any pending reconnection attempt.
72
+ * Clears the reconnection timer and transitions state from "reconnecting" to "disconnected" if applicable.
52
73
  */
53
74
  cancelReconnect(): void;
54
75
  /**
55
- * Clears the reconnect timer
76
+ * Clears the reconnect timer if one is set.
77
+ * Internal helper method used to clean up pending reconnection attempts.
56
78
  */
57
79
  private clearReconnectTimer;
58
80
  /**
59
- * Gets the current reconnection attempt count
81
+ * Gets the current reconnection attempt count.
82
+ *
83
+ * @returns The number of reconnection attempts made so far
60
84
  */
61
85
  getReconnectAttempts(): number;
62
86
  /**
63
- * Gets the next reconnection delay
87
+ * Gets the next reconnection delay in milliseconds.
88
+ * This value increases with each attempt due to exponential backoff.
89
+ *
90
+ * @returns The delay in milliseconds before the next reconnection attempt
64
91
  */
65
92
  getNextDelay(): number;
66
93
  /**
67
- * Cleanup method
94
+ * Cleanup method that clears all timers and resources.
95
+ * Should be called when the ConnectionManager is no longer needed.
68
96
  */
69
97
  destroy(): void;
70
98
  }
package/dist/client.d.cts CHANGED
@@ -1,4 +1,4 @@
1
- import { a as DEFAULT_RECONNECTION_CONFIG, i as ConnectionState, n as VeraniClientOptions, o as ReconnectionConfig, r as ConnectionManager, t as VeraniClient } from "./client-BaMxxGWr.cjs";
2
- import { a as ServerMessage, i as PROTOCOL_VERSION, o as VeraniMessage, t as ClientMessage } from "./types-BefWc1M_.cjs";
3
- import { a as encodeFrame, i as encodeClientMessage, n as decodeFrame, o as encodeServerMessage, r as decodeServerMessage, t as decodeClientMessage } from "./decode-D5ZPxqwe.cjs";
1
+ import { a as DEFAULT_RECONNECTION_CONFIG, i as ConnectionState, n as VeraniClientOptions, o as ReconnectionConfig, r as ConnectionManager, t as VeraniClient } from "./client-C3BlxAY_.cjs";
2
+ import { a as ServerMessage, i as PROTOCOL_VERSION, o as VeraniMessage, t as ClientMessage } from "./types-DOI6EHQJ.cjs";
3
+ import { a as encodeFrame, i as encodeClientMessage, n as decodeFrame, o as encodeServerMessage, r as decodeServerMessage, t as decodeClientMessage } from "./decode--RaAAv0U.cjs";
4
4
  export { type ClientMessage, ConnectionManager, type ConnectionState, DEFAULT_RECONNECTION_CONFIG, PROTOCOL_VERSION, type ReconnectionConfig, type ServerMessage, VeraniClient, type VeraniClientOptions, type VeraniMessage, decodeClientMessage, decodeFrame, decodeServerMessage, encodeClientMessage, encodeFrame, encodeServerMessage };
package/dist/client.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { a as DEFAULT_RECONNECTION_CONFIG, i as ConnectionState, n as VeraniClientOptions, o as ReconnectionConfig, r as ConnectionManager, t as VeraniClient } from "./client-DxcWUNF7.mjs";
2
- import { a as ServerMessage, i as PROTOCOL_VERSION, o as VeraniMessage, t as ClientMessage } from "./types-Ds_V-GWZ.mjs";
3
- import { a as encodeFrame, i as encodeClientMessage, n as decodeFrame, o as encodeServerMessage, r as decodeServerMessage, t as decodeClientMessage } from "./decode-E39NapB5.mjs";
1
+ import { a as DEFAULT_RECONNECTION_CONFIG, i as ConnectionState, n as VeraniClientOptions, o as ReconnectionConfig, r as ConnectionManager, t as VeraniClient } from "./client-CV5RrpZX.mjs";
2
+ import { a as ServerMessage, i as PROTOCOL_VERSION, o as VeraniMessage, t as ClientMessage } from "./types-_41fL9Dn.mjs";
3
+ import { a as encodeFrame, i as encodeClientMessage, n as decodeFrame, o as encodeServerMessage, r as decodeServerMessage, t as decodeClientMessage } from "./decode-BUzd77kA.mjs";
4
4
  export { type ClientMessage, ConnectionManager, type ConnectionState, DEFAULT_RECONNECTION_CONFIG, PROTOCOL_VERSION, type ReconnectionConfig, type ServerMessage, VeraniClient, type VeraniClientOptions, type VeraniMessage, decodeClientMessage, decodeFrame, decodeServerMessage, encodeClientMessage, encodeFrame, encodeServerMessage };
@@ -1,22 +1,28 @@
1
- import { r as MessageFrame } from "./types-BefWc1M_.cjs";
1
+ import { r as MessageFrame } from "./types-DOI6EHQJ.cjs";
2
2
 
3
3
  //#region src/shared/encode.d.ts
4
4
 
5
5
  /**
6
- * Encodes a message frame to JSON string for transmission
6
+ * Encodes a message frame to JSON string for transmission over WebSocket.
7
+ * This is the core encoding function used by both client and server.
8
+ *
7
9
  * @param frame - The message frame to encode
8
10
  * @returns JSON string representation of the frame
9
- * @throws Error if encoding fails
11
+ * @throws Error if JSON serialization fails
10
12
  */
11
13
  declare function encodeFrame(frame: MessageFrame): string;
12
14
  /**
13
- * Encodes a client message to JSON string
15
+ * Encodes a client message to JSON string.
16
+ * Alias for encodeFrame, provided for semantic clarity when encoding client messages.
17
+ *
14
18
  * @param message - The client message to encode
15
19
  * @returns JSON string representation
16
20
  */
17
21
  declare function encodeClientMessage(message: MessageFrame): string;
18
22
  /**
19
- * Encodes a server message to JSON string
23
+ * Encodes a server message to JSON string.
24
+ * Alias for encodeFrame, provided for semantic clarity when encoding server messages.
25
+ *
20
26
  * @param message - The server message to encode
21
27
  * @returns JSON string representation
22
28
  */
@@ -24,19 +30,26 @@ declare function encodeServerMessage(message: MessageFrame): string;
24
30
  //#endregion
25
31
  //#region src/shared/decode.d.ts
26
32
  /**
27
- * Decodes a raw message into a MessageFrame
33
+ * Decodes a raw message into a MessageFrame.
34
+ * This is the core decoding function used by both client and server.
35
+ * Handles JSON parsing and validates the resulting object structure.
36
+ *
28
37
  * @param raw - Raw data from WebSocket (string, ArrayBuffer, etc)
29
- * @returns Decoded MessageFrame or null if invalid
38
+ * @returns Decoded MessageFrame or null if parsing or validation fails
30
39
  */
31
40
  declare function decodeFrame(raw: any): MessageFrame | null;
32
41
  /**
33
- * Decodes a client message
42
+ * Decodes a client message.
43
+ * Alias for decodeFrame, provided for semantic clarity when decoding client messages.
44
+ *
34
45
  * @param raw - Raw data from client WebSocket
35
46
  * @returns Decoded message or null if invalid
36
47
  */
37
48
  declare function decodeClientMessage(raw: any): MessageFrame | null;
38
49
  /**
39
- * Decodes a server message
50
+ * Decodes a server message.
51
+ * Alias for decodeFrame, provided for semantic clarity when decoding server messages.
52
+ *
40
53
  * @param raw - Raw data from server WebSocket
41
54
  * @returns Decoded message or null if invalid
42
55
  */
@@ -1,22 +1,28 @@
1
- import { r as MessageFrame } from "./types-Ds_V-GWZ.mjs";
1
+ import { r as MessageFrame } from "./types-_41fL9Dn.mjs";
2
2
 
3
3
  //#region src/shared/encode.d.ts
4
4
 
5
5
  /**
6
- * Encodes a message frame to JSON string for transmission
6
+ * Encodes a message frame to JSON string for transmission over WebSocket.
7
+ * This is the core encoding function used by both client and server.
8
+ *
7
9
  * @param frame - The message frame to encode
8
10
  * @returns JSON string representation of the frame
9
- * @throws Error if encoding fails
11
+ * @throws Error if JSON serialization fails
10
12
  */
11
13
  declare function encodeFrame(frame: MessageFrame): string;
12
14
  /**
13
- * Encodes a client message to JSON string
15
+ * Encodes a client message to JSON string.
16
+ * Alias for encodeFrame, provided for semantic clarity when encoding client messages.
17
+ *
14
18
  * @param message - The client message to encode
15
19
  * @returns JSON string representation
16
20
  */
17
21
  declare function encodeClientMessage(message: MessageFrame): string;
18
22
  /**
19
- * Encodes a server message to JSON string
23
+ * Encodes a server message to JSON string.
24
+ * Alias for encodeFrame, provided for semantic clarity when encoding server messages.
25
+ *
20
26
  * @param message - The server message to encode
21
27
  * @returns JSON string representation
22
28
  */
@@ -24,19 +30,26 @@ declare function encodeServerMessage(message: MessageFrame): string;
24
30
  //#endregion
25
31
  //#region src/shared/decode.d.ts
26
32
  /**
27
- * Decodes a raw message into a MessageFrame
33
+ * Decodes a raw message into a MessageFrame.
34
+ * This is the core decoding function used by both client and server.
35
+ * Handles JSON parsing and validates the resulting object structure.
36
+ *
28
37
  * @param raw - Raw data from WebSocket (string, ArrayBuffer, etc)
29
- * @returns Decoded MessageFrame or null if invalid
38
+ * @returns Decoded MessageFrame or null if parsing or validation fails
30
39
  */
31
40
  declare function decodeFrame(raw: any): MessageFrame | null;
32
41
  /**
33
- * Decodes a client message
42
+ * Decodes a client message.
43
+ * Alias for decodeFrame, provided for semantic clarity when decoding client messages.
44
+ *
34
45
  * @param raw - Raw data from client WebSocket
35
46
  * @returns Decoded message or null if invalid
36
47
  */
37
48
  declare function decodeClientMessage(raw: any): MessageFrame | null;
38
49
  /**
39
- * Decodes a server message
50
+ * Decodes a server message.
51
+ * Alias for decodeFrame, provided for semantic clarity when decoding server messages.
52
+ *
40
53
  * @param raw - Raw data from server WebSocket
41
54
  * @returns Decoded message or null if invalid
42
55
  */
@@ -1,4 +1,4 @@
1
- import { i as ConnectionState, n as VeraniClientOptions, t as VeraniClient } from "./client-BaMxxGWr.cjs";
1
+ import { i as ConnectionState, n as VeraniClientOptions, t as VeraniClient } from "./client-C3BlxAY_.cjs";
2
2
  import { B as payload, C as InferServerEvents, D as ServerPayloadMap, E as ServerPayload, F as EventPayloads, I as ExtractPayload, L as PayloadMarker, M as Contract, N as ContractDefinition, P as EventMap, R as defineContract, S as InferClientEvents, T as ServerEventNames, _ as ClientEventHandler, a as ValidationResult, b as ClientPayloadMap, d as getServerValidator, g as AllEventNames, h as withValidation, i as ValidationIssue, l as createValidatedListener, m as validateData, o as Validator, p as isValidatedContract, r as ValidationError, t as ValidatedContract, v as ClientEventNames, w as ServerEventHandler, x as InferChannels, y as ClientPayload, z as isContract } from "./validation-Dw-KMz9Q.cjs";
3
3
 
4
4
  //#region src/typed/client.d.ts
@@ -1,4 +1,4 @@
1
- import { i as ConnectionState, n as VeraniClientOptions, t as VeraniClient } from "./client-DxcWUNF7.mjs";
1
+ import { i as ConnectionState, n as VeraniClientOptions, t as VeraniClient } from "./client-CV5RrpZX.mjs";
2
2
  import { B as payload, C as InferServerEvents, D as ServerPayloadMap, E as ServerPayload, F as EventPayloads, I as ExtractPayload, L as PayloadMarker, M as Contract, N as ContractDefinition, P as EventMap, R as defineContract, S as InferClientEvents, T as ServerEventNames, _ as ClientEventHandler, a as ValidationResult, b as ClientPayloadMap, d as getServerValidator, g as AllEventNames, h as withValidation, i as ValidationIssue, l as createValidatedListener, m as validateData, o as Validator, p as isValidatedContract, r as ValidationError, t as ValidatedContract, v as ClientEventNames, w as ServerEventHandler, x as InferChannels, y as ClientPayload, z as isContract } from "./validation-DCongzPL.mjs";
3
3
 
4
4
  //#region src/typed/client.d.ts
package/dist/typed.d.cts CHANGED
@@ -1,6 +1,6 @@
1
- import { n as ConnectionMeta } from "./types-BefWc1M_.cjs";
1
+ import { n as ConnectionMeta } from "./types-DOI6EHQJ.cjs";
2
2
  import { A as TypedServerEmit, B as payload, C as InferServerEvents, D as ServerPayloadMap, E as ServerPayload, F as EventPayloads, I as ExtractPayload, L as PayloadMarker, M as Contract, N as ContractDefinition, O as TypedClientEmit, P as EventMap, R as defineContract, S as InferClientEvents, T as ServerEventNames, _ as ClientEventHandler, a as ValidationResult, b as ClientPayloadMap, c as createValidatedHandler, f as getValidationErrorHandler, g as AllEventNames, h as withValidation, i as ValidationIssue, j as TypedServerListener, k as TypedClientListener, m as validateData, n as ValidationConfig, o as Validator, p as isValidatedContract, r as ValidationError, s as ValidatorMap, t as ValidatedContract, u as getClientValidator, v as ClientEventNames, w as ServerEventHandler, x as InferChannels, y as ClientPayload, z as isContract } from "./validation-Dw-KMz9Q.cjs";
3
- import { c as RoomDefinition, n as createActorHandler, r as ActorStub, u as VeraniActor } from "./actor-runtime-gMSqKdY5.cjs";
3
+ import { c as RoomDefinition, n as createActorHandler, r as ActorStub, u as VeraniActor } from "./actor-runtime-1TpQk-wg.cjs";
4
4
 
5
5
  //#region src/typed/server.d.ts
6
6
 
package/dist/typed.d.mts CHANGED
@@ -1,6 +1,6 @@
1
- import { n as ConnectionMeta } from "./types-Ds_V-GWZ.mjs";
1
+ import { n as ConnectionMeta } from "./types-_41fL9Dn.mjs";
2
2
  import { A as TypedServerEmit, B as payload, C as InferServerEvents, D as ServerPayloadMap, E as ServerPayload, F as EventPayloads, I as ExtractPayload, L as PayloadMarker, M as Contract, N as ContractDefinition, O as TypedClientEmit, P as EventMap, R as defineContract, S as InferClientEvents, T as ServerEventNames, _ as ClientEventHandler, a as ValidationResult, b as ClientPayloadMap, c as createValidatedHandler, f as getValidationErrorHandler, g as AllEventNames, h as withValidation, i as ValidationIssue, j as TypedServerListener, k as TypedClientListener, m as validateData, n as ValidationConfig, o as Validator, p as isValidatedContract, r as ValidationError, s as ValidatorMap, t as ValidatedContract, u as getClientValidator, v as ClientEventNames, w as ServerEventHandler, x as InferChannels, y as ClientPayload, z as isContract } from "./validation-DCongzPL.mjs";
3
- import { c as RoomDefinition, n as createActorHandler, r as ActorStub, u as VeraniActor } from "./actor-runtime-Dkz-u49p.mjs";
3
+ import { c as RoomDefinition, n as createActorHandler, r as ActorStub, u as VeraniActor } from "./actor-runtime-BOmyu8Vl.mjs";
4
4
 
5
5
  //#region src/typed/server.d.ts
6
6
 
@@ -0,0 +1,54 @@
1
+ //#region src/shared/types.d.ts
2
+ /**
3
+ * Core message types shared between client and server.
4
+ * These types define the protocol used for WebSocket communication in Verani.
5
+ */
6
+ /**
7
+ * Base message frame structure used for all WebSocket communication.
8
+ * All messages sent over WebSocket follow this structure.
9
+ */
10
+ interface MessageFrame {
11
+ type: string;
12
+ channel?: string;
13
+ data?: any;
14
+ }
15
+ /**
16
+ * Message sent from client to server.
17
+ * Extends MessageFrame with no additional fields, but semantically represents client-originated messages.
18
+ */
19
+ interface ClientMessage extends MessageFrame {
20
+ type: string;
21
+ channel?: string;
22
+ data?: any;
23
+ }
24
+ /**
25
+ * Message sent from server to client.
26
+ * Extends MessageFrame with no additional fields, but semantically represents server-originated messages.
27
+ */
28
+ interface ServerMessage extends MessageFrame {
29
+ type: string;
30
+ channel?: string;
31
+ data?: any;
32
+ }
33
+ /**
34
+ * Connection metadata attached to each WebSocket.
35
+ * This metadata is stored as a WebSocket attachment and survives actor hibernation.
36
+ * It identifies the user, client, and channels the connection is subscribed to.
37
+ */
38
+ interface ConnectionMeta {
39
+ userId: string;
40
+ clientId: string;
41
+ channels: string[];
42
+ }
43
+ /**
44
+ * Unified message type for both directions.
45
+ * Represents any message that can be sent over the Verani WebSocket protocol.
46
+ */
47
+ type VeraniMessage = ClientMessage | ServerMessage;
48
+ /**
49
+ * Protocol version for future compatibility.
50
+ * Used to identify the protocol version for potential future protocol upgrades.
51
+ */
52
+ declare const PROTOCOL_VERSION = "1.0.0";
53
+ //#endregion
54
+ export { ServerMessage as a, PROTOCOL_VERSION as i, ConnectionMeta as n, VeraniMessage as o, MessageFrame as r, ClientMessage as t };
@@ -0,0 +1,54 @@
1
+ //#region src/shared/types.d.ts
2
+ /**
3
+ * Core message types shared between client and server.
4
+ * These types define the protocol used for WebSocket communication in Verani.
5
+ */
6
+ /**
7
+ * Base message frame structure used for all WebSocket communication.
8
+ * All messages sent over WebSocket follow this structure.
9
+ */
10
+ interface MessageFrame {
11
+ type: string;
12
+ channel?: string;
13
+ data?: any;
14
+ }
15
+ /**
16
+ * Message sent from client to server.
17
+ * Extends MessageFrame with no additional fields, but semantically represents client-originated messages.
18
+ */
19
+ interface ClientMessage extends MessageFrame {
20
+ type: string;
21
+ channel?: string;
22
+ data?: any;
23
+ }
24
+ /**
25
+ * Message sent from server to client.
26
+ * Extends MessageFrame with no additional fields, but semantically represents server-originated messages.
27
+ */
28
+ interface ServerMessage extends MessageFrame {
29
+ type: string;
30
+ channel?: string;
31
+ data?: any;
32
+ }
33
+ /**
34
+ * Connection metadata attached to each WebSocket.
35
+ * This metadata is stored as a WebSocket attachment and survives actor hibernation.
36
+ * It identifies the user, client, and channels the connection is subscribed to.
37
+ */
38
+ interface ConnectionMeta {
39
+ userId: string;
40
+ clientId: string;
41
+ channels: string[];
42
+ }
43
+ /**
44
+ * Unified message type for both directions.
45
+ * Represents any message that can be sent over the Verani WebSocket protocol.
46
+ */
47
+ type VeraniMessage = ClientMessage | ServerMessage;
48
+ /**
49
+ * Protocol version for future compatibility.
50
+ * Used to identify the protocol version for potential future protocol upgrades.
51
+ */
52
+ declare const PROTOCOL_VERSION = "1.0.0";
53
+ //#endregion
54
+ export { ServerMessage as a, PROTOCOL_VERSION as i, ConnectionMeta as n, VeraniMessage as o, MessageFrame as r, ClientMessage as t };
package/dist/verani.d.cts CHANGED
@@ -1,6 +1,6 @@
1
- import { a as ServerMessage, i as PROTOCOL_VERSION, n as ConnectionMeta, o as VeraniMessage, r as MessageFrame, t as ClientMessage } from "./types-BefWc1M_.cjs";
2
- import { a as encodeFrame, i as encodeClientMessage, n as decodeFrame, o as encodeServerMessage, r as decodeServerMessage, t as decodeClientMessage } from "./decode-D5ZPxqwe.cjs";
3
- import { C as safeSerialize, S as safeDeserialize, _ as getPersistedKeys, a as EventHandler, b as isStateReady, c as RoomDefinition, d as PersistError, f as PersistNotReadyError, g as deletePersistedKey, h as clearPersistedState, i as BroadcastOptions, l as RpcBroadcastOptions, m as SafePersistOptions, n as createActorHandler, o as MessageContext, p as PersistableActor, r as ActorStub, s as RoomContext, t as ActorHandlerClass, u as VeraniActor, v as getPersistedState, w as setPeristErrorHandler, x as persistKey, y as initializePersistedState } from "./actor-runtime-gMSqKdY5.cjs";
1
+ import { a as ServerMessage, i as PROTOCOL_VERSION, n as ConnectionMeta, o as VeraniMessage, r as MessageFrame, t as ClientMessage } from "./types-DOI6EHQJ.cjs";
2
+ import { a as encodeFrame, i as encodeClientMessage, n as decodeFrame, o as encodeServerMessage, r as decodeServerMessage, t as decodeClientMessage } from "./decode--RaAAv0U.cjs";
3
+ import { C as safeSerialize, S as safeDeserialize, _ as getPersistedKeys, a as EventHandler, b as isStateReady, c as RoomDefinition, d as PersistError, f as PersistNotReadyError, g as deletePersistedKey, h as clearPersistedState, i as BroadcastOptions, l as RpcBroadcastOptions, m as SafePersistOptions, n as createActorHandler, o as MessageContext, p as PersistableActor, r as ActorStub, s as RoomContext, t as ActorHandlerClass, u as VeraniActor, v as getPersistedState, w as setPeristErrorHandler, x as persistKey, y as initializePersistedState } from "./actor-runtime-1TpQk-wg.cjs";
4
4
 
5
5
  //#region src/actor/router.d.ts
6
6
  /**
@@ -21,14 +21,47 @@ interface RoomDefinitionWithHandlers<TMeta extends ConnectionMeta = ConnectionMe
21
21
  off(event: string, handler?: EventHandler<TMeta, E, TState>): void;
22
22
  }
23
23
  /**
24
- * Defines a room with lifecycle hooks and metadata extraction
25
- * @param def - Room definition with optional hooks
24
+ * Defines a room with lifecycle hooks and metadata extraction.
25
+ * Creates a normalized room definition with default values and socket.io-like event handler methods.
26
+ * The returned room object supports `.on()` and `.off()` methods for event handling.
27
+ *
28
+ * @param def - Room definition with optional hooks, state, and configuration
26
29
  * @returns Normalized room definition with defaults and socket.io-like event handler methods
30
+ * @example
31
+ * ```typescript
32
+ * const room = defineRoom({
33
+ * websocketPath: "/ws",
34
+ * onConnect: (ctx) => console.log("User connected:", ctx.meta.userId),
35
+ * onMessage: (ctx, frame) => console.log("Message:", frame.type)
36
+ * });
37
+ *
38
+ * // Register event handlers
39
+ * room.on("chat", (ctx, data) => {
40
+ * ctx.emit.emit("message", data);
41
+ * });
42
+ * ```
27
43
  */
28
44
  declare function defineRoom<TMeta extends ConnectionMeta = ConnectionMeta, E = unknown, TState extends Record<string, unknown> = Record<string, unknown>>(def: RoomDefinition<TMeta, E, TState>): RoomDefinitionWithHandlers<TMeta, E, TState>;
29
45
  //#endregion
30
46
  //#region src/actor/attachment.d.ts
47
+ /**
48
+ * Stores connection metadata as a WebSocket attachment for hibernation survival.
49
+ * This allows the actor to restore session information when it wakes from hibernation.
50
+ *
51
+ * @param ws - The WebSocket connection to attach metadata to
52
+ * @param meta - Connection metadata containing userId, clientId, and channels
53
+ * @throws Error if serialization fails
54
+ */
31
55
  declare function storeAttachment(ws: WebSocket, meta: ConnectionMeta): void;
56
+ /**
57
+ * Restores WebSocket sessions from hibernation by deserializing attachments.
58
+ * Only restores sessions that are in OPEN state and have valid metadata.
59
+ * Sessions with invalid or missing metadata are skipped.
60
+ *
61
+ * @param actor - The actor instance with a sessions Map and ctx.getWebSockets() method
62
+ * @returns void - Sessions are added directly to actor.sessions Map
63
+ * @throws Error if deserialization fails critically (individual failures are logged and skipped)
64
+ */
32
65
  declare function restoreSessions(actor: any): void;
33
66
  //#endregion
34
67
  export { type ActorHandlerClass, type ActorStub, type BroadcastOptions, type ClientMessage, type ConnectionMeta, type MessageContext, type MessageFrame, PROTOCOL_VERSION, PersistError, PersistNotReadyError, type PersistableActor, type RoomContext, type RoomDefinition, type RpcBroadcastOptions, type SafePersistOptions, type ServerMessage, type VeraniActor, type VeraniMessage, clearPersistedState, createActorHandler, decodeClientMessage, decodeFrame, decodeServerMessage, defineRoom, deletePersistedKey, encodeClientMessage, encodeFrame, encodeServerMessage, getPersistedKeys, getPersistedState, initializePersistedState, isStateReady, persistKey, restoreSessions, safeDeserialize, safeSerialize, setPeristErrorHandler, storeAttachment };
package/dist/verani.d.mts CHANGED
@@ -1,6 +1,6 @@
1
- import { a as ServerMessage, i as PROTOCOL_VERSION, n as ConnectionMeta, o as VeraniMessage, r as MessageFrame, t as ClientMessage } from "./types-Ds_V-GWZ.mjs";
2
- import { a as encodeFrame, i as encodeClientMessage, n as decodeFrame, o as encodeServerMessage, r as decodeServerMessage, t as decodeClientMessage } from "./decode-E39NapB5.mjs";
3
- import { C as safeSerialize, S as safeDeserialize, _ as getPersistedKeys, a as EventHandler, b as isStateReady, c as RoomDefinition, d as PersistError, f as PersistNotReadyError, g as deletePersistedKey, h as clearPersistedState, i as BroadcastOptions, l as RpcBroadcastOptions, m as SafePersistOptions, n as createActorHandler, o as MessageContext, p as PersistableActor, r as ActorStub, s as RoomContext, t as ActorHandlerClass, u as VeraniActor, v as getPersistedState, w as setPeristErrorHandler, x as persistKey, y as initializePersistedState } from "./actor-runtime-Dkz-u49p.mjs";
1
+ import { a as ServerMessage, i as PROTOCOL_VERSION, n as ConnectionMeta, o as VeraniMessage, r as MessageFrame, t as ClientMessage } from "./types-_41fL9Dn.mjs";
2
+ import { a as encodeFrame, i as encodeClientMessage, n as decodeFrame, o as encodeServerMessage, r as decodeServerMessage, t as decodeClientMessage } from "./decode-BUzd77kA.mjs";
3
+ import { C as safeSerialize, S as safeDeserialize, _ as getPersistedKeys, a as EventHandler, b as isStateReady, c as RoomDefinition, d as PersistError, f as PersistNotReadyError, g as deletePersistedKey, h as clearPersistedState, i as BroadcastOptions, l as RpcBroadcastOptions, m as SafePersistOptions, n as createActorHandler, o as MessageContext, p as PersistableActor, r as ActorStub, s as RoomContext, t as ActorHandlerClass, u as VeraniActor, v as getPersistedState, w as setPeristErrorHandler, x as persistKey, y as initializePersistedState } from "./actor-runtime-BOmyu8Vl.mjs";
4
4
 
5
5
  //#region src/actor/router.d.ts
6
6
  /**
@@ -21,14 +21,47 @@ interface RoomDefinitionWithHandlers<TMeta extends ConnectionMeta = ConnectionMe
21
21
  off(event: string, handler?: EventHandler<TMeta, E, TState>): void;
22
22
  }
23
23
  /**
24
- * Defines a room with lifecycle hooks and metadata extraction
25
- * @param def - Room definition with optional hooks
24
+ * Defines a room with lifecycle hooks and metadata extraction.
25
+ * Creates a normalized room definition with default values and socket.io-like event handler methods.
26
+ * The returned room object supports `.on()` and `.off()` methods for event handling.
27
+ *
28
+ * @param def - Room definition with optional hooks, state, and configuration
26
29
  * @returns Normalized room definition with defaults and socket.io-like event handler methods
30
+ * @example
31
+ * ```typescript
32
+ * const room = defineRoom({
33
+ * websocketPath: "/ws",
34
+ * onConnect: (ctx) => console.log("User connected:", ctx.meta.userId),
35
+ * onMessage: (ctx, frame) => console.log("Message:", frame.type)
36
+ * });
37
+ *
38
+ * // Register event handlers
39
+ * room.on("chat", (ctx, data) => {
40
+ * ctx.emit.emit("message", data);
41
+ * });
42
+ * ```
27
43
  */
28
44
  declare function defineRoom<TMeta extends ConnectionMeta = ConnectionMeta, E = unknown, TState extends Record<string, unknown> = Record<string, unknown>>(def: RoomDefinition<TMeta, E, TState>): RoomDefinitionWithHandlers<TMeta, E, TState>;
29
45
  //#endregion
30
46
  //#region src/actor/attachment.d.ts
47
+ /**
48
+ * Stores connection metadata as a WebSocket attachment for hibernation survival.
49
+ * This allows the actor to restore session information when it wakes from hibernation.
50
+ *
51
+ * @param ws - The WebSocket connection to attach metadata to
52
+ * @param meta - Connection metadata containing userId, clientId, and channels
53
+ * @throws Error if serialization fails
54
+ */
31
55
  declare function storeAttachment(ws: WebSocket, meta: ConnectionMeta): void;
56
+ /**
57
+ * Restores WebSocket sessions from hibernation by deserializing attachments.
58
+ * Only restores sessions that are in OPEN state and have valid metadata.
59
+ * Sessions with invalid or missing metadata are skipped.
60
+ *
61
+ * @param actor - The actor instance with a sessions Map and ctx.getWebSockets() method
62
+ * @returns void - Sessions are added directly to actor.sessions Map
63
+ * @throws Error if deserialization fails critically (individual failures are logged and skipped)
64
+ */
32
65
  declare function restoreSessions(actor: any): void;
33
66
  //#endregion
34
67
  export { type ActorHandlerClass, type ActorStub, type BroadcastOptions, type ClientMessage, type ConnectionMeta, type MessageContext, type MessageFrame, PROTOCOL_VERSION, PersistError, PersistNotReadyError, type PersistableActor, type RoomContext, type RoomDefinition, type RpcBroadcastOptions, type SafePersistOptions, type ServerMessage, type VeraniActor, type VeraniMessage, clearPersistedState, createActorHandler, decodeClientMessage, decodeFrame, decodeServerMessage, defineRoom, deletePersistedKey, encodeClientMessage, encodeFrame, encodeServerMessage, getPersistedKeys, getPersistedState, initializePersistedState, isStateReady, persistKey, restoreSessions, safeDeserialize, safeSerialize, setPeristErrorHandler, storeAttachment };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "verani",
3
- "version": "0.8.0",
3
+ "version": "0.8.1",
4
4
  "description": "A simple, focused realtime SDK for Cloudflare Actors with Socket.io-like semantics",
5
5
  "license": "ISC",
6
6
  "keywords": [
@@ -1,46 +0,0 @@
1
- //#region src/shared/types.d.ts
2
- /**
3
- * Core message types shared between client and server
4
- */
5
- /**
6
- * Base message frame structure used for all WebSocket communication
7
- */
8
- interface MessageFrame {
9
- type: string;
10
- channel?: string;
11
- data?: any;
12
- }
13
- /**
14
- * Message sent from client to server
15
- */
16
- interface ClientMessage extends MessageFrame {
17
- type: string;
18
- channel?: string;
19
- data?: any;
20
- }
21
- /**
22
- * Message sent from server to client
23
- */
24
- interface ServerMessage extends MessageFrame {
25
- type: string;
26
- channel?: string;
27
- data?: any;
28
- }
29
- /**
30
- * Connection metadata attached to each WebSocket
31
- */
32
- interface ConnectionMeta {
33
- userId: string;
34
- clientId: string;
35
- channels: string[];
36
- }
37
- /**
38
- * Unified message type for both directions
39
- */
40
- type VeraniMessage = ClientMessage | ServerMessage;
41
- /**
42
- * Protocol version for future compatibility
43
- */
44
- declare const PROTOCOL_VERSION = "1.0.0";
45
- //#endregion
46
- export { ServerMessage as a, PROTOCOL_VERSION as i, ConnectionMeta as n, VeraniMessage as o, MessageFrame as r, ClientMessage as t };
@@ -1,46 +0,0 @@
1
- //#region src/shared/types.d.ts
2
- /**
3
- * Core message types shared between client and server
4
- */
5
- /**
6
- * Base message frame structure used for all WebSocket communication
7
- */
8
- interface MessageFrame {
9
- type: string;
10
- channel?: string;
11
- data?: any;
12
- }
13
- /**
14
- * Message sent from client to server
15
- */
16
- interface ClientMessage extends MessageFrame {
17
- type: string;
18
- channel?: string;
19
- data?: any;
20
- }
21
- /**
22
- * Message sent from server to client
23
- */
24
- interface ServerMessage extends MessageFrame {
25
- type: string;
26
- channel?: string;
27
- data?: any;
28
- }
29
- /**
30
- * Connection metadata attached to each WebSocket
31
- */
32
- interface ConnectionMeta {
33
- userId: string;
34
- clientId: string;
35
- channels: string[];
36
- }
37
- /**
38
- * Unified message type for both directions
39
- */
40
- type VeraniMessage = ClientMessage | ServerMessage;
41
- /**
42
- * Protocol version for future compatibility
43
- */
44
- declare const PROTOCOL_VERSION = "1.0.0";
45
- //#endregion
46
- export { ServerMessage as a, PROTOCOL_VERSION as i, ConnectionMeta as n, VeraniMessage as o, MessageFrame as r, ClientMessage as t };